hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
630e7f96b7e3672cbb3bf8845a4b776402c58c42
11,494
cpp
C++
src/ClasterizeByCentroids/main.cpp
vladimir-inoz/maputils
554fe1df70d8a77e572058b9e28ae717977ebc0a
[ "MIT" ]
null
null
null
src/ClasterizeByCentroids/main.cpp
vladimir-inoz/maputils
554fe1df70d8a77e572058b9e28ae717977ebc0a
[ "MIT" ]
null
null
null
src/ClasterizeByCentroids/main.cpp
vladimir-inoz/maputils
554fe1df70d8a77e572058b9e28ae717977ebc0a
[ "MIT" ]
null
null
null
/*! \file \brief Кластеризация по центроидам \details Программа предназначена для кластеризации входной геометрии по координатам центроидов. Номер кластера добавляется как новое поле для геометрии. Кластеризуется каждый входной файл по отдельности. \author Владимир Иноземцев \version 1.0 */ //gdal #include <gdal.h> #include <gdal_priv.h> #include <ogr_feature.h> #include <ogrsf_frmts.h> //std #include <memory> #include <string.h> #include <vector> #include <list> #include <iostream> #include <assert.h> //кластеризация #include <KMlocal.h> //мои модули #include <gdalutilities.h> #include <clasterutils.h> using namespace std; using namespace GDALUtilities::Boilerplates; ///непосредственно данные KMdata *dataPoints; ///число кластеров int nclasters; ///центры кластеризации KMfilterCenters *centers; ///исходные геометрии OGRGeometryCollection *src; ///массив индексов KMctrIdxArray closeCtr; void ClasterCore() { int stages = 100; KMterm term(100, 0, 0, 0, // run for 100 stages 0.10, // min consec RDL 0.10, // min accum RDL 3, // max run stages 0.50, // init. prob. of acceptance 10, // temp. run length 0.95); // temp. reduction factor //массив данных для алгоритма //строим дерево для сортировки dataPoints->buildKcTree(); //создаем структуру центров кластеров assert(nclasters > 0); centers = new KMfilterCenters(nclasters, *dataPoints); //запускаем алгоритм KMlocalLloyds kmLloyds(*centers, term); *centers = kmLloyds.execute(); //индексы closeCtr = new KMctrIdx[dataPoints->getNPts()]; //дистанции double* sqDist = new double[dataPoints->getNPts()]; //записываем дистанции centers->getAssignments(closeCtr, sqDist); } bool HaveClasternum(OGRLayer *currentLayer) { bool res = false; OGRFeatureDefn *poFDefn = currentLayer->GetLayerDefn(); for (int iField = 0; iField < poFDefn->GetFieldCount(); iField++) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField); if (strcmp(poFieldDefn->GetNameRef(), "clasternum") == 0) { std::cout << "Have clasternum field" << std::endl; res = true; } } if (!res) std::cout << "Don't have clasternum field" << std::endl; return res; } int main(int argc, char *argv[]) { //проверяем аргументы командной строки if (argc < 4) { std::cout << "USAGE: ClasterizeByCentroids" << "<in1> <in2> .. <inN> " << "<layer_name> <nclasters>" << std::endl; std::cout << "<in1>..<inN> - input files" << std::endl; std::cout << "<layer_name> - name of layer, from which" << "geometries are fetched. It should contain only" << "polygons." << std::endl; std::cout << "<nclasters> - number of result clasters," << "must be 2 or greater" << std::endl; exit(1); } //парсим аргументы //имя слоя string layerName(argv[argc - 2]); //число кластеров nclasters = atoi(argv[argc - 1]); if (nclasters < 2) { std::cout << "Invalid count of clasters!" << endl; std::cout << "Count of clasters should be 2 or greater!" << std::endl; exit(1); } //регистрируем все драйверы GDALAllRegister(); //датасеты для каждого из исходных файлов GDALUtilities::StringList flist; for (int i = 1;i < argc - 2;i++) flist.push_back(string(argv[i])); //проходимся по списку файлов, пытаемся читать каждый for (auto i = flist.begin();i != flist.end();i++) { //набор геометрических коллекций из данного входного файла TempOGC collection(newGeometryCollection(), destroy); //Dataset из входного файла //Открываем его в режиме чтения GDALDataset *inputDataset = (GDALDataset*)GDALOpenEx( (*i).c_str(), GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr); std::cout << "processing file \"" << (*i) << "\"" << std::endl; //нужный слой из Dataset входного файла OGRLayer *currentLayer = inputDataset->GetLayerByName(layerName.c_str()); //нет нужного слоя if (!currentLayer) { //выводим сообщение пользователю, что нет слоя SOURCE_LAYER в файле char* fname = inputDataset->GetFileList()[0]; if (fname) cout << "File \"" << fname << "\" does not contain layer \"" << layerName << "\"" << std::endl; else cout << "layer_error" << std::endl; std::cout << "This file contains layers:" << std::endl; //выводим список слоев for (int i = 0;i < inputDataset->GetLayerCount();i++) std::cout << "\"" << inputDataset->GetLayer(i)->GetName() << "\" " << std::endl; //пропускаем dataset continue; } //проверяем, имеет ли слой нужные нам возможности if (!currentLayer->TestCapability(OLCCreateField)) { std::cout << "Layer does not provide OLCCreateField" << " capability" << std::endl; continue; } if (!currentLayer->TestCapability(OLCRandomWrite)) { std::cout << "Layer does not provide OLCRandomWrite" << " capability" << std::endl; continue; } //проверяем, есть ли поле clasternum if (!HaveClasternum(currentLayer)) { //нет, создаем поле clasternum в слое OGRFieldDefn oClasterNum("clasternum", OFTInteger); if (currentLayer->CreateField(&oClasterNum) != OGRERR_NONE) { printf("Creating clasternum field failed.\n"); exit(1); } } //текущая фича OGRFeature *currentFeature; //смотрим, сколько фич в слое int nfeatures = 0; currentLayer->ResetReading(); while ((currentFeature = currentLayer->GetNextFeature()) != nullptr) { nfeatures++; //не забываем удалять, это копия объекта OGRFeature::DestroyFeature(currentFeature); } //для найденного количества фич инициализируем данные KMdata dataPoints = new KMdata(2, nfeatures); //читаем feature заново, считая центроиды currentLayer->ResetReading(); int featureCounter = 0; //красивый прогресс GDALUtilities::ProgressIndicator indicator(currentLayer->GetFeatureCount(), "Reading file"); //просматриваем все фичи заново while ((currentFeature = currentLayer->GetNextFeature()) != nullptr) { //отображаем прогресс в консоли indicator.incOperationCount(); //геометрия из входного файла OGRGeometry *currentGeometry; currentGeometry = currentFeature->GetGeometryRef(); //если нет геометрии в currentFeature, пропускаем его if (!currentGeometry) { OGRFeature::DestroyFeature(currentFeature); continue; } //если геометрия не того типа, пропускаем feature if (currentGeometry->getGeometryType() != wkbPolygon) { OGRFeature::DestroyFeature(currentFeature); continue; } //считаем failsafe центроид фичи shared_ptr<OGRPoint> centroid( GDALUtilities::FailsafeCentroid(currentGeometry), destroy); //перегоняем данные в KMlocal KMpoint &p = (*dataPoints)[featureCounter]; p[0] = centroid->getX(); p[1] = centroid->getY(); //освобождаем память фичи OGRFeature::DestroyFeature(currentFeature); featureCounter++; } //запускаем алгоритм кластеризации ClasterCore(); //изменяем поле clasternum у каждой фичи currentLayer->ResetReading(); featureCounter = 0; //просматриваем все фичи заново while ((currentFeature = currentLayer->GetNextFeature()) != nullptr) { //берем индекс кластера из массива int claster_idx = closeCtr[featureCounter++]; //в фиче меняем поле currentFeature->SetField("clasternum", claster_idx); //перезаписываем фичу в файле currentLayer->SetFeature(currentFeature); //освобождаем память фичи OGRFeature::DestroyFeature(currentFeature); } //теперь записываем геометрии кластеров в отдельные файлы for (int i = 0;i < nclasters;i++) { //имя слоя, соответствующего кластеру i string lname("claster_"); lname.append(std::to_string(i)); std::cout << "processing layer \"" << lname << "\"" << std::endl; //инициализация нового слоя OGRLayer *newLayer = inputDataset->CreateLayer(lname.c_str(), 0, wkbPolygon, 0); if (!newLayer) { std::cout << "Error while creating layer" << "\"" << lname << "\"" << std::endl; exit(1); } //в новый слой пробрасываем все атрибуты из исходного слоя //для этого сначала инициализируем эти атрибуты OGRFeatureDefn *poFDefn = currentLayer->GetLayerDefn(); for (int iField = 0; iField < poFDefn->GetFieldCount(); iField++) { OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField); if (newLayer->CreateField(poFieldDefn) != OGRERR_NONE) { std::cout << "Copying field failed." << std::endl; exit(1); } } //текст фильтра для фич string filter_str("clasternum="); filter_str.append(std::to_string(i)); //применяем фильтр currentLayer->SetAttributeFilter(filter_str.c_str()); //просматриваем все фичи, соответствующие фильтру currentLayer->ResetReading(); while ((currentFeature = currentLayer->GetNextFeature()) != nullptr) { //создаем новую фичу в слое кластера OGRFeature *poFeature; poFeature = OGRFeature::CreateFeature(newLayer->GetLayerDefn()); //из фичи копируем все атрибуты и геометрию if (OGR_F_SetFrom(poFeature, currentFeature, true) != OGRERR_NONE) { std::cout << "Copying feature failed." << std::endl; } //создаем фичу на слое if (newLayer->CreateFeature(poFeature) != OGRERR_NONE) { std::cout << "Failed to save the feature." << std::endl; exit(1); } //освобождаем память фичи OGRFeature::DestroyFeature(poFeature); } } GDALClose(inputDataset); } //говорим, что все ок std::cout << "Clasterizing ok" << std::endl; return 0; }
32.84
82
0.557682
[ "vector" ]
63159943d7823f84b6c9fe6b442c7d62345a678e
7,364
cpp
C++
src/biomolecules/sprelay/gui/indicator_button.cpp
lumik/sprelay
aaae1167038fc5477fc5dc9ee026d08c1d1b88bc
[ "BSD-3-Clause" ]
null
null
null
src/biomolecules/sprelay/gui/indicator_button.cpp
lumik/sprelay
aaae1167038fc5477fc5dc9ee026d08c1d1b88bc
[ "BSD-3-Clause" ]
65
2017-04-11T14:40:39.000Z
2022-01-28T18:24:39.000Z
src/biomolecules/sprelay/gui/indicator_button.cpp
lumik/sprelay
aaae1167038fc5477fc5dc9ee026d08c1d1b88bc
[ "BSD-3-Clause" ]
null
null
null
// -*-c++-*- /*************************************************************************** ** ** ** Controlling interface for K8090 8-Channel Relay Card from Velleman ** ** through usb using virtual serial port in Qt. ** ** Copyright (C) 2018 Jakub Klener ** ** ** ** This file is part of SpRelay application. ** ** ** ** You can redistribute it and/or modify it under the terms of the ** ** 3-Clause BSD License as published by the Open Source Initiative. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** 3-Clause BSD License for more details. ** ** ** ** You should have received a copy of the 3-Clause BSD License along ** ** with this program. ** ** If not, see https://opensource.org/licenses/ ** ** ** ****************************************************************************/ /*! * \file indicator_button.cpp * \brief The biomolecules::sprelay::gui::IndicatorButton and biomolecules::sprelay::gui::IndicatorLight widgets * which indicates their state by their color. * * \author Jakub Klener <lumiksro@centrum.cz> * \date 2018-06-26 * \copyright Copyright (C) 2018 Jakub Klener. All rights reserved. * * \copyright This project is released under the 3-Clause BSD License. You should have received a copy of the 3-Clause * BSD License along with this program. If not, see https://opensource.org/licenses/. */ #include "indicator_button.h" #include <QHBoxLayout> #include <QLabel> #include <QSize> #include <QString> namespace biomolecules { namespace sprelay { namespace gui { // TODO(lumik): improve documentation with examples. /*! * \class IndicatorLight * \remarks reentrant */ /*! * \brief Constructs the widget. * \param parent The widget's parent object in Qt ownership system. * * Sets the widget to false IndicatorLight::state and sets the light to red color. */ IndicatorLight::IndicatorLight(QWidget* parent) : QPushButton(parent), state_{false} { QSize indicatorSize(10, 10); setFixedSize(indicatorSize); setEnabled(false); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); if (state_) { setStyleSheet("background-color: green"); } else { setStyleSheet("background-color: red"); } } /*! * \property IndicatorLight::state * \brief This property maintains the state of indicator light. * * If the state is set true, the background color is green, otherwise the background color is red. When the state * changes, IndicatorLight::stateChanged() signal is emited. * * | Access functions: || * | - | - | * | **Access** | %IndicatorLight::state() | * | **Set** | IndicatorLight::setState() | * | **Notify** | IndicatorLight::stateChanged() | */ /*! * \brief Setter for IndicatorLight::state property. * \param state The required state. */ void IndicatorLight::setState(bool state) { if (state != state_) { state_ = state; if (state_) { setStyleSheet("background-color: green"); } else { setStyleSheet("background-color: red"); } emit stateChanged(); } } /*! * \fn IndicatorLight::stateChanged * \brief Signal which is emited each time the state changes. */ /*! * \class IndicatorButton * \remarks reentrant */ /*! * \brief Constructs the widget. * \param parent The widget's parent object in Qt ownership system. */ IndicatorButton::IndicatorButton(QWidget* parent) : QPushButton{parent} { initialize(""); } /*! * \brief Constructs the widget. * \param text The text displayed on the pushbutton. * \param parent The widget's parent object in Qt ownership system. */ IndicatorButton::IndicatorButton(const QString& text, QWidget* parent) : QPushButton{"", parent} { initialize(text); } /*! * \brief Constructs the widget. * \param icon The icon displayed on the pushbutton. See QPushButton documentation. * \param text The text displayed on the pushbutton. * \param parent The widget's parent object in Qt ownership system. */ IndicatorButton::IndicatorButton(const QIcon& icon, const QString& text, QWidget* parent) : QPushButton{icon, "", parent} { initialize(text); } /*! * \property IndicatorButton::state * \brief This property maintains the state of indicator button. * * If the state is set true, the indicator light color is green, otherwise the color is red. When the state changes, * IndicatorButton::stateChanged() signal is emited. * * | Access functions: || * | - | - | * | **Access** | bool %IndicatorButton::state() | * | **Set** | IndicatorButton::setState(bool state) | * | **Notify** | IndicatorButton::stateChanged() | */ /*! * \property IndicatorButton::text * \brief This property contains the text displayed on push button. * * | Access functions: || * | - | - | * | **Access** | QString %IndicatorButton::text() | * | **Set** | IndicatorButton::setText(const QString& text) | */ /*! * \brief Setter for the IndicatorButton::text property. * \param text The text. */ void IndicatorButton::setText(const QString& text) { label_->setText(text); } QString IndicatorButton::text() const { return label_->text(); } /*! * \brief Accessor for the inherited QWidget::sizeHint property. * \return The size hint. */ QSize IndicatorButton::sizeHint() const { return layout()->sizeHint(); } /*! * \fn IndicatorButton::setState(bool state) * \brief Setter for IndicatorLight::state property. * \param state The required state. */ /*! * \fn IndicatorButton::stateChanged * \brief Signal which is emited each time the state changes. */ void IndicatorButton::initialize(const QString& text) { auto layout = new QHBoxLayout{this}; indicator_ = new IndicatorLight{this}; label_ = new QLabel{text, this}; indicator_->setAttribute(Qt::WA_TransparentForMouseEvents); label_->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); label_->setTextInteractionFlags(Qt::NoTextInteraction); label_->setMouseTracking(false); label_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); layout->addWidget(indicator_); layout->setContentsMargins(5, 5, 5, 5); layout->addWidget(label_); layout->setSpacing(5); layout->setMargin(0); layout->setContentsMargins(5, 5, 5, 5); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); connect(indicator_, &IndicatorLight::stateChanged, this, &IndicatorButton::stateChanged); } } // namespace gui } // namespace sprelay } // namespace biomolecules
29.693548
118
0.603476
[ "object" ]
6315fab7a185baa38f66f281891a6fd1821104f5
1,444
cpp
C++
src/dx11/xGSdatabuffer.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-03-17T16:11:39.000Z
2021-02-08T18:03:23.000Z
src/dx11/xGSdatabuffer.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-07-15T07:02:44.000Z
2018-05-24T20:39:57.000Z
src/dx11/xGSdatabuffer.cpp
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
4
2016-03-20T11:43:11.000Z
2022-01-21T21:07:54.000Z
/* xGS 3D Low-level rendering API Low-level 3D rendering wrapper API with multiple back-end support (c) livingcreative, 2015 - 2018 https://github.com/livingcreative/xgs dx11/xGSdatabuffer.cpp DataBuffer object implementation class */ #include "xGSdatabuffer.h" #include "xGSstate.h" using namespace xGS; xGSDataBufferImpl::xGSDataBufferImpl(xGSImpl *owner) : xGSObjectBase(owner), p_buffer(nullptr) {} xGSDataBufferImpl::~xGSDataBufferImpl() {} GSbool xGSDataBufferImpl::AllocateImpl(const GSdatabufferdescription &desc, GSuint totalsize) { // TODO: allocate DX11 data buffer D3D11_BUFFER_DESC bufferdesc = {}; bufferdesc.Usage = D3D11_USAGE_DYNAMIC; bufferdesc.ByteWidth = p_size; bufferdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bufferdesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; p_owner->device()->CreateBuffer(&bufferdesc, nullptr, &p_buffer); return GS_TRUE; } void xGSDataBufferImpl::UpdateImpl(GSuint offset, GSuint size, const GSptr data) { // TODO: update DX11 data buffer } GSptr xGSDataBufferImpl::LockImpl(GSdword access) { p_locktype = GS_LOCKED; // TODO: lock DX11 data buffer return nullptr; } void xGSDataBufferImpl::UnlockImpl() { p_locktype = GS_NONE; // TODO: unlock DX11 data buffer } void xGSDataBufferImpl::ReleaseRendererResources() { // TODO: release DX11 data buffer ::Release(p_buffer); }
20.927536
93
0.726454
[ "object", "3d" ]
631d2baf97ef3d75e83ba548852fc423160276f9
82,728
cpp
C++
src/test_game.cpp
nekoshota/teippi_PronogoMod
590b59384118b4dc99800260356accf9d484eb63
[ "MIT" ]
null
null
null
src/test_game.cpp
nekoshota/teippi_PronogoMod
590b59384118b4dc99800260356accf9d484eb63
[ "MIT" ]
null
null
null
src/test_game.cpp
nekoshota/teippi_PronogoMod
590b59384118b4dc99800260356accf9d484eb63
[ "MIT" ]
null
null
null
#ifdef DEBUG #include "test_game.h" #include "unit.h" #include "offsets.h" #include "limits.h" #include "player.h" #include "common/assert.h" #include "tech.h" #include "order.h" #include "text.h" #include "bullet.h" #include "unitsearch.h" #include "targeting.h" #include "dialog.h" #include "yms.h" #include "ai.h" #include "ai_hit_reactions.h" #include "triggers.h" #include "possearch.hpp" #include <algorithm> #include "console/windows_wrap.h" using std::min; using std::get; #define TestAssert(s) if (!(s)) { if(IsDebuggerPresent()) { INT3(); } Fail(#s); return; } // This file has special permission for different brace style =) static void ClearTriggers() { for (int i = 0; i < Limits::ActivePlayers; i++) FreeTriggerList(&bw::triggers[i]); } Unit *GameTest::CreateUnitForTest(int unit_id, int player) { return CreateUnitForTestAt(unit_id, player, Point(100, 100)); } Unit *GameTest::CreateUnitForTestAt(int unit_id, int player, const Point &point) { Unit *unit = CreateUnit(unit_id, point.x, point.y, player); Assert(unit != nullptr); FinishUnit_Pre(unit); FinishUnit(unit); GiveAi(unit); unit->energy = unit->GetMaxEnergy(); return unit; } static void ClearUnits() { for (Unit *unit : *bw::first_active_unit) { Unit *loaded = unit->first_loaded; while (loaded) { Unit *next = loaded->next_loaded; loaded->order_flags |= 0x4; loaded->Kill(nullptr); loaded = next; } unit->order_flags |= 0x4; unit->Kill(nullptr); } for (Unit *unit : *bw::first_revealer) { unit->order_flags |= 0x4; unit->Kill(nullptr); } } static Unit *FindUnit(int unit_id) { for (Unit *unit : *bw::first_active_unit) { if (unit->unit_id == unit_id) return unit; } return nullptr; } static int UnitCount() { int count = 0; // Clang gives unused var warning for pretty for loop ;_; for (Unit *unit = *bw::first_active_unit; unit != nullptr; unit = unit->list.next) { count++; } return count; } static void AiPlayer(int player) { bw::players[player].type = 1; } static void NoAi() { for (int i = 0; i < Limits::ActivePlayers; i++) bw::players[i].type = 2; } static void Visions() { for (int i = 0; i < Limits::Players; i++) { bw::visions[i] = 0xff; } } static void ResetVisions() { for (int i = 0; i < Limits::Players; i++) { bw::visions[i] = 1 << i; } } static void SetEnemy(int player, int enemy) { bw::alliances[player][enemy] = 0; } static void AllyPlayers() { for (int i = 0; i < Limits::Players; i++) { for (int j = 0; j < Limits::Players; j++) { bw::alliances[i][j] = 1; } } } static bool NoUnits() { return *bw::first_active_unit == nullptr && *bw::first_revealer == nullptr; } static void GiveAllTechs() { for (int i = 0; i < Tech::None; i++) { for (int player = 0; player < Limits::Players; player++) SetTechLevel(i, player, 1); } } static void GiveTech(int tech, int player) { SetTechLevel(tech, player, 1); } static void ClearTechs() { for (int i = 0; i < Tech::None; i++) { for (int player = 0; player < Limits::Players; player++) SetTechLevel(i, player, 0); } } struct Test_Dummy : public GameTest { void Init() override { Pass(); } void NextFrame() override { } }; struct Test_Hallucination : public GameTest { Unit *ht; Unit *real; Unit *outsider; Unit *hallu; int hallu_dmg; int real_dmg; void Init() override { hallu_dmg = -1; real_dmg = -1; hallu = nullptr; } void NextFrame() override { switch (state) { case 0: state++; break; case 1: ht = CreateUnitForTest(Unit::HighTemplar, 0); real = CreateUnitForTest(Unit::Marine, 1); outsider = CreateUnitForTest(Unit::Marine, 2); IssueOrderTargetingUnit_Simple(ht, Order::Hallucination, real); state++; break; case 2: { int hallu_count = 0; for (Unit *unit : *bw::first_active_unit) { if (unit->flags & UnitStatus::Hallucination) { unit->death_timer -= 50; hallu_count++; hallu = unit; } } if (hallu != nullptr) { TestAssert(hallu_count == Spell::HallucinationCount); TestAssert(hallu->player == ht->player); TestAssert(hallu->ai == nullptr); IssueOrderTargetingUnit_Simple(hallu, Order::AttackUnit, outsider); IssueOrderTargetingUnit_Simple(real, Order::AttackUnit, hallu); IssueOrderTargetingUnit_Simple(outsider, Order::AttackUnit, real); state++; } } break; case 3: { if (real_dmg == -1 && real->GetHitPoints() != real->GetMaxHitPoints()) real_dmg = real->GetMaxHitPoints() - real->GetHitPoints(); if (hallu_dmg == -1 && hallu->GetHitPoints() != hallu->GetMaxHitPoints()) hallu_dmg = hallu->GetMaxHitPoints() - hallu->GetHitPoints(); if (real_dmg != -1 && hallu_dmg != -1) { TestAssert(real_dmg * 2 == hallu_dmg); Print("Testing for death -- takes a while"); state++; } } break; case 4: { // Test that they die for (Unit *unit : *bw::first_active_unit) { if (unit->flags & UnitStatus::Hallucination) return; } TestAssert(outsider->GetHitPoints() == outsider->GetMaxHitPoints()); Pass(); } } } }; struct Test_Plague : public GameTest { Unit *defi; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: defi = CreateUnitForTest(Unit::Defiler, 0); target = CreateUnitForTest(Unit::Marine, 0); IssueOrderTargetingUnit_Simple(defi, Order::Plague, target); state++; break; case 2: { int dmg = target->GetMaxHitPoints() - target->GetHitPoints(); if (dmg != 0) { TestAssert(target->plague_timer != 0); TestAssert(defi->plague_timer == 0); TestAssert(dmg == weapons_dat_damage[Weapon::Plague] / (Spell::PlagueTime + 1)); SetHp(target, 5 * 256); // Test that it doesn't kill state++; } } break; case 3: { TestAssert(!target->IsDying()); if (target->plague_timer == 0) Pass(); } } } }; struct Test_Storm : public GameTest { Unit *ht1; Unit *ht2; Unit *target; Rect16 storm_area; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { ht1 = CreateUnitForTestAt(Unit::HighTemplar, 0, Point(100, 100)); auto crect = ht1->GetCollisionRect(); ht2 = CreateUnitForTestAt(Unit::HighTemplar, 0, Point(100 + crect.Width(), 100)); target = CreateUnitForTestAt(Unit::Battlecruiser, 0, Point(300, 100)); IssueOrderTargetingUnit_Simple(ht1, Order::PsiStorm, target); state++; // Cases 2 and 3 should behave same, no matter if 2 storms are casted or 1 } break; case 2: case 3: { int dmg = target->GetMaxHitPoints() - target->GetHitPoints(); int storm_dmg = weapons_dat_damage[Weapon::PsiStorm]; TestAssert(dmg % storm_dmg == 0); if (dmg != 0) { TestAssert(dmg < storm_dmg * 10); bool storms_active = bullet_system->BulletCount() != 0; // The 2 hts don't cast in perfect sync, which might give an extra cycle of damage bool dmg_done = (dmg == storm_dmg * 8) || (state == 3 && dmg == storm_dmg * 9); if (!dmg_done) { TestAssert(storms_active); } else if (state == 2 && !storms_active) { target = CreateUnitForTestAt(Unit::Battlecruiser, 0, Point(100, 300)); IssueOrderTargetingUnit_Simple(ht1, Order::PsiStorm, target); IssueOrderTargetingUnit_Simple(ht2, Order::PsiStorm, target); state++; } else if (state == 3 && !storms_active) { ht1->energy = 200 * 256; IssueOrderTargetingUnit_Simple(ht1, Order::Hallucination, target); state++; } } } break; case 4: for (Unit *unit : *bw::first_active_unit) { if (unit->flags & UnitStatus::Hallucination) { target = unit; auto &pos = ht1->sprite->position; IssueOrderTargetingGround(target, Order::Move, pos.x, pos.y); state++; break; } } break; case 5: if (target->order != Order::Move) { TestAssert(target->GetCollisionRect().top < ht2->sprite->position.y); IssueOrderTargetingUnit_Simple(ht2, Order::PsiStorm, target); storm_area = Rect16(target->sprite->position, weapons_dat_outer_splash[Weapon::PsiStorm]); state++; } break; case 6: { // The units are so close that both hts die and the hallu as well if (ht1->IsDying()) { TestAssert(ht2->IsDying()); bool area_clear = true; unit_search->ForEachUnitInArea(storm_area, [&](Unit *u) { area_clear = false; return true; }); TestAssert(area_clear); Pass(); } } } } }; struct Test_ShieldOverlay : public GameTest { Unit *attacker; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: attacker = CreateUnitForTest(Unit::Marine, 0); target = CreateUnitForTest(Unit::Zealot, 0); IssueOrderTargetingUnit_Simple(attacker, Order::AttackUnit, target); state++; break; case 2: { // Fail if taken hp dmg and still hasn't found overlay TestAssert(target->GetHitPoints() == target->GetMaxHitPoints()); for (Image *img : target->sprite->first_overlay) { if (img->image_id == Image::ShieldOverlay) state++; } } break; case 3: { TestAssert(attacker->target != nullptr); target->shields = 0; for (Image *img : target->sprite->first_overlay) { if (img->image_id == Image::ShieldOverlay) return; } state++; } break; case 4: { if (attacker->target == nullptr) Pass(); else { for (Image *img : target->sprite->first_overlay) { TestAssert(img->image_id != Image::ShieldOverlay); } } } } } }; struct Test_ShieldOverlayHallu : public Test_ShieldOverlay { void Init() override { Test_ShieldOverlay::Init(); } void NextFrame() override { switch (state) { default: Test_ShieldOverlay::NextFrame(); break; case 1: { attacker = CreateUnitForTest(Unit::Marine, 0); target = CreateUnitForTest(Unit::Zealot, 0); Unit *ht = CreateUnitForTest(Unit::HighTemplar, 0); IssueOrderTargetingUnit_Simple(ht, Order::Hallucination, target); state = 100; } break; case 100: { for (Unit *unit : *bw::first_active_unit) { if (unit->flags & UnitStatus::Hallucination) { target = unit; IssueOrderTargetingUnit_Simple(attacker, Order::AttackUnit, target); state = 2; } } } } } }; struct Test_ShieldDamage : public GameTest { Unit *attacker; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { attacker = CreateUnitForTest(Unit::Marine, 0); target = CreateUnitForTest(Unit::Zealot, 0); IssueOrderTargetingUnit_Simple(attacker, Order::AttackUnit, target); state++; } break; case 2: { // Test that unit will not take hp damage as long as it has shields if (target->shields < 256) { Pass(); } else { TestAssert(target->GetHitPoints() == target->GetMaxHitPoints()); } } } } }; struct Test_LurkerAi : public GameTest { Unit *flyer; Unit *lurker; Point lurker_pos; void Init() override { Visions(); AiPlayer(1); } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { flyer = CreateUnitForTest(Unit::Scout, 0); lurker = CreateUnitForTest(Unit::Lurker, 1); TestAssert(lurker->ai != nullptr); IssueOrderTargetingNothing(lurker, Order::Burrow); IssueOrderTargetingUnit_Simple(flyer, Order::AttackUnit, lurker); state++; } break; case 2: case 3: { TestAssert(flyer->target != nullptr); TestAssert(lurker->sprite->main_image->drawfunc == 0); if (state == 2 && lurker->flags & UnitStatus::Burrowed) state++; if (state == 3 && lurker->flags & ~UnitStatus::Burrowed) { lurker_pos = lurker->sprite->position; state++; } } break; case 4: { TestAssert(flyer->target != nullptr); TestAssert(lurker->sprite->main_image->drawfunc == 0); // Pass if lurker flees if (lurker_pos != lurker->sprite->position) Pass(); } } } }; struct Test_BurrowerAi : public GameTest { Unit *flyer; Unit *hydra; void Init() override { Visions(); SetEnemy(1, 0); AiPlayer(1); } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { flyer = CreateUnitForTestAt(Unit::Valkyrie, 0, Point(100, 500)); hydra = CreateUnitForTest(Unit::Hydralisk, 1); state++; } break; case 2: { if (hydra->flags & UnitStatus::Burrowed) { auto &pos = hydra->sprite->position; IssueOrderTargetingGround(flyer, Order::Move, pos.x, pos.y); state++; } } break; case 3: { // Pass if the ai hydra is able to unburrow and attack if (flyer->GetHitPoints() != flyer->GetMaxHitPoints() && hydra->target == flyer) Pass(); } } } }; struct Test_Vision : public GameTest { Unit *unit; int begin_frame; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { unit = CreateUnitForTest(Unit::Overlord, *bw::local_player_id); begin_frame = *bw::frame_count; state++; } break; case 2: { TestAssert(unit->sprite->visibility_mask != 0); if (*bw::frame_count - begin_frame > 400) Pass(); } } } }; struct Test_Carrier : public GameTest { Unit *carrier; Unit *target; Unit *interceptor; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { carrier = CreateUnitForTest(Unit::Carrier, 0); target = CreateUnitForTest(Unit::Overlord, 0); carrier->IssueSecondaryOrder(Order::TrainFighter); carrier->build_queue[carrier->current_build_slot] = Unit::Interceptor; state++; } break; case 2: { if (carrier->carrier.in_child != nullptr) { interceptor = carrier->carrier.in_child; IssueOrderTargetingUnit_Simple(carrier, Order::CarrierAttack, target); state++; } } break; case 3: { // Test interceptor healing if (target->GetHitPoints() != target->GetMaxHitPoints()) { interceptor->shields /= 4; state++; } } break; case 4: { if (interceptor->order == Order::InterceptorReturn) state++; } break; case 5: { if (carrier->target == nullptr) { TestAssert(carrier->carrier.in_child == nullptr); TestAssert(interceptor->GetShields() == interceptor->GetMaxShields()); carrier->Kill(nullptr); state++; } } break; case 6: { if (interceptor->IsDying()) Pass(); } } } }; struct Test_Bunker : public GameTest { Unit *bunker; Unit *marine; Unit *enemy; void Init() override { } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { marine = CreateUnitForTest(Unit::Marine, 0); bunker = CreateUnitForTest(Unit::Bunker, 0); enemy = CreateUnitForTest(Unit::Zergling, 1); IssueOrderTargetingUnit_Simple(marine, Order::EnterTransport, bunker); state++; } break; case 2: { if (marine->flags & UnitStatus::InBuilding) { SetEnemy(0, 1); state++; } } break; case 3: { if (enemy->GetHealth() != enemy->GetMaxHealth()) { state++; } } break; case 4: { if (enemy->IsDying()) { IssueOrderTargetingNothing(bunker, Order::DisableDoodad); state++; } else { TestAssert(marine->target == enemy); TestAssert(marine->order_wait <= 8); } } break; case 5: { if (bunker->sprite->main_image->drawfunc == Image::DrawFunc::DetectedCloak) { bunker->Kill(nullptr); state++; } } break; case 6: { // The marine should die as well as it cannot be unloaded if (FindUnit(Unit::Marine) == nullptr) { Pass(); } else { TestAssert(FindUnit(Unit::Marine)->related != nullptr); TestAssert(!FindUnit(Unit::Bunker)->IsDying()); } } } } }; // Bw has this behaviour where creating an cloaked unit which does not have drawfunc 0 in main image, // causes it's child overlays also not appear as cloaked. However, when the unit is detected, the // child overlays get their drawfunc changed so they become cloaked. This desync between owner, // who doesn't ever detect it and has drawfunc 0, and detecting player, who has detected drawfunc, // causes issues as Image::Drawfunc_ProgressFrame controls whether units actually are cloaked or not struct Test_DrawfuncSync : public GameTest { Unit *vision; Unit *arbiter; Unit *archon; int drawfunc_seen; int drawfunc_cloaked; int drawfunc_detected; const int ArchonBeing = 135; void Init() override { ResetVisions(); } void NextFrame() override { switch (state) { case 0: case 3: case 6: if (NoUnits()) { state++; } break; case 1: { arbiter = CreateUnitForTest(Unit::Arbiter, 0); archon = CreateUnitForTest(Unit::Archon, 0); archon->sprite->main_image->drawfunc = 1; IssueOrderTargetingGround(archon, Order::Move, 100, 500); state++; } break; case 2: { if (archon->invisibility_effects == 0) { for (Image *img : archon->sprite->first_overlay) { if (img->image_id == ArchonBeing) { drawfunc_seen = img->drawfunc; ClearUnits(); state++; } } } } break; case 4: { vision = CreateUnitForTest(Unit::Wraith, 0); arbiter = CreateUnitForTest(Unit::Arbiter, 1); archon = CreateUnitForTest(Unit::Archon, 1); IssueOrderTargetingGround(archon, Order::Move, 100, 500); archon->sprite->main_image->drawfunc = 1; state++; } break; case 5: { if (archon->invisibility_effects == 0) { for (Image *img : archon->sprite->first_overlay) { if (img->image_id == ArchonBeing) { drawfunc_cloaked = img->drawfunc; ClearUnits(); state++; } } } } break; case 7: { arbiter = CreateUnitForTest(Unit::Arbiter, 1); archon = CreateUnitForTest(Unit::Archon, 1); archon->sprite->main_image->drawfunc = 1; state++; } break; case 8: { TestAssert(archon->invisibility_effects == 1); vision = CreateUnitForTest(Unit::Overlord, 0); IssueOrderTargetingGround(archon, Order::Move, 100, 500); state++; } break; case 9: { if (archon->invisibility_effects == 0) { for (Image *img : archon->sprite->first_overlay) { if (img->image_id == ArchonBeing) { drawfunc_detected = img->drawfunc; state++; } } } } break; case 10: { // Either having consistently same drawfunc or behaving as one would expect cloak is allowed // (As it currently just keeps drawfunc 0) if (drawfunc_seen >= Image::DrawFunc::Cloaking && drawfunc_seen <= Image::DrawFunc::DetectedDecloaking) { TestAssert(drawfunc_seen == drawfunc_detected); TestAssert(drawfunc_cloaked == drawfunc_detected + 3); } else { TestAssert(drawfunc_seen == drawfunc_detected); TestAssert(drawfunc_cloaked == drawfunc_detected); } Pass(); } } } }; struct AiSpell { int tech; int caster_unit_id; int target_unit_id; int attacker_unit_id; }; const AiSpell revenge_spells[] = { { Tech::Lockdown, Unit::Ghost, Unit::Wraith, Unit::None }, // Requires detector with hp > 80 { Tech::OpticalFlare, Unit::Medic, Unit::Overlord, Unit::Marine }, { Tech::Irradiate, Unit::ScienceVessel, Unit::Mutalisk, Unit::None }, // Requires unit which can attack the vessel and has over 200 shields { Tech::EmpShockwave, Unit::ScienceVessel, Unit::Archon, Unit::None }, { Tech::Ensnare, Unit::Queen, Unit::Wraith, Unit::None }, { Tech::SpawnBroodlings, Unit::Queen, Unit::Hydralisk, Unit::None }, { Tech::Plague, Unit::Defiler, Unit::Marine, Unit::None }, { Tech::PsionicStorm, Unit::HighTemplar, Unit::Marine, Unit::None }, { Tech::Feedback, Unit::DarkArchon, Unit::Ghost, Unit::None }, { Tech::Maelstrom, Unit::DarkArchon, Unit::Ultralisk, Unit::None }, { Tech::StasisField, Unit::Arbiter, Unit::Battlecruiser, Unit::None }, { Tech::DisruptionWeb, Unit::Corsair, Unit::Dragoon, Unit::None }, { -1, -1, -1 } }; // Imperfect, can detect idle casts as revenge casts struct Test_AiSpell : public GameTest { Unit *spellcaster; const AiSpell *spell; Point spawn_pos; // Because units like to get caught to spell cast in previous test void Init() override { ResetVisions(); SetEnemy(0, 1); SetEnemy(1, 0); AiPlayer(1); spell = revenge_spells; spawn_pos = Point(200, 200); } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { if (spell->tech == -1) { Pass(); return; } ClearTechs(); spellcaster = CreateUnitForTestAt(spell->caster_unit_id, 1, spawn_pos + Point(100, 100)); CreateUnitForTestAt(spell->target_unit_id, 0, spawn_pos); if (spell->attacker_unit_id != Unit::None) CreateUnitForTestAt(spell->attacker_unit_id, 0, spawn_pos); GiveTech(spell->tech, 1); state++; } break; case 2: { TestAssert(!spellcaster->IsDying()); if (spellcaster->energy != spellcaster->GetMaxEnergy()) { ClearUnits(); spawn_pos.x ^= 256; spell += 1; state = 0; } } } } }; struct AiCloakVariation { int unit_id; }; static AiCloakVariation ai_cloak_variations[] = { { Unit::Zealot }, { Unit::Goliath }, { Unit::Wraith }, { -1 } }; struct Test_AiCloak : public GameTest { Unit *cloaker; Unit *attacker; AiCloakVariation const *variation; void Init() override { ResetVisions(); SetEnemy(0, 1); SetEnemy(1, 0); AiPlayer(1); variation = ai_cloak_variations; } void NextFrame() override { switch (state) { case 0: state++; break; case 1: { if (variation->unit_id == -1) { state = 3; return; } cloaker = CreateUnitForTestAt(Unit::InfestedKerrigan, 1, Point(100, 100)); attacker = CreateUnitForTestAt(variation->unit_id, 0, Point(150, 100)); state++; } break; case 2: { TestAssert(!cloaker->IsDying() && !attacker->IsDying()); if (cloaker->IsInvisible()) { ClearUnits(); variation += 1; state = 0; } } break; case 3: { cloaker = CreateUnitForTestAt(Unit::InfestedKerrigan, 1, Point(100, 100)); attacker = CreateUnitForTestAt(Unit::Scout, 0, Point(150, 100)); cloaker->energy = 0; cloaker->hitpoints = 50 * 256; state++; } break; case 4: { if (cloaker->IsDying()) Pass(); cloaker->energy = 0; TestAssert(!cloaker->IsInvisible()); } } } }; struct Test_Liftoff : public GameTest { Unit *building; Unit *tank; Unit *burrower; void Init() override { } void NextFrame() override { switch (state) { case 0: building = CreateUnitForTestAt(Unit::CommandCenter, 0, Point(100, 100)); tank = CreateUnitForTestAt(Unit::SiegeTank_Sieged, 0, Point(200, 200)); burrower = CreateUnitForTestAt(Unit::Zergling, 0, Point(200, 200)); IssueOrderTargetingNothing(burrower, Order::Burrow); IssueOrderTargetingNothing(building, Order::LiftOff); state++; break; case 1: { if (burrower->order == Order::Burrowed) { IssueOrderTargetingGround(building, Order::Land, 100, 100); state++; } } break; case 2: { if (building->order == Order::Land && building->order_state == 3) { MoveUnit(tank, 100, 100); MoveUnit(burrower, 100, 100); state++; } } break; case 3: { if (UnitCount() == 1 && building->order != Order::Land) { TestAssert(building->order == units_dat_return_to_idle_order[building->unit_id]); TestAssert((building->sprite->last_overlay->flags & 4) == 0); // Test lifting once more IssueOrderTargetingNothing(building, Order::LiftOff); state++; } else { TestAssert(building->order == Order::Land); } } break; case 4: { if (~building->flags & UnitStatus::Building) { IssueOrderTargetingGround(building, Order::Land, 100, 100); state++; } } break; case 5: { if (building->order == Order::Land) state++; } break; case 6: { if (building->order != Order::Land) { TestAssert(!building->IsFlying()); TestAssert((building->sprite->last_overlay->flags & 4) == 0); building->IssueSecondaryOrder(Order::Train); building->build_queue[building->current_build_slot] = Unit::SCV; state++; } } break; case 7: { Unit *scv = FindUnit(Unit::SCV); if (scv != nullptr) { Pass(); } } } } }; struct Test_Siege : public GameTest { Unit *building; Unit *tank; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: building = CreateUnitForTestAt(Unit::CommandCenter, 0, Point(100, 100)); tank = CreateUnitForTestAt(Unit::SiegeTankTankMode, 0, Point(100, 100)); IssueOrderTargetingNothing(tank, Order::SiegeMode); state++; break; case 1: { if (UnitCount() == 1) { building->Kill(nullptr); tank = CreateUnitForTestAt(Unit::SiegeTankTankMode, 0, Point(100, 100)); target = CreateUnitForTestAt(Unit::Marine, 0, Point(250, 100)); IssueOrderTargetingNothing(tank, Order::SiegeMode); state++; } } break; case 2: { if (tank->unit_id == Unit::SiegeTank_Sieged && tank->order != Order::SiegeMode) { IssueOrderTargetingUnit_Simple(tank, Order::WatchTarget, target); state++; } } break; case 3: { if (UnitCount() == 1) { Pass(); } else { TestAssert(tank->target == target); } } } } }; struct Test_Bounce : public GameTest { Unit *muta; Unit *target; Unit *other; void Init() override { SetEnemy(0, 1); } void NextFrame() override { switch (state) { case 0: muta = CreateUnitForTestAt(Unit::Mutalisk, 0, Point(100, 100)); target = CreateUnitForTestAt(Unit::Marine, 1, Point(100, 100)); other = CreateUnitForTestAt(Unit::Marine, 1, Point(100, 100)); IssueOrderTargetingUnit_Simple(muta, Order::AttackUnit, target); state++; break; case 1: { TestAssert(muta->target == target); if (other->GetHealth() != other->GetMaxHealth()) { TestAssert(target->GetHealth() != target->GetMaxHealth()); state++; } } break; case 2: { if (muta->target != target) { TestAssert(other->GetHealth() > other->GetMaxHealth() / 2); Pass(); } } } } }; struct Test_Dweb : public GameTest { Unit *corsair; Unit *enemy; int next_unit_id; void Init() override { SetEnemy(1, 0); next_unit_id = 0; } void NextFrame() override { switch (state) { case 0: if (!NoUnits()) return; NextUnitId(); if (next_unit_id == Unit::None) { Pass(); return; } corsair = CreateUnitForTestAt(Unit::Corsair, 0, Point(100, 100)); IssueOrderTargetingGround(corsair, Order::DisruptionWeb, 150, 150); state++; break; case 1: { if (FindUnit(Unit::DisruptionWeb) != nullptr) { enemy = CreateUnitForTestAt(next_unit_id, 1, Point(150, 150)); next_unit_id += 1; state++; } } break; case 2: { if (FindUnit(Unit::DisruptionWeb) == nullptr) { ClearUnits(); state = 0; } else { TestAssert(corsair->GetHealth() == corsair->GetMaxHealth()); } } } } void NextUnitId() { while (next_unit_id != Unit::None) { if (units_dat_elevation_level[next_unit_id] == 4 && ~units_dat_flags[next_unit_id] & UnitFlags::Subunit && ~units_dat_flags[next_unit_id] & UnitFlags::Air && (units_dat_group_flags[next_unit_id] & 0x7) != 0 && // Require an race (units_dat_air_weapon[next_unit_id] != Weapon::None || (units_dat_subunit[next_unit_id] != Unit::None && units_dat_air_weapon[units_dat_subunit[next_unit_id]] != Weapon::None))) { return; } next_unit_id++; } } }; struct Test_RightClick : public GameTest { Unit *building; void Init() override { } void NextFrame() override { switch (state) { case 0: { int player = *bw::local_unique_player_id; building = CreateUnitForTestAt(Unit::CommandCenter, player, Point(100, 100)); state++; } break; case 1: { // Screen position is rounded down to eights, // so MoveScreen(300, 200) would do same thing MoveScreen(296, 200); int player = *bw::local_unique_player_id; frames_remaining = 50; bw::selection_groups[player][0] = building; bw::selection_groups[player][1] = nullptr; bw::client_selection_group2[0] = building; bw::client_selection_group[0] = building; *bw::primary_selected = building; for (int i = 1; i < Limits::Selection; i++) { bw::client_selection_group2[i] = nullptr; bw::client_selection_group[i] = nullptr; } *bw::client_selection_changed = 1; RefreshUi(); Event event; event.ext_type = 0; event.type = 0xe; event.unk4 = 0; event.x = 14; event.y = 10; GameScreenRClickEvent(&event); state++; } break; case 2: { if (building->rally.position == Point(310, 210)) { Pass(); } } } } }; struct Test_HoldPosition : public GameTest { Unit *attacker; Unit *enemy; int variant; void Init() override { SetEnemy(0, 1); variant = 1; } void NextFrame() override { switch (state) { case 0: { attacker = CreateUnitForTestAt(Unit::Marine, 0, Point(100, 100)); enemy = CreateUnitForTestAt(Unit::Battlecruiser, 1, Point(150, 100)); IssueOrderTargetingNothing(attacker, Order::HoldPosition); state++; } break; case 1: { // There was an crash when unit holding position was targeting unit which suddenly // became unattackable, so test for it becoming unattackable at different times if (variant == 7) { Pass(); return; } if (enemy->GetHealth() != enemy->GetMaxHealth()) { if (attacker->order_wait == variant) { if (enemy->IsInvincible()) { enemy->flags &= ~UnitStatus::Invincible; enemy->hitpoints = enemy->GetMaxHitPoints() * 256; variant++; } else { enemy->flags |= UnitStatus::Invincible; } } } } } } }; struct Test_Attack : public GameTest { Unit *attacker; Unit *enemy; int variant; void Init() override { variant = 1; } void NextFrame() override { switch (state) { // Bw has a bug where an unit ordered to attack will get stuck under following conditions: // - Attacker was moving before the order // - Enemy is barely in range // - Enemy is no longer in range after the first frame of attack order // - Attacker uses iscript.bin movement and its attack animation has no move commands // This test recreates those conditions case 0: { if (variant == 100) { Pass(); return; } attacker = CreateUnitForTestAt(Unit::Hydralisk, 0, Point(100, 100)); enemy = CreateUnitForTestAt(Unit::Guardian, 0, Point(300, 100)); IssueOrderTargetingGround(attacker, Order::Move, 600, 100); IssueOrderTargetingGround(enemy, Order::Move, 600, 100); state++; } break; case 1: { if (attacker->sprite->position.x > 200 + variant) { IssueOrderTargetingUnit_Simple(attacker, Order::AttackUnit, enemy); state++; } } break; case 2: { if (enemy->GetHealth() < enemy->GetMaxHealth() * 3 / 4) { ClearUnits(); state = 0; variant++; frames_remaining = 5000; } } } } }; struct Test_Splash : public GameTest { Unit *attacker; Unit *target; Unit *second_target; void Init() override { SetEnemy(0, 1); } void NextFrame() override { switch (state) { case 0: { target = CreateUnitForTestAt(Unit::Nexus, 0, Point(100, 150)); attacker = CreateUnitForTestAt(Unit::InfestedTerran, 0, Point(100, 300)); IssueOrderTargetingUnit_Simple(attacker, Order::SapUnit, target); state++; } break; case 1: { if (target->GetHealth() != target->GetMaxHealth()) { int dmg = weapons_dat_damage[units_dat_ground_weapon[Unit::InfestedTerran]]; TestAssert(target->GetMaxHealth() - target->GetHealth() > dmg * 3 / 4); ClearUnits(); target = CreateUnitForTestAt(Unit::SupplyDepot, 1, Point(100, 100)); second_target = CreateUnitForTestAt(Unit::SupplyDepot, 1, Point(100, 100)); attacker = CreateUnitForTestAt(Unit::Lurker, 0, Point(100, 150)); IssueOrderTargetingNothing(attacker, Order::Burrow); state++; } } break; case 2: { TestAssert(target->GetHealth() == second_target->GetHealth()); if (target->GetHealth() < target->GetMaxHealth() / 2) { Pass(); } } } } }; struct Test_AiAggro : public GameTest { Unit *ai_ling; Unit *target; void Init() override { AiPlayer(1); SetEnemy(1, 0); } void NextFrame() override { switch (state) { case 0: { // Should not aggro ai_ling = CreateUnitForTestAt(Unit::Zergling, 1, Point(100, 100)); target = CreateUnitForTestAt(Unit::Reaver, 0, Point(400, 100)); state++; frames_remaining = 300; } break; case 1: { TestAssert(ai_ling->ai != nullptr && ai_ling->ai->type == 1); TestAssert(ai_ling->order != Order::AttackUnit); if (frames_remaining < 100) Pass(); } } } }; struct Test_MindControl : public GameTest { Unit *da; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: { da = CreateUnitForTestAt(Unit::DarkArchon, 0, Point(100, 100)); target = CreateUnitForTestAt(Unit::Marine, 1, Point(100, 100)); IssueOrderTargetingUnit_Simple(da, Order::MindControl, target); state++; } break; case 1: { if (da->order == Order::MindControl) state++; } break; case 2: { if (target->player == da->player) { TestAssert(da->shields == 0); ClearUnits(); da = CreateUnitForTestAt(Unit::DarkArchon, 0, Point(100, 100)); target = CreateUnitForTest(Unit::Carrier, 1); target->IssueSecondaryOrder(Order::TrainFighter); target->build_queue[target->current_build_slot] = Unit::Interceptor; state++; } else { TestAssert(da->order == Order::MindControl); } } break; case 3: { if (target->carrier.in_child != nullptr || target->carrier.out_child != nullptr) { IssueOrderTargetingUnit_Simple(da, Order::MindControl, target); state++; } } break; case 4: { if (target->player == da->player) { Unit *interceptor = target->carrier.in_child; if (interceptor == nullptr) interceptor = target->carrier.out_child; TestAssert(interceptor && interceptor->player == da->player); Pass(); } } } } }; struct Test_PosSearch : public GameTest { Unit *unit; void Init() override { } void NextFrame() override { switch (state) { case 0: { unit = CreateUnitForTestAt(Unit::Marine, 0, Point(100, 100)); state++; } break; case 1: { Unit *result = unit_search->FindNearest(Point(100, 150), Rect16(Point(100, 150), 5), [](const auto *a) { return true; }); TestAssert(result == nullptr); result = unit_search->FindNearest(Point(150, 100), Rect16(Point(150, 100), 5), [](const auto *a) { return true; }); TestAssert(result == nullptr); result = unit_search->FindNearest(Point(110, 110), Rect16(Point(110, 100), 25), [](const auto *a) { return true; }); TestAssert(result == unit); result = unit_search->FindNearest(Point(110, 100), Rect16(Point(110, 100), 9), [](const auto *a) { return true; }); TestAssert(result == nullptr); result = unit_search->FindNearest(Point(110, 100), Rect16(Point(110, 100), 10), [](const auto *a) { return true; }); TestAssert(result == unit); Pass(); } } } }; struct Test_AiTarget : public GameTest { Unit *unit; Unit *enemy; void Init() override { SetEnemy(0, 1); SetEnemy(1, 0); AiPlayer(1); } void NextFrame() override { switch (state) { case 0: { unit = CreateUnitForTestAt(Unit::Devourer, 1, Point(100, 100)); enemy = CreateUnitForTestAt(Unit::Scout, 0, Point(120, 120)); state++; } break; case 1: { TestAssert(!unit->IsDying() && !enemy->IsDying()); if (unit->target == enemy) { CreateUnitForTestAt(Unit::Scout, 0, Point(80, 80)); state++; } } break; case 2: { if (unit->GetHealth() == 0 || enemy->GetHealth() == 0) { Pass(); } else { TestAssert(unit->target == enemy); } } } } }; struct Test_AttackMove : public GameTest { Unit *unit; Unit *enemy; Unit *enemy2; Unit *target; void Init() override { SetEnemy(0, 1); SetEnemy(1, 0); } void NextFrame() override { switch (state) { case 0: { unit = CreateUnitForTestAt(Unit::Guardian, 0, Point(100, 100)); enemy = CreateUnitForTestAt(Unit::HunterKiller, 1, Point(400, 100)); enemy2 = CreateUnitForTestAt(Unit::HunterKiller, 1, Point(400, 100)); IssueOrderTargetingGround(unit, Order::AttackMove, 400, 100); state++; } break; case 1: { SetHp(unit, 100 * 256); SetHp(enemy, 100 * 256); SetHp(enemy2, 100 * 256); if (unit->target != nullptr) { target = unit->target; IssueOrderTargetingGround(target, Order::Move, 1000, 100); state++; } } break; case 2: { if (target->order == Order::Move) { state++; } } break; case 3: { SetHp(unit, 100 * 256); SetHp(enemy, 100 * 256); SetHp(enemy2, 100 * 256); TestAssert(target->order == Order::Move); if (unit->target != target && unit->target != nullptr) { Pass(); } } } } }; struct Test_Detection : public GameTest { Unit *cloaked; Unit *detector; int wait; void Init() override { ResetVisions(); wait = 0; } void NextFrame() override { if (wait != 0) { wait -= 1; return; } // In Unit::ProgressFrames for invisible units const int cloak_wait = 30; switch (state) { case 0: { cloaked = CreateUnitForTestAt(Unit::Observer, 0, Point(100, 100)); detector = CreateUnitForTestAt(Unit::Marine, 1, Point(100, 100)); state++; wait = cloak_wait; } break; case 1: { TestAssert(cloaked->IsInvisibleTo(detector)); detector->Kill(nullptr); detector = CreateUnitForTestAt(Unit::Overlord, 1, Point(100, 100)); wait = cloak_wait; state++; } break; case 2: { TestAssert(!cloaked->IsInvisibleTo(detector)); detector->Kill(nullptr); detector = CreateUnitForTestAt(Unit::Queen, 1, Point(100, 100)); IssueOrderTargetingGround(detector, Order::Ensnare, 100, 100); state++; } break; case 3: { if (cloaked->ensnare_timer != 0) { wait = cloak_wait; state++; } } break; case 4: { TestAssert(!cloaked->IsInvisibleTo(detector)); state++; } break; case 5: { if (cloaked->ensnare_timer == 0) { wait = cloak_wait; state++; } } break; case 6: { TestAssert(cloaked->IsInvisibleTo(detector)); detector->Kill(nullptr); detector = CreateUnitForTestAt(Unit::Defiler, 1, Point(100, 100)); IssueOrderTargetingGround(detector, Order::Plague, 100, 100); state++; } break; case 7: { if (cloaked->plague_timer != 0) { wait = cloak_wait; state++; } } break; case 8: { TestAssert(!cloaked->IsInvisibleTo(detector)); state++; } break; case 9: { if (cloaked->plague_timer == 0) { wait = cloak_wait; state++; } } break; case 10: { TestAssert(cloaked->IsInvisibleTo(detector)); detector->Kill(nullptr); detector = CreateUnitForTestAt(Unit::Devourer, 1, Point(100, 100)); Unit *secondary = CreateUnitForTestAt(Unit::Devourer, 1, Point(100, 100)); IssueOrderTargetingUnit_Simple(secondary, Order::AttackUnit, detector); state++; } break; case 11: { if (detector->GetHealth() != detector->GetMaxHealth()) { wait = cloak_wait; state++; } } break; case 12: { // Acid spores should only apply to already detected units TestAssert(cloaked->IsInvisibleTo(detector)); Pass(); } } } }; struct Test_Death : public GameTest { int player; int next_unit_id; void Init() override { // Do some fighting as well SetEnemy(0, 1); SetEnemy(1, 1); AiPlayer(1); next_unit_id = 0; player = 0; } void NextFrame() override { switch (state) { case 0: NextUnitId(); if (next_unit_id == Unit::None) { next_unit_id = 0; player += 1; if (player == 2) player = NeutralPlayer; if (player == Limits::Players) { for (Unit *unit : *bw::first_active_unit) unit->Kill(nullptr); state++; } return; } CreateUnitForTestAt(next_unit_id, player, Point(300, 300)); next_unit_id += 1; break; case 1: { // Kill vespene geysers for (Unit *unit : *bw::first_active_unit) unit->Kill(nullptr); if (NoUnits()) Pass(); } } } void NextUnitId() { while (next_unit_id != Unit::None) { if (~units_dat_flags[next_unit_id] & UnitFlags::Subunit && units_dat_hitpoints[next_unit_id] > 1 && units_dat_armor_type[next_unit_id] != 0) // Skip independent { return; } next_unit_id++; } } }; /// More ai aggro stuff.. Parasite has barely any reactions, but if the queen's /// target at the moment the parasite bullet hits is same player as the unit being /// parasited, then the ai will attack it. (As Ai::UpdateAttackTarget() requires /// previous_attacker having target of same player) Additionally parasite has such a /// long range, that Ai::AskForHelp() may not even bother helping. struct Test_ParasiteAggro : public GameTest { Unit *queen; Unit *target; Unit *other; void Init() override { Visions(); AiPlayer(1); SetEnemy(1, 0); SetEnemy(0, 1); } void SetupNext(int queen_player, int target_unit, int other_unit) { ClearUnits(); int other_player = queen_player == 0 ? 1 : 0; queen = CreateUnitForTestAt(Unit::Queen, queen_player, Point(180, 100)); target = CreateUnitForTestAt(target_unit, other_player, Point(600, 100)); if (other_unit != Unit::None) other = CreateUnitForTestAt(other_unit, other_player, Point(530, 100)); IssueOrderTargetingUnit_Simple(queen, Order::Parasite, target); state++; } void NextFrame() override { switch (state) { case 0: { SetupNext(1, Unit::Marine, Unit::None); } break; case 1: { if (target->parasites == 0) return; // Human owned units don't care TestAssert(target->target == nullptr); SetupNext(0, Unit::Marine, Unit::None); } break; case 2: { if (target->parasites == 0) return; // Ai owned units don't care from a single parasite TestAssert(target->target == nullptr); SetupNext(0, Unit::Marine, Unit::Marine); } break; case 3: { if (queen->target == nullptr) { IssueOrderTargetingUnit_Simple(queen, Order::Parasite, target); // If it was just parasited, try again as the frames aligned just poorly // (Should maybe have random variance?) target->parasites = 0; queen->energy = 150 * 256; TestAssert(target->target == nullptr); return; } else if (target->parasites != 0) { // Ai cares if queen is targeting its unit at the time of hit TestAssert(target->target == queen); // But the queen should be far away enough for the other marine TestAssert(other->target == nullptr); SetupNext(0, Unit::Goliath, Unit::Goliath); } } break; case 4: { if (queen->target == nullptr) { IssueOrderTargetingUnit_Simple(queen, Order::Parasite, target); target->parasites = 0; queen->energy = 150 * 256; TestAssert(target->target == nullptr); return; } else if (target->parasites != 0) { TestAssert(target->target == queen); // Goliaths have range long enough to aggro even from parasite range TestAssert(other->target == queen); Pass(); } } } } }; struct Test_HitChance : public GameTest { void Init() override { } void NextFrame() override { switch (state) { case 0: { for (int i = 0; i < 32; i++) { Unit *unit = CreateUnitForTestAt(Unit::Marine, 1, Point(100, 100 + 20 * i)); Unit *enemy = CreateUnitForTestAt(Unit::Overlord, 0, Point(120, 100 + 20 * i)); IssueOrderTargetingUnit_Simple(unit, Order::AttackUnit, enemy); } state++; } break; case 1: { for (Bullet *bullet : bullet_system->ActiveBullets()) { if (bullet->DoesMiss()) { Pass(); } } for (Unit *unit : *bw::first_active_unit) { unit->hitpoints = unit->GetMaxHitPoints() * 256; } } } } }; struct OverlaySpell { int order; int caster_unit; int target_unit; }; const OverlaySpell overlay_spells[] = { { Order::Lockdown, Unit::Ghost, Unit::Goliath }, { Order::Restoration, Unit::Medic, Unit::SiegeTankTankMode }, { Order::OpticalFlare, Unit::Medic, Unit::Goliath }, { Order::DefensiveMatrix, Unit::ScienceVessel, Unit::SiegeTankTankMode }, { Order::Irradiate, Unit::ScienceVessel, Unit::Goliath, }, { Order::Ensnare, Unit::Queen, Unit::SiegeTankTankMode }, { Order::Plague, Unit::Defiler, Unit::Goliath }, // Note: If feedback kills it spawns a sprite instead of a image { Order::Feedback, Unit::DarkArchon, Unit::Battlecruiser }, { Order::Maelstrom, Unit::DarkArchon, Unit::Ultralisk }, { Order::MindControl, Unit::DarkArchon, Unit::Goliath }, { Order::StasisField, Unit::Arbiter, Unit::SiegeTankTankMode }, }; struct Test_SpellOverlay : public GameTest { vector<tuple<Unit *, int, bool>> targets; void Init() override { targets.clear(); } void NextFrame() override { switch (state) { case 0: { int overlay_spell_count = sizeof overlay_spells / sizeof(overlay_spells[0]); Point pos(100, 100); for (int i = 0; i < overlay_spell_count; i++) { pos.y += 120; if (pos.y > 32 * 60) { pos.y = 100; pos.x += 200; } auto spell = &overlay_spells[i]; Unit *spellcaster = CreateUnitForTestAt(spell->caster_unit, 1, pos); Unit *target = CreateUnitForTestAt(spell->target_unit, 0, pos + Point(30, 0)); IssueOrderTargetingUnit_Simple(spellcaster, spell->order, target); int default_overlay = target->GetTurret()->sprite->first_overlay->image_id; targets.emplace_back(target, default_overlay, false); } frames_remaining = 1000; state++; } break; case 1: { for (auto &tp : targets) { Unit *turret = get<Unit *>(tp)->GetTurret(); if (turret->sprite->first_overlay->image_id != get<int>(tp)) { get<bool>(tp) = true; } } if (std::all_of(targets.begin(), targets.end(), [](const auto &t) { return get<bool>(t); })) { Pass(); } } } } }; /// Turn1CWise is not supposed to do anything if the unit has a target. struct Test_Turn1CWise : public GameTest { Unit *turret; Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: { turret = CreateUnitForTestAt(Unit::MissileTurret, 0, Point(100, 100)); target = CreateUnitForTestAt(Unit::Scout, 0, Point(100, 150)); state++; } break; case 1: { if (turret->facing_direction == 0) { IssueOrderTargetingUnit_Simple(turret, Order::AttackUnit, target); frames_remaining = 10; state++; } } break; case 2: { if (bullet_system->BulletCount() == 1) Pass(); } } } }; /// When an attack which ignores armor gets absorbed by defensive matrix, the attack /// deals 128 damage to hitpoints, even if the unit had shields. struct Test_MatrixStorm : public GameTest { Unit *target; void Init() override { } void NextFrame() override { switch (state) { case 0: { Unit *vessel = CreateUnitForTestAt(Unit::ScienceVessel, 0, Point(100, 100)); target = CreateUnitForTestAt(Unit::Scout, 0, Point(100, 150)); IssueOrderTargetingUnit_Simple(vessel, Order::DefensiveMatrix, target); state++; } break; case 1: { if (target->matrix_timer != 0) { Unit *ht = CreateUnitForTestAt(Unit::HighTemplar, 0, Point(100, 100)); IssueOrderTargetingUnit_Simple(ht, Order::PsiStorm, target); frames_remaining = 250; state++; } } break; case 2: { int hp_dmg = units_dat_hitpoints[target->unit_id] - target->hitpoints; int shield_dmg = target->GetMaxShields() - target->GetShields(); TestAssert(shield_dmg == 0); TestAssert(hp_dmg == 0 || hp_dmg == 128); if (hp_dmg == 128) { state++; } } break; case 3: { if (bullet_system->BulletCount() == 0) Pass(); // There should not be a shield overlay either for (Image *img : target->sprite->first_overlay) { TestAssert(img->image_id != Image::ShieldOverlay); } } } } }; /// Tests Ai::UpdateAttackTarget and related code struct Test_AiTargetPriority : public GameTest { void Init() override { AiPlayer(1); SetEnemy(1, 0); } void NextFrame() override { switch (state) { case 0: case 1: { // Should prioritize the closer one, regardless of the creation order. const Point positions[] = { Point(100, 100), Point(200, 100) }; Unit *first = nullptr; if (state == 0) first = CreateUnitForTestAt(Unit::Marine, 0, positions[0]); Unit *second = CreateUnitForTestAt(Unit::Marine, 0, positions[1]); if (state == 1) first = CreateUnitForTestAt(Unit::Marine, 0, positions[0]); Unit *unit = CreateUnitForTestAt(Unit::Zergling, 1, Point(300, 100)); IssueOrderTargetingUnit_Simple(first, Order::AttackUnit, unit); IssueOrderTargetingUnit_Simple(second, Order::AttackUnit, unit); TestAssert(Ai::GetBestTarget(unit, { first, second }) == second); ClearUnits(); state++; } break; case 2: { // Here the guardian threatens marine (Marine is inside range), and zergling doesn't, // but zergling is inside marine's range and guardian isn't. // As such, the result will be one being active last. // That is bw's logic, but having the decision be consistent regardless of // order wouldn't be bad either. Often hits like these are in different frames, // and the ai could skip back and forth, which may be a "desired feature". // // In fact, hits over a single frame are more consistent than in bw, as // Ai::HitReactions does only one check, and in case of a "tie" like here, // the "best attacker of current frame" beats auto target. // If (x -> y -> z) means (Ai_ChooseBetterTarget(z, Ai_ChooseBetterTarget(y, x))), // vanilla bw would basically compare like this: // old target -> auto target -> attacker -> auto target -> attacker #2 -> auto target -> ... // \ Ai::UpdateAttackTarget #1 / \ Ai::UpdateAttackTarget #2 / \ ... #3 // whereas teippi does the following: // old target -> auto target -> (attacker -> attacker #2 -> attacker #3 -> ...) // \ #1 / \ #2 / \ #3 / \ ... // \ Ai::HitReactions::AddHit (UpdatePickedTarget) / // \ Ai::UpdateAttackTarget from Ai::HitReactions::UpdateAttackTargets / // It could be closer to bw's behaviour if Ai::HitReactions cached the auto target, // but bw's behaviour can be considered to be buggy. For example, if auto target // and attacker #1 "tie", but attacker #2 loses to attacker #1 while beating auto target, // bw would pick attacker #2 where we pick attacker #1. // // Anyways, those tie cases are rare, as they require the auto target to be a unit // which cannot attack const Point positions[] = { Point(100, 100), Point(270, 100) }; Unit *first; first = CreateUnitForTestAt(Unit::Guardian, 0, positions[0]); Unit *second = CreateUnitForTestAt(Unit::Zergling, 0, positions[1]); Unit *unit = CreateUnitForTestAt(Unit::Marine, 1, Point(350, 100)); IssueOrderTargetingUnit_Simple(first, Order::AttackUnit, unit); IssueOrderTargetingUnit_Simple(second, Order::AttackUnit, unit); TestAssert(Ai::GetBestTarget(unit, { first, second }) == second); TestAssert(Ai::GetBestTarget(unit, { second, first }) == first); ClearUnits(); state++; } break; case 3: { /// Test some of the internal logic Unit *ai = CreateUnitForTestAt(Unit::Zergling, 1, Point(100, 100)); Ai::UpdateAttackTargetContext uat(ai, false, false); Ai::UpdateAttackTargetContext allowing_critters(ai, true, false); // The unit is not targeting ai's units // So other fails and other succeeds Unit *other = CreateUnitForTestAt(Unit::Marine, 0, Point(100, 100)); TestAssert(other->target == nullptr); TestAssert(uat.CheckPreviousAttackerValid(other) == nullptr); TestAssert(uat.CheckValid(other) == other); // The unit is targeting ai's units other = CreateUnitForTestAt(Unit::Marine, 0, Point(100, 100)); IssueOrderTargetingUnit_Simple(other, Order::AttackUnit, ai); TestAssert(other->target == ai); TestAssert(uat.CheckPreviousAttackerValid(other) == other); TestAssert(uat.CheckValid(other) == other); // Can't attack that unit other = CreateUnitForTestAt(Unit::Wraith, 0, Point(100, 100)); IssueOrderTargetingUnit_Simple(other, Order::AttackUnit, ai); TestAssert(other->target == ai); TestAssert(uat.CheckPreviousAttackerValid(other) == nullptr); TestAssert(uat.CheckValid(other) == nullptr); // Test critter bool other = CreateUnitForTestAt(Unit::Bengalaas, 0, Point(100, 100)); TestAssert(uat.CheckValid(other) == nullptr); TestAssert(allowing_critters.CheckValid(other) == other); TestAssert(allowing_critters.CheckPreviousAttackerValid(other) == nullptr); Pass(); } } } }; struct TransmissionTest { int unit_id; Point pos; bool ok; }; // Well, these variants mostly test finding specific unit at a location but that's nice too const TransmissionTest transmission_tests[] = { { Unit::Marine, Point(100, 100), false }, { Unit::Zergling, Point(100, 100), true }, { Unit::Zergling, Point(400, 100), false }, }; struct Test_Transmission : public GameTest { Unit *unit; const TransmissionTest *variant; void Init() override { bw::locations[0] = Location { Rect32(50, 50, 150, 150), 0, 0 }; variant = transmission_tests; } void NextFrame() override { // May be initialized incorrectly, as the structure is incomplete Trigger trigger; memset(&trigger, 0, sizeof(Trigger)); trigger.actions[0].location = 1; trigger.actions[0].amount = 7; trigger.actions[0].misc = 500; trigger.actions[0].unit_id = Unit::Zergling; trigger.actions[0].sound_id = 0; trigger.actions[0].action_id = 0x7; switch (state) { case 0: { unit = CreateUnitForTestAt(variant->unit_id, 0, variant->pos); *bw::current_trigger = &trigger; *bw::trigger_current_player = 0; ProgressActions(&trigger); TestAssert(bw::player_wait_active[0] != 0); state++; } break; case 1: { if (bw::player_wait_active[0] == 0) { bool circle_flashing = unit->sprite->selection_flash_timer != 0; TestAssert(circle_flashing == variant->ok); variant++; const TransmissionTest *test_end = transmission_tests + sizeof transmission_tests / sizeof(transmission_tests[0]); ClearUnits(); state = 0; if (variant == test_end) { Pass(); } } } } } }; /// There was a bug where attackking interceptor caused workers to come help. /// Test that it no longer happens, but that attacking a building with a /// worker still works. struct Test_NearbyHelpers : public GameTest { Unit *helper; Unit *target; Unit *enemy; const TransmissionTest *variant; void Init() override { AiPlayer(1); SetEnemy(0, 1); SetEnemy(1, 0); } void CreateAiTown(const Point &pos, int player) { CreateUnitForTestAt(Unit::Nexus, player, pos); helper = CreateUnitForTestAt(Unit::Probe, player, pos + Point(0, 100)); Unit *mineral = CreateUnitForTestAt(Unit::MineralPatch1, NeutralPlayer, pos + Point(0, 200)); mineral->resource.resource_amount = 1500; AiScript_StartTown(pos.x, pos.y, 1, player); } void NextFrame() override { switch (state) { case 0: { CreateAiTown(Point(100, 100), 1); target = CreateUnitForTestAt(Unit::Carrier, 1, Point(100, 100)); enemy = CreateUnitForTestAt(Unit::Hydralisk, 0, Point(100, 600)); target->IssueSecondaryOrder(Order::TrainFighter); target->build_queue[target->current_build_slot] = Unit::Interceptor; state++; } break; case 1: { if (target->carrier.in_child != nullptr) { IssueOrderTargetingGround(enemy, Order::Move, 100, 100); state++; } } break; case 2: { SetHp(target, target->GetMaxHitPoints() * 256); SetHp(enemy, enemy->GetMaxHitPoints() * 256); if (target->carrier.out_child != nullptr) { IssueOrderTargetingUnit_Simple(enemy, Order::AttackUnit, target->carrier.out_child); state++; } } break; case 3: { SetHp(target, target->GetMaxHitPoints() * 256); SetHp(enemy, enemy->GetMaxHitPoints() * 256); TestAssert(helper->target != enemy); if (enemy->target == nullptr || enemy->target->unit_id != Unit::Interceptor) { IssueOrderTargetingGround(enemy, Order::Move, 100, 100); state--; } else if (enemy->target->GetHealth() != enemy->target->GetMaxHealth()) { // This test makes only sense if interceptors have no ai TestAssert(enemy->target->ai == nullptr); if (IsInArea(enemy->target, CallFriends_Radius, helper)) { frames_remaining = 50; state++; } } } break; case 4: { TestAssert(helper->target != enemy); if (frames_remaining == 1) { enemy->Kill(nullptr); frames_remaining = 5000; enemy = CreateUnitForTestAt(Unit::SCV, 0, Point(100, 500)); target = FindUnit(Unit::Nexus); IssueOrderTargetingUnit_Simple(enemy, Order::AttackUnit, target); state++; } } break; case 5: { SetHp(target, target->GetMaxHitPoints() * 256); SetHp(enemy, enemy->GetMaxHitPoints() * 256); if (enemy->target->GetHealth() != enemy->target->GetMaxHealth()) { if (IsInArea(enemy->target, CallFriends_Radius, helper)) { frames_remaining = 50; state++; } } } break; case 6: { SetHp(target, target->GetMaxHitPoints() * 256); if (frames_remaining == 1) { TestAssert(helper->target == enemy); Pass(); } } } } }; /// Checks that probes path correctly between two gateways. /// Bw has a pathing issue when a flingy.dat movement unit (probe) can't /// turn sharply enough to get in a gap between two units (gateways), /// even if the path planned to go there and the unit would fit. Bw would /// make the probe to dodge one of the gateways, as the flingy momementum /// "threw" the probe into gateway and it thought it was in way. This /// dodging would sometimes choose a suboptimal path around the gateway, /// sometimes even causing the probe to get completely stuck if there were /// even more obstacles that made dodging the gateway difficult. struct Test_PathingFlingyGap : public GameTest { int variant; Unit *probe; // If the probe goes either past the gap or to wrong direction from start, // something went wrong. int y_min; int y_max; void Init() override { variant = 0; // Create 5 gateways and 3 probes to block the path between 3 highest // and 2 lowest (Just so that the fastest path goes clearly between the // gateways -- for some reason it likes to path above more than below, // but that is not something this test is going to check/fix). for (auto i = 0; i < 5; i++) { CreateUnitForTestAt(Unit::Gateway, 0, Point(0x100, 0x30 + i * 0x60)); } CreateUnitForTestAt(Unit::Probe, 0, Point(0x100, 0x64)); CreateUnitForTestAt(Unit::Probe, 0, Point(0x100, 0xc4)); CreateUnitForTestAt(Unit::Probe, 0, Point(0x100, 0x184)); } void NextFrame() override { switch (state) { case 0: { bool left = variant == 0 || variant == 1; bool top = variant == 1 || variant == 3; int x; int y; int target_x; int target_y; const auto &probe_dbox = units_dat_dimensionbox[Unit::Probe]; const auto &gateway_dbox = units_dat_dimensionbox[Unit::Gateway]; if (top) { y = 0x120 - gateway_dbox.top - gateway_dbox.bottom; y_min = y - 16; y_max = 0xf0 + gateway_dbox.bottom + 1 + probe_dbox.top + 16; } else { y = 0x120 + gateway_dbox.top + gateway_dbox.bottom; y_max = y + 16; y_min = 0xf0 + gateway_dbox.bottom + 1 + probe_dbox.top - 16; } target_y = y; if (left) { x = 0x100 - gateway_dbox.left - probe_dbox.right - 1; target_x = 0x100 + gateway_dbox.right + probe_dbox.left + 2; } else { x = 0x100 + gateway_dbox.right + probe_dbox.left + 1; target_x = 0x100 - gateway_dbox.left - probe_dbox.right - 2; } probe = CreateUnitForTestAt(Unit::Probe, 0, Point(x, y)); IssueOrderTargetingGround(probe, Order::Move, target_x, target_y); state++; } break; case 1: { const auto &pos = probe->sprite->position; TestAssert(pos.y <= y_max); TestAssert(pos.y >= y_min); if (pos.x > 0xf0 && pos.x < 0x110) { // It should not be dodging either of the gateways TestAssert(probe->path != nullptr); TestAssert(probe->path->dodge_unit == nullptr); probe->Kill(nullptr); state = 0; variant++; if (variant == 4) { Pass(); } } } } } }; GameTests::GameTests() { current_test = -1; AddTest("Test test", new Test_Dummy); AddTest("Hallucination", new Test_Hallucination); AddTest("Plague", new Test_Plague); AddTest("Storm", new Test_Storm); AddTest("Shield overlay", new Test_ShieldOverlay); AddTest("Shield overlay - hallucinated", new Test_ShieldOverlayHallu); AddTest("Shield damage", new Test_ShieldDamage); AddTest("Lurker ai", new Test_LurkerAi); AddTest("Burrower ai", new Test_BurrowerAi); AddTest("Vision", new Test_Vision); AddTest("Carrier", new Test_Carrier); AddTest("Bunker", new Test_Bunker); AddTest("Unusual drawfunc sync", new Test_DrawfuncSync); AddTest("Ai spellcast", new Test_AiSpell); AddTest("Ai cloak", new Test_AiCloak); AddTest("Liftoff", new Test_Liftoff); AddTest("Siege mode", new Test_Siege); AddTest("Bounce", new Test_Bounce); AddTest("Disruption web", new Test_Dweb); AddTest("Right click", new Test_RightClick); AddTest("Hold position", new Test_HoldPosition); AddTest("Attack", new Test_Attack); AddTest("Splash", new Test_Splash); AddTest("Ai aggro", new Test_AiAggro); AddTest("Mind control", new Test_MindControl); AddTest("Pos search", new Test_PosSearch); AddTest("Ai targeting", new Test_AiTarget); AddTest("Attack move", new Test_AttackMove); AddTest("Detection", new Test_Detection); AddTest("Death", new Test_Death); AddTest("Parasite aggro", new Test_ParasiteAggro); AddTest("Hit chance", new Test_HitChance); AddTest("Spell overlays", new Test_SpellOverlay); AddTest("Iscript turn1cwise", new Test_Turn1CWise); AddTest("Matrix + storm", new Test_MatrixStorm); AddTest("Ai target priority", new Test_AiTargetPriority); AddTest("Transmission trigger", new Test_Transmission); AddTest("Nearby helpers", new Test_NearbyHelpers); AddTest("Pathing small gap w/ flingy movement", new Test_PathingFlingyGap); } void GameTests::AddTest(const char *name, GameTest *test) { test->name = name; test->id = tests.size(); tests.emplace_back(test); } void GameTests::RunTests(int first, int last) { current_test = first; last_test = last; if (last_test > tests.size()) last_test = tests.size(); NextTest(); } void GameTests::NextTest() { if (current_test == last_test) { Print("All tests passed!"); current_test = -1; return; } tests[current_test]->state = -1; ClearUnits(); if (CanStartTest()) { StartTest(); } } void GameTests::StartTest() { Print("Running test %d: %s", current_test, tests[current_test]->name); NoAi(); AllyPlayers(); GiveAllTechs(); ClearTriggers(); *bw::cheat_flags = 0; tests[current_test]->state = 0; tests[current_test]->Init(); CheckTest(); } bool GameTests::CanStartTest() { return bullet_system->BulletCount() == 0 && NoUnits(); } void GameTests::CheckTest() { if (tests[current_test]->status == GameTest::Status::Failed) { Print("Test failed %d: %s (%s)", current_test, tests[current_test]->name, tests[current_test]->fail_reason.c_str()); bw::game_speed_waits[*bw::game_speed] = 42; *bw::is_paused = 1; current_test = -1; } else if (tests[current_test]->status == GameTest::Status::Passed) { Print("Test passed %d: %s", current_test, tests[current_test]->name); current_test++; NextTest(); } } void GameTests::NextFrame() { if (current_test == -1) return; if (tests[current_test]->state == -1) { if (CanStartTest()) { StartTest(); } return; // Always return } tests[current_test]->frames_remaining -= 1; tests[current_test]->NextFrame(); CheckTest(); if (current_test != -1 && tests[current_test]->frames_remaining == 0) { Print("Test timeout %d: %s", current_test, tests[current_test]->name); bw::game_speed_waits[*bw::game_speed] = 42; *bw::is_paused = 1; current_test = -1; if (IsDebuggerPresent()) INT3(); } } #endif
38.26457
121
0.502454
[ "vector" ]
6334507a283075d765e9aa7596d13f6dab9dab69
2,043
cpp
C++
aws-cpp-sdk-lightsail/source/model/UpdateDistributionRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lightsail/source/model/UpdateDistributionRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lightsail/source/model/UpdateDistributionRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lightsail/model/UpdateDistributionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Lightsail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateDistributionRequest::UpdateDistributionRequest() : m_distributionNameHasBeenSet(false), m_originHasBeenSet(false), m_defaultCacheBehaviorHasBeenSet(false), m_cacheBehaviorSettingsHasBeenSet(false), m_cacheBehaviorsHasBeenSet(false), m_isEnabled(false), m_isEnabledHasBeenSet(false) { } Aws::String UpdateDistributionRequest::SerializePayload() const { JsonValue payload; if(m_distributionNameHasBeenSet) { payload.WithString("distributionName", m_distributionName); } if(m_originHasBeenSet) { payload.WithObject("origin", m_origin.Jsonize()); } if(m_defaultCacheBehaviorHasBeenSet) { payload.WithObject("defaultCacheBehavior", m_defaultCacheBehavior.Jsonize()); } if(m_cacheBehaviorSettingsHasBeenSet) { payload.WithObject("cacheBehaviorSettings", m_cacheBehaviorSettings.Jsonize()); } if(m_cacheBehaviorsHasBeenSet) { Array<JsonValue> cacheBehaviorsJsonList(m_cacheBehaviors.size()); for(unsigned cacheBehaviorsIndex = 0; cacheBehaviorsIndex < cacheBehaviorsJsonList.GetLength(); ++cacheBehaviorsIndex) { cacheBehaviorsJsonList[cacheBehaviorsIndex].AsObject(m_cacheBehaviors[cacheBehaviorsIndex].Jsonize()); } payload.WithArray("cacheBehaviors", std::move(cacheBehaviorsJsonList)); } if(m_isEnabledHasBeenSet) { payload.WithBool("isEnabled", m_isEnabled); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection UpdateDistributionRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Lightsail_20161128.UpdateDistribution")); return headers; }
24.035294
121
0.765541
[ "model" ]
6341861cf95967dc5d461e2cf3784bc15567fc07
1,366
cpp
C++
Lesson5/Exercise24/shortest_job_first.cpp
gogowonji/080239
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
[ "MIT" ]
33
2020-12-15T07:37:24.000Z
2022-03-08T16:26:37.000Z
Lesson5/Exercise24/shortest_job_first.cpp
gogowonji/080239
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
[ "MIT" ]
1
2021-05-08T19:28:31.000Z
2021-05-08T19:28:31.000Z
Lesson5/Exercise24/shortest_job_first.cpp
gogowonji/080239
e2af987cf5266f9da515fb2afe17dafe6b1ac01b
[ "MIT" ]
26
2021-01-04T07:21:31.000Z
2022-02-07T12:39:42.000Z
#include <iostream> #include <vector> #include <algorithm> #include <numeric> template<typename T> auto compute_waiting_times(std::vector<T>& service_times) { std::vector<T> W(service_times.size()); W[0] = 0; for (auto i = 1; i < service_times.size(); i++) W[i] = W[i - 1] + service_times[i - 1]; return W; } template<typename T> void print_vector(std::vector<T>& V) { for (auto& i : V) { std::cout.width(2); std::cout << i << " "; } std::cout << std::endl; } template<typename T> void compute_and_print_waiting_times(std::vector<T>& service_times) { auto waiting_times = compute_waiting_times<int>(service_times); std::cout << "- 처리 시간: "; print_vector<T>(service_times); std::cout << "- 대기 시간: "; print_vector<T>(waiting_times); auto ave_waiting_times = std::accumulate(waiting_times.begin(), waiting_times.end(), 0.0) / waiting_times.size(); std::cout << "- 평균 대기 시간: " << ave_waiting_times; std::cout << std::endl; } int main(int argc, char* argv[]) { std::vector<int> service_times {8, 1, 2, 4, 9, 2, 3, 5}; std::cout << "[처음 일 처리 시간 & 대기 시간]" << std::endl; compute_and_print_waiting_times<int>(service_times); // 일 처리 시간을 오름차순으로 정렬 std::sort(service_times.begin(), service_times.end()); std::cout << std::endl; std::cout << "[정렬 후 일 처리 시간 & 대기 시간]" << std::endl; compute_and_print_waiting_times<int>(service_times); }
23.551724
114
0.658858
[ "vector" ]
6349c028876c4b14bdedbfdad54877f6bdaf5a61
31,331
hpp
C++
src/Visual/Gui.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Visual/Gui.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Visual/Gui.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
#ifndef MEDYAN_Visual_Gui_hpp #define MEDYAN_Visual_Gui_hpp #include <cstdio> #include <type_traits> #include <imgui.h> #include <imgui_impl_glfw.h> #include <imgui_impl_opengl3.h> #include <imgui_internal.h> #include <imgui_stdlib.h> #include <nfd.h> #include "Visual/DisplaySettings.hpp" #include "Visual/DisplayStates.hpp" #include "Visual/FrameData.hpp" namespace medyan::visual { // Note: // - This must be used while OpenGL and GLFW environments are live class ImguiGuard { private: ImGuiContext* context_ = nullptr; public: ImguiGuard(GLFWwindow* window) { // Setup Dear ImGui context IMGUI_CHECKVERSION(); context_ = ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 330 core"); // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'docs/FONTS.md' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); } ~ImguiGuard() { // Cleanup ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(context_); } }; class ImguiDisableHelperGuard { bool yesPleaseReallyDisableItForReal_; public: ImguiDisableHelperGuard(bool forReal) : yesPleaseReallyDisableItForReal_(forReal) { if(yesPleaseReallyDisableItForReal_) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); } } ~ImguiDisableHelperGuard() { if(yesPleaseReallyDisableItForReal_) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); } } }; //----------------------------------------------------------------------------- // Auxiliary functions //----------------------------------------------------------------------------- // Returns whether the color is changed. template< int colorDof, std::enable_if_t< colorDof == 3 || colorDof == 4 >* = nullptr > inline bool guiAuxColorPickerPopup( const char* strId, float* pColor ) { bool changed = false; const bool bgColorPopup = ImGui::ColorButton( strId, ImVec4( pColor[0], pColor[1], pColor[2], colorDof == 3 ? 1.0f : pColor[3] ), 0 ); ImGui::SameLine(); ImGui::Text(strId); if(bgColorPopup) { ImGui::OpenPopup(strId); } if(ImGui::BeginPopup(strId)) { if(colorDof == 3) { changed = ImGui::ColorPicker3(strId, pColor, ImGuiColorEditFlags_PickerHueWheel); } else { changed = ImGui::ColorPicker4(strId, pColor, ImGuiColorEditFlags_PickerHueWheel); } ImGui::EndPopup(); } return changed; } inline bool guiAuxColorPicker3Popup(const char* strId, float* pColor) { return guiAuxColorPickerPopup<3>(strId, pColor); } inline bool guiAuxColorPicker4Popup(const char* strId, float* pColor) { return guiAuxColorPickerPopup<4>(strId, pColor); } // Function to build combo box automatically for an enumeration type. // // Returns whether a new value is selected. // // Notes: // - The elements in the enum type must be automatically valued (ie the // values are automatically 0, 1, 2, ...). // - The type must have "last_" as the last element. // - A "text(Enum)" function must be implemented to display the elements. template< typename Enum, typename Reselect, // function void(Enum old, Enum new) to execute when selected std::enable_if_t< std::is_enum_v< Enum > && std::is_invocable_r_v< void, Reselect, Enum, Enum > // Reselect: (Enum, Enum) -> void >* = nullptr // type requirements > inline bool guiAuxEnumComboBox( const char* name, Enum& value, Reselect&& reselect, ImGuiSelectableFlags flags = 0 ) { bool changed = false; if(ImGui::BeginCombo(name, text(value), 0)) { for (int i = 0; i < underlying(Enum::last_); ++i) { const Enum valueI = static_cast<Enum>(i); const bool isSelected = (value == valueI); if (ImGui::Selectable(text(valueI), isSelected, flags)) { const auto oldValue = value; value = valueI; reselect(oldValue, valueI); if(!isSelected) { // selected one item that was previously not selected changed = true; } } // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (isSelected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } return changed; } // Where Reselect function is a no-op. template< typename Enum, std::enable_if_t< std::is_enum_v< Enum > >* = nullptr // type requirements > inline bool guiAuxEnumComboBox( const char* name, Enum& value, ImGuiSelectableFlags flags = 0 ) { return guiAuxEnumComboBox(name, value, [](Enum, Enum) {}, flags); } // Tristate checkbox // // State: 0 -> unchecked, 1 -> checked, -1 -> intermediate // Clicking the checkbox will never set the state to -1. // // adapted from https://github.com/ocornut/imgui/issues/2644#issuecomment-507023896 inline bool guiAuxCheckboxTristate(const char* label, int* pState) { bool clicked = false; if (*pState == -1) { ImGui::PushItemFlag(ImGuiItemFlags_MixedValue, true); bool b = false; clicked = ImGui::Checkbox(label, &b); if (clicked) *pState = 1; ImGui::PopItemFlag(); } else { bool b = (*pState != 0); clicked = ImGui::Checkbox(label, &b); if (clicked) *pState = (int)b; } return clicked; } // check box to toggle flags // // Returns whether the flag is changed. template< typename UInt > inline bool guiAuxCheckboxFlags(const char* label, UInt& flag, UInt setTo) { const UInt oldFlag = flag; const bool atLeast1Set = flag & setTo; const bool allSet = (flag & setTo) == setTo; int state = allSet ? 1 : (atLeast1Set ? -1 : 0); if(guiAuxCheckboxTristate(label, &state)) { if(state == 1) { flag |= setTo; } else if(state == 0) { flag &= ~setTo; } // cannot be -1 } return flag != oldFlag; } // select file inline void guiAuxSelectFile(std::filesystem::path& file, bool selectDirectory = false) { nfdchar_t* filepath = nullptr; auto result = selectDirectory ? NFD_PickFolder(std::filesystem::current_path().string().c_str(), &filepath) : NFD_OpenDialog(nullptr, std::filesystem::current_path().string().c_str(), &filepath); if ( result == NFD_OKAY ) { file = filepath; std::free(filepath); } else if ( result == NFD_CANCEL ) { // do nothing } else { LOG(ERROR) << "Error: " << NFD_GetError(); } } //----------------------------------------------------------------------------- // Main GUI functions //----------------------------------------------------------------------------- inline void guiHelpWindow(DisplaySettings& displaySettings) { if(!displaySettings.gui.helpWindow) return; ImGui::SetNextWindowSize(ImVec2(360, 400), ImGuiCond_FirstUseEver); if (ImGui::Begin("help", &displaySettings.gui.helpWindow)) { if(ImGui::CollapsingHeader("controls", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Text("key controls:"); ImGui::BulletText("f: take snapshot of current screen"); ImGui::BulletText("g: toggle gui on/off"); ImGui::BulletText("w/a/s/d: move camera horizontally"); } } // End of help window, no matter Begin returns true or false. ImGui::End(); } // Functions for profile configuration // Returns whether the profile is changed. inline bool guiGeometryDisplaySettings(SurfaceDisplaySettings& settings) { bool changed = false; changed |= ImGui::Checkbox("enabled", &settings.enabled); changed |= guiAuxEnumComboBox("polygon", settings.polygonMode); return changed; } inline bool guiGeometryDisplaySettings(LineDisplaySettings& settings) { bool changed = false; changed |= ImGui::Checkbox("enabled", &settings.enabled); return changed; } inline bool guiActiveProfileConfig(MembraneProfile& profile) { bool changed = false; changed |= guiAuxEnumComboBox("element mode", profile.displaySettings.elementMode); if(profile.displaySettings.elementMode == MembraneDisplaySettings::ElementMode::edge) { changed |= ImGui::SliderFloat("edge extrude radius", &profile.displaySettings.edgeExtrudeRadius, 1.0f, 10.0f, "%.1f"); changed |= ImGui::SliderInt("edge extrude sides", &profile.displaySettings.edgeExtrudeSides, 4, 20); } changed |= guiGeometryDisplaySettings(profile.displaySettings.surface); changed |= guiAuxColorPicker3Popup("fixed color", profile.displaySettings.colorFixed.value.data()); return changed; } inline bool guiActiveProfileConfig(FilamentProfile& profile) { bool changed = false; // path mode specific changed |= guiAuxEnumComboBox("path mode", profile.displaySettings.pathMode); switch(profile.displaySettings.pathMode) { case FilamentDisplaySettings::PathMode::line: break; case FilamentDisplaySettings::PathMode::extrude: changed |= ImGui::SliderFloat("extrude radius", &profile.displaySettings.pathExtrudeRadius, 1.0f, 24.0f, "%.1f"); changed |= ImGui::SliderInt("extrude sides", &profile.displaySettings.pathExtrudeSides, 4, 20); break; case FilamentDisplaySettings::PathMode::bead: changed |= ImGui::SliderFloat("bead radius", &profile.displaySettings.beadRadius, 1.0f, 50.0f, "%.1f"); break; } if(displayGeometryType(profile.displaySettings) == DisplayGeometryType::line) { changed |= guiGeometryDisplaySettings(profile.displaySettings.line); } else { changed |= guiGeometryDisplaySettings(profile.displaySettings.surface); } changed |= guiAuxColorPicker3Popup("fixed color", profile.displaySettings.colorFixed.value.data()); return changed; } inline bool guiActiveProfileConfig(LinkerProfile& profile) { bool changed = false; // selector { // on/off checkbox bool filterOn = profile.selector.name.has_value(); const bool filterOnChanged = ImGui::Checkbox(filterOn ? "##filter check" : "filter##filter check", &filterOn); changed |= filterOnChanged; if(filterOnChanged) { if(filterOn) profile.selector.name.emplace(); else profile.selector.name.reset(); } // show text box if(filterOn) { ImGui::SameLine(); changed |= ImGui::InputText("filter##filter text", &*profile.selector.name); } } // path mode specific changed |= guiAuxEnumComboBox("path mode", profile.displaySettings.pathMode); switch(profile.displaySettings.pathMode) { case LinkerDisplaySettings::PathMode::line: break; case LinkerDisplaySettings::PathMode::extrude: changed |= ImGui::SliderFloat("extrude radius", &profile.displaySettings.pathExtrudeRadius, 1.0f, 24.0f, "%.1f"); changed |= ImGui::SliderInt("extrude sides", &profile.displaySettings.pathExtrudeSides, 4, 20); break; } if(displayGeometryType(profile.displaySettings) == DisplayGeometryType::line) { changed |= guiGeometryDisplaySettings(profile.displaySettings.line); } else { changed |= guiGeometryDisplaySettings(profile.displaySettings.surface); } // color changed |= guiAuxColorPicker3Popup("fixed color", profile.displaySettings.colorFixed.value.data()); return changed; } inline bool guiActiveProfileConfig(AuxLineProfile& profile) { bool changed = false; changed |= guiAuxCheckboxFlags("compartment border", profile.displaySettings.flag, AuxLineDisplaySettings::targetCompartmentBorder); changed |= guiAuxCheckboxFlags("compartment grid", profile.displaySettings.flag, AuxLineDisplaySettings::targetCompartmentAll); changed |= guiGeometryDisplaySettings(profile.displaySettings.line); return changed; } // Returns whether the profile is changed inline bool guiActiveProfileConfig(ElementProfile& profile) { bool changed = false; // Combo box to select target if(ImGui::BeginCombo("target", elementProfileDisplayName(profile.index()), 0)) { for (int i = 0; i < std::variant_size_v< ElementProfile >; ++i) { const bool isSelected = (profile.index() == i); if (ImGui::Selectable(elementProfileDisplayName(i), isSelected, 0)) { if(!isSelected) { // A new profile is chosen profile = makeProfileWithIndex(i); // Because we selected a profile that was not previously selected changed = true; } } // Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if (isSelected) { ImGui::SetItemDefaultFocus(); } } ImGui::EndCombo(); } // Display actual settings changed |= std::visit([](auto& actualProfile) { return guiActiveProfileConfig(actualProfile); }, profile); return changed; } inline void guiProfileWindow( DisplaySettings& displaySettings, DisplayStates& displayStates ) { if(!displaySettings.gui.profileWindow) return; ImGui::SetNextWindowSize(ImVec2(750, 300), ImGuiCond_FirstUseEver); if (ImGui::Begin("profile", &displaySettings.gui.profileWindow)) { static int selectedTrajectoryIndex = -1; // used only in trajectory mode. -1 means not selected static int selectedProfileIndex = -1; // used only when profiles are listed. -1 means not selected // left pane, for trajectory list { ImGui::BeginChild("trajectory pane", ImVec2(200, 0), true); if(displaySettings.displayMode == DisplayMode::trajectory) { if(ImGui::CollapsingHeader("new file", ImGuiTreeNodeFlags_Framed)) { static DisplayTrajectoryFileSettings newFile; const auto fileSelection = [&](std::filesystem::path& file, const char* buttonName) { if(ImGui::Button(buttonName)) { guiAuxSelectFile(file); } if(!file.empty()) { ImGui::SameLine(); char clearButtonLabelId[128]; std::snprintf(clearButtonLabelId, 128, "x##clear %s", buttonName); if(ImGui::Button(clearButtonLabelId)) { file.clear(); } ImGui::TextWrapped(file.string().c_str()); } }; fileSelection(newFile.trajSnapshot, "snapshot.traj"); // The "add" button { ImguiDisableHelperGuard guard(displayStates.sync.busy.load()); if(ImGui::Button("add")) { pushAnAsyncTask( displayStates.sync, // file information is copied but not referenced [&, file = newFile] { backgroundTaskReadTrajectory(displayStates.sync, file); } ); } } } } if(displaySettings.displayMode == DisplayMode::realtime) { // always select realtime ImGui::Selectable("realtime", true); } else { const int numTrajectories = displayStates.trajectoryDataStates.trajectories.size(); for (int i = 0; i < numTrajectories; ++i) { auto& thisTraj = displayStates.trajectoryDataStates.trajectories[i]; char label[64]; std::snprintf(label, 64, "%d %s", i, thisTraj.displayMasterSwitch ? "" : "disabled"); if (ImGui::Selectable(label, selectedTrajectoryIndex == i)) { selectedTrajectoryIndex = i; } if(ImGui::IsItemHovered() && ImGui::IsMouseClicked(ImGuiMouseButton_Right)) { thisTraj.displayMasterSwitch ^= true; if(thisTraj.displayMasterSwitch) { // mark mesh data to be updated for(auto& profileData : thisTraj.profileData) { profileData.shouldUpdateMeshData = true; } } } } } ImGui::EndChild(); } ImGui::SameLine(); // middle pane, for trajectory configuration and profiles { ImGui::BeginChild("config pane", ImVec2(250, 0), true); // The function to display all profiles const auto displayProfiles = [&](std::vector< ProfileWithMeshData >& vecProfileData) { // add profiles if(ImGui::Button("add profile")) { vecProfileData.emplace_back(); } const int numProfiles = vecProfileData.size(); for(int i = 0; i < numProfiles; ++i) { char label[128]; std::snprintf(label, 128, "%d %s", i, elementProfileDisplayName(vecProfileData[i].profile.index())); if(ImGui::Selectable(label, selectedProfileIndex == i)) { selectedProfileIndex = i; } } }; if(displaySettings.displayMode == DisplayMode::trajectory) { auto& trajectories = displayStates.trajectoryDataStates.trajectories; selectedTrajectoryIndex = std::min(selectedTrajectoryIndex, (int)trajectories.size() - 1); if(selectedTrajectoryIndex >= 0) { // files if(ImGui::CollapsingHeader("file")) { ImGui::TextWrapped("snapshot file: %s", trajectories[selectedTrajectoryIndex].inputs.trajSnapshot.string().c_str()); if(ImGui::Button("close")) { // close this file trajectories.erase(trajectories.begin() + selectedTrajectoryIndex); } } // profiles if(ImGui::CollapsingHeader("profiles", ImGuiTreeNodeFlags_DefaultOpen)) { if(selectedTrajectoryIndex < displayStates.trajectoryDataStates.trajectories.size()) { displayProfiles(displayStates.trajectoryDataStates.trajectories[selectedTrajectoryIndex].profileData); } } } } else { if(ImGui::CollapsingHeader("profiles", ImGuiTreeNodeFlags_DefaultOpen)) { displayProfiles(displayStates.realtimeDataStates.profileData); } } ImGui::EndChild(); } ImGui::SameLine(); // right pane, for profile configuration { ImGui::BeginChild("profile pane", ImVec2(0, 0), true); if(displaySettings.displayMode == DisplayMode::trajectory) { const bool valid = selectedTrajectoryIndex >= 0 && selectedTrajectoryIndex < displayStates.trajectoryDataStates.trajectories.size() && selectedProfileIndex >= 0 && selectedProfileIndex < displayStates.trajectoryDataStates.trajectories[selectedTrajectoryIndex].profileData.size(); if(valid) { auto& traj = displayStates.trajectoryDataStates.trajectories[selectedTrajectoryIndex]; if(ImGui::Button("remove profile")) { traj.profileData.erase(traj.profileData.begin() + selectedProfileIndex); } else { auto& profileData = traj.profileData[selectedProfileIndex]; if(guiActiveProfileConfig(profileData.profile)) { profileData.shouldUpdateMeshData = true; } } } } else { const bool valid = selectedProfileIndex >= 0 && selectedProfileIndex < displayStates.realtimeDataStates.profileData.size(); if(valid) { if(ImGui::Button("remove profile")) { displayStates.realtimeDataStates.profileData.erase(displayStates.realtimeDataStates.profileData.begin() + selectedProfileIndex); } else { auto& profileData = displayStates.realtimeDataStates.profileData[selectedProfileIndex]; if(guiActiveProfileConfig(profileData.profile)) { profileData.shouldUpdateMeshData = true; } } } } ImGui::EndChild(); } } // End of help window, no matter Begin returns true or false. ImGui::End(); } inline void guiTrajectoryControlPanel( DisplaySettings& displaySettings, DisplayStates& displayStates ) { // Playback ImGui::Checkbox("play", &displayStates.playback.isPlaying); ImGui::SliderFloat("speed", &displaySettings.playback.fps, 1, 24, "%.1f"); ImGui::SliderInt("playback", &displayStates.playback.currentFrame, 0, displayStates.playback.maxFrame); } inline void guiViewSettings(ObjectViewSettings& viewSettings) { using PT = ObjectViewSettings::Projection::Type; guiAuxColorPicker4Popup("background", viewSettings.canvas.bgColor.data()); if(ImGui::TreeNode("transformation")) { guiAuxEnumComboBox("projection", viewSettings.projection.type); ImGui::SliderFloat("z near", &viewSettings.projection.zNear, 1.0, 200.0, "%.1f"); ImGui::SliderFloat("z far", &viewSettings.projection.zFar, 1000.0, 20000.0, "%.1f"); ImGui::SliderFloat("camera key speed", &viewSettings.control.cameraKeyPositionPerFrame, 50.0, 500.0, "%.1f"); guiAuxEnumComboBox("mouse mode", viewSettings.control.cameraMouseMode); ImGui::TreePop(); } if(ImGui::TreeNode("snapshot")) { guiAuxEnumComboBox("snapshot resolution", viewSettings.control.snapshotResolution); if(viewSettings.control.snapshotResolution == ObjectViewSettings::Control::SnapshotResolution::scaleWithScreen) { ImGui::SliderFloat("snapshot scale", &viewSettings.control.snapshotScale, 0.1f, 10.0f, "%.1f"); ImGui::Checkbox("undo scaling orthographic", &viewSettings.control.snapshotUndoScaleOrtho); } else { ImGui::SliderInt("snapshot width", &viewSettings.control.snapshotWidth, 200, 1920); ImGui::SliderInt("snapshot height", &viewSettings.control.snapshotHeight, 150, 1080); } if(ImGui::Button("snapshot directory")) { guiAuxSelectFile(viewSettings.control.snapshotSavePath, true); } ImGui::TextWrapped("%s", viewSettings.control.snapshotSavePath.string().c_str()); ImGui::TreePop(); } } inline void guiMainWindow( DisplaySettings& displaySettings, DisplayStates & displayStates ) { const bool busy = displayStates.sync.busy.load(); // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup // Most ImGui functions would normally just crash if the context is missing. IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context."); ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar; // | ImGuiWindowFlags_NoCollapse; // We specify a default position/size in case there's no data in the .ini file. // We only do it to make the demo applications a little more welcoming, but typically this isn't required. ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(400, 600), ImGuiCond_FirstUseEver); // Main body of the Demo window starts here. if (!ImGui::Begin("medyan control", nullptr, windowFlags)) { // Early out if the window is collapsed, as an optimization. ImGui::End(); return; } // Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details. // e.g. Use 2/3 of the space for widgets and 1/3 for labels (default) // ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets. // ImGui::PushItemWidth(ImGui::GetFontSize() * -12); // Menu Bar if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("file")) { ImGui::MenuItem("(empty menu)", NULL, false, false); ImGui::EndMenu(); } if(ImGui::BeginMenu("window")) { ImGui::MenuItem("profile", nullptr, &displaySettings.gui.profileWindow, true); ImGui::EndMenu(); } if(ImGui::BeginMenu("help")) { ImGui::MenuItem("help window", nullptr, &displaySettings.gui.helpWindow, true); ImGui::EndMenu(); } ImGui::EndMenuBar(); } // Main display settings guiAuxEnumComboBox( "display mode", displaySettings.displayMode, [&](DisplayMode modeOld, DisplayMode modeNew) { switch(modeNew) { case DisplayMode::trajectory: if(modeOld != modeNew && displayStates.trajectoryDataStates.trajectories.empty()) { pushAnAsyncTask( displayStates.sync, [&] { backgroundTaskReadTrajectory(displayStates.sync, DisplayTrajectoryFileSettings {}); } ); } break; } }, busy ? ImGuiSelectableFlags_Disabled : 0 ); if(displaySettings.displayMode == DisplayMode::trajectory) { guiTrajectoryControlPanel(displaySettings, displayStates); } ImGui::Spacing(); if (ImGui::CollapsingHeader("info", ImGuiTreeNodeFlags_DefaultOpen)) { // Function to print view object information const auto printView = [](const ObjectViewSettings& viewSettings) { ImGui::Text("view"); ImGui::BulletText( "window size: (%d, %d)", viewSettings.canvas.width, viewSettings.canvas.height ); ImGui::BulletText( "camera position: (%.1f, %.1f, %.1f)", viewSettings.camera.position[0], viewSettings.camera.position[1], viewSettings.camera.position[2] ); ImGui::BulletText( "camera target: (%.1f, %.1f, %.1f)", viewSettings.camera.target[0], viewSettings.camera.target[1], viewSettings.camera.target[2] ); ImGui::BulletText("projection: %s", text(viewSettings.projection.type)); if(viewSettings.projection.type == ObjectViewSettings::Projection::Type::perspective) { ImGui::BulletText("fov: %.2f", viewSettings.projection.fov); } else { ImGui::BulletText("scale: %.1f", viewSettings.projection.scale); } ImGui::BulletText( "z range: (%.1f, %.1f)", viewSettings.projection.zNear, viewSettings.projection.zFar ); }; // busy information if(busy) { ImGui::Text("busy..."); ImGui::Separator(); } // fps information ImGui::Text("fps: %.1f", displayStates.timing.fps); ImGui::Separator(); // main view information printView(displaySettings.mainView); } if(ImGui::CollapsingHeader("settings", ImGuiTreeNodeFlags_DefaultOpen)) { // main view guiViewSettings(displaySettings.mainView); } // End of main window ImGui::End(); } // Note: // - This should only be used in GLFW main loop inline void imguiLoopRender( DisplaySettings& displaySettings, DisplayStates & displayStates ) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); if(displaySettings.gui.enabled) { guiMainWindow(displaySettings, displayStates); guiProfileWindow(displaySettings, displayStates); guiHelpWindow(displaySettings); } ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } } // namespace medyan::visual #endif
36.644444
202
0.589576
[ "mesh", "render", "object", "vector" ]
635200eaa1d0542fb34b651ac4b0c12a1bba98c9
49,088
cpp
C++
plugins/liberty_parser/test/liberty_parser.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
null
null
null
plugins/liberty_parser/test/liberty_parser.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
null
null
null
plugins/liberty_parser/test/liberty_parser.cpp
e7p/hal
2a88a8abefe5e2f79a74ec646e5fb3d8e6eb7cc8
[ "MIT" ]
null
null
null
#include "netlist_test_utils.h" #include "liberty_parser/liberty_parser.h" #include "hal_core/netlist/gate_library/gate_type/gate_type_lut.h" #include <experimental/filesystem> namespace hal { class LibertyParserTest : public ::testing::Test { protected: virtual void SetUp() { test_utils::init_log_channels(); } virtual void TearDown() { } }; /** * Testing the creation of a combinatorial Gate type with one input pin, one output pin and a boolean function. * * Functions: parse */ TEST_F(LibertyParserTest, check_combinatorial) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " date : \"April 3, 2020\"\n" // <- will be ignored " revision : 2015.03; \n" // <- will be ignored " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " area : 3; \n" // <- will be ignored " pin(I) {\n" " direction: input;\n" " capacitance : 1;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I\";\n" " x_function: \"!I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the name of the Gate library EXPECT_EQ(gl->get_name(), "TEST_GATE_LIBRARY"); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_GATE_TYPE"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; // Check the content of the created Gate type EXPECT_EQ(gt->get_base_type(), GateType::BaseType::combinatorial); // -- Check the pins EXPECT_EQ(gt->get_input_pins(), std::vector<std::string>({"I"})); EXPECT_EQ(gt->get_output_pins(), std::vector<std::string>({"O"})); // -- Check the boolean functions ASSERT_TRUE(gt->get_boolean_functions().find("O") != gt->get_boolean_functions().end()); EXPECT_EQ(gt->get_boolean_functions().at("O"), BooleanFunction::from_string("I", std::vector<std::string>({"I"}))); ASSERT_TRUE( gt->get_boolean_functions().find("O_undefined") != gt->get_boolean_functions().end()); // x_function EXPECT_EQ(gt->get_boolean_functions().at("O_undefined"), BooleanFunction::from_string("!I", std::vector<std::string>({"I"}))); } TEST_END } /** * Testing the creation of a LUT Gate type * * Functions: parse */ TEST_F(LibertyParserTest, check_lut) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { // Create a LUT Gate type with two input pins and four output pins // O0 and O2 generate their output by an initializer string. // O1 and O3 are given normal boolean functions. std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LUT) {\n" " lut (\"lut_out\") {\n" " data_category : \"test_category\";\n" " data_identifier : \"test_identifier\";\n" " direction : \"ascending\";\n" " }\n" " pin(I0) {\n" " direction: input;\n" " }\n" " pin(I1) {\n" " direction: input;\n" " }\n" " pin(O0) {\n" " direction: output;\n" " function: \"lut_out\";\n" " }\n" " pin(O1) {\n" " direction: output;\n" " function: \"I0 ^ I1\";\n" " }\n" " pin(O2) {\n" " direction: output;\n" " function: \"lut_out\";\n" " }\n" " pin(O3) {\n" " direction: output;\n" " function: \"I0 & I1\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_LUT"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; ASSERT_EQ(gt->get_base_type(), GateType::BaseType::lut); const GateTypeLut* gt_lut = dynamic_cast<const GateTypeLut*>(gt); // Check the content of the created Gate type EXPECT_EQ(gt_lut->get_input_pins(), std::vector<std::string>({"I0", "I1"})); EXPECT_EQ(gt_lut->get_output_pins(), std::vector<std::string>({"O0", "O1", "O2", "O3"})); ASSERT_TRUE(gt_lut->get_boolean_functions().find("O1") != gt_lut->get_boolean_functions().end()); EXPECT_EQ(gt_lut->get_boolean_functions().at("O1"), BooleanFunction::from_string("I0 ^ I1", std::vector<std::string>({"I0", "I1"}))); ASSERT_TRUE(gt_lut->get_boolean_functions().find("O3") != gt_lut->get_boolean_functions().end()); EXPECT_EQ(gt_lut->get_boolean_functions().at("O3"), BooleanFunction::from_string("I0 & I1", std::vector<std::string>({"I0", "I1"}))); // -- LUT specific EXPECT_EQ(gt_lut->get_output_from_init_string_pins(), std::unordered_set<std::string>({"O0", "O2"})); EXPECT_EQ(gt_lut->get_config_data_category(), "test_category"); EXPECT_EQ(gt_lut->get_config_data_identifier(), "test_identifier"); EXPECT_EQ(gt_lut->is_config_data_ascending_order(), true); } { // Create a simple LUT Gate type with an descending bit order std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LUT) {\n" " lut (\"lut_out\") {\n" " data_category : \"test_category\";\n" " data_identifier : \"test_identifier\";\n" " direction : \"descending\";\n" " }\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"lut_out\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_LUT"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; ASSERT_EQ(gt->get_base_type(), GateType::BaseType::lut); const GateTypeLut* gt_lut = dynamic_cast<const GateTypeLut*>(gt); // Check the content of the created Gate type EXPECT_EQ(gt_lut->is_config_data_ascending_order(), false); } TEST_END } /** * Testing the creation of flip-flops * * Functions: parse */ TEST_F(LibertyParserTest, check_flip_flop) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { // Create a flip-flop Gate type with two input pins and four output pins std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_FF) {\n" " ff (\"IQ\" , \"IQN\") {\n" " next_state : \"D\";\n" " clocked_on : \"CLK\";\n" " clocked_on_also : \"CLK\";\n" " preset : \"S\";\n" " clear : \"R\";\n" " clear_preset_var1 : L;\n" " clear_preset_var2 : H;\n" " direction : ascending;\n" " }\n" " pin(CLK) {\n" " direction: input;\n" " clock: true;\n" " }\n" " pin(CE) {\n" " direction: input;\n" " }\n" " pin(D) {\n" " direction: input;\n" " }\n" " pin(R) {\n" " direction: input;\n" " }\n" " pin(S) {\n" " direction: input;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " pin(QN) {\n" " direction: output;\n" " function: \"IQN\";\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"S & R & D\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_FF"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; ASSERT_EQ(gt->get_base_type(), GateType::BaseType::ff); const GateTypeSequential* gt_ff = dynamic_cast<const GateTypeSequential*>(gt); // Check the content of the created Gate type EXPECT_EQ(gt_ff->get_input_pins(), std::vector<std::string>({"CLK", "CE", "D", "R", "S"})); EXPECT_EQ(gt_ff->get_output_pins(), std::vector<std::string>({"Q", "QN", "O"})); ASSERT_TRUE(gt_ff->get_boolean_functions().find("O") != gt_ff->get_boolean_functions().end()); EXPECT_EQ(gt_ff->get_boolean_functions().at("O"), BooleanFunction::from_string("S & R & D", std::vector<std::string>({"S", "R", "D"}))); // -- Check the boolean functions of the ff group that are parsed (currently only next_state, clock_on(clock), preset(set) and clear(reset) are parsed ) ASSERT_TRUE(gt_ff->get_boolean_functions().find("next_state") != gt_ff->get_boolean_functions().end()); EXPECT_EQ(gt_ff->get_boolean_functions().at("next_state"), BooleanFunction::from_string("D", std::vector<std::string>({"D"}))); ASSERT_TRUE(gt_ff->get_boolean_functions().find("clock") != gt_ff->get_boolean_functions().end()); EXPECT_EQ(gt_ff->get_boolean_functions().at("clock"), BooleanFunction::from_string("CLK", std::vector<std::string>({"CLK"}))); ASSERT_TRUE(gt_ff->get_boolean_functions().find("preset") != gt_ff->get_boolean_functions().end()); EXPECT_EQ(gt_ff->get_boolean_functions().at("preset"), BooleanFunction::from_string("S", std::vector<std::string>({"S"}))); ASSERT_TRUE(gt_ff->get_boolean_functions().find("clear") != gt_ff->get_boolean_functions().end()); EXPECT_EQ(gt_ff->get_boolean_functions().at("clear"), BooleanFunction::from_string("R", std::vector<std::string>({"R"}))); // -- Check the output pins EXPECT_EQ(gt_ff->get_state_output_pins(), std::unordered_set<std::string>({"Q"})); EXPECT_EQ(gt_ff->get_inverted_state_output_pins(), std::unordered_set<std::string>({"QN"})); // -- Check the set-reset behaviour EXPECT_EQ(gt_ff->get_set_reset_behavior(), std::make_pair(GateTypeSequential::SetResetBehavior::L, GateTypeSequential::SetResetBehavior::H)); } TEST_END } /** * Testing the creation of a latches * * Functions: parse */ TEST_F(LibertyParserTest, check_latch) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { // Create a flip-flop Gate type with two input pins and four output pins std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LATCH) {\n" " latch (\"IQ\" , \"IQN\") {\n" " enable : \"G\";\n" " data_in : \"D\";\n" " preset : \"S\";\n" " clear : \"R\";\n" " clear_preset_var1 : N;\n" " clear_preset_var2 : T;\n" " }\n" " pin(G) {\n" " direction: input;\n" " }\n" " pin(D) {\n" " direction: input;\n" " }\n" " pin(S) {\n" " direction: input;\n" " }\n" " pin(R) {\n" " direction: input;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " pin(QN) {\n" " direction: output;\n" " function: \"IQN\";\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"S & R & D\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_LATCH"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; ASSERT_EQ(gt->get_base_type(), GateType::BaseType::latch); const GateTypeSequential* gt_latch = dynamic_cast<const GateTypeSequential*>(gt); // Check the content of the created Gate type EXPECT_EQ(gt_latch->get_input_pins(), std::vector<std::string>({"G", "D", "S", "R"})); EXPECT_EQ(gt_latch->get_output_pins(), std::vector<std::string>({"Q", "QN", "O"})); ASSERT_TRUE(gt_latch->get_boolean_functions().find("O") != gt_latch->get_boolean_functions().end()); EXPECT_EQ(gt_latch->get_boolean_functions().at("O"), BooleanFunction::from_string("S & R & D", std::vector<std::string>({"S", "R", "D"}))); // -- Check the boolean functions of the latch group that are parsed (currently only enable, data_in, preset(set) and clear(reset) are parsed) ASSERT_TRUE( gt_latch->get_boolean_functions().find("enable") != gt_latch->get_boolean_functions().end()); EXPECT_EQ(gt_latch->get_boolean_functions().at("enable"), BooleanFunction::from_string("G", std::vector<std::string>({"G"}))); ASSERT_TRUE(gt_latch->get_boolean_functions().find("data") != gt_latch->get_boolean_functions().end()); EXPECT_EQ(gt_latch->get_boolean_functions().at("data"), BooleanFunction::from_string("D", std::vector<std::string>({"D"}))); ASSERT_TRUE( gt_latch->get_boolean_functions().find("preset") != gt_latch->get_boolean_functions().end()); EXPECT_EQ(gt_latch->get_boolean_functions().at("preset"), BooleanFunction::from_string("S", std::vector<std::string>({"S"}))); ASSERT_TRUE(gt_latch->get_boolean_functions().find("clear") != gt_latch->get_boolean_functions().end()); EXPECT_EQ(gt_latch->get_boolean_functions().at("clear"), BooleanFunction::from_string("R", std::vector<std::string>({"R"}))); // -- Check the output pins EXPECT_EQ(gt_latch->get_state_output_pins(), std::unordered_set<std::string>({"Q"})); EXPECT_EQ(gt_latch->get_inverted_state_output_pins(), std::unordered_set<std::string>({"QN"})); // -- Check the set-reset behaviour EXPECT_EQ(gt_latch->get_set_reset_behavior(), std::make_pair(GateTypeSequential::SetResetBehavior::N, GateTypeSequential::SetResetBehavior::T)); } TEST_END } /** * Testing the usage of multiline comments (via '/ *' and '* /' (without space)) * * Functions: parse */ TEST_F(LibertyParserTest, check_multiline_comment) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { // The output pins O0, O1, O2, O3 should be created, C0, C1, C2, C3 shouldn't std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O0) { direction: output; function: \"I\"; }\n" " pin(O1) { direction: output; function: \"I\"; } /* pin(C0) { direction: output; function: \"I\"; }*/\n" " pin(O2) { direction: output; function: \"I\"; }\n" " /*pin(C1) { direction: output; function: \"I\"; }\n" " pin(C2) { direction: output; function: \"I\"; }\n" " pin(C3) { direction: output; function: \"I\"; }*/\n" " pin(O3) { direction: output; function: \"I\"; }\n" " \n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // Check that the Gate type was created auto gate_types = gl->get_gate_types(); ASSERT_EQ(gate_types.size(), 1); auto gt_it = gate_types.find("TEST_GATE_TYPE"); ASSERT_TRUE(gt_it != gate_types.end()); const GateType* gt = gt_it->second; // Check that only the pins outside the comments are created EXPECT_EQ(gt->get_input_pins(), std::vector<std::string>({"I"})); EXPECT_EQ(gt->get_output_pins(), std::vector<std::string>({"O0", "O1", "O2", "O3"})); } TEST_END } /** * Testing the correct handling of invalid input and other uncommon inputs * * Functions: parse */ TEST_F(LibertyParserTest, check_invalid_input) { TEST_START if(!test_utils::known_issue_tests_active()){ SUCCEED(); return; } { // Pass an empty input stream NO_COUT_TEST_BLOCK; std::stringstream input(""); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // For a ff, use an undefined clear_preset_var1 behaviour (not in {L,H,N,T,X}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_FF) {\n" " ff (\"IQ\" , \"IQN\") {\n" " next_state : \"P\";\n" " clocked_on : \"P\";\n" " preset : \"P\";\n" " clear : \"P\";\n" " clear_preset_var1 : Z;\n" " clear_preset_var2 : L;\n" " }\n" " pin(P) {\n" " direction: input;\n" " clock: true;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // For a ff, use an undefined clear_preset_var2 behaviour (not in {L,H,N,T,X}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_FF) {\n" " ff (\"IQ\" , \"IQN\") {\n" " next_state : \"P\";\n" " clocked_on : \"P\";\n" " preset : \"P\";\n" " clear : \"P\";\n" " clear_preset_var1 : L;\n" " clear_preset_var2 : Z;\n" " }\n" " pin(P) {\n" " direction: input;\n" " clock: true;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // For a latch, use an undefined clear_preset_var1 behaviour (not in {L,H,N,T,X}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LATCH) {\n" " latch (\"IQ\" , \"IQN\") {\n" " enable : \"P\";\n" " data_in : \"P\";\n" " preset : \"P\";\n" " clear : \"P\";\n" " clear_preset_var1 : Z;\n" " clear_preset_var2 : L;\n" " }\n" " pin(P) {\n" " direction: input;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // For a latch, use an undefined clear_preset_var1 behaviour (not in {L,H,N,T,X}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LATCH) {\n" " latch (\"IQ\" , \"IQN\") {\n" " enable : \"P\";\n" " data_in : \"P\";\n" " preset : \"P\";\n" " clear : \"P\";\n" " clear_preset_var1 : L;\n" " clear_preset_var2 : Z;\n" " }\n" " pin(P) {\n" " direction: input;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"IQ\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // Use an undefined direction in the lut group block (not in {ascending, descending}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LUT) {\n" " lut (\"lut_out\") {\n" " data_category : \"test_category\";\n" " data_identifier : \"test_identifier\";\n" " direction : \"north-east\";\n" // <-"north-east" is no valid data direction " }\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"lut_out\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // Use an undefined direction in the ff group block (not in {ascending, descending}) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_LUT) {\n" " lut (\"IQ\" , \"IQN\") {\n" " direction : \"north-east\";\n" // <-"north-east" is no valid data direction " }\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // Use a pin with an unknown direction (not in {input, output}) as an input pin NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: WAMBO;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); // NOTE: Ok, only 'I' is not parsed auto g_types = gl->get_gate_types(); ASSERT_TRUE(g_types.find("TEST_GATE_TYPE") != g_types.end()); EXPECT_EQ(g_types["TEST_GATE_TYPE"]->get_output_pins().size(), 1); EXPECT_TRUE(g_types["TEST_GATE_TYPE"]->get_input_pins().empty()); } /*{ // NOTE: Works (is ok?) // Use an unknown variable in a boolean function NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I & WAMBO\";\n" // <- WAMBO is undefined " }\n" " }\n" "}"); LibertyParser liberty_parser(input); std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); // NOTE: Ok? BF is parsed anyway with Variable WAMBO }*/ { // Use an unknown cell group (should be filtered out) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " biological_cell (\"A\" , \"B\") {\n" // the parser does not support biological cells ;) " cell_type: eukaryotic; \n" " species: dog; \n " " has_cell_wall: nope; \n " " }\n" " pin(P) {\n" " direction: input;\n" " }\n" " pin(Q) {\n" " direction: output;\n" " function: \"P\";\n" " }\n" " }" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); auto gate_types = gl->get_gate_types(); ASSERT_TRUE(gate_types.find("TEST_GATE_TYPE") != gate_types.end()); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_base_type(), GateType::BaseType::combinatorial); } { // Define a pin twice NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I\";\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"!I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // Define a Gate type twice NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"!I\";\n" " }\n" " }\n" " cell(TEST_GATE_TYPE) {\n" " pin(I0) {\n" " direction: input;\n" " }\n" " pin(O0) {\n" " direction: output;\n" " function: \"!I0\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); EXPECT_EQ(gl, nullptr); } { // Pin got no direction (should be ignored) NO_COUT_TEST_BLOCK; std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(I_nodir) {\n" " capacitance : 1.0;" " }\n" " pin(O) {\n" " direction: output;\n" " function: \"I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); auto gate_types = gl->get_gate_types(); ASSERT_TRUE(gate_types.find("TEST_GATE_TYPE") != gate_types.end()); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_base_type(), GateType::BaseType::combinatorial); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_input_pins().size(), 1); } { // Test the usage of complex attributes std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " complex_attr(param1, param2);\n" " direction: output;\n" " function: \"!I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); auto gate_types = gl->get_gate_types(); ASSERT_TRUE(gate_types.find("TEST_GATE_TYPE") != gate_types.end()); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_base_type(), GateType::BaseType::combinatorial); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_output_pins().size(), 1); } if(test_utils::known_issue_tests_active()) { // ISSUE: Interprets backslash as character of attribute name ("direction\") // Test usage of a backslash (\) to continue a statement over multiple lines std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin(O) {\n" " complex_attr(param1, param2);\n" " direction\\\n" " : output;\n" " function: \"!I\";\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_NE(gl, nullptr); auto gate_types = gl->get_gate_types(); ASSERT_TRUE(gate_types.find("TEST_GATE_TYPE") != gate_types.end()); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_base_type(), GateType::BaseType::combinatorial); EXPECT_EQ(gate_types.at("TEST_GATE_TYPE")->get_output_pins().size(), 1); // ISSUE: fails } { // Test empty pin names std::stringstream input("library (TEST_GATE_LIBRARY) {\n" " define(cell);\n" " cell(TEST_GATE_TYPE) {\n" " pin(I) {\n" " direction: input;\n" " }\n" " pin() {\n" " direction: output;\n" " }\n" " }\n" "}"); LibertyParser liberty_parser; std::unique_ptr<GateLibrary> gl = liberty_parser.parse("imaginary_path", input); ASSERT_EQ(gl, nullptr); } TEST_END } } //namespace hal
57.212121
168
0.337088
[ "vector" ]
63565d9c606d7768d8d77eec108e3fff70deec34
9,939
cc
C++
examples/others/mathintprt/mathintprt.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
5
2020-04-11T21:30:19.000Z
2021-12-04T16:16:09.000Z
examples/others/mathintprt/mathintprt.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
examples/others/mathintprt/mathintprt.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
/* * NOTE: This example does not work under cygwin. */ #include "TaskGraph" #include "TaskUserFunctions.h" #include <cstdio> #include <vector> #include <map> #define MAX_EXPRESSION_ARGS 3 #define Register_Command(name, arity) \ commandVector.push_back( mathCommand ( (name), (arity) ) ); \ commandDictionary[(name)] = commandVector.size()-1; using namespace tg; struct mathExpr; struct mathCommand; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; static std::vector<mathExpr> expressionVector; static std::vector<mathCommand> commandVector; static std::map< const char*, unsigned, ltstr > commandDictionary; static int global_id = 0; extern "C" int tg_add ( int a, int b ) { return a+b; } extern "C" int tg_ifz ( int b, int x, int y ) { return b?x:y; } extern "C" int tg_mgc ( int x ) { return x?x+tg_mgc(x-1):0; } extern "C" int tg_div ( int x, int y ) { return x/y; } extern "C" int tg_mul ( int x, int y ) { return x*y; } struct mathCommand { friend struct mathExpr; public: mathCommand ( ) : id(0), arity(0), name(NULL) { } mathCommand ( const char *_name, int _arity ) { id = ++global_id; arity = _arity; name = new char[strlen(_name)+1]; strcpy ( name, _name ); switch ( arity ) { case 1: address = new TaskFunction1<int, int> ( name ); break; case 2: address = new TaskFunction2<int, int, int> ( name ); break; case 3: address = new TaskFunction3<int, int, int, int> ( name ); break; default: printf ( "Error: No support for functions with more than 4 arguments!\n" ); address = NULL; } } mathCommand ( const mathCommand& obj ) { id = obj.id; arity = obj.arity; name = new char[strlen(obj.name)+1]; strcpy ( name, obj.name ); address = obj.address; } const mathCommand& operator= ( const mathCommand& obj ) { if (this != &obj) { id = obj.id; arity = obj.arity; name = new char[strlen(obj.name)+1]; strcpy ( name, obj.name ); address = obj.address; } return *this; } unsigned id; unsigned arity; char *name; void *address; }; struct mathExpr { friend struct mathCommand; public: mathExpr ( ) : evaluated ( false ), arity ( 0 ) { }; mathExpr ( int _value ) : id ( 0 ), value ( TaskExpression(_value) ), evaluated ( true ), arity ( 0 ) { } mathExpr ( TaskExpression &_expr ) : id ( 0 ), value ( _expr ), evaluated ( true ), arity( 0 ) { } mathExpr ( TaskScalarVariable &_expr ) : id ( 0 ), value ( TaskExpression(_expr) ), evaluated ( true ), arity( 0 ) { } mathExpr ( const char *name, mathExpr _arg1 ) : id ( commandDictionary[name] ), value ( 0 ), evaluated ( false ), arity ( 1 ) { expressionVector.push_back ( _arg1 ); arguments[0] = expressionVector.size()-1; }; mathExpr ( const char *name, mathExpr _arg1, mathExpr _arg2 ) : id ( commandDictionary[name] ), value ( 0 ), evaluated ( false ), arity ( 2 ) { expressionVector.push_back ( _arg1 ); arguments[0] = expressionVector.size()-1; expressionVector.push_back ( _arg2 ); arguments[1] = expressionVector.size()-1; }; mathExpr ( const char *name, mathExpr _arg1, mathExpr _arg2, mathExpr _arg3 ) : id ( commandDictionary[name] ), value ( 0 ), evaluated ( false ), arity ( 3 ) { expressionVector.push_back ( _arg1 ); arguments[0] = expressionVector.size()-1; expressionVector.push_back ( _arg2 ); arguments[1] = expressionVector.size()-1; expressionVector.push_back ( _arg3 ); arguments[2] = expressionVector.size()-1; }; mathExpr ( const mathExpr& obj ) { id = obj.id; value = obj.value; evaluated = obj.evaluated; arity = obj.arity; for ( int i = 0; i < MAX_EXPRESSION_ARGS; i++ ) arguments[i] = obj.arguments[i]; } const mathExpr& operator= ( const mathExpr& obj ) { if (this != &obj) { id = obj.id; value = obj.value; evaluated = obj.evaluated; arity = obj.arity; for ( int i = 0; i < MAX_EXPRESSION_ARGS; i++ ) arguments[i] = obj.arguments[i]; } return *this; } TaskExpression eval ( ) { if ( evaluated ) { return value; } else { switch ( arity ) { case 1: return (reinterpret_cast<TaskFunction1<int,int>*>(commandVector[id].address))->call ( expressionVector[arguments[0]].eval() ); case 2: return (reinterpret_cast<TaskFunction2<int,int,int>*>(commandVector[id].address))->call ( expressionVector[arguments[0]].eval(), expressionVector[arguments[1]].eval() ); case 3: return (reinterpret_cast<TaskFunction3<int,int,int,int>*>(commandVector[id].address))->call ( expressionVector[arguments[0]].eval(), expressionVector[arguments[1]].eval(), expressionVector[arguments[2]].eval() ); default: printf ( "Error: No support for functions with more than 4 arguments!\n" ); return TaskExpression ( ); } } } unsigned id; TaskExpression value; bool evaluated; unsigned arity; unsigned arguments[MAX_EXPRESSION_ARGS]; }; void script_error ( const char* script, int index ) { printf ( "Parse Error: %s\n", script); printf ( "Position: "); for ( int i = 0; i < index; i++ ) putchar(' '); printf ( "^ here\n"); } void ignore_space ( const char *script, unsigned &i ) { while ( isspace(script[i]) ) i++; } bool script_next ( const char *script, unsigned &i, bool closing) { if ( closing ) { if ( script[i] != ')' ) { printf ( "Error, expected \")\".\n" ); script_error(script, i); return false; } else { i++; } } else { if ( script[i] != ',' ) { printf ( "Error, expected \",\".\n" ); script_error(script, i); return false; } else { i++; } } ignore_space ( script, i ); return true; } mathExpr parser ( const char* script, unsigned &i, unsigned nvars, TaskScalarVariable **vars, bool closing = false , bool first = false ) { int intvalue = 0, j = 0, k = 0; int sign = 1; char name[31]; bool isvalue = false; unsigned arity = 0, n; std::map<const char*, unsigned>::iterator comm; mathExpr mExpr; if ( isdigit( script[i] ) || script[i] == '-' || script[i] == '+' ) { isvalue = true; if ( script[i] == '-' ) { sign = -1; i++; if ( !isdigit(script[i]) ) { printf("Error, expected digit after sign.\n"); script_error(script, i); return mathExpr(); } } else if ( script[i] == '+' ) { i++; if ( !isdigit(script[i]) ) { printf("Error, expected digit after sign.\n"); script_error(script, i); return mathExpr(); } } while ( script[i] && isdigit(script[i]) ) intvalue = intvalue*10 + script[i++]-'0'; intvalue *= sign; } else if ( isalpha(script[i]) || script[i] == '_' || isdigit(script[i]) ) { j = 0; while ( ( isalpha(script[i]) || script[i] == '_' || isdigit(script[i]) ) && j < 31 ) name[j++] = script[i++]; name[j] = '\0'; } else { script_error(script, i); return mathExpr(); } ignore_space ( script, i ); if ( isvalue ) { if ( !script_next(script, i, closing) ) { return mathExpr(); } return mathExpr ( intvalue ); } else { if ( j > 3 && name[0] == 'a' && name[1] == 'r' && name[2] == 'g' && isdigit(name[3]) ) { k = 3; n = 0; while ( isdigit(name[k]) ) n = n*10 + name[k++]-'0'; if ( n > nvars ) { printf ( "Error, arg%d is not provided.", n ); script_error(script, i); return mathExpr (); } if ( !script_next(script, i, closing) ) { return mathExpr(); } return mathExpr ( *(vars[n]) ); } else { if ( script[i] != '(' ) { printf ( "Error: too long command name or command %s not followed by \"(\"!\n", name ); script_error(script, i); return mathExpr(); } i++; ignore_space ( script, i ); comm = commandDictionary.find ( name ); if ( comm != commandDictionary.end() ) { arity = commandVector[commandDictionary[name]].arity; } else { printf ( "Error: command \"%s\" not found!\n", name ); script_error(script, i); return mathExpr(); } switch ( arity ) { case 1: { mathExpr mExpr1( name, parser(script, i, nvars, vars, true) ); if ( !first && !script_next(script, i, closing) ) { return mathExpr(); } return mExpr1; } case 2: { mathExpr lhs = parser(script, i, nvars, vars); mathExpr rhs = parser(script, i, nvars, vars, true); mathExpr mExpr2( name, lhs, rhs ); if ( !first && !script_next(script, i, closing) ) { return mathExpr(); } return mExpr2; } case 3: { mathExpr lhs = parser(script, i, nvars, vars); mathExpr middle = parser(script, i, nvars, vars); mathExpr rhs = parser(script, i, nvars, vars, true); mathExpr mExpr3( name, lhs, middle, rhs ); if ( !first && !script_next(script, i, closing) ) { return mathExpr(); } return mExpr3; } default: printf ( "Error: No support for functions with more than 4 arguments!\n" ); return mathExpr ( ); } } } return mathExpr ( ); } typedef TaskGraph<int, int, int, int, int, int> TG; void interpret ( TG &t, const char *filename ) { FILE *fp; char script[1000]; unsigned index = 0; fp = fopen ( filename, "r" ); fgets ( script, 1000, fp ); fclose ( fp ); taskgraph( TG, t, tuple5( input1, input2, input3, input4, input5 ) ) { TaskScalarVariable* vars[5]; vars[0] = &input1; vars[1] = &input2; vars[2] = &input3; vars[3] = &input4; vars[4] = &input5; tReturn( parser(script, index, 5, vars, false, true ).eval() ); } } int main ( int argc, char **argv ) { #ifdef ENV_CYGWIN fprintf(stderr, "This example does not work in cygwin due to linking issues in Windows\n"); return -1; #endif Register_Command("tg_add", 2); Register_Command("tg_ifz", 3); Register_Command("tg_mgc", 1); Register_Command("tg_div", 2); Register_Command("tg_mul", 2); TG t; interpret ( t, "math_script" ); t.compile ( tg::GCC, true ); int arg1= 24; int arg2= 0; int arg3= 0; int arg4= 0; int arg5= 0; printf ( "result = %d\n", t.execute ( arg1, arg2, arg3, arg4, arg5 ) ); }
27.455801
217
0.61153
[ "vector" ]
636212a2244603a577589e5db24bb2a79abc76fb
8,310
cpp
C++
src/ArmadilloHTTP.cpp
philbowles/ArmadilloHTTP
2c22ca50795af0ed8e37907dc3d1ec4963a82162
[ "MIT" ]
1
2021-05-24T09:30:22.000Z
2021-05-24T09:30:22.000Z
src/ArmadilloHTTP.cpp
philbowles/ArmadilloHTTP
2c22ca50795af0ed8e37907dc3d1ec4963a82162
[ "MIT" ]
null
null
null
src/ArmadilloHTTP.cpp
philbowles/ArmadilloHTTP
2c22ca50795af0ed8e37907dc3d1ec4963a82162
[ "MIT" ]
1
2021-07-19T23:01:53.000Z
2021-07-19T23:01:53.000Z
#include<pmbtools.h> #include<ArmadilloHTTP.h> ArmadilloHTTP::ArmadilloHTTP(): AardvarkTCP(){ onTCPdisconnect([=](int8_t e){ _scavenge(); }); rx([=](const uint8_t* d,size_t s){ _rx(d,s); }); } void ArmadilloHTTP::_appendHeaders(std::string* p){ for(auto const& r:requestHeaders) *p+=r.first+": "+r.second+"\r\n"; *p+="\r\n"; } bool ArmadilloHTTP::_compareHeader(const std::string& h,const std::string& v){ if(_response.responseHeaders.count(uppercase(h)) && uppercase(_response.responseHeaders[uppercase(h)])==uppercase(v)) return true; return false; } void ArmadilloHTTP::_execute(const uint8_t* d,size_t s){ _response.data=d; _response.length=s; _userfn(_response); _inflight=false; if(_compareHeader("Connection","close"))close(); } size_t ArmadilloHTTP::_getContentLength(){ size_t len=0; if(_response.responseHeaders.count(contentLengthTag())) len=atoi(_response.responseHeaders[contentLengthTag()].c_str()); return len; } void ArmadilloHTTP::_getMethods(const std::string& hdr){ ARMA_PRINT4("_getMethods %s (already have %d)\n",hdr.c_str(),_response.allowedMethods.size()); if(!_response.allowedMethods.size()){ if(_response.responseHeaders.count(hdr)){ ARMA_PRINT4("ALLOWING: %s\n",_response.responseHeaders[hdr].c_str()); std::vector<std::string> aloud=split(_response.responseHeaders[hdr],","); for(auto const& a:aloud) _response.allowedMethods.insert(trim(a)); } } } void ArmadilloHTTP::_measure(const uint8_t* d,size_t s){ size_t len=_getContentLength(); if(len){ if(len < getMaxPayloadSize()) _sendRequest(ARMA_PHASE_EXECUTE); else _error(ARMA_ERROR_TOO_BIG,len); } } void ArmadilloHTTP::_preflight(const uint8_t* d,size_t s){ _getMethods("ALLOW"); _getMethods("ACCESS-CONTROL-ALLOW-METHODS"); if(_response.allowedMethods.count(_phaseVerb[ARMA_PHASE_EXECUTE])) _sendRequest(ARMA_PHASE_MEASURE); else _error(ARMA_ERROR_VERB_PROHIBITED); } void ArmadilloHTTP::_prepare(uint32_t phase,const std::string& verb,const std::string& url,ARMA_FN_HTTP f,const VARK_NVP_MAP& fields){ if(_inflight) { ARMA_PRINT4("REJECTED: BUSY - %s %s\n",verb.data(),url.data()); _error(ARMA_ERROR_BUSY); } else { _inflight=true; _phaseVerb[ARMA_PHASE_EXECUTE]=verb; _userfn=f; // _parseURL(url); if(fields.size()){ if(requestHeaders.count(contentTypeTag())){ std::string type=requestHeaders[contentTypeTag()]; if(type=="application/json") _bodydata=nvp2json(fields); // else ARMA_PRINT1("unknown c-type %s\n",type.data()); } else { addRequestHeader(contentTypeTag(),"application/x-www-form-urlencoded"); _bodydata=flattenMap(fields,"=","&",urlencode); } } // onTCPconnect([=](){_sendRequest(phase); }); TCPconnect(); } } void ArmadilloHTTP::_chunkItUp(uint8_t* pMsg,const uint8_t* d,size_t s){ size_t chunk=0; do { size_t n=0; for(uint8_t* i=pMsg;i<(pMsg+6);i++) if(*i=='\r' || *i=='\n') n+=*i; ARMA_PRINT4("stray fragment metric=%d\n",n); // if n != 23 , invalid chunk count if(n<23){ ARMA_PRINT4("SF addchunk length %d total now %d in %d chunks\n",s,_sigmaChunx,_chunks.size()); uint8_t* frag=2+((_chunks.back().data+_chunks.back().len)-s); memcpy(frag,pMsg,s); } else { chunk=hex2uint(pMsg); ARMA_PRINT4("Looks like a valid chunk of length %d\n",chunk); if(chunk){ _sigmaChunx+=chunk; while((*pMsg++)!='\r'); _chunks.emplace_back(++pMsg,chunk,true); ARMA_PRINT4("NC addchunk length %d total now %d in %d chunks\n",chunk,_sigmaChunx,_chunks.size()); pMsg+=chunk+2; if(!(pMsg < d+s)) return; } else { // rebuild block from frags ARMA_PRINT4("reassemble length %d from %d chunks\n",_sigmaChunx,_chunks.size()); uint8_t* reassembled=mbx::getMemory(_sigmaChunx); if(reassembled){ uint8_t* r=reassembled; for(auto &c:_chunks){ ARMA_PRINT4("UNCHUNKING\n"); dumphex(c.data,c.len); memcpy(r,c.data,c.len); c.clear(); } _chunks.clear(); _chunks.shrink_to_fit(); _execute(reassembled,_sigmaChunx); mbx::clear(reassembled); _sigmaChunx=0; return; } else { _error(VARK_INPUT_TOO_BIG); close(); return; } } } } while(chunk); } void ArmadilloHTTP::_rx(const uint8_t* d,size_t s){ ARMA_PRINT1("RX 0x%08x len=%d FH=%u\n",d,s,_HAL_freeHeap()); if(_sigmaChunx) { uint8_t* pMsg=(uint8_t*) d; _chunkItUp(pMsg,d,s); } else { auto i=strstr((const char*) d,"\r\n\r\n"); ptrdiff_t szHdrs=(const uint8_t*) i-d; if(szHdrs > s) return; uint8_t* pMsg=(uint8_t*) (d+szHdrs+4); const size_t msgLen=s-(szHdrs+4); ARMA_PRINT4("Looks like hdrs n=%d msgLen=%d @ 0x%08x\n",szHdrs,msgLen,pMsg); std::string rawheaders; rawheaders.assign((const char*) d,szHdrs); std::vector<std::string> hdrs=split(rawheaders,"\r\n"); std::vector<std::string> status=split(hdrs[0]," "); _response.httpResponseCode=atoi(status[1].c_str()); ARMA_PRINT4("_response.httpResponseCode=%d\n",_response.httpResponseCode); for(auto const h:std::vector<std::string>(++hdrs.begin(),hdrs.end())){ std::vector<std::string> deco2=split(h,": "); _response.responseHeaders[uppercase(deco2[0])]=deco2.size() > 1 ? deco2[1]:""; } rawheaders.clear(); rawheaders.shrink_to_fit(); hdrs.clear(); // for(auto const h:_response.responseHeaders) ARMA_PRINT1("RH %s=%s\n",h.first.c_str(),h.second.c_str()); if(_compareHeader("TRANSFER-ENCODING","CHUNKED")) _chunkItUp(pMsg,d,s); else { switch(_phase){ case ARMA_PHASE_PREFLIGHT: _preflight(pMsg,msgLen); break; case ARMA_PHASE_MEASURE: _measure(pMsg,msgLen); break; case ARMA_PHASE_EXECUTE: _execute(pMsg,msgLen); break; } } } } void ArmadilloHTTP::_scavenge(){ ARMA_PRINT4("_scavenge() IN FH=%u\n",_HAL_freeHeap()); _bodydata.clear(); requestHeaders.clear(); _response.responseHeaders.clear(); _response.allowedMethods.clear(); _response.httpResponseCode=0; _phase=ARMA_PHASE_PREFLIGHT; for(auto &c:_chunks) c.clear(); _sigmaChunx=0; _inflight=false; ARMA_PRINT4("_scavenge() UT FH=%u\n",_HAL_freeHeap()); } void ArmadilloHTTP::_sendRequest(uint32_t phase){ _phase=phase; std::string req=_phaseVerb[_phase]+" "; req.append(_URL.path).append(_URL.query.size() ? std::string("?")+_URL.query:"").append(" HTTP/1.1\r\nHost: ").append(_URL.host).append("\r\n"); req.append("User-Agent: ArmadilloHTTP/").append(ARDUINO_BOARD).append("/").append(ARMADILLO_VERSION).append("\r\n"); switch(phase){ case ARMA_PHASE_PREFLIGHT: addRequestHeader("Access-Control-Request-Method",_phaseVerb[ARMA_PHASE_EXECUTE]); _appendHeaders(&req); break; case ARMA_PHASE_EXECUTE: addRequestHeader(contentLengthTag(),stringFromInt(_bodydata.size())); addRequestHeader("Connection","close"); _appendHeaders(&req); req+=_bodydata; break; default: _appendHeaders(&req); break; } txdata((const uint8_t*) req.c_str(),req.size()); // hang on to the string :) }
37.264574
148
0.575572
[ "vector" ]
6368bf92e92dd5c5ec489770980e66292601d7d5
6,227
cc
C++
sstmac/backends/native/clock_cycle_parallel/thread_barrier.cc
minyee/sst-macro
fd2c52b3872b9c49af77f5f82b3177cc7bbe403c
[ "BSD-Source-Code" ]
4
2017-11-18T22:49:38.000Z
2021-01-22T18:33:50.000Z
sstmac/backends/native/clock_cycle_parallel/thread_barrier.cc
minyee/sst-macro
fd2c52b3872b9c49af77f5f82b3177cc7bbe403c
[ "BSD-Source-Code" ]
null
null
null
sstmac/backends/native/clock_cycle_parallel/thread_barrier.cc
minyee/sst-macro
fd2c52b3872b9c49af77f5f82b3177cc7bbe403c
[ "BSD-Source-Code" ]
1
2019-03-14T23:04:47.000Z
2019-03-14T23:04:47.000Z
/** Copyright 2009-2017 National Technology and Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government retains certain rights in this software. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525. Copyright (c) 2009-2017, NTESS 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 Sandia Corporation 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. Questions? Contact sst-macro-help@sandia.gov */ #include <sstmac/backends/native/clock_cycle_parallel/thread_barrier.h> #include <iostream> #include <sprockit/spkt_string.h> namespace sstmac { namespace native { void thread_barrier::lock(lock_t* l) { #ifdef SSTMAC_USE_SPINLOCK pthread_spin_lock(l); #else pthread_mutex_lock(l); #endif } void thread_barrier::unlock(lock_t* l) { #ifdef SSTMAC_USE_SPINLOCK pthread_spin_unlock(l); #else pthread_mutex_unlock(l); #endif } int64_t thread_barrier::run(int me, int level, int nthread, int64_t vote, vote_type_t ty, thread_barrier_functor* functor) { if (nthread==1){ if (level == 0) abort(); if (functor){ return functor->execute(vote); } else { return vote; } } barrier_state& myst = levels_[level][me]; myst.vote = vote; int next_nthread = nthread/2 + (nthread%2); int next_me = me/2; int next_level = level+1; int role = me % 2; if (role == 0){ int partner = me + 1; if (partner >= nthread){ return run(next_me, next_level, next_nthread, vote, ty, functor); //just go right on } else { barrier_state& pst = levels_[level][partner]; lock_t* plock = pst.in_lock; lock_t* mylock = myst.out_lock; lock(plock); //make sure my partner is unlocked //my partner arrived at the barrier if I reach here int64_t next_vote; switch (ty){ case vote_type_t::min: next_vote = std::min(myst.vote, pst.vote); break; case vote_type_t::max: next_vote = std::max(myst.vote, pst.vote); break; } myst.vote = run(next_me, next_level, next_nthread, next_vote, ty, functor); //okay, I will now own a different lock //swap things for the next iteration myst.out_lock = plock; pst.in_lock = mylock; //at this point, my partner is waiting for me to unlock unlock(mylock); } } else { int partner = me - 1; barrier_state& myst = levels_[level][me]; barrier_state& pst = levels_[level][partner]; lock_t* plock = pst.out_lock; lock_t* mylock = myst.in_lock; unlock(mylock); //unlock myself so partner knows I am here //lock on partner to wait on partner signal lock(plock); myst.out_lock = plock; pst.in_lock = mylock; //I receive the vote, not merge it myst.vote = pst.vote; } return myst.vote; } int64_t thread_barrier::vote(int me, int64_t vote, vote_type_t ty, thread_barrier_functor* functor) { if (ty == vote_type_t::max){ static thread_lock lock; lock.lock(); lock.unlock(); } return run(me, 0, nthread_, vote, ty, functor); } void thread_barrier::start(int me, thread_barrier_functor* functor) { //send a fake vote run(me, 0, nthread_, 0, vote_type_t::min, functor); } int thread_barrier::init_level(int level, int num, int offset) { std::vector<barrier_state>& vec = levels_[level]; vec.resize(num); for (int i=0; i < num; ++i, ++offset){ barrier_state& st = vec[i]; st.in_lock = &in_locks_[offset]; st.out_lock = &out_locks_[offset]; #ifdef SSTMAC_USE_SPINLOCK pthread_spin_init(st.in_lock, PTHREAD_PROCESS_PRIVATE); pthread_spin_init(st.out_lock, PTHREAD_PROCESS_PRIVATE); #else pthread_mutex_init(st.in_lock, NULL); pthread_mutex_init(st.out_lock, NULL); #endif lock(st.in_lock); lock(st.out_lock); } return offset; } void thread_barrier::init(int nthread) { nthread_ = nthread; if (nthread == 1){ return; //nothing to do here } int nlevels = 0; int num_locks = 1; twoPowN_ = 1; while (twoPowN_ < nthread){ nlevels++; twoPowN_ *= 2; num_locks += twoPowN_; } levels_.resize(nlevels); //maybe not a power of two, also no thread lock for top of tree(+1) int extra = twoPowN_ - nthread + 1; num_locks -= extra; in_locks_ = new lock_t[num_locks]; out_locks_ = new lock_t[num_locks]; int offset = init_level(0, nthread, 0); int numNextLevel = twoPowN_ / 2; for (int i=1; i < nlevels; ++i){ offset = init_level(i, numNextLevel, offset); numNextLevel /= 2; } } thread_barrier::thread_barrier(int nthread) { init(nthread); } } }
28.56422
90
0.701783
[ "vector" ]
6372da68579456feb20bae9edc644fddcff834c4
237
cpp
C++
LeetCode/Problems/Algorithms/#338_CountingBits_sol4_dp_O(N).cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#338_CountingBits_sol4_dp_O(N).cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#338_CountingBits_sol4_dp_O(N).cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> countBits(int num) { vector<int> answer(num + 1); for(int i = 1; i <= num; ++i){ answer[i] = (i % 2) + answer[i / 2]; } return answer; } };
23.7
49
0.438819
[ "vector" ]
63740896bd10a7409bc8ed93714a3204b45474b0
1,111
cpp
C++
Contests/Codeforces_Round_#706/probC.cpp
francoisvogel/cp
ae59cf635ab19382d924344fbb137ab9ae631103
[ "MIT" ]
1
2021-10-02T15:40:33.000Z
2021-10-02T15:40:33.000Z
Contests/Codeforces_Round_#706/probC.cpp
francoisvogel/cp
ae59cf635ab19382d924344fbb137ab9ae631103
[ "MIT" ]
null
null
null
Contests/Codeforces_Round_#706/probC.cpp
francoisvogel/cp
ae59cf635ab19382d924344fbb137ab9ae631103
[ "MIT" ]
null
null
null
/* * Author: Francois Vogel * Comment: */ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <functional> using namespace std; using namespace __gnu_pbds; #define pii pair<int, int> #define f first #define s second #define vi vector<int> #define all(x) x.begin(), x.end() #define pb push_back #define ins insert #define cls clear #define ll long long #define ld long double typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; void test() { int n; cin >> n; vi x, y; for (int i = 0; i < 2*n; i++) { int lx, ly; cin >> lx >> ly; if (lx == 0) y.pb(abs(ly)); else x.pb(abs(lx)); } sort(all(x)); sort(all(y)); ld sum = 0; for (int i = 0; i < n; i++) { ld a = x[i]; ld b = y[i]; sum += sqrtl(a*a+b*b); } cout.precision(17); cout << sum << endl; } signed main() { cin.tie(0); // ios_base::sync_with_stdio(0); int t; cin >> t; while (t--) test(); int d = 0; d++; }
18.213115
100
0.562556
[ "vector" ]
6375a0b72dc4620c8598dca78936fbad7e132ad8
9,177
cpp
C++
eX0/src/InputManager.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
54
2015-03-09T08:38:12.000Z
2021-06-20T15:54:57.000Z
eX0/src/InputManager.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
7
2015-03-02T21:03:54.000Z
2017-12-21T06:06:00.000Z
eX0/src/InputManager.cpp
shurcooL/eX0
425cdd4bace184bef3b63efa0867add4e469e291
[ "MIT" ]
10
2015-03-11T06:38:38.000Z
2021-05-10T04:35:33.000Z
#include "globals.h" InputManager * g_pInputManager = NULL; InputManager * InputManager::m_pInstance = NULL; InputManager::InputManager() : m_oListeners(), m_oListenersMutex(glfwCreateMutex()), m_bIsMousePointerVisible(true), m_oJoysticks() { eX0_assert(m_pInstance == NULL, "m_pInstance wasn't == NULL, means we have more than 1 instance of InputManager, not right"); m_pInstance = this; SetGlfwCallbacks(); InitializeJoysticks(); } InputManager::~InputManager() { RemoveGlfwCallbacks(); ShowMouseCursor(); glfwDestroyMutex(m_oListenersMutex); m_pInstance = nullptr; } void InputManager::RegisterListener(InputListener * pListener) { glfwLockMutex(m_oListenersMutex); m_oListeners.push_back(pListener); glfwUnlockMutex(m_oListenersMutex); } void InputManager::UnregisterListener(InputListener * pListener) { glfwLockMutex(m_oListenersMutex); for (std::vector<InputListener *>::iterator it1 = m_oListeners.begin(); it1 != m_oListeners.end(); ++it1) if ((*it1) == pListener) { m_oListeners.erase(it1); break; } glfwUnlockMutex(m_oListenersMutex); } void InputManager::ShowMouseCursor() { m_bIsMousePointerVisible = true; glfwEnable(GLFW_MOUSE_CURSOR); } void InputManager::HideMouseCursor() { m_bIsMousePointerVisible = false; glfwDisable(GLFW_MOUSE_CURSOR); } bool InputManager::IsMousePointerVisible() { return (true == m_bIsMousePointerVisible || false == glfwGetWindowParam(GLFW_ACTIVE)); } void InputManager::SetGlfwCallbacks() { glfwSetKeyCallback(&InputManager::ProcessKey); glfwSetCharCallback(&InputManager::ProcessChar); glfwSetMouseButtonCallback(&InputManager::ProcessMouseButton); glfwSetMousePosCallback(&InputManager::ProcessMousePos); glfwSetMouseWheelCallback(&InputManager::ProcessMouseWheel); } void InputManager::RemoveGlfwCallbacks() { glfwSetKeyCallback(NULL); glfwSetCharCallback(NULL); glfwSetMouseButtonCallback(NULL); glfwSetMousePosCallback(NULL); glfwSetMouseWheelCallback(NULL); } void InputManager::InitializeJoysticks() { for (u_int nJoystick = GLFW_JOYSTICK_1; nJoystick <= GLFW_JOYSTICK_LAST; ++nJoystick) { if (GL_TRUE == glfwGetJoystickParam(nJoystick, GLFW_PRESENT)) { Joystick_t oJoystick; oJoystick.nId = nJoystick; oJoystick.nAxes = glfwGetJoystickParam(nJoystick, GLFW_AXES); oJoystick.nButtons = glfwGetJoystickParam(nJoystick, GLFW_BUTTONS); m_oJoysticks.push_back(oJoystick); std::cout << "Joystick id=" << oJoystick.nId << ": " << oJoystick.nAxes << " axes, " << oJoystick.nButtons << " buttons.\n"; } } std::cout << m_oJoysticks.size() << " joysticks initialized.\n"; } void GLFWCALL InputManager::ProcessKey(int nKey, int nAction) { //printf(" ProcessKey %d %d\n", nKey, nAction); glfwLockMutex(m_pInstance->m_oListenersMutex); for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessButton(0 /* Keyboard */, nKey, (GLFW_PRESS == nAction)); } glfwUnlockMutex(m_pInstance->m_oListenersMutex); // DEBUG: Hack, remove old behaviour eventually InputProcessKey(nKey, nAction); } void GLFWCALL InputManager::ProcessChar(int nChar, int nAction) { //printf(" ProcessChar %d %d\n", nChar, nAction); glfwLockMutex(m_pInstance->m_oListenersMutex); for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessCharacter(nChar, (GLFW_PRESS == nAction)); } glfwUnlockMutex(m_pInstance->m_oListenersMutex); // DEBUG: Hack, remove old behaviour eventually InputProcessChar(nChar, nAction); } void GLFWCALL InputManager::ProcessMouseButton(int nMouseButton, int nAction) { //printf(" ProcessMouseButton %d %d\n", nMouseButton, nAction); glfwLockMutex(m_pInstance->m_oListenersMutex); if (true == m_pInstance->IsMousePointerVisible()) { for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessMouseButton(nMouseButton, (GLFW_PRESS == nAction)); } } else { for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessButton(1000 /* Mouse */, nMouseButton, (GLFW_PRESS == nAction)); } } glfwUnlockMutex(m_pInstance->m_oListenersMutex); // DEBUG: Hack, remove old behaviour eventually InputProcessMouse(nMouseButton, nAction); } void GLFWCALL InputManager::ProcessMousePos(int nMousePosX, int nMousePosY) { //printf(" ProcessMousePos %d %d\n", nMousePosX, nMousePosY); //printf(" mouse pos x = %d, cursor visible = %d\n", nMousePosX, m_pInstance->IsMousePointerVisible() ? 1 : 0); glfwLockMutex(m_pInstance->m_oListenersMutex); static bool bPreviousMousePosSet = false; if (true == m_pInstance->IsMousePointerVisible()) { bPreviousMousePosSet = false; for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessMousePosition(nMousePosX, nMousePosY); } //printf(" pointer moved to = (%d, %d)\n", nMousePosX, nMousePosY); } else { static int nPreviousMousePosX; static int nPreviousMousePosY; if (false == bPreviousMousePosSet) { //printf(" initial mouse pos = (%d, %d)\n", nMousePosX, nMousePosY); nPreviousMousePosX = nMousePosX; nPreviousMousePosY = nMousePosY; bPreviousMousePosSet = true; } else { int nMouseMovedX = nMousePosX - nPreviousMousePosX; int nMouseMovedY = nMousePosY - nPreviousMousePosY; nPreviousMousePosX = nMousePosX; nPreviousMousePosY = nMousePosY; for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessSlider(1000 /* Mouse */, 0 /* Mouse X Axis */, static_cast<double>(nMouseMovedX)); (*it1)->ProcessSlider(1000 /* Mouse */, 1 /* Mouse Y Axis */, static_cast<double>(nMouseMovedY)); } } } glfwUnlockMutex(m_pInstance->m_oListenersMutex); } void GLFWCALL InputManager::ProcessMouseWheel(int nMouseWheelPosition) { //printf(" ProcessMouseWheel %d\n", nMouseWheelPosition); glfwLockMutex(m_pInstance->m_oListenersMutex); if (true == m_pInstance->IsMousePointerVisible()) { } else { static int nPreviousMouseWheelPosition; int nMouseWheelMoved = nMouseWheelPosition - nPreviousMouseWheelPosition; nPreviousMouseWheelPosition = nMouseWheelPosition; for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->ProcessSlider(1000 /* Mouse */, 2 /* Mouse Wheel */, nMouseWheelMoved); } } glfwUnlockMutex(m_pInstance->m_oListenersMutex); } void InputManager::ProcessJoysticks() { glfwLockMutex(m_pInstance->m_oListenersMutex); int nDevice = 2000; // Joystick for (std::vector<Joystick_t>::iterator it1 = m_oJoysticks.begin(); it1 != m_oJoysticks.end(); ++nDevice) { Joystick_t oJoystick = *it1; float * pJoystickPos = new float[oJoystick.nAxes]; u_char * pJoystickButtons = new u_char[oJoystick.nButtons]; int nReturnedAxes = glfwGetJoystickPos(oJoystick.nId, pJoystickPos, oJoystick.nAxes); int nReturnedButtons = glfwGetJoystickButtons(oJoystick.nId, pJoystickButtons, oJoystick.nButtons); for (u_int nAxis = 0; nAxis < oJoystick.nAxes; ++nAxis) { for (std::vector<InputListener *>::reverse_iterator it2 = m_pInstance->m_oListeners.rbegin(); it2 != m_pInstance->m_oListeners.rend(); ++it2) { (*it2)->ProcessAxis(nDevice /* Joystick Number */, nAxis /* Axis Number */, pJoystickPos[nAxis] /* Axis Position */); } } for (u_int nButton = 0; nButton < oJoystick.nButtons; ++nButton) { for (std::vector<InputListener *>::reverse_iterator it2 = m_pInstance->m_oListeners.rbegin(); it2 != m_pInstance->m_oListeners.rend(); ++it2) { (*it2)->ProcessButton(nDevice /* Joystick Number */, nButton /* Button Number */, (GLFW_PRESS == pJoystickButtons[nButton]) /* Button Pressed */); } } delete[] pJoystickPos; delete[] pJoystickButtons; if (0 == nReturnedAxes && 0 == nReturnedButtons) { // Joystick no longer functional/connected std::cout << "WARNING: Joystick id=" << oJoystick.nId << " has been disconnected.\n"; it1 = m_oJoysticks.erase(it1); } else ++it1; } glfwUnlockMutex(m_pInstance->m_oListenersMutex); } void InputManager::TimePassed(double dTimePassed) { glfwLockMutex(m_pInstance->m_oListenersMutex); for (std::vector<InputListener *>::reverse_iterator it1 = m_pInstance->m_oListeners.rbegin(); it1 != m_pInstance->m_oListeners.rend(); ++it1) { (*it1)->TimePassed(dTimePassed); } glfwUnlockMutex(m_pInstance->m_oListenersMutex); }
30.287129
151
0.705786
[ "vector" ]
638541012ecc08d91973e40c481312d7107beab4
6,015
hpp
C++
DirectXer/src/Containers.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
DirectXer/src/Containers.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
DirectXer/src/Containers.hpp
palikar/DirectXer
c21b87eed220fc54d97d5363e8a33bd0944a2596
[ "MIT" ]
null
null
null
#pragma once #include <robin_hood.h> #include <Utils.hpp> #include <Types.hpp> #include <Config.hpp> #include <Logging.hpp> #include <GraphicsCommon.hpp> #include <Tags.hpp> template<class T, class Allocator> class Vector : public Allocator { public: /* ----- Constructors ----- */ // Default constructor Vector() : Count(0), Data(0), Size(0) {}; explicit Vector(size_t s) : Count(s) , Data(Allocator::allocate(s)) , Size(s) { for (size_t index = 0; index < Count; ++index) Data[index] = T(); } /* -------- ITERATORS --------*/ T* begin() { return &Data[0]; } const T* begin() const { return &Data[0]; } T* end() { return &Data[Count]; } const T* end() const { return &Data[Count]; } const T* cbegin() const { return &Data[0]; } const T* cend() const { return &Data[Count]; } /*----------------------------*/ /* -------- CAPACITY -------- */ inline bool empty() const { return (Count == 0); } inline bool full() const { return (Count == Size); } // Returns size of allocated storate capacity inline size_t capacity() const { return Size; } // Requests a change in capacity // reserve() will never decrase the capacity. inline void reserve(size_t newmalloc) { T* p = Allocator::allocate(newmalloc); memcpy(p, Data, Count * sizeof(T)); Data = p; Size = newmalloc; } // Changes the Vector's size. // If the newsize is smaller, the last elements will be lost. // Has a default value param for custom values when resizing. inline void resize(size_t newsize, T val = T()) { reserve(newsize); for (size_t index = Count; index < newsize; ++index) Data[index] = T(); Count = newsize; } // Returns the size of the Vector (number of elements). inline size_t size() const { return Count; } /*----------------------------*/ /* -------- MODIFIERS --------*/ // Removes all elements from the Vector // Capacity is not changed. inline void clear() { Count = 0; } // Inserts element at the back inline void push_back(const T& d) { Assert(Size != 0, "Your code is bad. Please reserve something before using the vector"); if (Count == Size) reserve(2 * Size); Data[Count] = d; ++Count; } inline void insert(const T*, std::initializer_list<T> elements) { for (const auto e : elements) { push_back(e); } } inline void insertAt(size_t index, T element) { Assert(Size != 0, "Your code is bad. Please reserve something before using the vector"); if (Count == Size) reserve(2 * Size); // memcpy(Data + index + 1, Data + index, sizeof(T)*(Count - index)); for (size_t i = Count; i > index; --i) { Data[i] = Data[i - 1]; } Data[index] = element; ++Count; } // Removes the last element from the Vector inline void pop_back() { --Count; } inline T* erase(T* ptr) { Assert(ptr >= Data && ptr <= (Data + Count), "This is not a pointer into the vector"); size_t start = ptr - Data == 0 ? 0 : ptr - Data - 1; for (size_t i = start; i < Count - 1; ++i) { Data[i] = Data[i + 1]; } Count -= 1; return Data + start; } inline T* erase_fast(T* ptr) { Assert(ptr >= Data && ptr <= (Data + Count), "This is not a pointer into the vector"); size_t start = ptr - Data; Data[start] = Data[Count - 1]; Count -= 1; return ptr; } inline void erase(const T* start, const T* end) { if (start == end) return; Assert(end >= Data && end <= (Data + Count), ""); Assert(start >= Data && start <= (Data + Count), ""); Count -= (end - start); } /*----------------------------*/ /* ----- ELEMENT ACCESS ----- */ // Access elements with bounds checking inline T& at(size_t n) { if (n < 0 || Count <= n) Assert(false, ""); return Data[n]; } // Access elements with bounds checking for constant Vectors. inline const T& at(size_t n) const { if (n < 0 || Count <= n) Assert(false, ""); return Data[n]; } // Access elements, no bounds checking inline T& operator[](size_t i) { return Data[i]; } // Access elements, no bounds checking inline const T& operator[](size_t i) const { return Data[i]; } // Returns a reference to the first element inline T& front() { return Data[0]; } // Returns a reference to the first element inline const T& front() const { return Data[0]; } // Returns a reference to the last element inline T& back() { return Data[Count - 1]; } // Returns a reference to the last element inline const T& back() const { return Data[Count - 1]; } // Returns a pointer to the array used by Vector inline T* data() { return Data; } // Returns a pointer to the array used by Vector inline const T* data() const { return Data; } /*----------------------------*/ size_t Count; // Number of elements in Vector T* Data; // Pointer to first element of Vector size_t Size; // Total space used by Vector including // elements and free space. }; #if USE_CUSTOM_ALLOCATORS template<class T> using TempVector = Vector<T, TempStdAllocator<T>>; template<class T, SystemTag Tag = Tag_Unknown> using BulkVector = Vector<T, BulkStdAllocator<T, Tag>>; template<class T, SystemTag Tag = Tag_Unknown> using MallocVector = Vector<T, MallocStdAllocator<T, Tag>>; using String = std::string_view; template<class Key, class Value, SystemTag Tag = Tag_Unknown> using Map = robin_hood::unordered_map<Key, Value, RobinAllocator<Tag>>; #else #include <vector> #include <string> template<class T> using TempVector = std::vector<T>; template<class T> using BulkVector = std::vector<T>; using String = std::string_view; template<class Key, class Value> using Map = robin_hood::unordered_map<Key, Value>; #endif inline String CopyStringInMemory(char* memory, String str) { memcpy(memory, str.data(), str.size()); return {memory, str.size()}; } inline String CopyStringInMemoryAndIncrement(char*& memory, String str) { memcpy(memory, str.data(), str.size()); char* beg = memory; memory += str.size(); return {beg, str.size()}; }
18.680124
90
0.61995
[ "vector" ]
b0cc1e322c52c358eed948d9a917c542f54d9156
1,378
cpp
C++
043-multiply-strings/multiply-strings.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
043-multiply-strings/multiply-strings.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
2
2021-03-31T19:10:41.000Z
2021-12-13T19:58:15.000Z
043-multiply-strings/multiply-strings.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
// Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. // // Example 1: // // // Input: num1 = "2", num2 = "3" // Output: "6" // // Example 2: // // // Input: num1 = "123", num2 = "456" // Output: "56088" // // // Note: // // // The length of both num1 and num2 is < 110. // Both num1 and num2 contain only digits 0-9. // Both num1 and num2 do not contain any leading zero, except the number 0 itself. // You must not use any built-in BigInteger library or convert the inputs to integer directly. // // static const auto _=[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: string multiply(string num1, string num2) { if(num1=="0"||num2=="0") return "0"; int n1=num1.size(),n2=num2.size(); vector<int> res(n1+n2,0); int r1,r2,sum; for(int i=n1-1;i>=0;--i){ r1=num1[i]-'0'; for(int j=n2-1;j>=0;--j){ r2=num2[j]-'0'; sum=r1*r2+res[i+j+1]; res[i+j+1]=sum%10; res[i+j]+=sum/10; } } string res1; int i=0; while(res[i]==0) ++i; while(i<n1+n2){ res1+=res[i]+'0'; ++i; } return res1; } };
23.355932
140
0.513788
[ "vector" ]
b0d436996f0e9b3bd61b1b345c7b7956cdf8faea
2,849
cpp
C++
test/memoryfile.cpp
bfierz/vcl.filesystem
bcbf19a465fefe7d9998839dc0be4f6fccb5e316
[ "MIT" ]
null
null
null
test/memoryfile.cpp
bfierz/vcl.filesystem
bcbf19a465fefe7d9998839dc0be4f6fccb5e316
[ "MIT" ]
null
null
null
test/memoryfile.cpp
bfierz/vcl.filesystem
bcbf19a465fefe7d9998839dc0be4f6fccb5e316
[ "MIT" ]
null
null
null
/* * This file is part of the Visual Computing Library (VCL) release under the * MIT license. * * Copyright (c) 2014-2016 Basil Fierz * * 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. */ // VCL configuration #include <vcl/config/global.h> // C++ standard library #include <algorithm> // Include the relevant parts from the library #include <vcl/filesystem/mountpoints/memorymountpoint.h> #include <vcl/filesystem/util/memoryfile.h> #include <vcl/filesystem/filesystem.h> // Google test #include <gtest/gtest.h> TEST(MemoryFileTest, SimpleMemoryFileRW) { using namespace Vcl::FileSystem::Util; // Data to test std::vector<uint32_t> ref(4000); int n = { 0 }; std::generate(ref.begin(), ref.end(), [&n] { return n++; }); // Write the data to the memory file MemoryFile mem_file{ "SampleFile" }; mem_file.write(0, ref.data(), ref.size() * sizeof(uint32_t)); // Read the data back std::vector<uint32_t> read_back(4000); mem_file.read(0, read_back.data(), read_back.size() * sizeof(uint32_t)); EXPECT_TRUE(std::equal(ref.begin(), ref.end(), read_back.begin(), read_back.end())); } TEST(MemoryFileTest, SimpleMemoryFileInFileSystem) { using namespace Vcl::FileSystem; FileSystem fs; fs.addMountPoint(std::make_unique<MemoryMountPoint>("Basics", "/")); // Data to test std::vector<uint32_t> ref(4000); int n = { 0 }; std::generate(ref.begin(), ref.end(), [&n] { return n++; }); // Write the data to the memory file auto writer = fs.createWriter("/SampleFile"); writer->write(ref.data(), ref.size() * sizeof(uint32_t)); // Read the data back std::vector<uint32_t> read_back(4000); auto reader = fs.createReader("/SampleFile"); reader->read(read_back.data(), read_back.size() * sizeof(uint32_t)); EXPECT_TRUE(std::equal(ref.begin(), ref.end(), read_back.begin(), read_back.end())); }
33.517647
85
0.723763
[ "vector" ]
b0d5d183b49b1aea5c594c4e7c8781aa744615d7
568
cpp
C++
math/linear_phi.cpp
warwick965/competitive-programming
78074365eff204b0331410a98f32cf41962e9644
[ "MIT" ]
6
2020-04-08T00:25:44.000Z
2021-09-04T20:39:15.000Z
math/linear_phi.cpp
warwick965/competitive-programming
78074365eff204b0331410a98f32cf41962e9644
[ "MIT" ]
2
2020-04-09T06:59:12.000Z
2020-04-09T14:56:32.000Z
math/linear_phi.cpp
warwick965/competitive-programming
78074365eff204b0331410a98f32cf41962e9644
[ "MIT" ]
6
2020-04-16T03:47:06.000Z
2021-09-07T10:21:32.000Z
#include <bits/stdc++.h> using namespace std; #define N (int)1e6 int phi[N+1]; void sieve(){ for(int i = 1;i <= N;i++) phi[i] = i-1; phi[1] = 1; vector<int>primes; for(int i = 2;i <= N;i++){ if (phi[i] == i-1) primes.push_back(i); for(auto p:primes){ if (i*p > N) break; if (i%p == 0){ phi[i*p] = phi[i]*p; break; } phi[i*p] = phi[i]*phi[p]; } } } int main(){ sieve(); int x;cin>>x; cout << phi[x] << endl; return 0; }
15.777778
47
0.40669
[ "vector" ]
b0d6d373efd0dcf00d966339b702d03a7733fa50
3,197
cpp
C++
main.cpp
Hiroaki-Tanaka-0606/CGSolve
1fa04a46e3025febfb67e23d50686e82118dd433
[ "MIT" ]
null
null
null
main.cpp
Hiroaki-Tanaka-0606/CGSolve
1fa04a46e3025febfb67e23d50686e82118dd433
[ "MIT" ]
null
null
null
main.cpp
Hiroaki-Tanaka-0606/CGSolve
1fa04a46e3025febfb67e23d50686e82118dd433
[ "MIT" ]
null
null
null
#include <stdio.h> #include "matrix_util.h" #include "CGSolve.h" #include <time.h> extern "C"{ void dgesv_(int* N, int* NRHS, double* A, int* LDA, int* IPIV, double* B, int* LDB, int* INFO); } const char* format="%12.5f "; int main(){ int N=160; double threshold=1e-10; int iterMax=1000; double** A=alloc_dmatrix(N,N); double* b=alloc_dvector(N); double* x=alloc_dvector(N); double* alpha=alloc_dvector(iterMax); double* beta=alloc_dvector(iterMax); double** r=alloc_dmatrix(iterMax,N); int iteration=0; int i,j; for(i=0;i<N;i++){ for(j=0;j<N;j++){ if(i==j){ A[i][j]=2; }else if(i==j-1 || i==j+1){ A[i][j]=1; }else{ A[i][j]=0; } } if(i==0){ b[i]=1; }else{ b[i]=0; } //b[i]=i+1; x[i]=0; } //print matrix A printf("A: %d * %d matrix\n",N,N); for(i=0;i<N;i++){ for(j=0;j<N;j++){ printf(format,A[i][j]); } printf("\n"); } //print vector b printf("b: %d * 1 vector\n",N); printf("transposed: "); for(i=0;i<N;i++){ printf(format,b[i]); } printf("\n\n"); //solve Ax=b by CG method printf("Solve A*x=b by CG method\n"); bool verbose=true; CGSolve(&N,A,b,&threshold,&iterMax,&iteration,x,alpha,beta,r,&verbose); printf("Calculation end with %d iterations\n",iteration); if(iteration==iterMax){ printf("Solution is not converged\n"); } printf("Solution: x(transposed)="); for(i=0;i<N;i++){ printf(format,x[i]); } printf("\n\n"); //solve Ax=b by LAPACK printf("Solve A*x=b by LAPACK dgesv\n"); int NRHS=1; int INFO; int* IPIV=alloc_ivector(N); dgesv_(&N, &NRHS, &A[0][0], &N, &IPIV[0], &b[0], &N, &INFO); if(INFO==0){ printf("Solution: x(transposed)="); for(i=0;i<N;i++){ printf(format,b[i]); } printf("\n"); }else{ printf("Not Successful\n"); } //solve (A+sI)x=b by shifted CG method printf("Solve (A+sI)x=b by shifted CG method\n"); double s=0; double ds=0.0001; int count=100000; int t; printf("s=%.5f+%.5ft, t=1 to %d\n",s,ds,count); clock_t start=clock(); for(t=0;t<count;t++){ s+=ds; ShiftedCGSolve(&N,alpha,beta,r,&iteration,&s,x); /* printf("s=%.3f, Solution: x(transposed)=",s); for(i=0;i<N;i++){ printf(format,x[i]); } printf("\n");*/ } clock_t end=clock(); double time=static_cast<double>(end-start)/CLOCKS_PER_SEC; printf("Calculation end\n"); printf("Time: "); printf(format,time); printf(" sec.\n"); //solve (A+sI)x=b by LAPACk printf("Solve (A+sI)x=b by LAPACK dgesv\n"); s=0; printf("s=%.5f+%.5ft, t=1 to %d\n",s,ds,count); start=clock(); for(t=0;t<count;t++){ s+=ds; for(i=0;i<N;i++){ for(j=0;j<N;j++){ if(i==j){ A[i][j]=2+s; }else if(i==j-1 || i==j+1){ A[i][j]=1; }else{ A[i][j]=0; } } if(i==0){ b[i]=1; }else{ b[i]=0; } //b[i]=i+1; } dgesv_(&N, &NRHS, &A[0][0], &N, &IPIV[0], &b[0], &N, &INFO); /* if(INFO==0){ printf("s=%.3f, Solution: x(transposed)=",s); for(i=0;i<N;i++){ printf(format,b[i]); } printf("\n"); }else{ printf("Not Successful\n"); }*/ } end=clock(); time=static_cast<double>(end-start)/CLOCKS_PER_SEC; printf("Calculation end\n"); printf("Time: "); printf(format,time); printf(" sec.\n"); }
19.259036
96
0.560213
[ "vector" ]
b0dd6b7a37c94c586cbd99ca796ff9527d272387
10,927
cpp
C++
simulation.cpp
GabriellaXue/Cashier-Line-Sim
ae0984e02db0df40aa7d0effcad45e1039712614
[ "MIT" ]
1
2021-04-14T10:06:50.000Z
2021-04-14T10:06:50.000Z
simulation.cpp
GabriellaXue/Cashier-Line-Sim
ae0984e02db0df40aa7d0effcad45e1039712614
[ "MIT" ]
1
2021-04-13T15:59:43.000Z
2021-04-13T15:59:43.000Z
simulation.cpp
GabriellaXue/Cashier-Line-Sim
ae0984e02db0df40aa7d0effcad45e1039712614
[ "MIT" ]
null
null
null
/** * @file simulation.cpp * Implementation of Simulation class which is used to handle cashier simulation. */ #include <vector> using std::vector; #include <tuple> using std::tuple; #include <string> using std::string; #include <iostream> using std::cout; using std::endl; #include <queue> using std::queue; #include <list> using std::list; #include <algorithm> using std::make_heap; using std::reverse; using std::sort_heap; #include <utility> using std::pair; using std::make_pair; #include <sstream> #include <map> using std::map; /** * Constructs a Simulation with registers number and customer list. * Intialize register queue as empty for all the registers. * NOTE: register number is one indexed for register queue. * @param numReg number of registers * @param customerLs list of customer with format ({customer type}, {time arrive}, {number of items}) */ Simulation::Simulation(int numReg, queue< tuple<string, int, int> > customerLs) { numRegister_ = numReg; customerList_ = customerLs; for (int i = 0; i < numRegister_; i++) { regQueue_.push_back(make_pair(0, std::to_string(i+1))); queue<Customer> newQueue; regMap_[i + 1] = newQueue; } make_heap(regQueue_.begin(), regQueue_.end()); reverse(regQueue_.begin(), regQueue_.end()); } /** * Time is measured in minutes. * * The training cashier is assign to the highest number register. * * Regular cashier takes one minute to process each item, * while training cashier takes two. * * Simulation starts at t = 0, while all registers are empty. * * Customer type: * A: choose the shortest line * B: choose empty line, or check last customer item number, the less the better * * Customers finish checking out are not in line. * * If customers arrive at the same time, who has less items choose line first. * It same number of items, A choose first. */ int Simulation::simulate() { while (!customerList_.empty()) { vector<Simulation::Customer> waitToServe = serveNext(); sortItemNum(waitToServe, 0, waitToServe.size() - 1); list<Customer> tmpList; int count = 1; for (auto customer : waitToServe) { if (customer.itemNum == count) { if (customer.type.compare("A") == 0) { tmpList.push_front(customer); } else { tmpList.push_back(customer); } } else { processService(tmpList); tmpList.clear(); count ++; if (customer.type.compare("A") == 0) { tmpList.push_front(customer); } else { tmpList.push_back(customer); } } } processService(tmpList); tmpList.clear(); } return checkTime(); } /** * Check the time in each register line and output the longest one. * @return return the longest time. */ int Simulation::checkTime() { int longestTime = 0; for (auto it = regMap_.begin(); it != regMap_.end(); it ++) { queue<Customer> toCheck = it->second; Simulation::Customer currCustomer = toCheck.front(); int begin = currCustomer.arrivalT; begin += currCustomer.processingT; toCheck.pop(); while(!toCheck.empty()) { currCustomer = toCheck.front(); if (begin >= currCustomer.arrivalT) { } else { begin = currCustomer.arrivalT; } begin += currCustomer.processingT; toCheck.pop(); } longestTime = (longestTime < begin) ? begin : longestTime; } printInfo(longestTime); return longestTime; } /** * Enqueue customer according to the type requirement. * @param tmpList current customer list within the same timestamp */ void Simulation::processService(list<Simulation::Customer> tmpList) { for (auto customer : tmpList) { // check if could pop for (auto it = regMap_.begin(); it != regMap_.end(); it ++) { queue<Customer> toCheck = it->second; if (toCheck.empty()) { continue; } Simulation::Customer currCustomer = toCheck.front(); if (currCustomer.arrivalT + currCustomer.processingT <= customer.arrivalT) { toCheck.pop(); // update the `regQueue_` as well for (int i = 0; i < regQueue_.size(); i++) { if (regQueue_[i].second.compare(std::to_string(it->first)) == 0) { regQueue_[i].first --; } } } } pair<int, string> potentialPos = regQueue_.front(); stringstream str(potentialPos.second); int toInt = 0; str >> toInt; pair<int, string> bestPos; // avoid using training register if there are other available ones bool found = false; if (toInt == numRegister_) { int tmp = potentialPos.first; for (auto item : regQueue_) { if (item.first == tmp && item.second.compare(potentialPos.second)) { bestPos = item; found = true; break; } } if (!found) { bestPos = potentialPos; } } else { bestPos = potentialPos; } stringstream tmpStr(bestPos.second); int tmpInt = 0; tmpStr >> tmpInt; if (customer.type.compare("A") == 0) { customer.processingT = (tmpInt == numRegister_) ? customer.itemNum * 2 : customer.itemNum; customer.currReg = bestPos.second; customer.waitNum = bestPos.first; regMap_[tmpInt].push(customer); for (int i = 0; i < regQueue_.size(); i++) { if (regQueue_[i].second.compare(bestPos.second) == 0) { regQueue_[i].first ++; } } sort_heap(regQueue_.begin(), regQueue_.end()); } else { if (bestPos.first == 0) { customer.processingT = (tmpInt == numRegister_) ? customer.itemNum * 2 : customer.itemNum; customer.currReg = bestPos.second; customer.waitNum = 0; regMap_[tmpInt].push(customer); for (int i = 0; i < regQueue_.size(); i++) { if (regQueue_[i].second.compare(bestPos.second) == 0) { regQueue_[i].first ++; } } sort_heap(regQueue_.begin(), regQueue_.end()); } else { int minItem = 0; int bestLine = numRegister_; for (auto it = regMap_.begin(); it != regMap_.end(); it++) { Simulation::Customer lastCustomer = it->second.back(); if (lastCustomer.itemNum == minItem) { if (it->first < bestLine) { bestLine = it->first; } } else if (lastCustomer.itemNum == minItem) { minItem = lastCustomer.itemNum; bestLine = it->first; } } customer.processingT = (bestLine == numRegister_) ? customer.itemNum * 2 : customer.itemNum; customer.currReg = bestLine; customer.waitNum = regMap_[bestLine].size(); regMap_[bestLine].push(customer); for (int i = 0; i < regQueue_.size(); i++) { if (regQueue_[i].second.compare(std::to_string(bestLine)) == 0) { regQueue_[i].first ++; sort_heap(regQueue_.begin(), regQueue_.end()); } } } } } } /** * Sort customer list based on item number. * @param toSort a list of customer to be sorted. */ void Simulation::sortItemNum(vector<Simulation::Customer> &toSort, int start, int end) { if (start >= end) return; int mid = (end + start) / 2; int pivot = partition(toSort, start, end, mid); sortItemNum(toSort, start, pivot - 1); sortItemNum(toSort, pivot + 1, end); } /** * A utility function to swap two values. */ void Simulation::swap(Simulation::Customer& a, Simulation::Customer& b) { unsigned long tmpId = a.id; string tmpType = a.type; int tmpItemNum = a.itemNum; int tmpTime = a.arrivalT; a.id = b.id; a.type = b.type; a.itemNum = b.itemNum; a.arrivalT = b.arrivalT; b.id = tmpId; b.type = tmpType; b.itemNum = tmpItemNum; b.arrivalT = tmpTime; } /** * This function takes the middle element as pivot, * places the pivot element at its correct position in sorted array, * and places all smaller (smaller than pivot) to left of pivot * and all greater elements to right of pivot. * * @param toSort a list of value to be partitioned. * @param start the begin idx of the list. * @param end the end idx of the list. * @param pivotIdx the pivot idx of the list. * @return the pivotIdx after sorting */ int Simulation::partition(vector<Simulation::Customer> &toSort, int start, int end, int pivotIdx) { int pivotVal = toSort[pivotIdx].itemNum; Simulation::swap(toSort[pivotIdx], toSort[end]); int storeIdx = start; for (int i = start; i < end; i++) { if (toSort[i].itemNum > pivotVal) { Simulation::swap(toSort[i], toSort[storeIdx]); storeIdx++; } } Simulation::swap(toSort[storeIdx], toSort[end]); return storeIdx; } /** * Customers waiting to be served at the same time. * @return a list of current waiting customers. */ vector<Simulation::Customer> Simulation::serveNext() { int currTime = 0; vector<Simulation::Customer> sameTimeArrival; while (!customerList_.empty()) { tuple<string, int, int> currCustomer = customerList_.front(); int customerTime = std::get<1>(currCustomer); if (currTime == 0) { currTime = customerTime; } else if (customerTime != currTime) { break; } unsigned long uid = generateId(); string customerType = std::get<0>(currCustomer); int itemNumber = std::get<2>(currCustomer); Simulation::Customer newCustomer(uid, customerType, itemNumber, customerTime); sameTimeArrival.push_back(newCustomer); customerList_.pop(); } return sameTimeArrival; } /** * Output simulation info. * @param num a time integer. */ void Simulation::printInfo(int num) { std::cout << "Finished at: t=" << num << " " << "minutes" << std::endl; } /** * Generate unique id for each customer. * @return A customer id. */ unsigned long Simulation::generateId() { return ++uid; }
32.715569
108
0.565297
[ "vector" ]
b0ddf5c0d57e89052d5127205e66dbf24ffd16be
1,295
cpp
C++
leetcode/isIdealPermutation.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/isIdealPermutation.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
leetcode/isIdealPermutation.cpp
jcpince/algorithms
c43dd8e98a0f0df691ead5f25c2c17a9241db908
[ "MIT" ]
null
null
null
/* 775. Global and Local Inversions Medium We have some permutation A of [0, 1, ..., N - 1], where N is the length of A. The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j]. The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1]. Return true if and only if the number of global inversions is equal to the number of local inversions. Example 1: Input: A = [1,0,2] Output: true Explanation: There is 1 global inversion, and 1 local inversion. Example 2: Input: A = [1,2,0] Output: false Explanation: There are 2 global inversions, and 1 local inversion. Note: A will be a permutation of [0, 1, ..., A.length - 1]. A will have length in range [1, 5000]. The time limit for this problem has been reduced. Test cases: [0] [1,0,2] [1,2,0] [0,2,1,4,3] [2,1,0] */ /* Idea: Check that all permutations are local*/ class Solution { public: bool isIdealPermutation(vector<int>& A) { vector<int>::iterator it = A.begin(); int prev = *it++, idx = 1; if (prev > 1) return false; while (it != A.end()) { if (*it > (idx+1)) return false; if (*it < (prev-1)) return false; prev = *it++; idx++; } return true; } };
23.545455
102
0.598456
[ "vector" ]
b0df80d6c14f1547d12c77b363087e6872b16108
1,310
cpp
C++
generative-adversarial-network/src/Application.cpp
tautvydass/vu-coursework
604e8e38b14849b832782d45f7321cc8b2275b5f
[ "Apache-2.0" ]
1
2019-04-16T09:49:35.000Z
2019-04-16T09:49:35.000Z
generative-adversarial-network/src/Application.cpp
tautvydass/vu-coursework
604e8e38b14849b832782d45f7321cc8b2275b5f
[ "Apache-2.0" ]
null
null
null
generative-adversarial-network/src/Application.cpp
tautvydass/vu-coursework
604e8e38b14849b832782d45f7321cc8b2275b5f
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <armadillo> #include "utils/ImageUtils.h" #include "utils/Benchmark.h" #include "models/neural-network-model/discriminator/ArtDiscriminatorModel.h" #include "models/neural-network-model/generator/ArtGeneratorModel.h" #define LOG(x) std::cout << x << std::endl; #define IMAGE_SIZE 64 #define INPUT_LENGTH IMAGE_SIZE * IMAGE_SIZE * 3 #define GENERATOR_HIDDEN_LAYER_NODE_COUNT 128 #define DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT 64 using namespace arma; void testDiscriminator() { ArtDiscriminatorModel* model = new ArtDiscriminatorModel(INPUT_LENGTH); model->addHiddenLayer(DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT); model->addHiddenLayer(DISCRIMINATOR_HIDDEN_LAYER_NODE_COUNT); model->init(); ArtDiscriminatorModelResult* result = model->discriminateArt(randu<vec>(INPUT_LENGTH)); delete result; delete model; } void testGenerator() { ArtGeneratorModel* model = new ArtGeneratorModel(INPUT_LENGTH); model->addHiddenLayer(GENERATOR_HIDDEN_LAYER_NODE_COUNT); model->addHiddenLayer(GENERATOR_HIDDEN_LAYER_NODE_COUNT); model->init(); vec result = model->calculate(randu<vec>(INPUT_LENGTH)); delete model; } int main() { Benchmark::run(testDiscriminator, 5, "Discriminator Test"); Benchmark::run(testGenerator, 5, "Generator Test"); system("PAUSE"); return 0; }
25.192308
88
0.79084
[ "model" ]
b0e792364b24107d35710dcc2512fb823ee11e86
8,095
cpp
C++
src/lib/operators/jit_operator/specialization/llvm_extensions.cpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
2
2019-05-28T12:09:04.000Z
2019-05-29T08:18:43.000Z
src/lib/operators/jit_operator/specialization/llvm_extensions.cpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
69
2019-05-24T10:01:32.000Z
2019-12-13T19:09:05.000Z
src/lib/operators/jit_operator/specialization/llvm_extensions.cpp
nilsthamm/hyrise
75a701f281bb7dc1636832012c43005ec3c66384
[ "MIT" ]
null
null
null
#include "llvm_extensions.hpp" #include <llvm/Analysis/ConstantFolding.h> #include <llvm/IR/Constants.h> #include <unordered_set> #include "jit_runtime_pointer.hpp" #pragma clang diagnostic ignored "-Wshadow-all" #pragma clang diagnostic ignored "-Wmissing-prototypes" namespace opossum { const std::shared_ptr<const JitRuntimePointer>& GetRuntimePointerForValue(const llvm::Value* value, // NOLINT SpecializationContext& context) { // If the value exists in the value map, use the mapped value (i.e., the value in the cloned function) for the lookup auto mapped_value = value; if (context.llvm_value_map.count(value)) { mapped_value = context.llvm_value_map.lookup(value); } // Try serving results from cache if (context.runtime_value_map.count(mapped_value)) { return context.runtime_value_map[mapped_value]; } if (const auto constant_expr = llvm::dyn_cast<llvm::ConstantExpr>(mapped_value)) { // Case 1: The value is an IntToPtr instruction embedded in a ConstExpr: // This type of instruction casts a constant integer value to a pointer // Take the constant integer from the instruction (operand 0), and convert it to a constant runtime pointer if (constant_expr->getType()->isPointerTy()) { if (constant_expr->getOpcode() == llvm::Instruction::IntToPtr) { if (const auto address = llvm::dyn_cast<llvm::ConstantInt>(constant_expr->getOperand(0))) { context.runtime_value_map[mapped_value] = std::make_shared<JitConstantRuntimePointer>(address->getValue().getLimitedValue()); } } } } else if (const auto load_inst = llvm::dyn_cast<llvm::LoadInst>(mapped_value)) { if (load_inst->getType()->isPointerTy()) { // Case 2: The value is a Load instruction: // Try to resolve the pointer this instruction loads its value from and create a runtime pointer object from it if (const auto base = std::dynamic_pointer_cast<const JitKnownRuntimePointer>( GetRuntimePointerForValue(load_inst->getPointerOperand(), context))) { context.runtime_value_map[mapped_value] = std::make_shared<JitDereferencedRuntimePointer>(base); } } } else if (const auto get_element_ptr_inst = llvm::dyn_cast<llvm::GetElementPtrInst>(mapped_value)) { // Case 3: The value is a GetElementPtr instruction: // Try to get 1) the constant offset this instructions applies, and 2) the pointer the offset is applied to // If both values can be obtained create a corresponding runtime pointer object llvm::APInt offset(64, 0); if (get_element_ptr_inst->accumulateConstantOffset(context.module->getDataLayout(), offset)) { if (const auto base = std::dynamic_pointer_cast<const JitKnownRuntimePointer>( GetRuntimePointerForValue(get_element_ptr_inst->getPointerOperand(), context))) { context.runtime_value_map[mapped_value] = std::make_shared<JitOffsetRuntimePointer>(base, offset.getLimitedValue()); } } } else if (const auto bitcast_inst = llvm::dyn_cast<llvm::BitCastInst>(mapped_value)) { // Case 3: The value is a BitCast instruction: // BitCast instructions only change the type, but never the value of a pointer value. // We can thus ignore the type-cast and simply continue with the pointer operand if (const auto base = std::dynamic_pointer_cast<const JitKnownRuntimePointer>( GetRuntimePointerForValue(bitcast_inst->getOperand(0), context))) { context.runtime_value_map[mapped_value] = std::make_shared<JitOffsetRuntimePointer>(base, 0L); } } // If we could not resolve the value until here we mark it as unresolvable in the runtime value map to prevent further // resolution attempts if (!context.runtime_value_map.count(mapped_value)) { context.runtime_value_map[mapped_value] = std::make_shared<JitRuntimePointer>(); } return context.runtime_value_map[mapped_value]; } // Preforms constant folding (i.e., recursively simplifies operations on constant values by simulating the operation and // substituting the computation with the constant result) llvm::Constant* ConstantFoldInstruction(llvm::Instruction* inst, llvm::ArrayRef<llvm::Constant*> operands, // NOLINT const llvm::DataLayout& data_layout, const llvm::TargetLibraryInfo* target_library_info) { // PHI nodes cannot be constant folded if (auto* phi_node = llvm::dyn_cast<llvm::PHINode>(inst)) { return nullptr; } // Load Instructions cannot be constant folded if (const auto* load_inst = llvm::dyn_cast<llvm::LoadInst>(inst)) { return nullptr; } // Individually handle instructions that are not captured by the generic llvm::ConstantFoldInstOperands function if (const auto* compare_inst = llvm::dyn_cast<llvm::CmpInst>(inst)) { return llvm::ConstantFoldCompareInstOperands(compare_inst->getPredicate(), operands[0], operands[1], data_layout, target_library_info); } else if (auto* insert_value_inst = llvm::dyn_cast<llvm::InsertValueInst>(inst)) { return llvm::ConstantExpr::getInsertValue(llvm::cast<llvm::Constant>(insert_value_inst->getAggregateOperand()), llvm::cast<llvm::Constant>(insert_value_inst->getInsertedValueOperand()), insert_value_inst->getIndices()); } else if (auto* extract_value_inst = llvm::dyn_cast<llvm::ExtractValueInst>(inst)) { return llvm::ConstantExpr::getExtractValue(llvm::cast<llvm::Constant>(extract_value_inst->getAggregateOperand()), extract_value_inst->getIndices()); } // Forward all other cases to LLVM return llvm::ConstantFoldInstOperands(inst, operands, data_layout, target_library_info); } llvm::Constant* ResolveConditionRec(llvm::Value* value, SpecializationContext& context, // NOLINT std::unordered_set<llvm::Value*>& failed) { // If resolving the value failed already we fail early here if (failed.count(value)) { return nullptr; } // If the value is already a constant simply return the same value if (auto const_value = llvm::dyn_cast<llvm::Constant>(value)) { return const_value; } if (auto load = llvm::dyn_cast<llvm::LoadInst>(value)) { const auto runtime_pointer = std::dynamic_pointer_cast<const JitKnownRuntimePointer>( GetRuntimePointerForValue(load->getPointerOperand(), context)); if (runtime_pointer && runtime_pointer->is_valid() && load->getType()->isIntegerTy()) { const auto address = runtime_pointer->address(); const auto int_type = llvm::dyn_cast<llvm::IntegerType>(load->getType()); const auto bit_width = int_type->getIntegerBitWidth(); const auto value = dereference_flexible_width_int_pointer(address, bit_width); return llvm::ConstantInt::get(int_type, value, int_type->getSignBit() > 0); } } else if (auto inst = llvm::dyn_cast<llvm::Instruction>(value)) { failed.insert(value); std::vector<llvm::Constant*> ops; for (auto& use : inst->operands()) { auto op = ResolveConditionRec(use.get(), context, failed); if (!op) { return nullptr; } ops.push_back(op); } const llvm::Triple module_triple(context.module->getTargetTriple()); const llvm::TargetLibraryInfoImpl target_lib_info_impl(module_triple); const llvm::TargetLibraryInfo target_lib_info(target_lib_info_impl); return ConstantFoldInstruction(inst, ops, context.module->getDataLayout(), &target_lib_info); } return nullptr; } llvm::Constant* ResolveCondition(llvm::Value* Value, SpecializationContext& Context) { // NOLINT // Keeps track of all operands that failed to resolve to a constant to avoid duplicate lookups std::unordered_set<llvm::Value*> resolution_failed; return ResolveConditionRec(Value, Context, resolution_failed); } } // namespace opossum
50.59375
120
0.699444
[ "object", "vector" ]
b0e90f6134ecfb7eebe51cee13798fc312dad708
1,535
cpp
C++
two pointers/Leetcode_two_pointers/567_permutation_in_string.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
two pointers/Leetcode_two_pointers/567_permutation_in_string.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
two pointers/Leetcode_two_pointers/567_permutation_in_string.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 567_permutation_in_string.cpp // Leetcode_two_pointers // // Created by Hadley on 15.08.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> using namespace std; class Solution { public: bool checkInclusion(string s1, string s2) { auto n1=s1.length();auto n2=s2.length(); if(n1>n2)return false; vector<int>m1(26,0); for(auto &x:s1){ m1[x-'a']++; } for(int j=0;j<=n2-n1;j++){ int i=0; vector<int>m2(26,0); while(i<n1){ m2[s2[j+i]-'a']++; i++; } if(m1==m2){ return true; } } return false; } }; class Solution2 { public: bool checkInclusion(string s1, string s2) { auto n1=s1.length();auto n2=s2.length(); if(n1>n2)return false; vector<int>m1(26,0); for(auto &x:s1){ m1[x-'a']++; } vector<int>m2(26,0); int i=0; while(i<n1){ m2[s2[i]-'a']++; } if(m1==m2)return true; for(int j=1;j<=n2-n1;j++){ m2[s2[j-1]-'a']--; m2[s2[j+n1-1]-'a']++; if(m1==m2){ return true; } } return false; } };
20.466667
49
0.468404
[ "vector" ]
b0e9d6ab2bbf77f5a219d696dac666f5e337eafe
3,062
cpp
C++
Libraries/include/openal-impl-vid1/SoundBuffer.cpp
acalasanzs/dessor
c262b49db88d63510266ffce8d61f6ae1b5e1fd6
[ "MIT" ]
1
2021-09-09T10:03:20.000Z
2021-09-09T10:03:20.000Z
Libraries/include/openal-impl-vid1/SoundBuffer.cpp
acalasanzs/dessor
c262b49db88d63510266ffce8d61f6ae1b5e1fd6
[ "MIT" ]
null
null
null
Libraries/include/openal-impl-vid1/SoundBuffer.cpp
acalasanzs/dessor
c262b49db88d63510266ffce8d61f6ae1b5e1fd6
[ "MIT" ]
null
null
null
#include "SoundBuffer.h" #include <sndfile.h> #include <inttypes.h> #include <AL\alext.h> SoundBuffer* SoundBuffer::get() { static SoundBuffer* sndbuf = new SoundBuffer(); return sndbuf; } ALuint SoundBuffer::addSoundEffect(const char* filename) { ALenum err, format; ALuint buffer; SNDFILE* sndfile; SF_INFO sfinfo; short* membuf; sf_count_t num_frames; ALsizei num_bytes; /* Open the audio file and check that it's usable. */ sndfile = sf_open(filename, SFM_READ, &sfinfo); if (!sndfile) { fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); return 0; } if (sfinfo.frames < 1 || sfinfo.frames >(sf_count_t)(INT_MAX / sizeof(short)) / sfinfo.channels) { fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); sf_close(sndfile); return 0; } /* Get the sound format, and figure out the OpenAL format */ format = AL_NONE; if (sfinfo.channels == 1) format = AL_FORMAT_MONO16; else if (sfinfo.channels == 2) format = AL_FORMAT_STEREO16; else if (sfinfo.channels == 3) { if (sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) format = AL_FORMAT_BFORMAT2D_16; } else if (sfinfo.channels == 4) { if (sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) format = AL_FORMAT_BFORMAT3D_16; } if (!format) { fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); sf_close(sndfile); return 0; } /* Decode the whole audio file to a buffer. */ membuf = static_cast<short*>(malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short))); num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); if (num_frames < 1) { free(membuf); sf_close(sndfile); fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); return 0; } num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); /* Buffer the audio data into a new buffer object, then free the data and * close the file. */ buffer = 0; alGenBuffers(1, &buffer); alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); free(membuf); sf_close(sndfile); /* Check if an error occured, and clean up if so. */ err = alGetError(); if (err != AL_NO_ERROR) { fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); if (buffer && alIsBuffer(buffer)) alDeleteBuffers(1, &buffer); return 0; } p_SoundEffectBuffers.push_back(buffer); // add to the list of known buffers return buffer; } bool SoundBuffer::removeSoundEffect(const ALuint& buffer) { auto it = p_SoundEffectBuffers.begin(); while (it != p_SoundEffectBuffers.end()) { if (*it == buffer) { alDeleteBuffers(1, &*it); it = p_SoundEffectBuffers.erase(it); return true; } else { ++it; } } return false; // couldn't find to remove } SoundBuffer::SoundBuffer() { p_SoundEffectBuffers.clear(); } SoundBuffer::~SoundBuffer() { alDeleteBuffers(p_SoundEffectBuffers.size(), p_SoundEffectBuffers.data()); p_SoundEffectBuffers.clear(); }
23.374046
97
0.696277
[ "object" ]
b0ea53e7c4243b48e2e1eb2fc74c0962630dcbeb
16,301
cc
C++
library/endpoint.cc
driplineorg/dripline-cpp
4f6490226eefc16a880ae5b342014b590f6115af
[ "Apache-2.0" ]
1
2021-09-06T10:07:55.000Z
2021-09-06T10:07:55.000Z
library/endpoint.cc
driplineorg/dripline-cpp
4f6490226eefc16a880ae5b342014b590f6115af
[ "Apache-2.0" ]
56
2019-02-22T02:15:42.000Z
2021-09-10T19:46:35.000Z
library/endpoint.cc
driplineorg/dripline-cpp
4f6490226eefc16a880ae5b342014b590f6115af
[ "Apache-2.0" ]
1
2021-06-28T14:10:39.000Z
2021-06-28T14:10:39.000Z
/* * endpoint.cc * * Created on: Aug 14, 2018 * Author: N.S. Oblath */ #define DRIPLINE_API_EXPORTS #include "endpoint.hh" #include "dripline_exceptions.hh" #include "service.hh" #include "throw_reply.hh" #include "logger.hh" #ifdef DL_PYTHON #include "reply_cache.hh" #include "pybind11/pybind11.h" #include "pybind11/pytypes.h" #endif LOGGER( dlog, "endpoint" ); namespace dripline { endpoint::endpoint( const std::string& a_name ) : f_name( a_name ), f_service(), f_lockout_tag(), f_lockout_key( generate_nil_uuid() ) { } endpoint::endpoint( const endpoint& a_orig ) : f_name( a_orig.f_name ), f_service( a_orig.f_service ), f_lockout_tag( a_orig.f_lockout_tag ), f_lockout_key( a_orig.f_lockout_key ) {} endpoint::endpoint( endpoint&& a_orig ) : f_name( std::move(a_orig.f_name) ), f_service( std::move(a_orig.f_service) ), f_lockout_tag( std::move(a_orig.f_lockout_tag) ), f_lockout_key( std::move(a_orig.f_lockout_key) ) {} endpoint::~endpoint() {} endpoint& endpoint::operator=( const endpoint& a_orig ) { f_name = a_orig.f_name; f_service = a_orig.f_service; f_lockout_tag = a_orig.f_lockout_tag; f_lockout_key = a_orig.f_lockout_key; return *this; } endpoint& endpoint::operator=( endpoint&& a_orig ) { f_name = std::move(a_orig.f_name); f_service = std::move(a_orig.f_service); f_lockout_tag = std::move(a_orig.f_lockout_tag); f_lockout_key = std::move(a_orig.f_lockout_key); return *this; } reply_ptr_t endpoint::submit_request_message( const request_ptr_t a_request_ptr) { return this->on_request_message( a_request_ptr );; } void endpoint::submit_alert_message( const alert_ptr_t a_alert_ptr) { return this->on_alert_message( a_alert_ptr ); } void endpoint::submit_reply_message( const reply_ptr_t a_reply_ptr) { return this->on_reply_message( a_reply_ptr ); } reply_ptr_t endpoint::on_request_message( const request_ptr_t a_request ) { // reply object to store whatever reply we end up with reply_ptr_t t_reply; // lambda to send the reply. this local function is defined so we can send from within the catch block if needed before rethrowing. auto t_replier = [&t_reply, &a_request, this](){ // send the reply if the request had a reply-to if( a_request->reply_to().empty() ) { LWARN( dlog, "Not sending reply (reply-to empty)\n" << " Return code: " << t_reply->get_return_code() << '\n' << " Return message: " << t_reply->return_message() << '\n' << " Payload:\n" << t_reply->payload() ); } else { send_reply( t_reply ); } }; try { if( ! a_request->get_is_valid() ) { std::string t_message( "Request message was not valid" ); // check in the payload for error information if( a_request->payload().is_node() ) { const scarab::param_node& t_payload = a_request->payload().as_node(); if( t_payload.has("error") ) t_message += "; " + t_payload["error"]().as_string(); } throw throw_reply( dl_service_error_decoding_fail{}, a_request->get_payload_ptr()->clone() ) << "Request message was not valid"; } // the lockout key must be valid if( ! a_request->get_lockout_key_valid() ) { throw throw_reply( dl_service_error_invalid_key{} ) << "Lockout key could not be parsed"; } switch( a_request->get_message_operation() ) { case op_t::get: { t_reply = __do_get_request( a_request ); break; } // end "get" operation case op_t::set: { t_reply = __do_set_request( a_request ); break; } // end "set" operation case op_t::cmd: { t_reply = __do_cmd_request( a_request ); break; } default: throw throw_reply( dl_service_error_invalid_method() ) << "Unrecognized message operation: <" << a_request->get_message_operation() << ">"; break; } // end switch on message type // reply to be sent outside the try block } catch( const throw_reply& e ) { if( e.ret_code().rc_value() == dl_success::s_value ) { LINFO( dlog, "Replying with: " << e.return_message() ); } else { LWARN( dlog, "Replying with: " << e.return_message() ); } t_reply = a_request->reply( e.ret_code(), e.return_message() ); t_reply->set_payload( e.get_payload_ptr()->clone() ); // don't rethrow a throw_reply // reply to be sent outside the catch block } #ifdef DL_PYTHON catch( const pybind11::error_already_set& e ) { // check whether the error message from python starts with the keyword // the keyword should be the name of the python class if( std::string(e.what()).substr(0, throw_reply::py_throw_reply_keyword().size()) == throw_reply::py_throw_reply_keyword() ) { reply_cache* t_reply_cache = reply_cache::get_instance(); if( t_reply_cache->ret_code().rc_value() == dl_success::s_value ) { LINFO( dlog, "Replying with: " << t_reply_cache->return_message() ); } else { LWARN( dlog, "Replying with: " << t_reply_cache->return_message() ); } t_reply = a_request->reply( t_reply_cache->ret_code(),t_reply_cache->return_message() ); t_reply->set_payload( t_reply_cache->get_payload_ptr()->clone() ); // don't rethrow a throw_reply // reply to be sent outside the catch block } else { // treat the python exception as a standard exception LERROR( dlog, "Caught exception from Python: " << e.what() ); t_reply = a_request->reply( dl_unhandled_exception(), e.what() ); t_replier(); // send the reply before rethrowing throw; // unhandled exceptions should rethrow because they're by definition unhandled } } #endif catch( const std::exception& e ) { LERROR( dlog, "Caught exception: " << e.what() ); t_reply = a_request->reply( dl_unhandled_exception(), e.what() ); t_replier(); // send the reply before rethrowing throw; // unhandled exceptions should rethrow because they're by definition unhandled } // send the reply t_replier(); return t_reply; } void endpoint::sort_message( message_ptr_t a_message ) { if( a_message->is_request() ) { on_request_message( std::static_pointer_cast< msg_request >( a_message ) ); } else if( a_message->is_alert() ) { on_alert_message( std::static_pointer_cast< msg_alert >( a_message ) ); } else if( a_message->is_reply() ) { on_reply_message( std::static_pointer_cast< msg_reply >( a_message ) ); } else { throw dripline_error() << "Unknown message type"; } } void endpoint::send_reply( reply_ptr_t a_reply ) const { if( ! f_service ) { LWARN( dlog, "Cannot send reply because the service pointer is not set" ); return; } LDEBUG( dlog, "Sending reply message to <" << a_reply->routing_key() << ">:\n" << " Return code: " << a_reply->get_return_code() << '\n' << " Return message: " << a_reply->return_message() << '\n' << " Payload:\n" << a_reply->payload() ); sent_msg_pkg_ptr t_receive_reply; try { t_receive_reply = f_service->send( a_reply ); } catch( message_ptr_t ) { LWARN( dlog, "Operating in offline mode; message not sent" ); return; } catch( connection_error& e ) { LERROR( dlog, "Unable to connect to the broker:\n" << e.what() ); return; } catch( dripline_error& e ) { LERROR( dlog, "Dripline error while sending reply:\n" << e.what() ); return; } if( ! t_receive_reply->f_successful_send ) { LERROR( dlog, "Failed to send reply:\n" + t_receive_reply->f_send_error_message ); return; } return; } void endpoint::on_reply_message( const reply_ptr_t ) { throw dripline_error() << "Base endpoint does not handle reply messages"; } void endpoint::on_alert_message( const alert_ptr_t ) { throw dripline_error() << "Base endpoint does not handle alert messages"; } reply_ptr_t endpoint::__do_run_request( const request_ptr_t a_request ) { LDEBUG( dlog, "Run operation request received" ); if( ! authenticate( a_request->lockout_key() ) ) { std::stringstream t_conv; t_conv << a_request->lockout_key(); std::string t_message( "Request denied due to lockout (key used: " + t_conv.str() + ")" ); LINFO( dlog, t_message ); return a_request->reply( dl_service_error_access_denied(), t_message ); } return do_run_request( a_request ); } reply_ptr_t endpoint::__do_get_request( request_ptr_t a_request ) { LDEBUG( dlog, "Get operation request received" ); std::string t_query_type; if( ! a_request->parsed_specifier().empty() ) { t_query_type = a_request->parsed_specifier().front(); } if( t_query_type == "is-locked" ) { a_request->parsed_specifier().pop_front(); return handle_is_locked_request( a_request ); } return do_get_request( a_request ); } reply_ptr_t endpoint::__do_set_request( const request_ptr_t a_request ) { LDEBUG( dlog, "Set request received" ); if( ! authenticate( a_request->lockout_key() ) ) { std::stringstream t_conv; t_conv << a_request->lockout_key(); std::string t_message( "Request denied due to lockout (key used: " + t_conv.str() + ")" ); LINFO( dlog, t_message ); return a_request->reply( dl_service_error_access_denied(), t_message ); } return do_set_request( a_request ); } reply_ptr_t endpoint::__do_cmd_request( const request_ptr_t a_request ) { LDEBUG( dlog, "Cmd request received" ); std::string t_instruction; if( ! a_request->parsed_specifier().empty() ) { t_instruction = a_request->parsed_specifier().front(); } //LWARN( mtlog, "uuid string: " << a_request->get_payload().get_value( "key", "") << ", uuid: " << uuid_from_string( a_request->get_payload().get_value( "key", "") ) ); // this condition includes the exception for the unlock instruction that allows us to force the unlock regardless of the key. // disable_key() checks the lockout key if it's not forced, so it's okay that we bypass this call to authenticate() for the unlock instruction. if( ! authenticate( a_request->lockout_key() ) && t_instruction != "unlock" && t_instruction != "ping" && t_instruction != "set_condition" ) { std::stringstream t_conv; t_conv << a_request->lockout_key(); std::string t_message( "Request denied due to lockout (key used: " + t_conv.str() + ")" ); LINFO( dlog, t_message ); return a_request->reply( dl_service_error_access_denied(), t_message ); } if( t_instruction == "lock" ) { a_request->parsed_specifier().pop_front(); return handle_lock_request( a_request ); } else if( t_instruction == "unlock" ) { a_request->parsed_specifier().pop_front(); return handle_unlock_request( a_request ); } else if( t_instruction == "ping" ) { a_request->parsed_specifier().pop_front(); return handle_ping_request( a_request ); } else if( t_instruction == "set_condition" ) { a_request->parsed_specifier().pop_front(); return handle_set_condition_request( a_request ); } return do_cmd_request( a_request ); } uuid_t endpoint::enable_lockout( const scarab::param_node& a_tag, uuid_t a_key ) { if( is_locked() ) return generate_nil_uuid(); if( a_key.is_nil() ) f_lockout_key = generate_random_uuid(); else f_lockout_key = a_key; f_lockout_tag = a_tag; return f_lockout_key; } bool endpoint::disable_lockout( const uuid_t& a_key, bool a_force ) { if( ! is_locked() ) return true; if( ! a_force && a_key != f_lockout_key ) return false; f_lockout_key = generate_nil_uuid(); f_lockout_tag.clear(); return true; } bool endpoint::authenticate( const uuid_t& a_key ) const { LDEBUG( dlog, "Authenticating with key <" << a_key << ">" ); if( is_locked() ) return check_key( a_key ); return true; } reply_ptr_t endpoint::handle_lock_request( const request_ptr_t a_request ) { uuid_t t_new_key = enable_lockout( a_request->get_sender_info(), a_request->lockout_key() ); if( t_new_key.is_nil() ) { return a_request->reply( dl_resource_error(), "Unable to lock server" );; } scarab::param_ptr_t t_payload_ptr( new scarab::param_node() ); scarab::param_node& t_payload_node = t_payload_ptr->as_node(); t_payload_node.add( "key", string_from_uuid( t_new_key ) ); return a_request->reply( dl_success(), "Server is now locked", std::move(t_payload_ptr) ); } reply_ptr_t endpoint::handle_unlock_request( const request_ptr_t a_request ) { if( ! is_locked() ) { return a_request->reply( dl_warning_no_action_taken(), "Already unlocked" ); } bool t_force = a_request->payload().get_value( "force", false ); if( disable_lockout( a_request->lockout_key(), t_force ) ) { return a_request->reply( dl_success(), "Server unlocked" ); } return a_request->reply( dl_resource_error(), "Failed to unlock server" );; } reply_ptr_t endpoint::handle_set_condition_request( const request_ptr_t a_request ) { return this->__do_handle_set_condition_request( a_request ); } reply_ptr_t endpoint::handle_is_locked_request( const request_ptr_t a_request ) { bool t_is_locked = is_locked(); scarab::param_ptr_t t_reply_payload( new scarab::param_node() ); scarab::param_node& t_reply_node = t_reply_payload->as_node(); t_reply_node.add( "is_locked", t_is_locked ); if( t_is_locked ) t_reply_node.add( "tag", f_lockout_tag ); return a_request->reply( dl_success(), "Checked lock status", std::move(t_reply_payload) ); } reply_ptr_t endpoint::handle_ping_request( const request_ptr_t a_request ) { return a_request->reply( dl_success(), "Hello, " + a_request->sender_exe() ); } } /* namespace dripline */
35.591703
176
0.567573
[ "object" ]
b0eea8da9af2b7ad22cd6dc37af86f87abc36672
1,033
cpp
C++
2-Data_Structures_and_Libraries/2.4-Data_Structures_with_Our-Own_Libraries/1-Graph_Data_Structures_Problems/EdyJunior/10895.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
1
2017-11-16T10:56:17.000Z
2017-11-16T10:56:17.000Z
2-Data_Structures_and_Libraries/2.4-Data_Structures_with_Our-Own_Libraries/1-Graph_Data_Structures_Problems/EdyJunior/10895.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
null
null
null
2-Data_Structures_and_Libraries/2.4-Data_Structures_with_Our-Own_Libraries/1-Graph_Data_Structures_Problems/EdyJunior/10895.cpp
IFCE-CP/CP3-solutions
1abcabd9a06968184a55d3b0414637019014694c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define F first #define S second #define mp(x, y) make_pair(x, y) #define pb(x) push_back(x) using namespace std; typedef pair<int, int> pii; int main() { int m, n; while (scanf("%d %d", &m, &n) != EOF && m + n) { vector<vector<pii>> g(n + 1); for (int i = 1, r, c; i <= m; i++) { scanf("%d", &r); int pos[r]; for (int j = 0; j < r; j++) scanf("%d", &pos[j]); for (int j = 0; j < r; j++) { scanf("%d", &c); g[pos[j]].pb(mp(i, c)); } } printf("%d %d\n", n, m); for (int i = 1; i <= n; i++) { printf("%lu", g[i].size()); for (auto gi : g[i]) printf(" %d", gi.F); printf("\n"); for (int j = 0; j < g[i].size(); j++) { if (j) printf(" "); printf("%d", g[i][j].S); } printf("\n"); } } return 0; }
24.595238
52
0.346563
[ "vector" ]
b0f3f3db03a2a0646c98450d3c46a0cefb19b425
14,001
cpp
C++
src/asiEngine/func/asiEngine_BuildPatchFunc.cpp
CadQuery/AnalysisSitus
f3b379ca9158325a21e50fefba8133cab51d9cd9
[ "BSD-3-Clause" ]
3
2021-11-04T01:36:56.000Z
2022-03-10T07:11:01.000Z
src/asiEngine/func/asiEngine_BuildPatchFunc.cpp
CadQuery/AnalysisSitus
f3b379ca9158325a21e50fefba8133cab51d9cd9
[ "BSD-3-Clause" ]
null
null
null
src/asiEngine/func/asiEngine_BuildPatchFunc.cpp
CadQuery/AnalysisSitus
f3b379ca9158325a21e50fefba8133cab51d9cd9
[ "BSD-3-Clause" ]
1
2021-09-25T18:14:30.000Z
2021-09-25T18:14:30.000Z
//----------------------------------------------------------------------------- // Created on: 09 July 2019 //----------------------------------------------------------------------------- // Copyright (c) 2019-present, Sergey Slyadnev // 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 the copyright holder(s) nor the // names of all 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 AUTHORS 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. //----------------------------------------------------------------------------- // Own include #include <asiEngine_BuildPatchFunc.h> // asiAlgo includes #include <asiAlgo_Timer.h> // asiEngine includes #include <asiEngine_RE.h> // Active Data includes #include <ActData_ParameterFactory.h> #if defined USE_MOBIUS // Mobius includes #include <mobius/cascade.h> #include <mobius/geom_ApproxBSurf.h> #include <mobius/geom_BuildAveragePlane.h> #include <mobius/geom_InterpolateMultiCurve.h> #include <mobius/geom_FairBCurve.h> #include <mobius/geom_PlaneSurface.h> #include <mobius/geom_SkinSurface.h> using namespace mobius; #endif //----------------------------------------------------------------------------- #define numArgsBeforeCoedges 4 //----------------------------------------------------------------------------- Handle(asiEngine_BuildPatchFunc) asiEngine_BuildPatchFunc::Instance() { return new asiEngine_BuildPatchFunc(); } //----------------------------------------------------------------------------- const char* asiEngine_BuildPatchFunc::GUID() { return "A7E0D6DA-AC44-44D8-B9A0-01F0AF6F814B"; } //----------------------------------------------------------------------------- const char* asiEngine_BuildPatchFunc::GetGUID() const { return GUID(); } //----------------------------------------------------------------------------- int asiEngine_BuildPatchFunc::execute(const Handle(ActAPI_HParameterList)& inputs, const Handle(ActAPI_HParameterList)& outputs, const Handle(Standard_Transient)& userData) const { /* ============================ * Interpret input Parameters * ============================ */ // User data is a Data Model instance. Handle(asiEngine_Model) M = Handle(asiEngine_Model)::DownCast(userData); // if ( M.IsNull() ) { m_progress.SendLogMessage(LogErr(Normal) << "User data is not a Data Model instance."); return 1; // Error. } // Vector of coedges. std::vector<Handle(asiData_ReCoedgeNode)> coedges; // Get Patch Node. Handle(asiData_RePatchNode) patchNode = Handle(asiData_RePatchNode)::DownCast( outputs->First()->GetNode() ); m_progress.SendLogMessage( LogNotice(Normal) << "Executing tree function '%1%2'..." << this->GetName() << patchNode->RootLabel().Tag() ); // Get min number of knots. const int minNumKnots = Handle(ActData_IntParameter)::DownCast( inputs->Value(1) )->GetValue(); // Get mesh approximation flag. const bool approxMesh = Handle(ActData_BoolParameter)::DownCast( inputs->Value(2) )->GetValue(); // Get the value of fairing coefficient. const double approxLambda = Handle(ActData_RealParameter)::DownCast( inputs->Value(3) )->GetValue(); // Boolean flag indicating if the visual debugging is enabled. m_bPlotterEnabled = Handle(ActData_BoolParameter)::DownCast( inputs->Value(4) )->GetValue(); m_progress.SendLogMessage( LogInfo(Normal) << "Mesh nodes approximation mode: %1." << approxMesh ); // if ( approxMesh ) m_progress.SendLogMessage( LogInfo(Normal) << "Fairing coefficient: %1." << approxLambda ); // Collect coedges. int currIdx = 1; const int numCoedges = (inputs->Length() + numArgsBeforeCoedges) / 2; // for ( ActAPI_HParameterList::Iterator it(*inputs); it.More(); it.Next(), ++currIdx ) { // Skip min number of knots and other non-coedge inputs. if ( currIdx <= numArgsBeforeCoedges ) continue; if ( currIdx > numCoedges + numArgsBeforeCoedges ) break; const Handle(ActAPI_IUserParameter)& uParam = it.Value(); // Handle(asiData_ReCoedgeNode) coedge = Handle(asiData_ReCoedgeNode)::DownCast( uParam->GetNode() ); if ( !coedge.IsNull() ) coedges.push_back(coedge); else break; } /* ============= * Build patch * ============= */ asiEngine_RE reApi(M, m_progress, m_bPlotterEnabled ? m_plotter : nullptr); // Fill Coons. Handle(Geom_BSplineSurface) bsurf; // if ( !reApi.FillPatchCoons(coedges, minNumKnots, bsurf) ) return 0; /* ============================================================= * Extract inner mesh nodes if mesh approximation is requested * ============================================================= */ // Extract inner nodes. Handle(asiAlgo_BaseCloud<double>) pts; // if ( approxMesh && !this->extractMeshNodes(M, patchNode, pts) ) { // Let's return at least Coons... patchNode->SetSurface(bsurf); // Error. m_progress.SendLogMessage( LogErr(Normal) << "Cannot approximate, falling back with Coons..." ); return 0; } /* ================================================== * Approximate points with a B-surface if requested * ================================================== */ Handle(Geom_BSplineSurface) approxSurf; // if ( approxMesh && !this->approxMeshNodes(bsurf, pts, approxLambda, approxSurf) ) { // Let's return at least Coons... patchNode->SetSurface(bsurf); // Error. m_progress.SendLogMessage( LogErr(Normal) << "Cannot approximate, falling back with Coons..." ); return 0; } if ( approxMesh ) bsurf = approxSurf; /* ======================= * Set output Parameters * ======================= */ // Set the surface to the output Parameter indirectly using the Patch Node. patchNode->SetSurface(bsurf); return 0; // Success. } //----------------------------------------------------------------------------- bool asiEngine_BuildPatchFunc::validateInput(const Handle(ActAPI_HParameterList)& inputs) const { // Check the number of arguments. const int numArgs = inputs->Length(); // if ( numArgs % 2 != 0 ) { m_progress.SendLogMessage(LogErr(Normal) << "Number of arguments is unexpected (%1)." << numArgs); return false; } const int numCoedges = (numArgs - numArgsBeforeCoedges) / 2; int currIdx = 1; // Check Parameter types. for ( ActAPI_HParameterList::Iterator it(*inputs); it.More(); it.Next(), ++currIdx ) { const Handle(ActAPI_IUserParameter)& uParam = it.Value(); if ( currIdx == 1 ) { // We expect that "Min number of knots" is connected first. if ( !uParam->IsKind( STANDARD_TYPE(ActData_IntParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_IntParameter)->Name() ); return false; } } else if ( currIdx == 2 ) { // We expect that "Approx. nodes" is connected then. if ( !uParam->IsKind( STANDARD_TYPE(ActData_BoolParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_BoolParameter)->Name() ); return false; } } else if ( currIdx == 3 ) { // We expect that "Approx. lambda" is connected then. if ( !uParam->IsKind( STANDARD_TYPE(ActData_RealParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_RealParameter)->Name() ); return false; } } else if ( currIdx == 3 ) { // We expect that "Enable plotter" is connected then. if ( !uParam->IsKind( STANDARD_TYPE(ActData_BoolParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_BoolParameter)->Name() ); return false; } } else if ( currIdx <= numCoedges + numArgsBeforeCoedges ) { // We expect that "SameSense" flags are connected then. if ( !uParam->IsKind( STANDARD_TYPE(ActData_BoolParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_BoolParameter)->Name() ); return false; } } else { // We expect that curves are connected then. if ( !uParam->IsKind( STANDARD_TYPE(ActData_ShapeParameter) ) ) { m_progress.SendLogMessage( LogErr(Normal) << "Input Parameter %1 is not of the expected type %2." << currIdx << STANDARD_TYPE(ActData_ShapeParameter)->Name() ); return false; } } } return true; } //----------------------------------------------------------------------------- ActAPI_ParameterTypeStream asiEngine_BuildPatchFunc::inputSignature() const { return ActAPI_ParameterTypeStream(); } //----------------------------------------------------------------------------- ActAPI_ParameterTypeStream asiEngine_BuildPatchFunc::outputSignature() const { return ActAPI_ParameterTypeStream() << Parameter_Shape; // Surface patch. } //----------------------------------------------------------------------------- bool asiEngine_BuildPatchFunc::extractMeshNodes(const Handle(asiEngine_Model)& model, const Handle(asiData_RePatchNode)& patch, Handle(asiAlgo_BaseCloud<double>)& pts) const { // Prepare service API. asiEngine_RE api(model, m_progress, m_bPlotterEnabled ? m_plotter : nullptr); // Get triangles captured by contour. Handle(Poly_Triangulation) regionTris; // if ( !api.ExtractBoundedRegion(patch, regionTris) ) { m_progress.SendLogMessage( LogErr(Normal) << "Cannot extract the region captured by contour of patch '%1'." << patch->GetId() ); return false; } // Get nodes of the captured region. pts = new asiAlgo_BaseCloud<double>; // for ( int i = 1; i <= regionTris->NbNodes(); ++i ) { const gp_Pnt& P = regionTris->Node(i); pts->AddElement( P.X(), P.Y(), P.Z() ); } return true; } //----------------------------------------------------------------------------- bool asiEngine_BuildPatchFunc::approxMeshNodes(const Handle(Geom_BSplineSurface)& initSurf, const Handle(asiAlgo_BaseCloud<double>)& pts, const double lambda, Handle(Geom_BSplineSurface)& resultSurf) const { #if defined USE_MOBIUS // Convert to Mobius point cloud. t_ptr<t_pcloud> mobPts = new t_pcloud; // for ( int k = 0; k < pts->GetNumberOfElements(); ++k ) mobPts->AddPoint( cascade::GetMobiusPnt( pts->GetElement(k) ) ); // Convert to Mobius form. t_ptr<t_bsurf> mobInitSurf = cascade::GetMobiusBSurface(initSurf); TIMER_NEW TIMER_GO // Prepare approximation tool. geom_ApproxBSurf approx(mobPts, mobInitSurf); // Constraint the boundary. const int nPolesU = int( mobInitSurf->GetPoles().size() ); const int nPolesV = int( mobInitSurf->GetPoles()[0].size() ); // for ( int i = 0; i < nPolesU; ++i ) { approx.AddPinnedPole( i, 0 ); approx.AddPinnedPole( i, nPolesV - 1 ); } // for ( int j = 0; j < nPolesV; ++j ) { approx.AddPinnedPole( 0, j ); approx.AddPinnedPole( nPolesU - 1, j ); } // Approximate. if ( !approx.Perform(lambda) ) { m_progress.SendLogMessage(LogErr(Normal) << "Approximation failed."); return false; } TIMER_FINISH TIMER_COUT_RESULT_NOTIFIER(m_progress, "Approximate (passed initial surface)") // Get result. t_ptr<t_bsurf> mobResSurf = approx.GetResult(); // Convert to OpenCascade B-surface. resultSurf = cascade::GetOpenCascadeBSurface(mobResSurf); return true; #else m_progress.SendLogMessage(LogErr(Normal) << "Surface approximation module is not available."); return false; #endif }
34.400491
112
0.58053
[ "mesh", "vector", "model" ]
7c0503b0df0fa8bb7373dd7fb178e0cf0d46c170
321
cpp
C++
leet_code/arrays/maxSubarr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/arrays/maxSubarr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
leet_code/arrays/maxSubarr.cpp
sahilduhan/codeforces
a8042d52c12806e026fd7027e35e97ed8b4eeed6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxSubArray(vector<int> &nums) { int sum = 0, max_sum = INT_MIN; for (auto it : nums){ sum += it; max_sum= max(sum, max_sum); if(sum<0) sum=0; } return max_sum; } };
18.882353
39
0.501558
[ "vector" ]
7c0cd9d2ba545e76118edaa1ce0678e8054e28ce
7,741
hpp
C++
src/navigation/navigation.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
9
2021-07-31T16:22:24.000Z
2022-01-19T18:14:31.000Z
src/navigation/navigation.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
91
2021-07-29T18:21:30.000Z
2022-03-31T20:44:55.000Z
src/navigation/navigation.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
null
null
null
#pragma once #include "kalman_filter.hpp" #include "stripe_handler.hpp" #include <math.h> #include <array> #include <cstdint> #include <fstream> #include <data/data.hpp> #include <data/data_point.hpp> #include <sensors/imu.hpp> #include <utils/logger.hpp> #include <utils/math/integrator.hpp> #include <utils/math/statistics.hpp> namespace hyped { namespace navigation { class Navigation { public: using ImuDataArray = std::array<data::ImuData, data::Sensors::kNumImus>; using ImuDataPointArray = data::DataPoint<ImuDataArray>; using NavigationVectorArray = std::array<data::NavigationVector, data::Sensors::kNumImus>; using ImuAxisData = std::array<std::array<data::nav_t, data::Sensors::kNumImus>, 3>; using NavigationArray = std::array<data::nav_t, data::Sensors::kNumImus>; using NavigationArrayOneFaulty = std::array<data::nav_t, data::Sensors::kNumImus - 1>; using FilterArray = std::array<KalmanFilter, data::Sensors::kNumImus>; /** * @brief Construct a new Navigation object * * @param log System logger * @param axis Axis used of acceleration measurements */ explicit Navigation(utils::Logger &log, uint32_t axis = 0); /** * @brief Get the current state of the navigation module * * @return ModuleStatus the current state of the navigation module */ data::ModuleStatus getModuleStatus() const; /** * @brief Get the measured acceleration [m/s^2] * * @return nav_t Returns the forward component of acceleration vector (negative when * decelerating) [m/s^2] */ data::nav_t getAcceleration() const; /** * @brief Get the measured velocity [m/s] * * @return nav_t Returns the forward component of velocity vector [m/s] */ data::nav_t getVelocity() const; /** * @brief Get the measured displacement [m] * * @return nav_t Returns the forward component of displacement vector [m] */ data::nav_t getDisplacement() const; /** * @brief Get the emergency braking distance [m] * * @return nav_t emergency braking distance [m] */ data::nav_t getEmergencyBrakingDistance() const; /** * @brief Get the braking distance [m] * * @return nav_t braking distance [m] */ data::nav_t getBrakingDistance() const; /** * @brief Get the determined gravity calibration [m/s^2] * * @return NavitationArray recorded gravitational acceleration [m/s^2] */ NavigationVectorArray getGravityCalibration() const; /** * @brief Determine the value of gravitational acceleration measured by sensors at rest */ void calibrateGravity(); /** * @brief Apply Tukey's fences to an array of readings * * @param pointer to array of original acceleration readings * @param threshold value */ void tukeyFences(NavigationArray &data_array, const data::nav_t threshold); /** * @brief Update central data structure */ void updateData(); /** * @brief Take acceleration readings from IMU, filter, integrate and then update central data * structure with new values (i.e. the meat'n'potatoes of navigation). */ void navigate(); /** * @brief Initialise timestamps for integration */ void initialiseTimestamps(); /** * @brief Used to check whether initial timestamps have been set * * @return Boolean whether init timestamps have been set */ bool getHasInit(); /* * @brief Set initialisation of timestamps to true */ void setHasInit(); /** * @brief Disable keyence readings to have any impact on the run. */ void disableKeyenceUsage(); /** * @brief Set the keyence used to fake, so the system knows to use central timestamps. */ void setKeyenceFake(); /** * @brief Enable writing to file nav_data.csv */ void logWrite(); private: static constexpr int kMaxCalibrationAttempts = 3; static constexpr int kCalibrationQueries = 10000; // number of previous measurements stored static constexpr int kPreviousMeasurements = 1000; static constexpr char kDelimiter = '\t'; static constexpr int kPrintFreq = 1; static constexpr data::nav_t kEmergencyDeceleration = 24; static constexpr data::nav_t kTukeyThreshold = 1; // 0.75 static constexpr data::nav_t kTukeyIQRBound = 3; static constexpr data::nav_t kStripeDistance = 30.48; static constexpr data::nav_t kPodMass = 250; // kg static constexpr data::nav_t kMomentOfInertiaWheel = 0.04; // kgm² static constexpr uint32_t kNumBrakes = 4; static constexpr data::nav_t kFrictionCoefficient = 0.38; static constexpr data::nav_t kSpringCompression = 40; static constexpr data::nav_t kSpringCoefficient = 18; static constexpr data::nav_t kEmbrakeAngle = 0.52; static constexpr data::nav_t kPi = 3.14159265359; // Have to approximate // System communication utils::Logger &log_; data::Data &data_; data::ModuleStatus status_; uint32_t log_counter_; uint32_t movement_axis_; // acceptable variances for calibration measurements: {x, y, z} std::array<data::nav_t, 3> calibration_limits_; // Calibration variances in each dimension, necessary for vibration checking std::array<data::nav_t, 3> calibration_variance_; // Array of previous measurements std::array<ImuAxisData, kPreviousMeasurements> previous_measurements_; // Current point in recent measurements, to save space uint16_t current_measurements_; // Boolean value to check if the array has been filled, to not wrong variance bool previous_filled_; // Flag to write to file bool write_to_file_; // Kalman filters to filter each IMU measurement individually FilterArray filters_; // Counter for consecutive outlier output from each IMU std::array<uint32_t, data::Sensors::kNumImus> imu_outlier_counter_; // Array of booleans to signify which IMUs are reliable or faulty std::array<bool, data::Sensors::kNumImus> is_imu_reliable_; // Counter of how many IMUs have failed uint32_t num_outlier_imus_; // To store estimated values ImuDataPointArray sensor_readings_; data::DataPoint<data::nav_t> acceleration_; data::DataPoint<data::nav_t> velocity_; data::DataPoint<data::nav_t> displacement_; NavigationVectorArray gravity_calibration_; // Initial timestamp (for comparisons) uint32_t initial_timestamp_; // Previous timestamp uint32_t previous_timestamp_; // Uncertainty in distance data::nav_t displacement_uncertainty_; // Uncertainty in velocity data::nav_t velocity_uncertainty_; // Previous acceleration measurement, necessary for uncertainty determination data::nav_t previous_acceleration_; // Previous velocity measurement data::nav_t previous_velocity_; // Have initial timestamps been set? bool has_initial_time_; // Stripe counter object StripeHandler stripe_counter_; // Flags if keyences are used and if real bool is_keyence_used_; bool is_keyence_real_; // To convert acceleration -> velocity -> distance utils::math::Integrator<data::nav_t> acceleration_integrator_; // acceleration to velocity utils::math::Integrator<data::nav_t> velocity_integrator_; // velocity to distance /** * @brief Query sensors to determine acceleration, velocity and distance */ void queryImus(); /** * @brief Query Keyence sensors to determine whether a stripe is found, update stripe_counter_ * accordingly */ void queryKeyence(); /** * @brief Update uncertainty in distance obtained through IMU measurements. */ void updateUncertainty(); /** * @brief Check for vibrations */ void checkVibration(); }; } // namespace navigation } // namespace hyped
32.120332
99
0.707661
[ "object", "vector" ]
7c0d7fa65361c02622675959eb4d9f24f82e86a7
2,268
cpp
C++
src/17_phone_num.cpp
coolspeed/leetcode
d5fdcd3ba9849327b43e35bf3b5cb2bd1d8e312d
[ "CC0-1.0" ]
1
2015-06-12T02:32:51.000Z
2015-06-12T02:32:51.000Z
src/17_phone_num.cpp
coolspeed/leetcode
d5fdcd3ba9849327b43e35bf3b5cb2bd1d8e312d
[ "CC0-1.0" ]
null
null
null
src/17_phone_num.cpp
coolspeed/leetcode
d5fdcd3ba9849327b43e35bf3b5cb2bd1d8e312d
[ "CC0-1.0" ]
null
null
null
/* 25 / 25 test cases passed. Status: Accepted Runtime: 0 ms Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want. */ #include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: vector<string> letterCombinations(string digits) { vector<string> ret; if (digits.size() <= 0) return ret; setUpCharTable(); int retSize = 1; int digitSize = digits.size(); for (int i = 0; i < digitSize; i++) retSize *= charTable[digits[i] - '0'].size(); vector<string> ret2(retSize, ""); for (int j = 0; j < ret2.size(); j++) { int product = 1; for (int k = 0; k < digitSize; k++) { int currCharSize = charTable[digits[k] - '0'].size(); int currIndex = (j / product) % currCharSize; ret2[j] += charTable[digits[k] - '0'][currIndex]; product *= currCharSize; } } return ret2; } private: void setUpCharTable(); vector<vector<int>> charTable; }; void Solution::setUpCharTable() { this->charTable.clear(); this->charTable.push_back({}); this->charTable.push_back({}); this->charTable.push_back({ 'a', 'b', 'c' }); this->charTable.push_back({ 'd', 'e', 'f' }); this->charTable.push_back({ 'g', 'h', 'i' }); this->charTable.push_back({ 'j', 'k', 'l' }); this->charTable.push_back({ 'm', 'n', 'o' }); this->charTable.push_back({ 'p', 'q', 'r', 's' }); this->charTable.push_back({ 't', 'u', 'v' }); this->charTable.push_back({ 'w', 'x', 'y', 'z' }); } int main() { Solution mysolution = Solution(); string digits = "23"; vector<string> ret = mysolution.letterCombinations(digits); // print ret cout << "====================================================" << endl; for (string elem : ret) cout << elem << endl; cin.get(); return 0; }
25.772727
98
0.55291
[ "vector" ]
7c1eb1f0615b7b94d26492f84dcacebf5b6252ab
4,275
hpp
C++
src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Evolution/Systems/GrMhd/GhValenciaDivClean/FiniteDifference/ReconstructWork.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <array> #include <boost/functional/hash.hpp> #include <cstddef> #include <utility> #include "DataStructures/FixedHashMap.hpp" #include "DataStructures/Tensor/TypeAliases.hpp" #include "Domain/Structure/MaxNumberOfNeighbors.hpp" #include "Evolution/Systems/GeneralizedHarmonic/Tags.hpp" /// \cond template <typename TagsList> class Variables; namespace gsl { template <typename> class not_null; } // namespace gsl template <size_t Dim> class Direction; template <size_t Dim> class ElementId; template <size_t Dim> class Element; template <size_t Dim> class Mesh; namespace EquationsOfState { template <bool IsRelativistic, size_t ThermodynamicDim> class EquationOfState; } // namespace EquationsOfState /// \endcond namespace grmhd::GhValenciaDivClean::fd { /*! * \brief Reconstructs \f$\rho, p, Wv^i, B^i\f$, \f$\Phi\f$, and the spacetime * metric, then computes the Lorentz factor, upper spatial velocity, specific * internal energy, specific enthalpy, and the conserved variables. All results * are written into `vars_on_lower_face` and `vars_on_upper_face`. */ template <typename SpacetimeTagsToReconstruct, typename PrimsTags, typename SpacetimeAndConsTags, typename TagsList, size_t ThermodynamicDim, typename HydroReconstructor, typename SpacetimeReconstructor, typename ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags> void reconstruct_prims_work( gsl::not_null<std::array<Variables<TagsList>, 3>*> vars_on_lower_face, gsl::not_null<std::array<Variables<TagsList>, 3>*> vars_on_upper_face, const HydroReconstructor& hydro_reconstructor, const SpacetimeReconstructor& spacetime_reconstructor, const ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags& spacetime_vars_for_grmhd, const Variables<PrimsTags>& volume_prims, const Variables<SpacetimeAndConsTags>& volume_spacetime_and_cons_vars, const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos, const Element<3>& element, const FixedHashMap< maximum_number_of_neighbors(3) + 1, std::pair<Direction<3>, ElementId<3>>, std::vector<double>, boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data, const Mesh<3>& subcell_mesh, size_t ghost_zone_size); /*! * \brief Reconstructs \f$\rho, p, Wv^i, B^i\f$, \f$\Phi\f$, the spacetime * metric, \f$\Phi_{iab}\f$, and \f$\Pi_{ab}\f$, then computes the Lorentz * factor, upper spatial velocity, specific internal energy, specific enthalpy, * and the conserved variables. All results are written into `vars_on_face`. * * This is used on DG elements to reconstruct their subcell neighbors' solution * on the shared faces. */ template < typename TagsList, typename PrimsTags, size_t ThermodynamicDim, typename LowerHydroReconstructor, typename LowerSpacetimeReconstructor, typename UpperHydroReconstructor, typename UpperSpacetimeReconstructor, typename ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags> void reconstruct_fd_neighbor_work( gsl::not_null<Variables<TagsList>*> vars_on_face, const LowerHydroReconstructor& reconstruct_lower_neighbor_hydro, const LowerSpacetimeReconstructor& reconstruct_lower_neighbor_spacetime, const UpperHydroReconstructor& reconstruct_upper_neighbor_hydro, const UpperSpacetimeReconstructor& reconstruct_upper_neighbor_spacetime, const ComputeGrmhdSpacetimeVarsFromReconstructedSpacetimeTags& spacetime_vars_for_grmhd, const Variables<PrimsTags>& subcell_volume_prims, const Variables<tmpl::list< gr::Tags::SpacetimeMetric<3>, GeneralizedHarmonic::Tags::Phi<3>, GeneralizedHarmonic::Tags::Pi<3>>>& subcell_volume_spacetime_vars, const EquationsOfState::EquationOfState<true, ThermodynamicDim>& eos, const Element<3>& element, const FixedHashMap< maximum_number_of_neighbors(3) + 1, std::pair<Direction<3>, ElementId<3>>, std::vector<double>, boost::hash<std::pair<Direction<3>, ElementId<3>>>>& neighbor_data, const Mesh<3>& subcell_mesh, const Direction<3>& direction_to_reconstruct, size_t ghost_zone_size); } // namespace grmhd::GhValenciaDivClean::fd
42.326733
79
0.767485
[ "mesh", "vector" ]
7c21e70ba296e6ae557228e56155e0b5e6ab3cbc
9,785
cpp
C++
src/storage/index/bplustree_index.cpp
abhijithanilkumar/terrier
5d05d15894b8338d997eb874268a40bc41f67b30
[ "MIT" ]
null
null
null
src/storage/index/bplustree_index.cpp
abhijithanilkumar/terrier
5d05d15894b8338d997eb874268a40bc41f67b30
[ "MIT" ]
null
null
null
src/storage/index/bplustree_index.cpp
abhijithanilkumar/terrier
5d05d15894b8338d997eb874268a40bc41f67b30
[ "MIT" ]
null
null
null
#include "storage/index/bplustree_index.h" #include "storage/index/compact_ints_key.h" #include "storage/index/generic_key.h" #include "transaction/deferred_action_manager.h" #include "transaction/transaction_context.h" namespace noisepage::storage::index { template <typename KeyType> BPlusTreeIndex<KeyType>::BPlusTreeIndex(IndexMetadata &&metadata) : Index(std::move(metadata)), bplustree_{new BPlusTree<KeyType, TupleSlot>} {} template <typename KeyType> void BPlusTreeIndex<KeyType>::PerformGarbageCollection() { // B+ Tree does not require any garbage collection } template <typename KeyType> size_t BPlusTreeIndex<KeyType>::EstimateHeapUsage() const { return bplustree_->EstimateHeapUsage(); } template <typename KeyType> bool BPlusTreeIndex<KeyType>::Insert(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) { NOISEPAGE_ASSERT(!(metadata_.GetSchema().Unique()), "This Insert is designed for secondary indexes with no uniqueness constraints."); KeyType index_key; index_key.SetFromProjectedRow(tuple, metadata_, metadata_.GetSchema().GetColumns().size()); auto predicate = [](const TupleSlot slot) -> bool { return false; }; const bool result = bplustree_->Insert(bplustree_->GetElement(index_key, location), predicate); NOISEPAGE_ASSERT( result, "non-unique index shouldn't fail to insert. If it did, something went wrong deep inside the BPlusTree itself."); // Register an abort action with the txn context in case of rollback txn->RegisterAbortAction([=]() { const bool UNUSED_ATTRIBUTE result = bplustree_->DeleteElement(bplustree_->GetElement(index_key, location)); NOISEPAGE_ASSERT(result, "Delete on the index failed."); }); return result; } template <typename KeyType> bool BPlusTreeIndex<KeyType>::InsertUnique(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) { NOISEPAGE_ASSERT(metadata_.GetSchema().Unique(), "This Insert is designed for indexes with uniqueness constraints."); KeyType index_key; index_key.SetFromProjectedRow(tuple, metadata_, metadata_.GetSchema().GetColumns().size()); // The predicate checks if any matching keys have write-write conflicts or are still visible to the calling txn. auto predicate = [txn](const TupleSlot slot) -> bool { const auto *const data_table = slot.GetBlock()->data_table_; const auto has_conflict = data_table->HasConflict(*txn, slot); const auto is_visible = data_table->IsVisible(*txn, slot); return has_conflict || is_visible; }; // Insert a key-value pair const bool result = bplustree_->Insert(bplustree_->GetElement(index_key, location), predicate); if (result) { // Register an abort action with the txn context in case of rollback txn->RegisterAbortAction([=]() { const bool UNUSED_ATTRIBUTE result = bplustree_->DeleteElement(bplustree_->GetElement(index_key, location)); NOISEPAGE_ASSERT(result, "Delete on the index failed."); }); } else { // Presumably you've already made modifications to a DataTable (the source of the TupleSlot argument to this // function) however, the index found a constraint violation and cannot allow that operation to succeed. For MVCC // correctness, this txn must now abort for the GC to clean up the version chain in the DataTable correctly. txn->SetMustAbort(); } return result; } template <typename KeyType> void BPlusTreeIndex<KeyType>::Delete(common::ManagedPointer<transaction::TransactionContext> txn, const ProjectedRow &tuple, TupleSlot location) { KeyType index_key; index_key.SetFromProjectedRow(tuple, metadata_, metadata_.GetSchema().GetColumns().size()); NOISEPAGE_ASSERT(!(location.GetBlock()->data_table_->HasConflict(*txn, location)) && !(location.GetBlock()->data_table_->IsVisible(*txn, location)), "Called index delete on a TupleSlot that has a conflict with this txn or is still visible."); // Register a deferred action for the GC with txn manager. See base function comment. txn->RegisterCommitAction([=](transaction::DeferredActionManager *deferred_action_manager) { deferred_action_manager->RegisterDeferredAction([=]() { const bool UNUSED_ATTRIBUTE result = bplustree_->DeleteElement(bplustree_->GetElement(index_key, location)); NOISEPAGE_ASSERT(result, "Deferred delete on the index failed."); }); }); } template <typename KeyType> void BPlusTreeIndex<KeyType>::ScanKey(const transaction::TransactionContext &txn, const ProjectedRow &key, std::vector<TupleSlot> *value_list) { NOISEPAGE_ASSERT(value_list->empty(), "Result set should begin empty."); std::vector<TupleSlot> results; // Build search key KeyType index_key; index_key.SetFromProjectedRow(key, metadata_, metadata_.GetSchema().GetColumns().size()); // Perform lookup in BPlusTree bplustree_->FindValueOfKey(index_key, &results); // Avoid resizing our value_list, even if it means over-provisioning value_list->reserve(results.size()); // Perform visibility check on result for (const auto &result : results) { if (IsVisible(txn, result)) value_list->emplace_back(result); } NOISEPAGE_ASSERT(!(metadata_.GetSchema().Unique()) || (metadata_.GetSchema().Unique() && value_list->size() <= 1), "Invalid number of results for unique index."); } template <typename KeyType> void BPlusTreeIndex<KeyType>::ScanAscending(const transaction::TransactionContext &txn, ScanType scan_type, uint32_t num_attrs, ProjectedRow *low_key, ProjectedRow *high_key, uint32_t limit, std::vector<TupleSlot> *value_list) { NOISEPAGE_ASSERT(value_list->empty(), "Result set should begin empty."); NOISEPAGE_ASSERT(scan_type == ScanType::Closed || scan_type == ScanType::OpenLow || scan_type == ScanType::OpenHigh || scan_type == ScanType::OpenBoth, "Invalid scan_type passed into BPlusTreeIndex::Scan"); bool low_key_exists = (scan_type == ScanType::Closed || scan_type == ScanType::OpenHigh); bool high_key_exists = (scan_type == ScanType::Closed || scan_type == ScanType::OpenLow); // The predicate checks if any matching keys are still visible to the calling txn. auto predicate = [&txn](const TupleSlot slot) -> bool { return IsVisible(txn, slot); }; // Build search keys KeyType index_low_key, index_high_key; if (low_key_exists) index_low_key.SetFromProjectedRow(*low_key, metadata_, num_attrs); if (high_key_exists) index_high_key.SetFromProjectedRow(*high_key, metadata_, num_attrs); bool scan_completed = false; while (!scan_completed) { value_list->clear(); scan_completed = bplustree_->ScanAscending(index_low_key, index_high_key, low_key_exists, num_attrs, high_key_exists, limit, value_list, &metadata_, predicate); } } template <typename KeyType> void BPlusTreeIndex<KeyType>::ScanDescending(const transaction::TransactionContext &txn, const ProjectedRow &low_key, const ProjectedRow &high_key, std::vector<TupleSlot> *value_list) { NOISEPAGE_ASSERT(value_list->empty(), "Result set should begin empty."); // Build search keys KeyType index_low_key, index_high_key; index_low_key.SetFromProjectedRow(low_key, metadata_, metadata_.GetSchema().GetColumns().size()); index_high_key.SetFromProjectedRow(high_key, metadata_, metadata_.GetSchema().GetColumns().size()); bool scan_completed = false; std::vector<TupleSlot> results; while (!scan_completed) { results.clear(); scan_completed = bplustree_->ScanDescending(index_low_key, index_high_key, &results); } for (const auto &result : results) { if (IsVisible(txn, result)) value_list->emplace_back(result); } } template <typename KeyType> void BPlusTreeIndex<KeyType>::ScanLimitDescending(const transaction::TransactionContext &txn, const ProjectedRow &low_key, const ProjectedRow &high_key, std::vector<TupleSlot> *value_list, uint32_t limit) { NOISEPAGE_ASSERT(value_list->empty(), "Result set should begin empty."); NOISEPAGE_ASSERT(limit > 0, "Limit must be greater than 0."); // The predicate checks if any matching keys are still visible to the calling txn. auto predicate = [&txn](const TupleSlot slot) -> bool { return IsVisible(txn, slot); }; // Build search keys KeyType index_low_key, index_high_key; index_low_key.SetFromProjectedRow(low_key, metadata_, metadata_.GetSchema().GetColumns().size()); index_high_key.SetFromProjectedRow(high_key, metadata_, metadata_.GetSchema().GetColumns().size()); bool scan_completed = false; while (!scan_completed) { value_list->clear(); scan_completed = bplustree_->ScanLimitDescending(index_low_key, index_high_key, value_list, limit, predicate); } } template <typename KeyType> uint64_t BPlusTreeIndex<KeyType>::GetSize() const { return bplustree_->GetSize(); } template class BPlusTreeIndex<CompactIntsKey<8>>; template class BPlusTreeIndex<CompactIntsKey<16>>; template class BPlusTreeIndex<CompactIntsKey<24>>; template class BPlusTreeIndex<CompactIntsKey<32>>; template class BPlusTreeIndex<GenericKey<64>>; template class BPlusTreeIndex<GenericKey<128>>; template class BPlusTreeIndex<GenericKey<256>>; template class BPlusTreeIndex<GenericKey<512>>; } // namespace noisepage::storage::index
44.885321
120
0.716607
[ "vector" ]
7c27b208f4877036ab09251a9f2976b1d5c51afa
3,965
cpp
C++
aws-cpp-sdk-dataexchange/source/model/ApiGatewayApiAsset.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-dataexchange/source/model/ApiGatewayApiAsset.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-dataexchange/source/model/ApiGatewayApiAsset.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/dataexchange/model/ApiGatewayApiAsset.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DataExchange { namespace Model { ApiGatewayApiAsset::ApiGatewayApiAsset() : m_apiDescriptionHasBeenSet(false), m_apiEndpointHasBeenSet(false), m_apiIdHasBeenSet(false), m_apiKeyHasBeenSet(false), m_apiNameHasBeenSet(false), m_apiSpecificationDownloadUrlHasBeenSet(false), m_apiSpecificationDownloadUrlExpiresAtHasBeenSet(false), m_protocolType(ProtocolType::NOT_SET), m_protocolTypeHasBeenSet(false), m_stageHasBeenSet(false) { } ApiGatewayApiAsset::ApiGatewayApiAsset(JsonView jsonValue) : m_apiDescriptionHasBeenSet(false), m_apiEndpointHasBeenSet(false), m_apiIdHasBeenSet(false), m_apiKeyHasBeenSet(false), m_apiNameHasBeenSet(false), m_apiSpecificationDownloadUrlHasBeenSet(false), m_apiSpecificationDownloadUrlExpiresAtHasBeenSet(false), m_protocolType(ProtocolType::NOT_SET), m_protocolTypeHasBeenSet(false), m_stageHasBeenSet(false) { *this = jsonValue; } ApiGatewayApiAsset& ApiGatewayApiAsset::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ApiDescription")) { m_apiDescription = jsonValue.GetString("ApiDescription"); m_apiDescriptionHasBeenSet = true; } if(jsonValue.ValueExists("ApiEndpoint")) { m_apiEndpoint = jsonValue.GetString("ApiEndpoint"); m_apiEndpointHasBeenSet = true; } if(jsonValue.ValueExists("ApiId")) { m_apiId = jsonValue.GetString("ApiId"); m_apiIdHasBeenSet = true; } if(jsonValue.ValueExists("ApiKey")) { m_apiKey = jsonValue.GetString("ApiKey"); m_apiKeyHasBeenSet = true; } if(jsonValue.ValueExists("ApiName")) { m_apiName = jsonValue.GetString("ApiName"); m_apiNameHasBeenSet = true; } if(jsonValue.ValueExists("ApiSpecificationDownloadUrl")) { m_apiSpecificationDownloadUrl = jsonValue.GetString("ApiSpecificationDownloadUrl"); m_apiSpecificationDownloadUrlHasBeenSet = true; } if(jsonValue.ValueExists("ApiSpecificationDownloadUrlExpiresAt")) { m_apiSpecificationDownloadUrlExpiresAt = jsonValue.GetString("ApiSpecificationDownloadUrlExpiresAt"); m_apiSpecificationDownloadUrlExpiresAtHasBeenSet = true; } if(jsonValue.ValueExists("ProtocolType")) { m_protocolType = ProtocolTypeMapper::GetProtocolTypeForName(jsonValue.GetString("ProtocolType")); m_protocolTypeHasBeenSet = true; } if(jsonValue.ValueExists("Stage")) { m_stage = jsonValue.GetString("Stage"); m_stageHasBeenSet = true; } return *this; } JsonValue ApiGatewayApiAsset::Jsonize() const { JsonValue payload; if(m_apiDescriptionHasBeenSet) { payload.WithString("ApiDescription", m_apiDescription); } if(m_apiEndpointHasBeenSet) { payload.WithString("ApiEndpoint", m_apiEndpoint); } if(m_apiIdHasBeenSet) { payload.WithString("ApiId", m_apiId); } if(m_apiKeyHasBeenSet) { payload.WithString("ApiKey", m_apiKey); } if(m_apiNameHasBeenSet) { payload.WithString("ApiName", m_apiName); } if(m_apiSpecificationDownloadUrlHasBeenSet) { payload.WithString("ApiSpecificationDownloadUrl", m_apiSpecificationDownloadUrl); } if(m_apiSpecificationDownloadUrlExpiresAtHasBeenSet) { payload.WithString("ApiSpecificationDownloadUrlExpiresAt", m_apiSpecificationDownloadUrlExpiresAt.ToGmtString(DateFormat::ISO_8601)); } if(m_protocolTypeHasBeenSet) { payload.WithString("ProtocolType", ProtocolTypeMapper::GetNameForProtocolType(m_protocolType)); } if(m_stageHasBeenSet) { payload.WithString("Stage", m_stage); } return payload; } } // namespace Model } // namespace DataExchange } // namespace Aws
22.027778
136
0.749054
[ "model" ]
7c2991f0540be417143a9833a0dba2cdbb9c1c1e
29,012
cpp
C++
shell/osshell/snapins/devmgr/snapin/utils.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/osshell/snapins/devmgr/snapin/utils.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/osshell/snapins/devmgr/snapin/utils.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (C) Microsoft Corporation Module Name: utils.cpp Abstract: This module implements some utilities classes Author: William Hsieh (williamh) created Revision History: --*/ #include "devmgr.h" // // CPropSheetData implementation // // Every device or class has a CPropSheetData as a member. // When m_hWnd contains a valid window handle, it indicates the device/class // has a active property sheet. This helps us to do this: // (1). We are sure that there is only one property sheet can be created // for the device/class at time in a single console no matter how many // IComponents(snapins, windows) are running in the same console. // For example, when users asks for the properties for the device/class // we can bring the active one to the foreground without creating a // new one. // (2). We can warn the user that a removal of the device is not allowed // when the device has an active property sheet. // (3). We can warn the user that there are property sheets active // when a "refresh" is requsted. CPropSheetData::CPropSheetData() { memset(&m_psh, 0, sizeof(m_psh)); m_MaxPages = 0; m_lConsoleHandle = 0; m_hWnd = NULL; } // This function creates(or initialize) the propery sheet data header. // // INPUT: hInst -- the module instance handle // hwndParent -- parent window handle // MaxPages -- max pages allowed for this property sheet. // lConsoleHandle -- MMC property change notify handle. // // OUTPUT: TRUE if succeeded. // FALSE if failed(mostly, memory allocation error). GetLastError // will report the error code. // BOOL CPropSheetData::Create( HINSTANCE hInst, HWND hwndParent, UINT MaxPages, LONG_PTR lConsoleHandle ) { // nobody should try to create the property sheet while it is // still alive. ASSERT (NULL == m_hWnd); if (MaxPages > 64 || NULL == hInst) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } // if not page array is allocated or the existing // array is too small, allocate a new array. if (!m_psh.phpage || m_MaxPages < MaxPages) { if (m_MaxPages) { ASSERT(m_psh.phpage); delete [] m_psh.phpage; m_psh.phpage = NULL; } m_psh.phpage = new HPROPSHEETPAGE[MaxPages]; m_MaxPages = MaxPages; } // initialize the header m_psh.nPages = 0; m_psh.dwSize = sizeof(m_psh); m_psh.dwFlags = PSH_PROPTITLE | PSH_NOAPPLYNOW; m_psh.hwndParent = hwndParent; m_psh.hInstance = hInst; m_psh.pszCaption = NULL; m_lConsoleHandle = lConsoleHandle; return TRUE; } // This function inserts the given HPROPSHEETPAGE to the // specific location. // // INPUT: hPage -- the page to be inserted. // Position -- the location to be inserted. // Position < 0, then append the page // // OUTPUT: TRUE if the page is inserted successfully. // FALSE if the page is not inserted. GetLastError will // return the error code. // BOOL CPropSheetData::InsertPage( HPROPSHEETPAGE hPage, int Position ) { if (NULL == hPage || (Position > 0 && (UINT)Position >= m_MaxPages)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } // make sure we have space for a new page. if (m_psh.nPages >= m_MaxPages) { SetLastError(ERROR_BUFFER_OVERFLOW); return FALSE; } if (Position < 0 || (UINT)Position >= m_psh.nPages) { // append the page. This also include the very first page. // Most pages are appened. m_psh.phpage[m_psh.nPages++] = hPage; } else { ASSERT(m_psh.nPages); // move the page around so that we // can insert the new page to the // specific location. // At this moment, we know we have space to accomodate the // new page(so we can assume that &m_psh.phpage[m_psh.nPage] // is valid. Also, we are here because there is at least one // pages in the array. for (int i = m_psh.nPages; i > Position; i--) m_psh.phpage[i] = m_psh.phpage[i - 1]; m_psh.phpage[Position] = hPage; m_psh.nPages++; } return TRUE; } // // This function receives notification from its attached // property pages about their window(dialog) creation // It takes a chance to record the property sheet window handle // which we can use to dismiss the property sheet or bring it // to the foreground. // INPUT: // hWnd -- the property page's window handle // // OUTPUT: // NONE // void CPropSheetData::PageCreateNotify(HWND hWnd) { ASSERT(hWnd); hWnd = ::GetParent(hWnd); if (!m_hWnd) m_hWnd = hWnd; } // // This function receives notification from its attached // property pages about their window(dialog) destroy. // When all attached pages are gone, this function // reset its internal states and free memory allocation // WARNING!!!! Do not delete the object when the attached // window handle counts reaches 0 because we can be reused -- // the reason we have a separate Create functions. // // INPUT: // hWnd -- the property page's window handle // // OUTPUT: // NONE // void CPropSheetData::PageDestroyNotify(HWND hWnd) { UNREFERENCED_PARAMETER(hWnd); m_hWnd = NULL; delete [] m_psh.phpage; m_psh.phpage = NULL; m_MaxPages = 0; memset(&m_psh, 0, sizeof(m_psh)); if (m_lConsoleHandle) MMCFreeNotifyHandle(m_lConsoleHandle); m_lConsoleHandle = 0; if (!m_listProvider.IsEmpty()) { POSITION pos = m_listProvider.GetHeadPosition(); while (NULL != pos) { delete m_listProvider.GetNext(pos); } m_listProvider.RemoveAll(); } } CPropSheetData::~CPropSheetData() { if (m_lConsoleHandle) MMCFreeNotifyHandle(m_lConsoleHandle); if (!m_listProvider.IsEmpty()) { POSITION pos = m_listProvider.GetHeadPosition(); while (NULL != pos) { delete m_listProvider.GetNext(pos); } m_listProvider.RemoveAll(); } if (m_psh.phpage) delete [] m_psh.phpage; } BOOL CPropSheetData::PropertyChangeNotify( LPARAM lParam ) { if (m_lConsoleHandle) { MMCPropertyChangeNotify(m_lConsoleHandle, lParam); return TRUE; } return FALSE; } // // CDialog implementation // INT_PTR CALLBACK CDialog::DialogWndProc( HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { CDialog* pThis = (CDialog *) GetWindowLongPtr(hDlg, DWLP_USER); BOOL Result; switch (uMsg) { case WM_INITDIALOG: pThis = (CDialog *)lParam; ASSERT(pThis); SetWindowLongPtr(hDlg, DWLP_USER, (LONG_PTR)pThis); pThis->m_hDlg = hDlg; Result = pThis->OnInitDialog(); break; case WM_COMMAND: if (pThis) { pThis->OnCommand(wParam, lParam); } Result = FALSE; break; case WM_NOTIFY: if (pThis) { Result = pThis->OnNotify((LPNMHDR)lParam); } else { Result = FALSE; } break; case WM_DESTROY: if (pThis) { Result = pThis->OnDestroy(); } else { Result = FALSE; } break; case WM_HELP: if (pThis) { pThis->OnHelp((LPHELPINFO)lParam); } Result = FALSE; break; case WM_CONTEXTMENU: if (pThis) { pThis->OnContextMenu((HWND)wParam, LOWORD(lParam), HIWORD(lParam)); } Result = FALSE; break; default: Result = FALSE; break; } return Result; } // // class String implementation // String::String() { m_pData = new StringData; if (!m_pData) throw &g_MemoryException; } String::String( const String& strSrc ) { m_pData = strSrc.m_pData; m_pData->AddRef(); } String::String( int Len ) { StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[Len + 1]; if (pNewData && ptszNew) { pNewData->Len = 0; pNewData->ptsz = ptszNew; m_pData = pNewData; } else { delete pNewData; delete [] ptszNew; throw &g_MemoryException; } } String::String( LPCTSTR lptsz ) { int Len = lstrlen(lptsz); StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[Len + 1]; if (pNewData && ptszNew) { StringCchCopy(ptszNew, Len+1, lptsz); pNewData->Len = Len; pNewData->ptsz = ptszNew; m_pData = pNewData; } else { delete pNewData; delete [] ptszNew; throw &g_MemoryException; } } void String::Empty() { if (m_pData->Len) { StringData* pNewData = new StringData; if (pNewData) { m_pData->Release(); m_pData = pNewData; } else { throw &g_MemoryException; } } } String& String::operator=( const String& strSrc ) { // look out for aliasings !!!! if (this != &strSrc) { // add the reference count first before release the old one // in case our string data is the same as strSrc's. strSrc.m_pData->AddRef(); m_pData->Release(); m_pData = strSrc.m_pData; } return *this; } String& String::operator=( LPCTSTR ptsz ) { // if we are pointing to the same string, // do nothing if (ptsz == m_pData->ptsz) return *this; // // str = NULL --> empty the string // if (!ptsz) { Empty(); return *this; } // a new assignment, allocate a new string data StringData* pNewData = new StringData; int len = lstrlen(ptsz); TCHAR* ptszNew = new TCHAR[len + 1]; if (pNewData && ptszNew) { StringCchCopy(ptszNew, len+1, ptsz); pNewData->Len = len; pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; } else { //memory allocation failure delete pNewData; delete [] ptszNew; throw g_MemoryException; } return *this; } String& String::operator+=( const String& strSrc ) { if (strSrc.GetLength()) { int TotalLen = m_pData->Len + strSrc.GetLength(); StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[TotalLen + 1]; if (pNewData && ptszNew) { StringCchCopy(ptszNew, TotalLen+1, m_pData->ptsz); StringCchCat(ptszNew, TotalLen+1, (LPCTSTR)strSrc); ptszNew[TotalLen] = TEXT('\0'); pNewData->Len = TotalLen; pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; } else { delete pNewData; delete [] ptszNew; throw &g_MemoryException; } } return *this; } String& String::operator+=( LPCTSTR ptsz ) { if (ptsz) { int len = lstrlen(ptsz); if (len) { StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[len + m_pData->Len + 1]; if (ptszNew && pNewData) { StringCchCopy(ptszNew, len + m_pData->Len + 1, m_pData->ptsz); StringCchCat(ptszNew, len + m_pData->Len + 1, ptsz); ptszNew[len + m_pData->Len] = TEXT('\0'); pNewData->Len = len + m_pData->Len; pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; } else { delete pNewData; delete [] ptszNew; throw &g_MemoryException; } } } return *this; } TCHAR& String::operator[]( int Index ) { ASSERT(Index < m_pData->Len); // make a separate copy of the string data TCHAR* ptszNew = new TCHAR[m_pData->Len + 1]; StringData* pNewData = new StringData; if (ptszNew && pNewData) { StringCchCopy(ptszNew, m_pData->Len + 1, m_pData->ptsz); pNewData->ptsz = ptszNew; pNewData->Len = m_pData->Len; m_pData->Release(); m_pData = pNewData; return ptszNew[Index]; } else { delete pNewData; delete [] ptszNew; throw &g_MemoryException; } } String::operator LPTSTR() { StringData* pNewData = new StringData; if (pNewData) { if (m_pData->Len) { TCHAR* ptszNew = new TCHAR[m_pData->Len + 1]; if (ptszNew) { StringCchCopy(ptszNew, m_pData->Len + 1, m_pData->ptsz); pNewData->ptsz = ptszNew; } else { delete pNewData; throw &g_MemoryException; } } pNewData->Len = m_pData->Len; m_pData->Release(); m_pData = pNewData; return m_pData->ptsz; } else { throw &g_MemoryException ; } } // // This is a friend function to String // Remember that we can NOT return a reference or a pointer. // This function must return "by-value" String operator+( const String& str1, const String& str2 ) { int TotalLen = str1.GetLength() + str2.GetLength(); String strThis(TotalLen); StringCchCopy(strThis.m_pData->ptsz, TotalLen+1, str1); StringCchCat(strThis.m_pData->ptsz, TotalLen+1, str2); strThis.m_pData->Len = TotalLen; return strThis; } BOOL String::LoadString( HINSTANCE hInstance, int ResourceId ) { // we have no idea how long the string will be. // The strategy here is to allocate a stack-based buffer which // is large enough for most cases. If the buffer is too small, // we then use heap-based buffer and increment the buffer size // on each try. TCHAR tszTemp[256]; long FinalSize, BufferSize; BufferSize = ARRAYLEN(tszTemp); TCHAR* HeapBuffer = NULL; // first try FinalSize = ::LoadString(hInstance, ResourceId, tszTemp, BufferSize); // // LoadString returns the size of the string it loaded, not including the // NULL termiated char. So if the returned len is one less then the // provided buffer size, our buffer is too small. // if (FinalSize < (BufferSize - 1)) { // we got what we want HeapBuffer = tszTemp; } else { // the stack based buffer is too small, we have to switch to heap // based. BufferSize = ARRAYLEN(tszTemp); // should 32k chars big enough???? while (BufferSize < 0x8000) { BufferSize += 256; // make sure there is no memory leak ASSERT(NULL == HeapBuffer); // allocate a new buffer HeapBuffer = new TCHAR[BufferSize]; if (HeapBuffer) { // got a new buffer, another try... FinalSize = ::LoadString(hInstance, ResourceId, HeapBuffer, BufferSize); if (FinalSize < (BufferSize - 1)) { //got it! break; } } else { throw &g_MemoryException; } // discard the buffer delete [] HeapBuffer; HeapBuffer = NULL; } } if (HeapBuffer) { TCHAR* ptszNew = new TCHAR[FinalSize + 1]; StringData* pNewData = new StringData; if (pNewData && ptszNew) { StringCchCopy(ptszNew, FinalSize + 1, HeapBuffer); // release the old string data because we will have a new one m_pData->Release(); m_pData = pNewData; m_pData->ptsz = ptszNew; m_pData->Len = FinalSize; if (HeapBuffer != tszTemp) { delete [] HeapBuffer; } return TRUE; } else { delete [] ptszNew; delete pNewData; if (HeapBuffer != tszTemp) { delete [] HeapBuffer; } throw &g_MemoryException; } } return FALSE; } // // This function creates an full-qualified machine name for the // local computer. // BOOL String::GetComputerName() { TCHAR tszTemp[MAX_PATH]; // the GetComputerName api only return the name only. // we must prepend the UNC signature. tszTemp[0] = _T('\\'); tszTemp[1] = _T('\\'); ULONG NameLength = ARRAYLEN(tszTemp) - 2; if (::GetComputerName(tszTemp + 2, &NameLength)) { int Len = lstrlen(tszTemp); StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[Len + 1]; if (pNewData && ptszNew) { pNewData->Len = Len; StringCchCopy(ptszNew, Len + 1, tszTemp); pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; return TRUE; } else { delete pNewData; delete []ptszNew; throw &g_MemoryException; } } return FALSE; } BOOL String::GetSystemWindowsDirectory() { TCHAR tszTemp[MAX_PATH]; if (::GetSystemWindowsDirectory(tszTemp, ARRAYLEN(tszTemp))) { int Len = lstrlen(tszTemp); StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[Len + 1]; if (pNewData && ptszNew) { pNewData->Len = Len; StringCchCopy(ptszNew, Len + 1, tszTemp); pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; return TRUE; } else { delete pNewData; delete []ptszNew; throw &g_MemoryException; } } return FALSE; } BOOL String::GetSystemDirectory() { TCHAR tszTemp[MAX_PATH]; if (::GetSystemDirectory(tszTemp, ARRAYLEN(tszTemp))) { int Len = lstrlen(tszTemp); StringData* pNewData = new StringData; TCHAR* ptszNew = new TCHAR[Len + 1]; if (pNewData && ptszNew) { pNewData->Len = Len; StringCchCopy(ptszNew, Len + 1, tszTemp); pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; return TRUE; } else { delete pNewData; delete []ptszNew; throw &g_MemoryException; } } return FALSE; } void String::Format( LPCTSTR FormatString, ... ) { // according to wsprintf specification, the max buffer size is // 1024 TCHAR* pBuffer = new TCHAR[1024]; if (pBuffer) { va_list arglist; va_start(arglist, FormatString); StringCchVPrintf(pBuffer, 1024, FormatString, arglist); va_end(arglist); int len = lstrlen(pBuffer); if (len) { TCHAR* ptszNew = new TCHAR[len + 1]; StringData* pNewData = new StringData; if (pNewData && ptszNew) { pNewData->Len = len; StringCchCopy(ptszNew, len + 1, pBuffer); pNewData->ptsz = ptszNew; m_pData->Release(); m_pData = pNewData; delete [] pBuffer; return; } else { delete [] pBuffer; delete [] ptszNew; delete pNewData; throw &g_MemoryException; } } } throw &g_MemoryException; } // // templates // template <class T> inline void ContructElements(T* pElements, int Count) { ASSERT(Count > 0); memset((void*)pElements, Count * sizeof(T)); for (; Count; pElments++, Count--) { // call the class's ctor // note the placement. new((void*)pElements) T; } } // // CCommandLine implementation // // code adapted from C startup code -- see stdargv.c // It walks through the given CmdLine and calls ParseParam // when an argument is encountered. // An argument must in this format: // </command arg_to_command> or <-command arg_to_command> void CCommandLine::ParseCommandLine( LPCTSTR CmdLine ) { LPCTSTR p; LPTSTR args, pDst; BOOL bInQuote; BOOL bCopyTheChar; int nSlash; p = CmdLine; args = new TCHAR[lstrlen(CmdLine) + 1]; if (!args) return; for (;;) { // skip blanks while (_T(' ') == *p || _T('\t') == *p) p++; // nothing left, bail if (_T('\0') == *p) break; // 2N backslashes + '\"' ->N backslashes plus string delimiter // 2N + 1 baclslashes + '\"' ->N backslashes plus literal '\"' // N backslashes -> N backslashes nSlash = 0; bInQuote = FALSE; pDst = args; for (;;) { bCopyTheChar = TRUE; //count how may backslashes while(_T('\\') == *p) { p++; nSlash++; } if (_T('\"') == *p) { if (0 == (nSlash % 2)) { // 2N backslashes plus '\"' ->N baskslashes plus // delimiter if (bInQuote) // double quote inside quoted string // skip the first and copy the second. if (_T('\"') == p[1]) p++; else bCopyTheChar = FALSE; else bCopyTheChar = FALSE; // toggle quoted status bInQuote = !bInQuote; } nSlash /= 2; } while (nSlash) { *pDst++ = _T('\\'); nSlash--; } if (_T('\0') == *p || (!bInQuote && (_T(' ') == *p || _T('\t') == *p))) { break; } // copy char to args if (bCopyTheChar) { *pDst++ = *p; } p++; } // we have a complete argument now. Null terminates it and // let the derived class parse the argument. *pDst = _T('\0'); // skip blanks to see if this is the last argument while (_T(' ') == *p || _T('\t') == *p) p++; BOOL bFlag; bFlag = (_T('/') == *args || _T('-') == *args); pDst = (bFlag) ? args + 1 : args; ParseParam(pDst, bFlag); } delete [] args; } // // CSafeRegistry implementation // BOOL CSafeRegistry::Open( HKEY hKeyAncestor, LPCTSTR KeyName, REGSAM Access ) { DWORD LastError; // we shouldn't have a valid key -- or memory leak // Also, a key name must be provided -- or open nothing ASSERT(!m_hKey && KeyName); LastError = ::RegOpenKeyEx(hKeyAncestor, KeyName, 0, Access, &m_hKey); SetLastError(LastError); return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::Create( HKEY hKeyAncestor, LPCTSTR KeyName, REGSAM Access, DWORD* pDisposition, DWORD Options, LPSECURITY_ATTRIBUTES pSecurity ) { ASSERT(KeyName && !m_hKey); DWORD Disposition; DWORD LastError; LastError = ::RegCreateKeyEx(hKeyAncestor, KeyName, 0, TEXT(""), Options, Access, pSecurity, &m_hKey, &Disposition ); SetLastError(LastError); if (ERROR_SUCCESS == LastError && pDisposition) { *pDisposition = Disposition; } if (ERROR_SUCCESS != LastError) m_hKey = NULL; return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::SetValue( LPCTSTR ValueName, DWORD Type, const PBYTE pData, DWORD DataLen ) { ASSERT(m_hKey); DWORD LastError; LastError = ::RegSetValueEx(m_hKey, ValueName, 0, Type, pData, DataLen); SetLastError(LastError); return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::SetValue( LPCTSTR ValueName, LPCTSTR Value ) { return SetValue(ValueName, REG_SZ, (PBYTE)Value, (lstrlen(Value) + 1) * sizeof(TCHAR) ); } BOOL CSafeRegistry::GetValue( LPCTSTR ValueName, DWORD* pType, const PBYTE pData, DWORD* pDataLen ) { ASSERT(m_hKey); DWORD LastError; LastError = ::RegQueryValueEx(m_hKey, ValueName, NULL, pType, pData, pDataLen); SetLastError(LastError); return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::GetValue( LPCTSTR ValueName, String& str ) { DWORD Type, Size; Size = 0; BOOL Result = FALSE; // check size before Type because when the size is zero, type contains // undefined data. if (GetValue(ValueName, &Type, NULL, &Size) && Size && REG_SZ == Type) { // we do not want to throw an exception here. // so guard it try { BufferPtr<BYTE> BufferPtr(Size); Result = GetValue(ValueName, &Type, BufferPtr, &Size); if (Result) str = (LPCTSTR)(BYTE*)BufferPtr; } catch(CMemoryException* e) { e->Delete(); SetLastError(ERROR_NOT_ENOUGH_MEMORY); Result = FALSE; } } return Result; } BOOL CSafeRegistry::EnumerateSubkey( DWORD Index, LPTSTR Buffer, DWORD* BufferSize ) { DWORD LastError; FILETIME LastWrite; LastError = ::RegEnumKeyEx(m_hKey, Index, Buffer, BufferSize, NULL, NULL, NULL, &LastWrite); SetLastError(LastError); return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::DeleteValue( LPCTSTR ValueName ) { ASSERT(m_hKey); DWORD LastError = ::RegDeleteValue(m_hKey, ValueName); SetLastError(LastError); return ERROR_SUCCESS == LastError; } BOOL CSafeRegistry::DeleteSubkey( LPCTSTR SubkeyName ) { ASSERT(m_hKey); CSafeRegistry regSubkey; TCHAR KeyName[MAX_PATH]; FILETIME LastWrite; DWORD KeyNameLen; for (;;) { KeyNameLen = ARRAYLEN(KeyName); // always uses index 0(the first subkey) if (!regSubkey.Open(m_hKey, SubkeyName, KEY_WRITE | KEY_ENUMERATE_SUB_KEYS) || ERROR_SUCCESS != ::RegEnumKeyEx(regSubkey, 0, KeyName, &KeyNameLen, NULL, NULL, NULL, &LastWrite) || !regSubkey.DeleteSubkey(KeyName)) { break; } // close the key so that we will re-open it on each loop // -- we have deleted one subkey and without closing // the key, the index to RegEnumKeyEx will be confusing regSubkey.Close(); } // now delete the subkey ::RegDeleteKey(m_hKey, SubkeyName); return TRUE; }
23.97686
87
0.515787
[ "object" ]
7c346d40e7d875ae0d771ffd043c3f09335a6d60
176
hpp
C++
include/linear_algebra/linear_algebra.hpp
TheTryton/linear_algebra
1975bab581e56451e2a7e45749374f11274248a5
[ "MIT" ]
null
null
null
include/linear_algebra/linear_algebra.hpp
TheTryton/linear_algebra
1975bab581e56451e2a7e45749374f11274248a5
[ "MIT" ]
null
null
null
include/linear_algebra/linear_algebra.hpp
TheTryton/linear_algebra
1975bab581e56451e2a7e45749374f11274248a5
[ "MIT" ]
null
null
null
#pragma once #include "vector/vector.hpp" #include "vector/vector.inl" #include "matrix/matrix.hpp" #include "matrix/matrix.inl" #include "equation_system/equation_system.hpp"
25.142857
46
0.784091
[ "vector" ]
7c360135562f91712d30a672cf81fa7ebdc5bc73
3,848
hpp
C++
fsc/include/worker_thread.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/worker_thread.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/worker_thread.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// (c) Copyright 2008 Samuel Debionne. // // Distributed under the MIT Software License. (See accompanying file // license.txt) or copy at http://www.opensource.org/licenses/mit-license.php) // // See http://code.google.com/p/fsc-sdk/ for the library home page. // // $Revision: $ // $History: $ /// \file work_thread.hpp /// The main loop (apart from the GUI one) #if !defined(__WORKER_THREAD_HPP__) #define __WORKER_THREAD_HPP__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <boost/array.hpp> #include <cockpit.hpp> #include <win/event.hpp> //#include <iocards/usb_expansion_card.hpp> //#include <fsx/sim_connect.hpp> #include <fsx/dispatch_proc.hpp> #define WORK_PRECONDITION(x) _ASSERT((x)) //struct context //{ // context(fsx::sim_connect& _sc, iocards::usb_expansion_card& _hid, basic_cockpit& _cockpit) // : sc_(_sc), hid_(_hid), cockpit_(_cockpit) {} // // fsx::sim_connect& sc_; // iocards::usb_expansion_card& hid_; // basic_cockpit& cockpit_; //}; /// A callable object that implements the main loop class work { public: enum event {EVENT_SIMCONNECT, EVENT_HID, EVENT_EXIT}; work( basic_cockpit& _ckpt, win::event_t _simconn_event, win::event_t _hid_event, win::event_t _exit_event) : ckpt_(_ckpt) { WORK_PRECONDITION((_simconn_event.get() != INVALID_HANDLE_VALUE)); WORK_PRECONDITION((_hid_event.get() != INVALID_HANDLE_VALUE)); WORK_PRECONDITION((_exit_event.get() != INVALID_HANDLE_VALUE)); events_[EVENT_SIMCONNECT] = _simconn_event.get(); events_[EVENT_HID] = _hid_event.get(); events_[EVENT_EXIT] = _exit_event.get(); } void operator()() { bool exit = false; while (!exit) { DWORD EvtId = ::WaitForMultipleObjects(events_.size(), events_.c_array(), FALSE, INFINITE); switch (EvtId) { case WAIT_OBJECT_0 + EVENT_SIMCONNECT: ckpt_.sim().call_dispatch(dispatch_proc, &exit); break; case WAIT_ABANDONED_0 + EVENT_HID: case WAIT_TIMEOUT: ckpt_.hw().cancel_io(); break; case WAIT_OBJECT_0 + EVENT_HID: //LDBG_ << std::setbase(std::ios_base::hex) // << (int) ckpt_.hid_.input_buffer[0] << " " // << (int) input_buffer[1] << " " // << (int) input_buffer[2] << " " // << (int) input_buffer[3] << " " // << (int) input_buffer[4] << " " // << (int) input_buffer[5] << " " // << (int) input_buffer[6] << " " // << (int) input_buffer[7] << " " // << (int) input_buffer[8]; { DWORD nb_bytes_transferred = ckpt_.hw().overlapped_result(); //TODO: Parse HID buffer... //boost::dynamic_bitset<> bitset(res.second * 8); //hid_to_event_mapping bitset // Initiate a new read DWORD nb_bytes_read = ckpt_.hw().read(); //hr = sc.transmit_client_event(SIMCONNECT_OBJECT_ID_USER, EVENT_MIXTURE_SET, input_buffer[2] * 0x40, SIMCONNECT_GROUP_PRIORITY_HIGHEST, SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY); } break; case WAIT_OBJECT_0 + EVENT_EXIT: exit = true; break; default : LERR_ << "unexpected event: " << EvtId; } } } private: boost::array<HANDLE, 3> events_; basic_cockpit& ckpt_; }; #endif //__WORKER_THREAD_HPP__
30.0625
197
0.547297
[ "object" ]
7c382a167ae2888711e339b5b132776f5800132d
8,682
hpp
C++
src/Database/Implementations/StandaloneDatabase.hpp
prostoiChelovek/faceDetector
9cecefbf6d52b1cee971ec342d6a9ae8f593b60b
[ "MIT" ]
2
2019-07-10T13:05:34.000Z
2019-08-09T11:23:09.000Z
src/Database/Implementations/StandaloneDatabase.hpp
prostoiChelovek/faceDetector
9cecefbf6d52b1cee971ec342d6a9ae8f593b60b
[ "MIT" ]
null
null
null
src/Database/Implementations/StandaloneDatabase.hpp
prostoiChelovek/faceDetector
9cecefbf6d52b1cee971ec342d6a9ae8f593b60b
[ "MIT" ]
1
2019-08-09T11:23:11.000Z
2019-08-09T11:23:11.000Z
/** * @file StandaloneDatabase.h * @author Люнгрин Андрей aka prostoichelovek <iam.prostoi.chelovek@gmail.com> * @date 26 Aug 2020 * @copyright MIT License * * @brief This file contains a standalone Database implementation */ #ifndef FACES_STANDALONEDATABASE_HPP #define FACES_STANDALONEDATABASE_HPP #include <utility> #include <fstream> #include <picojson.h> // from third-party/miniconf #include <Database/Database.hpp> namespace faces { /** * A standalone implementation of the Database, which uses a JSON file as a storage */ template<typename EntryT, typename IdentifierT = unsigned long> class StandaloneDatabase : public Database<EntryT, IdentifierT> { public: /** * @param path - path to the JSON file of the DB */ explicit StandaloneDatabase(std::string path) : _path(std::move(path)) {} EntryT get(IdentifierT id) override; std::vector<IdentifierT> getEntriesList() override; IdentifierT add(EntryT const &entry) override; void update(IdentifierT id, EntryT const &entry) override; bool save() override; bool load() override; protected: const std::string _path; picojson::value _data; /** * Parses a JSON from the given file stream * * @param file - a stream to parse from * * @throws std::logic_error - if the parsing failed */ void _loadJson(std::ifstream &file); /** * Gets a json object of the entry with the given id * * @param id - an id of the requested entry * * @throws std::out_of_range - if the requested id is not found * @throws std::logic_error - if tge object with the requested id has incorrect type * * @return a reference to the json object at the requested id */ picojson::object &_getEntryJson(IdentifierT const &id); /** * Converts the actual value of the json value container to std::any * * @throws std::bad_cast - if the given json value has an unsupported type */ static std::any _valueToAny(picojson::value const &value); /** * Converts a given std::any value to the json value container * * @throws std::bad_cast - if the given std::any value has an unsupported type */ static picojson::value _anyToValue(std::any const &value); /** * Converts id to string */ static std::string _getStringId(IdentifierT const &id); /** * Initializes a json object with entry's values */ static picojson::object _entryToJson(EntryT const &entry); }; template<typename EntryT, typename IdentifierT> EntryT StandaloneDatabase<EntryT, IdentifierT>::get(IdentifierT id) { picojson::object const &entryObj = _getEntryJson(id); std::map<std::string, std::any> entryAttributes; for (auto const &[name, valueJson] : entryObj) { std::any value = _valueToAny(valueJson); entryAttributes[name] = value; } return EntryT(entryAttributes); } template<typename EntryT, typename IdentifierT> std::vector<IdentifierT> StandaloneDatabase<EntryT, IdentifierT>::getEntriesList() { std::vector<IdentifierT> res; auto &obj = _data.get<picojson::object>(); for (auto const &[key, value] : obj) { if constexpr (!std::is_same_v<picojson::object::key_type, IdentifierT>) { if constexpr (std::is_arithmetic_v<IdentifierT>) { std::istringstream iss(key); IdentifierT id; iss >> id; res.emplace_back(id); } else { res.emplace_back(static_cast<IdentifierT>(key)); } } else { res.emplace_back(key); } } return res; } template<typename EntryT, typename IdentifierT> IdentifierT StandaloneDatabase<EntryT, IdentifierT>::add(const EntryT &entry) { std::vector<IdentifierT> entries = getEntriesList(); IdentifierT nextId = *std::max_element(entries.begin(), entries.end()) + 1; auto &obj = _data.get<picojson::object>(); picojson::value entryJsonValue(_entryToJson(entry)); obj[_getStringId(nextId)] = entryJsonValue; return nextId; } template<typename EntryT, typename IdentifierT> void StandaloneDatabase<EntryT, IdentifierT>::update(IdentifierT id, const EntryT &entry) { picojson::object &entryObj = _getEntryJson(id); entryObj = _entryToJson(entry); } template<typename EntryT, typename IdentifierT> bool StandaloneDatabase<EntryT, IdentifierT>::save() { try { std::ofstream file(_path); file.exceptions(file.exceptions() | std::ifstream::failbit | std::ifstream::badbit); if (!_data.is<picojson::object>()) { _data = picojson::value(picojson::object()); } _data.serialize(std::ostream_iterator<char>(file), true); } catch (std::exception &e) { spdlog::error("Cannot save a database to '{}': {}", _path, e.what()); return false; } return true; } template<typename EntryT, typename IdentifierT> bool StandaloneDatabase<EntryT, IdentifierT>::load() { try { std::ifstream file(_path); if (!file.is_open() || file.bad()) { throw std::ios_base::failure(strerror(errno)); } _loadJson(file); } catch (std::exception &e) { spdlog::error("Cannot load a database from '{}': {}", _path, e.what()); return false; } return true; } template<typename EntryT, typename IdentifierT> void StandaloneDatabase<EntryT, IdentifierT>::_loadJson(std::ifstream &file) { std::string err = picojson::parse(_data, file); if (!err.empty()) { throw std::logic_error(err); } if (!_data.is<picojson::object>()) { throw std::logic_error("json file has an incorrect format"); } } template<typename EntryT, typename IdentifierT> picojson::object &StandaloneDatabase<EntryT, IdentifierT>::_getEntryJson(const IdentifierT &id) { picojson::object &obj = _data.get<picojson::object>(); std::string strId = _getStringId(id); if (obj.find(strId) == obj.end()) { throw std::out_of_range("Entry with ID='" + strId + "' does not exist in the database"); } picojson::value &entryJson = obj[strId]; if (!entryJson.is<picojson::object>()) { throw std::logic_error("Entry with ID='" + strId + "' has an incorrect format"); } return entryJson.get<picojson::object>(); } template<typename EntryT, typename IdentifierT> std::any StandaloneDatabase<EntryT, IdentifierT>::_valueToAny(const picojson::value &value) { if (value.is<bool>()) { return value.get<bool>(); } if (value.is<double>()) { return value.get<double>(); } if (value.is<std::string>()) { return value.get<std::string>(); } if (value.is<picojson::object>()) { return value.get<picojson::object>(); } throw std::bad_cast(); } template<typename EntryT, typename IdentifierT> picojson::value StandaloneDatabase<EntryT, IdentifierT>::_anyToValue(const std::any &value) { if (value.type() == typeid(bool)) { return picojson::value(std::any_cast<bool>(value)); } if (value.type() == typeid(std::string)) { return picojson::value(std::any_cast<std::string>(value)); } return picojson::value(anyCast<double>(value)); } template<typename EntryT, typename IdentifierT> std::string StandaloneDatabase<EntryT, IdentifierT>::_getStringId(const IdentifierT &id) { std::stringstream ss; ss << id; return ss.str(); } template<typename EntryT, typename IdentifierT> picojson::object StandaloneDatabase<EntryT, IdentifierT>::_entryToJson(const EntryT &entry) { picojson::object res; const std::map<std::string, std::any> attributes = entry.getAttributes(); for (auto const &[key, value] : attributes) { res[key] = _anyToValue(value); } return res; } } #endif //FACES_STANDALONEDATABASE_HPP
32.639098
101
0.5956
[ "object", "vector" ]
7c3dbf9f34575f4343c30953d2fcf27c72faf169
11,556
cpp
C++
src/cpp/mummer-lib/delta-filter.cpp
UTbioinf/SMSC
0d5765518b3863d2363f264d9f256063c7f7ce71
[ "MIT" ]
null
null
null
src/cpp/mummer-lib/delta-filter.cpp
UTbioinf/SMSC
0d5765518b3863d2363f264d9f256063c7f7ce71
[ "MIT" ]
2
2019-05-31T06:36:36.000Z
2019-09-18T22:13:09.000Z
src/cpp/mummer-lib/delta-filter.cpp
UTbioinf/SMSC
0d5765518b3863d2363f264d9f256063c7f7ce71
[ "MIT" ]
1
2021-12-01T10:30:58.000Z
2021-12-01T10:30:58.000Z
//------------------------------------------------------------------------------ // Modified by: zijuexiansheng // Programmer: Adam M Phillippy, The Institute for Genomic Research // File: delta-filter.cc // Date: 09 / 22 / 2004 // // Usage: delta-filter [options] <deltafile> // Try 'show-coords -h' for more information // // Description: For use in conjunction with the MUMmer package. // "delta-filter" cleans delta alignment files by filtering // alignments that fail to meet the specifications required by the // command line switches. Produces a new, filtered delta file on // stdout, and works for both nucleotide and amino-acid alignments. // //------------------------------------------------------------------------------ #include <map> #include <vector> #include <string> #include <sstream> #include <iostream> #include <algorithm> #include <cstdlib> #include <cmath> #include "delta-filter.h" using namespace std; void DeltaFilter::insert_dep() { tigrinc::DeltaEdge_t* dep = new tigrinc::DeltaEdge_t(); pair<map<string, tigrinc::DeltaNode_t>::iterator, bool> insret; //-- Find the reference node in the graph, add a new one if necessary insret = refnodes.insert(map<string, tigrinc::DeltaNode_t>::value_type (record_m.idR, tigrinc::DeltaNode_t())); dep->refnode = &((insret.first)->second); //-- If a new reference node if ( insret.second ) { dep->refnode->id = &((insret.first)->first); dep->refnode->len = record_m.lenR; } //-- Find the query node in the graph, add a new one if necessary insret = qrynodes.insert(map<string, tigrinc::DeltaNode_t>::value_type (record_m.idQ, tigrinc::DeltaNode_t())); dep->qrynode = &((insret.first)->second); //-- If a new query node if ( insret.second ) { dep->qrynode->id = &((insret.first)->first); dep->qrynode->len = record_m.lenQ; } //-- Build the edge dep->build(record_m); dep->refnode->edges.push_back(dep); dep->qrynode->edges.push_back(dep); record_m.clear(); } // Definition of DeltaFilter DeltaFilter::DeltaFilter(): OPT_QLIS(false), // do query based LIS OPT_RLIS(false), // do reference based LIS OPT_GLIS(false), // do global LIS OPT_1to1(false), // do 1-to-1 alignment OPT_MtoM(false), // do M-to-M alignment OPT_MinLength(0), // minimum alignment length OPT_MinIdentity(0.0), // minimum %identity OPT_MinUnique(0.0), // minimum %unique OPT_MaxOverlap(100.0), // maximum olap as % of align len OPT_Epsilon(-1.0), // negligible alignment score is_first_record(true) { srand(1); } void DeltaFilter::set_parameters(const delta_filter_Params& params) { if(params.options & DELTA_FILTER_SET_e) OPT_Epsilon = params.e; if(params.options & DELTA_FILTER_SET_g) OPT_GLIS = true; if(params.options & DELTA_FILTER_SET_i) OPT_MinIdentity = params.i; if(params.options & DELTA_FILTER_SET_l) OPT_MinLength = params.l; if(params.options & DELTA_FILTER_SET_o) OPT_MaxOverlap = params.o; if(params.options & DELTA_FILTER_SET_q) OPT_QLIS = true; if(params.options & DELTA_FILTER_SET_r) OPT_RLIS = true; if(params.options & DELTA_FILTER_SET_u) OPT_MinUnique = params.u; if(params.options & DELTA_FILTER_SET_m) OPT_MtoM = true; if(params.options & DELTA_FILTER_SET_1) OPT_1to1 = true; if ( OPT_MinIdentity < 0.0 || OPT_MinIdentity > 100.0 ) { cerr << "ERROR: Minimum identity must be within the range [0, 100]\n"; exit(1); } if ( OPT_MinLength < 0 ) { cerr << "ERROR: Minimum length must be greater than or equal to zero\n"; exit(1); } if ( OPT_MinUnique < 0.0 || OPT_MinUnique > 100.0 ) { cerr << "ERROR: Minimum uniqueness must be within the range [0, 100]\n"; exit(1); } if ( OPT_MaxOverlap < 0.0 || OPT_MaxOverlap > 100.0 ) { cerr << "ERROR: Maximum overlap must be within the range [0, 100]\n"; exit(1); } } void DeltaFilter::reset_parameters() { OPT_QLIS = false; // do query based LIS OPT_RLIS = false; // do reference based LIS OPT_GLIS = false; // do global LIS OPT_1to1 = false; // do 1-to-1 alignment OPT_MtoM = false; // do M-to-M alignment OPT_MinLength = 0; // minimum alignment length OPT_MinIdentity = 0.0; // minimum %identity OPT_MinUnique = 0.0; // minimum %unique OPT_MaxOverlap = 100.0; // maximum olap as % of align len OPT_Epsilon = -1.0; // negligible alignment score } void DeltaFilter::set_refpath(const string& refpath) { this->refpath = refpath; } void DeltaFilter::set_qrypath(const string& qrypath) { this->qrypath = qrypath; } void DeltaFilter::set_datatype(const string& datatype) { if(datatype == tigrinc::NUCMER_STRING) this->datatype = tigrinc::NUCMER_DATA; else if(datatype == tigrinc::PROMER_STRING) this->datatype = tigrinc::PROMER_DATA; else this->datatype = tigrinc::NULL_DATA; } void DeltaFilter::add_record_header(const std::string& idR, const std::string& idQ, long lenR, long lenQ) { if(lenR <= 0 || lenQ <= 0) { cerr << "lenR <= 0 or lenQ <= 0" << endl; exit(1); } if(!is_first_record) insert_dep(); else is_first_record = false; record_m.idR = idR; record_m.idQ = idQ; record_m.lenR = lenR; record_m.lenQ = lenQ; } void DeltaFilter::add_alignment(long sR, long eR, long sQ, long eQ, long idyc, long simc, long stpc, const vector<long>& all_deltas) { if ( sR <= 0 || eR <= 0 || sQ <= 0 || eQ <= 0 || idyc < 0 || simc < 0 || stpc < 0 ) { cerr << "sR | eR | sQ | eQ | <=0 or idyc | simc | stpc < 0" << endl; cerr << sR << ' ' << eR << ' ' << sQ << ' ' << eQ << ' ' << idyc << ' ' << simc << ' ' << stpc << endl; exit(1); } record_m.aligns.push_back( tigrinc::DeltaAlignment_t() ); tigrinc::DeltaAlignment_t& align = record_m.aligns.back(); align.sR = sR; align.eR = eR; align.sQ = sQ; align.eQ = eQ; align.idyc = idyc; align.simc = simc; align.stpc = stpc; align.deltas.reserve( all_deltas.size() + 1 ); float total = labs(eR - sR) + 1.0; if(datatype == tigrinc::PROMER_DATA) total /= 3.0; for(vector<long>::const_iterator d_it = all_deltas.begin(); d_it != all_deltas.end(); ++d_it) { if(*d_it < 0) ++total; align.deltas.push_back( *d_it ); } align.deltas.push_back( 0 ); align.idy = (total - (float)align.idyc) / total * 100.0; align.sim = (total - (float)align.simc) / total * 100.0; align.stp = (float)align.stpc / (total * 2.0) * 100.0; } void DeltaFilter::add_alignment(long sR, long eR, long sQ, long eQ, long idyc, long simc, long stpc) { if ( sR <= 0 || eR <= 0 || sQ <= 0 || eQ <= 0 || idyc < 0 || simc < 0 || stpc < 0 ) { cerr << "sR | eR | sQ | eQ | <=0 or idyc | simc | stpc < 0" << endl; cerr << sR << ' ' << eR << ' ' << sQ << ' ' << eQ << ' ' << idyc << ' ' << simc << ' ' << stpc << endl; exit(1); } if(!record_m.aligns.empty()) { tigrinc::DeltaAlignment_t& ali = record_m.aligns.back(); ali.deltas.push_back( 0 ); ali.idy = (record_m_total - (float)ali.idyc) / record_m_total * 100.0; ali.sim = (record_m_total - (float)ali.simc) / record_m_total * 100.0; ali.stp = (float)ali.stpc / (record_m_total * 2.0) * 100.0; } record_m.aligns.push_back( tigrinc::DeltaAlignment_t() ); tigrinc::DeltaAlignment_t& align = record_m.aligns.back(); align.sR = sR; align.eR = eR; align.sQ = sQ; align.eQ = eQ; align.idyc = idyc; align.simc = simc; align.stpc = stpc; record_m_total = labs(eR - sR) + 1.0; if(datatype == tigrinc::PROMER_DATA) record_m_total /= 3.0; } void DeltaFilter::add_indel(long d) { tigrinc::DeltaAlignment_t& align = record_m.aligns.back(); if(d < 0) ++record_m_total; align.deltas.push_back( d ); } void DeltaFilter::add_finished() { if(record_m.aligns.empty()) return; tigrinc::DeltaAlignment_t& ali = record_m.aligns.back(); ali.deltas.push_back( 0 ); ali.idy = (record_m_total - (float)ali.idyc) / record_m_total * 100.0; ali.sim = (record_m_total - (float)ali.simc) / record_m_total * 100.0; ali.stp = (float)ali.stpc / (record_m_total * 2.0) * 100.0; } void DeltaFilter::run_delta_filter() { if(!is_first_record) insert_dep(); else return; if ( OPT_MinIdentity > 0 || OPT_MinLength > 0 ) flagScore(OPT_MinLength, OPT_MinIdentity); //-- Uniqueness requirements if ( OPT_MinUnique > 0 ) flagUNIQ(OPT_MinUnique); //-- Query-based LIS if ( OPT_QLIS ) flagQLIS(OPT_Epsilon, OPT_MaxOverlap); //-- Reference-based LIS if ( OPT_RLIS ) flagRLIS(OPT_Epsilon, OPT_MaxOverlap); //-- Global LIS if ( OPT_GLIS ) flagGLIS(OPT_Epsilon); //-- M-to-M if ( OPT_MtoM ) flagMtoM(OPT_Epsilon, OPT_MaxOverlap); //-- 1-to-1 if ( OPT_1to1 ) flag1to1(OPT_Epsilon, OPT_MaxOverlap); } void DeltaFilter::get_result(delta_filter_ProcessResult& processFilter) { if(is_first_record) return; bool header; long s1, e1, s2, e2; map<string, tigrinc::DeltaNode_t>::const_iterator mi; vector<tigrinc::DeltaEdge_t *>::const_iterator ei; vector<tigrinc::DeltaEdgelet_t *>::const_iterator eli; for ( mi = qrynodes.begin(); mi != qrynodes.end(); ++ mi ) { for ( ei = (mi->second).edges.begin(); ei != (mi->second).edges.end(); ++ ei ) { header = false; for ( eli = (*ei)->edgelets.begin(); eli != (*ei)->edgelets.end(); ++ eli ) { if ( ! (*eli)->isGOOD ) continue; //-- Print the sequence header if ( ! header ) { processFilter.store_header( processFilter.res, (*ei)->refnode->id->c_str(), (*ei)->qrynode->id->c_str(), (*ei)->refnode->len, (*ei)->qrynode->len); header = true; } //-- Print the alignment s1 = (*eli)->loR; e1 = (*eli)->hiR; s2 = (*eli)->loQ; e2 = (*eli)->hiQ; if ( (*eli)->dirR == tigrinc::REVERSE_DIR ) swap (s1, e1); if ( (*eli)->dirQ == tigrinc::REVERSE_DIR ) swap (s2, e2); processFilter.new_cluster(processFilter.res, s1, e1, s2, e2, (*eli)->idyc, (*eli)->simc, (*eli)->stpc); istringstream iss((*eli)->delta); long t_dt; while(iss >> t_dt) { if(t_dt == 0) break; processFilter.add_delta(processFilter.res, t_dt); } } } } } void DeltaFilter::clear() { is_first_record = true; tigrinc::DeltaGraph_t::clear(); }
30.172324
132
0.557113
[ "vector" ]
7c41d4def0959bc557754cb4564b17cf1c700f00
1,014
cpp
C++
Codeforces/Round-496-Div3/E1.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
Codeforces/Round-496-Div3/E1.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
Codeforces/Round-496-Div3/E1.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
// Sorting // 5 // 12-08-2020 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vi a(n + 1); int x = 0; for (int i = 1; i <= n; i++) { cin >> a[i]; if (a[i] == m) x = i; } map <int, int> dif; int lt = 0, gt = 0; dif[0] = 1; for (int i = x - 1; i >= 1; i--) { if (a[i] > m) gt++; if (a[i] < m) lt++; dif[gt - lt]++; } ll ans = dif[0] + dif[1]; lt = 0, gt = 0; for (int i = x + 1; i <= n; i++) { if (a[i] > m) gt++; if (a[i] < m) lt++; int d = gt - lt; ans += dif[-d]; ans += dif[1 - d]; } cout << ans << '\n'; return (0); }
19.132075
42
0.489152
[ "vector" ]
7c4425553580d2b02523b97c02b612b4376cb1e8
12,724
hpp
C++
include/cpm/bootstrap_theme.hpp
wichtounet/cpm
83d6bbe32e3230ced5341b8f3d7a4c447a2f5067
[ "MIT" ]
45
2015-06-15T05:45:39.000Z
2022-03-22T06:41:09.000Z
include/cpm/bootstrap_theme.hpp
wichtounet/cpm
83d6bbe32e3230ced5341b8f3d7a4c447a2f5067
[ "MIT" ]
1
2015-07-01T12:53:11.000Z
2015-07-07T13:05:53.000Z
include/cpm/bootstrap_theme.hpp
wichtounet/cpm
83d6bbe32e3230ced5341b8f3d7a4c447a2f5067
[ "MIT" ]
8
2015-06-16T03:50:54.000Z
2020-06-26T16:40:08.000Z
//======================================================================= // Copyright (c) 2015-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef CPM_BOOTSTRAP_THEME_HPP #define CPM_BOOTSTRAP_THEME_HPP #include "cpm/io.hpp" #include "cpm/data.hpp" namespace cpm { struct bootstrap_theme { const reports_data& data; cxxopts::Options& options; std::ostream& stream; std::string current_compiler; std::string current_configuration; std::size_t current_column = 0; bootstrap_theme(const reports_data& data, cxxopts::Options& options, std::ostream& stream, std::string compiler, std::string configuration) : data(data), options(options), stream(stream), current_compiler(std::move(compiler)), current_configuration(std::move(configuration)) {} void include(){ stream << "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\" rel=\"stylesheet\">\n"; stream << "<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css\" rel=\"stylesheet\">\n"; stream << R"=====( <style> .jumbotron { padding-top: 38px; padding-bottom: 8px; margin-bottom: 5px; } .page-header { margin-top: 10px; } </style> )====="; } void header(){ stream << R"=====( <nav id="myNavbar" class="navbar navbar-default navbar-inverse navbar-fixed-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Results</a> </div> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="nav navbar-nav"> <li class="active"><a href="index.html">Home</a></li> <li><a href="https://github.com/wichtounet/cpm">Generated with CPM</a></li> </ul> </div> </div> </nav> )====="; } void footer(){ stream << R"=====( <hr> <div class="row"> <div class="col-xs-12"> <footer> <p>Generated with <a href="https://github.com/wichtounet/cpm">CPM</a></p> </footer> </div> </div> </div> )====="; if(options.count("pages")){ stream << "</div>\n"; stream << "</div>\n"; } } void before_information(std::string name){ stream << "<div class=\"jumbotron\">\n"; stream << "<div class=\"container-fluid\">\n"; stream << "<h1>" << name << "</h1>\n"; stream << "<div class=\"row\">\n"; stream << "<div class=\"col-xs-3\">\n"; stream << "<ul>\n"; } void after_information(){ stream << "</ul>\n"; stream << "</div>\n"; //col-xs-3 if(data.compilers.size() > 1 || data.configurations.size() > 1){ stream << "<div class=\"col-xs-9\">\n"; } } void compiler_buttons(){ stream << R"=====(<div class="row">)====="; stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select compiler: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; if(options.count("pages")){ for(auto& compiler : data.compilers){ auto file = cpm::filify(compiler, current_configuration, data.sub_part); if(compiler == current_compiler){ stream << "<a class=\"btn btn-primary\" href=\"" << file << "\">" << compiler << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << file << "\">" << compiler << "</a>\n"; } } } else { for(auto& compiler : data.compilers){ if(compiler == current_compiler){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(compiler, current_configuration) << "\">" << compiler << "</a>\n"; } } } stream << "</div>\n"; //btn-group stream << "</div>\n"; //col-xs-12 stream << "</div>\n"; //row } void configuration_buttons(){ if(data.compilers.size() > 1){ stream << R"=====(<div class="row" style="padding-top:5px;">)====="; } else { stream << R"=====(<div class="row">)====="; } stream << R"=====(<div class="col-xs-12">)====="; stream << R"=====(<span>Select configuration: </span>)====="; stream << R"=====(<div class="btn-group" role="group">)====="; if(options.count("pages")){ for(auto& configuration : data.configurations){ auto file = cpm::filify(current_compiler, configuration, data.sub_part); if(configuration == current_configuration){ stream << "<a class=\"btn btn-primary\" href=\"" << file << "\">" << configuration << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << file << "\">" << configuration << "</a>\n"; } } } else { for(auto& configuration : data.configurations){ if(configuration == current_configuration){ stream << "<a class=\"btn btn-primary\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } else { stream << "<a class=\"btn btn-default\" href=\"" << cpm::filify(current_compiler, configuration) << "\">" << configuration << "</a>\n"; } } } stream << "</div>\n"; //btn-group stream << "</div>\n"; //col-xs-12 stream << "</div>\n"; //row } void after_buttons(){ if(data.compilers.size() > 1 || data.configurations.size() > 1){ stream << "</div>\n"; //col-xs-9 } stream << "</div>\n"; //row stream << "</div>\n"; //container-fluid stream << "</div>\n"; //jumbotron if(options.count("pages")){ stream << R"=====( <div class=container-fluid> <div class="row"> <div class="col-xs-2"> <ul class="nav nav-stacked" id="sidebar"> )====="; for(auto& link : data.files){ stream << "<li><a href=\"" << link.second << "\">" << link.first << "</a></li>" << std::endl; } stream << R"=====( </ul> </div> <div class="col-xs-10"> <div class=container-fluid> )====="; } else { stream << "<div class=\"container-fluid\">\n"; } } virtual void start_column(const std::string& style = ""){ std::size_t columns = 1; //Always the first grapah if(data.documents.size() > 1 && !options.count("disable-time")){ ++columns; } if(data.compilers.size() > 1 && !options.count("disable-compiler")){ ++columns; } if(data.configurations.size() > 1 && !options.count("disable-configuration")){ ++columns; } if(!options.count("disable-summary")){ ++columns; } if(columns < 4){ stream << "<div class=\"col-xs-" << 12 / columns << "\"" << style << ">\n"; } else if(columns == 4){ if(current_column == 2){ stream << "</div>\n"; stream << "<div class=\"row\" style=\"display:flex; margin-top: 10px;\">\n"; } stream << "<div class=\"col-xs-6\"" << style << ">\n"; } else if(columns == 5){ if(current_column == 3){ stream << "</div>\n"; stream << "<div class=\"row\" style=\"display:flex; margin-top: 10px;\">\n"; } if(current_column < 3){ stream << "<div class=\"col-xs-4\"" << style << ">\n"; } else if(current_column == 3){ stream << "<div class=\"col-xs-4\"" << style << ">\n"; } else if(current_column == 4){ stream << "<div class=\"col-xs-8\"" << style << ">\n"; } } ++current_column; } virtual void close_column(){ stream << "</div>\n"; } void before_graph(std::size_t id){ start_column(); stream << "<div id=\"chart_" << id << "\" style=\"height: 400px;\"></div>\n"; } void after_graph(){ close_column(); } void before_result(const std::string& title, bool sub, const std::vector<cpm::document_cref>& /*documents*/){ stream << "<div class=\"page-header\">\n"; stream << "<h2>" << title << "</h2>\n"; stream << "</div>\n"; if(sub){ stream << "<div class=\"row\" style=\"display:flex; align-items: flex-end\">\n"; } else { stream << "<div class=\"row\">\n"; } current_column = 0; } void after_result(){ stream << "</div>\n"; } void before_sub_graphs(std::size_t id, std::vector<std::string> graphs){ start_column("style=\"align-self: flex-start; \""); stream << "<div role=\"tabpanel\">\n"; stream << "<ul class=\"nav nav-tabs\" role=\"tablist\">\n"; std::string active = "class=\"active\""; std::size_t sub = 0; for(auto& g : graphs){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub++); stream << "<li " << active << " role=\"presentation\"><a href=\"#" << sub_id << "\" aria-controls=\"" << sub_id << "\" role=\"tab\" data-toggle=\"tab\">" << g << "</a></li>\n"; active = ""; } stream << "</ul>\n"; stream << "<div class=\"tab-content\">\n"; } void after_sub_graphs(){ stream << "</div>\n"; stream << "</div>\n"; close_column(); } void before_sub_graph(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<div id=\"chart_" << id << "-" << sub << "\" style=\"height: 400px;\"></div>\n"; } void after_sub_graph(){ stream << "</div>\n"; } void before_summary(){ start_column(); stream << "<table class=\"table\">\n"; } void after_summary(){ stream << "</table>\n"; close_column(); } void before_sub_summary(std::size_t id, std::size_t sub){ auto sub_id = std::string("sub") + std::to_string(id) + "-" + std::to_string(sub); std::string active; if(sub == 0){ active = " active"; } stream << "<div role=\"tabpanel\" class=\"tab-pane" << active << "\" id=\"" << sub_id << "\">\n"; stream << "<table class=\"table\">\n"; } void after_sub_summary(){ stream << "</table>\n"; stream << "</div>\n"; } void cell(const std::string& v){ stream << "<td>" << v << "</td>\n"; } void red_cell(const std::string& v){ stream << "<td class=\"danger\">"<< v << "</td>\n"; } void green_cell(const std::string& v){ stream << "<td class=\"success\">" << v << "</td>\n"; } template<typename T> bootstrap_theme& operator<<(const T& v){ stream << v; return *this; } }; } //end of namespace cpm #endif //CPM_BOOTSTRAP_THEME_HPP
33.572559
156
0.466363
[ "vector" ]
7c49ef1f1f4f5fdb643f762e9c43aa26610e8fc4
811
cc
C++
components/services/heap_profiling/allocation.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/services/heap_profiling/allocation.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/services/heap_profiling/allocation.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 "components/services/heap_profiling/allocation.h" #include "base/hash/hash.h" namespace heap_profiling { namespace { uint32_t ComputeHash(const std::vector<Address>& addrs) { return base::Hash(addrs.data(), addrs.size() * sizeof(Address)); } } // namespace AllocationSite::AllocationSite(AllocatorType allocator, std::vector<Address>&& stack, int context_id) : allocator(allocator), stack(std::move(stack)), context_id(context_id), hash_(ComputeHash(this->stack)) {} AllocationSite::~AllocationSite() = default; } // namespace heap_profiling
28.964286
73
0.675709
[ "vector" ]
7c4b6e79e984bc42e8aa6d270deb7d052471fd07
16,139
cpp
C++
hsolv/hsolvdoc.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
1
2020-05-18T00:57:57.000Z
2020-05-18T00:57:57.000Z
hsolv/hsolvdoc.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
1
2018-05-02T13:43:31.000Z
2018-05-02T13:43:31.000Z
hsolv/hsolvdoc.cpp
ResonanceGroup/FEMM
227f1cb46fc18b298e2da48d732692c206d0539f
[ "MIT" ]
3
2018-05-02T13:38:43.000Z
2021-05-19T10:48:49.000Z
// hsolvdoc.cpp : implementation of the Chsolvdoc class // #include <stdafx.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include "hsolv.h" #include "hsolvDlg.h" #include "mesh.h" #include "spars.h" #include "hsolvdoc.h" ///////////////////////////////////////////////////////////////////////////// // Chsolvdoc construction/destruction Chsolvdoc::Chsolvdoc() { TheView=NULL; Precision=NULL; LengthUnits=NULL; ProblemType=NULL; Coords=NULL; BandWidth=NULL; NumNodes=NULL; NumEls=NULL; NumBlockProps=NULL; NumPBCs=NULL; NumLineProps=NULL; NumPointProps=NULL; NumCircProps=NULL; NumBlockLabels=NULL; meshnode=NULL; meshele=NULL; Tprev=NULL; blockproplist=NULL; lineproplist=NULL; nodeproplist=NULL; circproplist=NULL; labellist=NULL; pbclist=NULL; PathName=NULL; extRo=extRi=extZo=NULL; } Chsolvdoc::~Chsolvdoc() { // This space for rent. } void Chsolvdoc::CleanUp() { if (meshnode!=NULL) free(meshnode); if (meshele!=NULL) free(meshele); if (blockproplist!=NULL) free(blockproplist); if (lineproplist!=NULL) free(lineproplist); if (nodeproplist!=NULL) free(nodeproplist); if (circproplist!=NULL) free(circproplist); if (labellist!=NULL) free(labellist); if (pbclist!=NULL) free(pbclist); if (Tprev!=NULL) free(Tprev); } ///////////////////////////////////////////////////////////////////////////// // Chsolvdoc commands char* StripKey(char *c) { char *d; int i,k; k=(int) strlen(c); for(i=0;i<k;i++){ if (c[i] == '='){ d=c+i+1; return d; } } return c+k; } BOOL Chsolvdoc::OnOpenDocument() { FILE *fp; int j,k; char s[1024],q[1024]; char *v; CPointProp PProp; CBoundaryProp BProp; CMaterialProp MProp; CCircuit CProp; CBlockLabel blk; sprintf(s,"%s.feh",PathName); if ((fp=fopen(s,"rt"))==NULL){ fprintf(stderr,"Couldn't read from specified .feh file\n"); return FALSE; } // define some defaults Precision=1.e-08; Depth=-1; ProblemType=0; Coords=0; NumPointProps=0; NumLineProps=0; NumBlockProps=0; NumCircProps=0; // parse the file while (fgets(s,1024,fp)!=NULL) { sscanf(s,"%s",q); // Precision if( _strnicmp(q,"[precision]",11)==0){ v=StripKey(s); sscanf(v,"%lf",&Precision); q[0]=NULL; } // Units of length used by the problem if( _strnicmp(q,"[lengthunits]",13)==0){ v=StripKey(s); sscanf(v,"%s",q); if( _strnicmp(q,"inches",6)==0) LengthUnits=0; else if( _strnicmp(q,"millimeters",11)==0) LengthUnits=1; else if( _strnicmp(q,"centimeters",1)==0) LengthUnits=2; else if( _strnicmp(q,"mils",4)==0) LengthUnits=4; else if( _strnicmp(q,"microns",6)==0) LengthUnits=5; else if( _strnicmp(q,"meters",6)==0) LengthUnits=3; q[0]=NULL; } // Depth for 2D planar problems; if( _strnicmp(q,"[depth]",7)==0){ v=StripKey(s); sscanf(v,"%lf",&Depth); q[0]=NULL; } // Problem Type (planar or axisymmetric) if( _strnicmp(q,"[problemtype]",13)==0){ v=StripKey(s); sscanf(v,"%s",q); if( _strnicmp(q,"planar",6)==0) ProblemType=0; if( _strnicmp(q,"axisymmetric",3)==0) ProblemType=1; q[0]=NULL; } // Coordinates (cartesian or polar) if( _strnicmp(q,"[coordinates]",13)==0){ v=StripKey(s); sscanf(v,"%s",q); if ( _strnicmp(q,"cartesian",4)==0) Coords=0; if ( _strnicmp(q,"polar",5)==0) Coords=1; q[0]=NULL; } // properties for axisymmetric external region if( _strnicmp(q,"[extzo]",7)==0){ v=StripKey(s); sscanf(v,"%lf",&extZo); q[0]=NULL; } if( _strnicmp(q,"[extro]",7)==0){ v=StripKey(s); sscanf(v,"%lf",&extRo); q[0]=NULL; } if( _strnicmp(q,"[extri]",7)==0){ v=StripKey(s); sscanf(v,"%lf",&extRi); q[0]=NULL; } // Point Properties if( _strnicmp(q,"[pointprops]",12)==0){ v=StripKey(s); sscanf(v,"%i",&k); if (k>0) nodeproplist=(CPointProp *)calloc(k,sizeof(CPointProp)); q[0]=NULL; } if( _strnicmp(q,"<beginpoint>",11)==0){ PProp.V=0; PProp.qp=0; q[0]=NULL; } if( _strnicmp(q,"<tp>",4)==0){ v=StripKey(s); sscanf(v,"%lf",&PProp.V); q[0]=NULL; } if( _strnicmp(q,"<qp>",4)==0){ v=StripKey(s); sscanf(v,"%lf",&PProp.qp); q[0]=NULL; } if( _strnicmp(q,"<endpoint>",9)==0){ nodeproplist[NumPointProps]=PProp; NumPointProps++; q[0]=NULL; } // Boundary Properties; if( _strnicmp(q,"[bdryprops]",11)==0){ v=StripKey(s); sscanf(v,"%i",&k); if (k>0) lineproplist=(CBoundaryProp *)calloc(k,sizeof(CBoundaryProp)); q[0]=NULL; } if( _strnicmp(q,"<beginbdry>",11)==0){ BProp.BdryFormat=0; BProp.Tset=0; BProp.Tinf=0; BProp.qs=0; BProp.beta=0; BProp.h=0; q[0]=NULL; } if( _strnicmp(q,"<bdrytype>",10)==0){ v=StripKey(s); sscanf(v,"%i",&BProp.BdryFormat); q[0]=NULL; } if( _strnicmp(q,"<Tset>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&BProp.Tset); q[0]=NULL; } if( _strnicmp(q,"<qs>",4)==0){ v=StripKey(s); sscanf(v,"%lf",&BProp.qs); q[0]=NULL; } if( _strnicmp(q,"<beta>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&BProp.beta); q[0]=NULL; } if( _strnicmp(q,"<h>",3)==0){ v=StripKey(s); sscanf(v,"%lf",&BProp.h); q[0]=NULL; } if( _strnicmp(q,"<Tinf>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&BProp.Tinf); q[0]=NULL; } if( _strnicmp(q,"<endbdry>",9)==0){ lineproplist[NumLineProps]=BProp; NumLineProps++; q[0]=NULL; } // Block Properties; if( _strnicmp(q,"[blockprops]",12)==0){ v=StripKey(s); sscanf(v,"%i",&k); if (k>0) blockproplist=(CMaterialProp *)calloc(k,sizeof(CMaterialProp)); q[0]=NULL; } // timestep if( _strnicmp(q,"[dt]",4)==0){ v=StripKey(s); sscanf(v,"%lf",&dT); q[0]=NULL; } // Previous Solution File if( _strnicmp(q,"[prevsoln]",10)==0){ int i; v=StripKey(s); // have to do this carefully to accept a filename with spaces k=(int) strlen(v); for(i=0;i<k;i++) if(v[i]=='\"'){ v=v+i+1; i=k; } k=(int) strlen(v); if(k>0) for(i=k-1;i>=0;i--){ if(v[i]=='\"'){ v[i]=0; i=-1; } } PrevSoln=v; q[0]=NULL; } if( _strnicmp(q,"<beginblock>",12)==0){ MProp.Kx=1; MProp.Ky=1; // permittivity, relative MProp.Kt=0; MProp.qv=0; // charge density, C/m^3 MProp.npts=0; q[0]=NULL; } if( _strnicmp(q,"<Kx>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&MProp.Kx); q[0]=NULL; } if( _strnicmp(q,"<Ky>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&MProp.Ky); q[0]=NULL; } if( _strnicmp(q,"<Kt>",6)==0){ v=StripKey(s); sscanf(v,"%lf",&MProp.Kt); MProp.Kt*=1.e6; q[0]=NULL; } if( _strnicmp(q,"<qv>",5)==0){ v=StripKey(s); sscanf(v,"%lf",&MProp.qv); q[0]=NULL; } if( _strnicmp(q,"<TKPoints>",10)==0){ v=StripKey(s); sscanf(v,"%i",&MProp.npts); if (MProp.npts>0) { for(j=0;j<MProp.npts;j++){ fgets(s,1024,fp); sscanf(s,"%lf %lf",&MProp.Kn[j].re,&MProp.Kn[j].im); } } q[0]=NULL; } if( _strnicmp(q,"<endblock>",9)==0){ blockproplist[NumBlockProps]=MProp; NumBlockProps++; q[0]=NULL; } // Conductor Properties if( _strnicmp(q,"[conductorprops]",16)==0){ v=StripKey(s); sscanf(v,"%i",&k); if(k>0) circproplist=(CCircuit *)calloc(k,sizeof(CCircuit)); q[0]=NULL; } if( _strnicmp(q,"<beginconductor>",16)==0){ CProp.V=0; CProp.q=0; CProp.CircType=0; q[0]=NULL; } if( _strnicmp(q,"<tc>",4)==0){ v=StripKey(s); sscanf(v,"%lf",&CProp.V); q[0]=NULL; } if( _strnicmp(q,"<qc>",4)==0){ v=StripKey(s); sscanf(v,"%lf",&CProp.q); q[0]=NULL; } if( _strnicmp(q,"<conductortype>",15)==0){ v=StripKey(s); sscanf(v,"%i",&CProp.CircType); q[0]=NULL; } if( _strnicmp(q,"<endconductor>",14)==0){ circproplist[NumCircProps]=CProp; NumCircProps++; q[0]=NULL; } // read in regional attributes if(_strnicmp(q,"[numblocklabels]",13)==0){ int i; v=StripKey(s); sscanf(v,"%i",&k); if (k>0) labellist=(CBlockLabel *)calloc(k, sizeof(CBlockLabel)); NumBlockLabels=k; for(i=0;i<k;i++) { fgets(s,1024,fp); sscanf(s,"%lf %lf %i %lf %i %i",&blk.x,&blk.y,&blk.BlockType, &blk.MaxArea,&blk.InGroup,&blk.IsExternal); blk.IsDefault = blk.IsExternal & 2; blk.IsExternal = blk.IsExternal & 1; blk.BlockType--; labellist[i]=blk; } q[0]=NULL; } } fclose(fp); return TRUE; } BOOL Chsolvdoc::LoadPrev() { if (PrevSoln.GetLength()==0) return TRUE; FILE *fp; double x,y; int k; char s[1024],q[256]; if ((fp=fopen(PrevSoln,"rt"))==NULL){ MsgBox("Couldn't read from specified previous solution\n"); return FALSE; } // parse the file k=0; while (fgets(s,1024,fp)!=NULL) { sscanf(s,"%s",q); if( _strnicmp(q,"[solution]",11)==0){ k=1; break; } } // case where the solution is never found. if (k==0) { fclose(fp); MsgBox("Couldn't read from specified previous solution\n"); return FALSE; } // read in the solution fgets(s,1024,fp); sscanf(s,"%i",&k); if(k!=NumNodes) { fclose(fp); MsgBox("Previous solution mesh doesn't match current mesh\n"); return FALSE; } Tprev=(double *)calloc(NumNodes,sizeof(double)); for(k=0;k<NumNodes;k++) { fgets(s,1024,fp); sscanf(s,"%lf %lf %lf",&x,&y,&Tprev[k]); } return TRUE; } BOOL Chsolvdoc::LoadMesh() { int i,j,k,q,n0,n1,n; char infile[256]; FILE *fp; char s[1024]; // double c[]={25.4,1.,10.,1000.,0.0254,0.001}; double c[]={0.0254,0.001,0.01,1,2.54e-5,1.e-6}; //read meshnodes; sprintf(infile,"%s.node",PathName); if((fp=fopen(infile,"rt"))==NULL){ return FALSE; } fgets(s,1024,fp); sscanf(s,"%i",&k); NumNodes=k; meshnode=(CNode *)calloc(k,sizeof(CNode)); CNode node; for(i=0;i<k;i++){ fscanf(fp,"%i",&j); fscanf(fp,"%lf",&node.x); fscanf(fp,"%lf",&node.y); fscanf(fp,"%i",&n); if(n>1){ // strip off point BC number; j=n & 0xffff; j=j-2; if (j<0) j=-1; // strip off Conductor number n= (n - (n & 0xffff))/0x10000 - 1; } else{ j=-1; n=-1; } node.bc=j; node.InConductor=n; // convert all lengths to internal working units of mm node.x*=c[LengthUnits]; node.y*=c[LengthUnits]; meshnode[i]=node; } fclose(fp); //read in periodic boundary conditions; sprintf(infile,"%s.pbc",PathName); if((fp=fopen(infile,"rt"))==NULL){ return FALSE; } fgets(s,1024,fp); sscanf(s,"%i",&k); NumPBCs=k; if (k!=0) pbclist=(CCommonPoint *)calloc(k,sizeof(CCommonPoint)); CCommonPoint pbc; for(i=0;i<k;i++){ fscanf(fp,"%i",&j); fscanf(fp,"%i",&pbc.x); fscanf(fp,"%i",&pbc.y); fscanf(fp,"%i",&pbc.t); pbclist[i]=pbc; } fclose(fp); // read in elements; sprintf(infile,"%s.ele",PathName); if((fp=fopen(infile,"rt"))==NULL){ return FALSE; } fgets(s,1024,fp); sscanf(s,"%i",&k); NumEls=k; meshele=(CElement *)calloc(k,sizeof(CElement)); CElement elm; int defaultLabel; for(i=0,defaultLabel=-1;i<NumBlockLabels;i++) if (labellist[i].IsDefault) defaultLabel=i; for(i=0;i<k;i++){ fscanf(fp,"%i",&j); fscanf(fp,"%i",&elm.p[0]); fscanf(fp,"%i",&elm.p[1]); fscanf(fp,"%i",&elm.p[2]); fscanf(fp,"%i",&elm.lbl); elm.lbl--; if(elm.lbl<0) elm.lbl=defaultLabel; if(elm.lbl<0){ CString msg; msg ="Material properties have not been defined for\n"; msg+="all regions. Press the \"Run Mesh Generator\"\n"; msg+="button to highlight the problem regions."; MsgBox(msg); fclose(fp); sprintf(infile,"%s.ele",PathName); DeleteFile(infile); sprintf(infile,"%s.node",PathName); DeleteFile(infile); sprintf(infile,"%s.pbc",PathName); DeleteFile(infile); sprintf(infile,"%s.poly",PathName); DeleteFile(infile); sprintf(infile,"%s.edge",PathName); DeleteFile(infile); exit(1); } // look up block type out of the list of block labels elm.blk=labellist[elm.lbl].BlockType; meshele[i]=elm; } fclose(fp); // initialize edge bc's and element permeabilities; for(i=0;i<NumEls;i++) for(j=0;j<3;j++) meshele[i].e[j] = -1; // read in edges to which boundary conditions are applied; // first, do a little bookkeeping so that element // associated with a give edge can be identified fast int *nmbr; int **mbr; nmbr=(int *)calloc(NumNodes,sizeof(int)); // Make a list of how many elements that tells how // many elements to which each node belongs. for(i=0;i<NumEls;i++) for(j=0;j<3;j++) nmbr[meshele[i].p[j]]++; // mete out some memory to build a list of the // connectivity... mbr=(int **)calloc(NumNodes,sizeof(int *)); for(i=0;i<NumNodes;i++){ mbr[i]=(int *)calloc(nmbr[i],sizeof(int)); nmbr[i]=0; } // fill up the connectivity information; for(i=0;i<NumEls;i++) for(j=0;j<3;j++) { k=meshele[i].p[j]; mbr[k][nmbr[k]]=i; nmbr[k]++; } sprintf(infile,"%s.edge",PathName); if((fp=fopen(infile,"rt"))==NULL) { return FALSE; } fscanf(fp,"%i",&k); // read in number of lines fscanf(fp,"%i",&j); // read in boundarymarker flag; for(i=0;i<k;i++) { fscanf(fp,"%i",&j); fscanf(fp,"%i",&n0); fscanf(fp,"%i",&n1); fscanf(fp,"%i",&n); // BC number; if (n<0) { n=(-n); j = (n & 0xffff) - 2; if (j<0) j = -1; // Conductor number; n= (n - (n & 0xffff))/0x10000 - 1; if (n>=0) { meshnode[n0].InConductor=n; meshnode[n1].InConductor=n; } } else j=-1; if (j>=0) { // search through elements to find one containing the line; // set corresponding edge equal to the bc number for(q=0,n=FALSE;q<nmbr[n0];q++) { elm=meshele[mbr[n0][q]]; if ((elm.p[0] == n0) && (elm.p[1] == n1)) {elm.e[0]=j; n=TRUE;} if ((elm.p[0] == n1) && (elm.p[1] == n0)) {elm.e[0]=j; n=TRUE;} if ((elm.p[1] == n0) && (elm.p[2] == n1)) {elm.e[1]=j; n=TRUE;} if ((elm.p[1] == n1) && (elm.p[2] == n0)) {elm.e[1]=j; n=TRUE;} if ((elm.p[2] == n0) && (elm.p[0] == n1)) {elm.e[2]=j; n=TRUE;} if ((elm.p[2] == n1) && (elm.p[0] == n0)) {elm.e[2]=j; n=TRUE;} meshele[mbr[n0][q]]=elm; //this is a little hack: line charge distributions should be applied //to at most one element; if((lineproplist[j].BdryFormat==2) && (n)) q=nmbr[n0]; } } } fclose(fp); // free up the connectivity information free(nmbr); for(i=0;i<NumNodes;i++) free(mbr[i]); free(mbr); // clear out temporary files sprintf(infile,"%s.ele",PathName); DeleteFile(infile); sprintf(infile,"%s.node",PathName); DeleteFile(infile); sprintf(infile,"%s.pbc",PathName); DeleteFile(infile); sprintf(infile,"%s.poly",PathName); DeleteFile(infile); return TRUE; } CComplex CMaterialProp::GetK(double t) { int i,j; // Kx returned as real part; // Ky returned as imag part if (npts==0) return (Kx+I*Ky); if (npts==1) return (Im(Kn[0])*(1+I)); if (t<=Re(Kn[0])) return (Im(Kn[0])*(1+I)); if (t>=Re(Kn[npts-1])) return (Im(Kn[npts-1])*(1+I)); for(i=0,j=1;j<npts;i++,j++) { if((t>=Re(Kn[i])) && (t<=Re(Kn[j]))) { return (1+I)*(Im(Kn[i])+Im(Kn[j]-Kn[i])*Re(t-Kn[i])/Re(Kn[j]-Kn[i])); } } return (Kx+I*Ky); }
21.957823
78
0.538075
[ "mesh" ]
7c56213a18bad4bb2fd2578c8ff5981a90e4d598
9,585
cpp
C++
TAO/tests/RTCORBA/Server_Declared/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/RTCORBA/Server_Declared/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/RTCORBA/Server_Declared/server.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: server.cpp 83471 2008-10-28 11:46:04Z sma $ #include "testS.h" #include "ace/Get_Opt.h" #include "tao/ORB_Core.h" #include "ace/Task.h" #include "tao/RTCORBA/RTCORBA.h" #include "tao/RTPortableServer/RTPortableServer.h" #include "../check_supported_priorities.cpp" class Test_i : public POA_Test { // = TITLE // An implementation for the Test interface in test.idl // public: Test_i (CORBA::ORB_ptr orb); // ctor void test_method (CORBA::Short priority); //FUZZ: disable check_for_lack_ACE_OS void shutdown (void); //FUZZ: enable check_for_lack_ACE_OS private: CORBA::ORB_var orb_; // The ORB }; Test_i::Test_i (CORBA::ORB_ptr orb) : orb_ (CORBA::ORB::_duplicate (orb)) { } void Test_i::test_method (CORBA::Short priority) { // Use RTCurrent to find out the CORBA priority of the current // thread. CORBA::Object_var obj = this->orb_->resolve_initial_references ("RTCurrent"); RTCORBA::Current_var current = RTCORBA::Current::_narrow (obj.in ()); if (CORBA::is_nil (obj.in ())) throw CORBA::INTERNAL (); CORBA::Short servant_thread_priority = current->the_priority (); // Print out the info. if (servant_thread_priority != priority) ACE_DEBUG ((LM_DEBUG, "ERROR: servant thread priority is not equal" "to method argument.\n")); ACE_DEBUG ((LM_DEBUG, "Server_Declared priority: %d " "Servant thread priority: %d\n", priority, servant_thread_priority)); } void Test_i::shutdown (void) { this->orb_->shutdown (0); } //************************************************************************* const ACE_TCHAR *ior_output_file1 = ACE_TEXT("test1.ior"); const ACE_TCHAR *ior_output_file2 = ACE_TEXT("test2.ior"); CORBA::Short poa_priority = -1; CORBA::Short object_priority = -1; // Parse command-line arguments. int parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("p:o:a:b:")); int c, result; while ((c = get_opts ()) != -1) switch (c) { case 'p': ior_output_file1 = get_opts.opt_arg (); break; case 'o': ior_output_file2 = get_opts.opt_arg (); break; case 'a': result = ::sscanf (ACE_TEXT_ALWAYS_CHAR (get_opts.opt_arg ()), "%hd", &poa_priority); if (result == 0 || result == EOF) ACE_ERROR_RETURN ((LM_ERROR, "Unable to process <-a> option"), -1); break; case 'b': result = ::sscanf (ACE_TEXT_ALWAYS_CHAR (get_opts.opt_arg ()), "%hd", &object_priority); if (result == 0 || result == EOF) ACE_ERROR_RETURN ((LM_ERROR, "Unable to process <-b> option"), -1); break; case '?': default: ACE_ERROR_RETURN ((LM_ERROR, "usage: %s " "-p <iorfile1> " "-o <iorfile2> " "-a <poa_priority> " "-b <object_priority> " "\n", argv [0]), -1); } if (poa_priority < 0 || object_priority < 0) ACE_ERROR_RETURN ((LM_ERROR, "Valid poa and object priorities must be" " specified.\nSee README file for more info\n"), -1); return 0; } int check_for_nil (CORBA::Object_ptr obj, const char *msg) { if (CORBA::is_nil (obj)) ACE_ERROR_RETURN ((LM_ERROR, "ERROR: Object reference <%C> is nil\n", msg), -1); else return 0; } int create_object (RTPortableServer::POA_ptr poa, CORBA::ORB_ptr orb, Test_i *server_impl, CORBA::Short priority, const ACE_TCHAR *filename) { // Register with poa. PortableServer::ObjectId_var id; if (priority > -1) id = poa->activate_object_with_priority (server_impl, priority); else id = poa->activate_object (server_impl); CORBA::Object_var server = poa->id_to_reference (id.in ()); // Print out the IOR. CORBA::String_var ior = orb->object_to_string (server.in ()); ACE_DEBUG ((LM_DEBUG, "<%C>\n\n", ior.in ())); // Print ior to the file. if (filename != 0) { FILE *output_file= ACE_OS::fopen (filename, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", filename), -1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } return 0; } class Task : public ACE_Task_Base { public: Task (ACE_Thread_Manager &thread_manager, CORBA::ORB_ptr orb); int svc (void); CORBA::ORB_var orb_; }; Task::Task (ACE_Thread_Manager &thread_manager, CORBA::ORB_ptr orb) : ACE_Task_Base (&thread_manager), orb_ (CORBA::ORB::_duplicate (orb)) { } int Task::svc (void) { try { // RTORB. CORBA::Object_var object = this->orb_->resolve_initial_references ("RTORB"); RTCORBA::RTORB_var rt_orb = RTCORBA::RTORB::_narrow (object.in ()); if (check_for_nil (rt_orb.in (), "RTORB") == -1) return -1; // RootPOA. object = this->orb_->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (object.in ()); if (check_for_nil (root_poa.in (), "RootPOA") == -1) return -1; // POAManager. PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); // Create child POA with SERVER_DECLARED PriorityModelPolicy, // and MULTIPLE_ID id uniqueness policy (so we can use one // servant to create several objects). CORBA::PolicyList poa_policy_list; poa_policy_list.length (2); poa_policy_list[0] = rt_orb->create_priority_model_policy (RTCORBA::SERVER_DECLARED, poa_priority); poa_policy_list[1] = root_poa->create_id_uniqueness_policy (PortableServer::MULTIPLE_ID); PortableServer::POA_var child_poa = root_poa->create_POA ("Child_POA", poa_manager.in (), poa_policy_list); RTPortableServer::POA_var rt_poa = RTPortableServer::POA::_narrow (child_poa.in ()); if (check_for_nil (rt_poa.in (), "RTPOA") == -1) return -1; // Servant. Test_i server_impl (this->orb_.in ()); // Create object 1 (it will inherit POA's priority). int result; ACE_DEBUG ((LM_DEBUG, "\nActivated object one as ")); result = create_object (rt_poa.in (), this->orb_.in (), &server_impl, -1, ior_output_file1); if (result == -1) return -1; // Create object 2 (override POA's priority). ACE_DEBUG ((LM_DEBUG, "\nActivated object two as ")); result = create_object (rt_poa.in (), this->orb_.in (), &server_impl, object_priority, ior_output_file2); if (result == -1) return -1; // Activate POA manager. poa_manager->activate (); // Start ORB event loop. this->orb_->run (); ACE_DEBUG ((LM_DEBUG, "Server ORB event loop finished\n\n")); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ( "Unexpected exception caught in Server_Declared test server:"); return -1; } return 0; } int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { // ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); // Parse arguments. if (parse_args (argc, argv) != 0) return -1; // Make sure we can support multiple priorities that are required // for this test. if (!check_supported_priorities (orb.in ())) return 2; // Thread Manager for managing task. ACE_Thread_Manager thread_manager; // Create task. Task task (thread_manager, orb.in ()); // Task activation flags. long flags = THR_NEW_LWP | THR_JOINABLE | orb->orb_core ()->orb_params ()->thread_creation_flags (); // Activate task. int result = task.activate (flags); if (result == -1) { if (errno == EPERM) { ACE_ERROR_RETURN ((LM_ERROR, "Cannot create thread with scheduling policy %s\n" "because the user does not have the appropriate privileges, terminating program....\n" "Check svc.conf options and/or run as root\n", sched_policy_name (orb->orb_core ()->orb_params ()->ace_sched_policy ())), 2); } else // Unexpected error. ACE_ASSERT (0); } // Wait for task to exit. result = thread_manager.wait (); ACE_ASSERT (result != -1); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught"); return -1; } return 0; }
26.699164
119
0.542097
[ "object" ]
7c56ebc8880b5af1159adbebf7e1ca8ec66b15e7
10,492
cpp
C++
dynamic/wrappers/cell_based/AbstractCentreBasedCellPopulation3_3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-02-04T16:10:53.000Z
2021-07-01T08:03:16.000Z
dynamic/wrappers/cell_based/AbstractCentreBasedCellPopulation3_3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
6
2017-06-22T08:50:41.000Z
2019-12-15T20:17:29.000Z
dynamic/wrappers/cell_based/AbstractCentreBasedCellPopulation3_3.cppwg.cpp
jmsgrogan/PyChaste
48a9863d2c941c71e47ecb72e917b477ba5c1413
[ "FTL" ]
3
2017-05-15T21:33:58.000Z
2019-10-27T21:43:07.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <set> #include <vector> #include <string> #include <map> #include "SmartPointers.hpp" #include "UblasIncludes.hpp" #include "AbstractCentreBasedCellPopulation.hpp" #include "AbstractCentreBasedCellPopulation3_3.cppwg.hpp" namespace py = pybind11; typedef AbstractCentreBasedCellPopulation<3,3 > AbstractCentreBasedCellPopulation3_3; PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>); typedef ::boost::numeric::ublas::c_vector<double, 3> _boost_numeric_ublas_c_vector_lt_double_3_gt_; typedef ::CellPtr _CellPtr; typedef ::std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > _std_set_lt_unsignedint_std_less_lt_unsignedint_gt__std_allocator_lt_unsignedint_gt__gt_; typedef ::std::vector<std::pair<Node<3> *, Node<3> *>, std::allocator<std::pair<Node<3> *, Node<3> *> > > & _std_vector_lt_std_pair_lt_Node_lt_3_gt_Ptr_Node_lt_3_gt_Ptr_gt__std_allocator_lt_std_pair_lt_Node_lt_3_gt_Ptr_Node_lt_3_gt_Ptr_gt__gt__gt_Ref; class AbstractCentreBasedCellPopulation3_3_Overloads : public AbstractCentreBasedCellPopulation3_3{ public: using AbstractCentreBasedCellPopulation3_3::AbstractCentreBasedCellPopulation; ::boost::numeric::ublas::c_vector<double, 3> GetLocationOfCellCentre(::CellPtr pCell) override { PYBIND11_OVERLOAD( _boost_numeric_ublas_c_vector_lt_double_3_gt_, AbstractCentreBasedCellPopulation3_3, GetLocationOfCellCentre, pCell); } double GetCellDataItemAtPdeNode(unsigned int pdeNodeIndex, ::std::string & rVariableName, bool dirichletBoundaryConditionApplies, double dirichletBoundaryValue) override { PYBIND11_OVERLOAD( double, AbstractCentreBasedCellPopulation3_3, GetCellDataItemAtPdeNode, pdeNodeIndex, rVariableName, dirichletBoundaryConditionApplies, dirichletBoundaryValue); } ::CellPtr AddCell(::CellPtr pNewCell, ::CellPtr pParentCell) override { PYBIND11_OVERLOAD( _CellPtr, AbstractCentreBasedCellPopulation3_3, AddCell, pNewCell, pParentCell); } bool IsCellAssociatedWithADeletedLocation(::CellPtr pCell) override { PYBIND11_OVERLOAD( bool, AbstractCentreBasedCellPopulation3_3, IsCellAssociatedWithADeletedLocation, pCell); } ::std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > GetNeighbouringLocationIndices(::CellPtr pCell) override { PYBIND11_OVERLOAD( _std_set_lt_unsignedint_std_less_lt_unsignedint_gt__std_allocator_lt_unsignedint_gt__gt_, AbstractCentreBasedCellPopulation3_3, GetNeighbouringLocationIndices, pCell); } void CheckForStepSizeException(unsigned int nodeIndex, ::boost::numeric::ublas::c_vector<double, 3> & rDisplacement, double dt) override { PYBIND11_OVERLOAD( void, AbstractCentreBasedCellPopulation3_3, CheckForStepSizeException, nodeIndex, rDisplacement, dt); } double GetDampingConstant(unsigned int nodeIndex) override { PYBIND11_OVERLOAD( double, AbstractCentreBasedCellPopulation3_3, GetDampingConstant, nodeIndex); } bool IsGhostNode(unsigned int index) override { PYBIND11_OVERLOAD( bool, AbstractCentreBasedCellPopulation3_3, IsGhostNode, index); } bool IsParticle(unsigned int index) override { PYBIND11_OVERLOAD( bool, AbstractCentreBasedCellPopulation3_3, IsParticle, index); } ::std::vector<std::pair<Node<3> *, Node<3> *>, std::allocator<std::pair<Node<3> *, Node<3> *> > > & rGetNodePairs() override { PYBIND11_OVERLOAD_PURE( _std_vector_lt_std_pair_lt_Node_lt_3_gt_Ptr_Node_lt_3_gt_Ptr_gt__std_allocator_lt_std_pair_lt_Node_lt_3_gt_Ptr_Node_lt_3_gt_Ptr_gt__gt__gt_Ref, AbstractCentreBasedCellPopulation3_3, rGetNodePairs, ); } void OutputCellPopulationParameters(::out_stream & rParamsFile) override { PYBIND11_OVERLOAD( void, AbstractCentreBasedCellPopulation3_3, OutputCellPopulationParameters, rParamsFile); } double GetDefaultTimeStep() override { PYBIND11_OVERLOAD( double, AbstractCentreBasedCellPopulation3_3, GetDefaultTimeStep, ); } void WriteVtkResultsToFile(::std::string const & rDirectory) override { PYBIND11_OVERLOAD_PURE( void, AbstractCentreBasedCellPopulation3_3, WriteVtkResultsToFile, rDirectory); } void AcceptCellWritersAcrossPopulation() override { PYBIND11_OVERLOAD( void, AbstractCentreBasedCellPopulation3_3, AcceptCellWritersAcrossPopulation, ); } }; void register_AbstractCentreBasedCellPopulation3_3_class(py::module &m){ py::class_<AbstractCentreBasedCellPopulation3_3 , AbstractCentreBasedCellPopulation3_3_Overloads , boost::shared_ptr<AbstractCentreBasedCellPopulation3_3 > , AbstractOffLatticeCellPopulation<3, 3> >(m, "AbstractCentreBasedCellPopulation3_3") .def( "GetLocationOfCellCentre", (::boost::numeric::ublas::c_vector<double, 3>(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr)) &AbstractCentreBasedCellPopulation3_3::GetLocationOfCellCentre, " " , py::arg("pCell") ) .def( "GetNodeCorrespondingToCell", (::Node<3> *(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr)) &AbstractCentreBasedCellPopulation3_3::GetNodeCorrespondingToCell, " " , py::arg("pCell") , py::return_value_policy::reference) .def( "GetCellDataItemAtPdeNode", (double(AbstractCentreBasedCellPopulation3_3::*)(unsigned int, ::std::string &, bool, double)) &AbstractCentreBasedCellPopulation3_3::GetCellDataItemAtPdeNode, " " , py::arg("pdeNodeIndex"), py::arg("rVariableName"), py::arg("dirichletBoundaryConditionApplies") = false, py::arg("dirichletBoundaryValue") = 0. ) .def( "AddCell", (::CellPtr(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr, ::CellPtr)) &AbstractCentreBasedCellPopulation3_3::AddCell, " " , py::arg("pNewCell"), py::arg("pParentCell") = ::CellPtr( ) ) .def( "CreateCellPair", (::std::pair<boost::shared_ptr<Cell>, boost::shared_ptr<Cell> >(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr, ::CellPtr)) &AbstractCentreBasedCellPopulation3_3::CreateCellPair, " " , py::arg("pCell1"), py::arg("pCell2") ) .def( "IsMarkedSpring", (bool(AbstractCentreBasedCellPopulation3_3::*)(::std::pair<boost::shared_ptr<Cell>, boost::shared_ptr<Cell> > const &)) &AbstractCentreBasedCellPopulation3_3::IsMarkedSpring, " " , py::arg("rCellPair") ) .def( "IsCellAssociatedWithADeletedLocation", (bool(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr)) &AbstractCentreBasedCellPopulation3_3::IsCellAssociatedWithADeletedLocation, " " , py::arg("pCell") ) .def( "GetNeighbouringLocationIndices", (::std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> >(AbstractCentreBasedCellPopulation3_3::*)(::CellPtr)) &AbstractCentreBasedCellPopulation3_3::GetNeighbouringLocationIndices, " " , py::arg("pCell") ) .def( "CheckForStepSizeException", (void(AbstractCentreBasedCellPopulation3_3::*)(unsigned int, ::boost::numeric::ublas::c_vector<double, 3> &, double)) &AbstractCentreBasedCellPopulation3_3::CheckForStepSizeException, " " , py::arg("nodeIndex"), py::arg("rDisplacement"), py::arg("dt") ) .def( "GetDampingConstant", (double(AbstractCentreBasedCellPopulation3_3::*)(unsigned int)) &AbstractCentreBasedCellPopulation3_3::GetDampingConstant, " " , py::arg("nodeIndex") ) .def( "IsGhostNode", (bool(AbstractCentreBasedCellPopulation3_3::*)(unsigned int)) &AbstractCentreBasedCellPopulation3_3::IsGhostNode, " " , py::arg("index") ) .def( "IsParticle", (bool(AbstractCentreBasedCellPopulation3_3::*)(unsigned int)) &AbstractCentreBasedCellPopulation3_3::IsParticle, " " , py::arg("index") ) .def( "rGetNodePairs", (::std::vector<std::pair<Node<3> *, Node<3> *>, std::allocator<std::pair<Node<3> *, Node<3> *> > > &(AbstractCentreBasedCellPopulation3_3::*)()) &AbstractCentreBasedCellPopulation3_3::rGetNodePairs, " " , py::return_value_policy::reference_internal) .def( "GetMeinekeDivisionSeparation", (double(AbstractCentreBasedCellPopulation3_3::*)()) &AbstractCentreBasedCellPopulation3_3::GetMeinekeDivisionSeparation, " " ) .def( "SetMeinekeDivisionSeparation", (void(AbstractCentreBasedCellPopulation3_3::*)(double)) &AbstractCentreBasedCellPopulation3_3::SetMeinekeDivisionSeparation, " " , py::arg("divisionSeparation") ) .def( "GetCentreBasedDivisionRule", (::boost::shared_ptr<AbstractCentreBasedDivisionRule<3, 3> >(AbstractCentreBasedCellPopulation3_3::*)()) &AbstractCentreBasedCellPopulation3_3::GetCentreBasedDivisionRule, " " ) .def( "SetCentreBasedDivisionRule", (void(AbstractCentreBasedCellPopulation3_3::*)(::boost::shared_ptr<AbstractCentreBasedDivisionRule<3, 3> >)) &AbstractCentreBasedCellPopulation3_3::SetCentreBasedDivisionRule, " " , py::arg("pCentreBasedDivisionRule") ) .def( "OutputCellPopulationParameters", (void(AbstractCentreBasedCellPopulation3_3::*)(::out_stream &)) &AbstractCentreBasedCellPopulation3_3::OutputCellPopulationParameters, " " , py::arg("rParamsFile") ) .def( "GetDefaultTimeStep", (double(AbstractCentreBasedCellPopulation3_3::*)()) &AbstractCentreBasedCellPopulation3_3::GetDefaultTimeStep, " " ) ; }
49.961905
251
0.672322
[ "vector" ]
7c5cb3309d2dc5ba4e5ca403c9fa34e512f33517
50,253
cc
C++
ge/generator/ge_generator.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
207
2020-03-28T02:12:50.000Z
2021-11-23T18:27:45.000Z
ge/generator/ge_generator.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
4
2020-04-17T07:32:44.000Z
2021-06-26T04:55:03.000Z
ge/generator/ge_generator.cc
mindspore-ai/graphengine
460406cbd691b963d125837f022be5d8abd1a637
[ "Apache-2.0" ]
13
2020-03-28T02:52:26.000Z
2021-07-03T23:12:54.000Z
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "framework/generator/ge_generator.h" #include <atomic> #include "common/ge/ge_util.h" #include "common/ge/plugin_manager.h" #include "framework/common/helper/model_helper.h" #include "framework/common/helper/om_file_helper.h" #include "framework/common/util.h" #include "common/util/error_manager/error_manager.h" #include "framework/common/debug/ge_log.h" #include "framework/common/debug/log.h" #include "external/ge/ge_api.h" #include "graph/debug/ge_attr_define.h" #include "graph/ge_context.h" #include "graph/manager/graph_manager.h" #include "graph/manager/graph_var_manager.h" #include "graph/manager/util/rt_context_util.h" #include "graph/operator_factory_impl.h" #include "graph/opsproto_manager.h" #include "graph/utils/graph_utils.h" #include "graph/utils/type_utils.h" #include "init/gelib.h" #include "common/model/ge_model.h" #include "analyzer/analyzer.h" using std::map; using std::string; using std::vector; namespace { const char *const kAttrOpType = "op_type"; const char *const kEngineNameDefault = "default"; const char *const kVectorEngine = "VectorEngine"; const char *const kAIcoreEngine = "AIcoreEngine"; const char *const kFileNameSuffix = "online"; const char *const kAicpuAllshape = "_AllShape"; constexpr char const *kAttrSupportDynamicShape = "support_dynamicshape"; const int64_t kDynamicDimValue = -2; const int kDefaultDeviceId = 0; const int kDefaultJobId = 0; const int32_t kFuzzBuildPattern = 1; std::map<ge::OpEngineType, std::string> engine_type_map{ {ge::ENGINE_SYS, kEngineNameDefault}, {ge::ENGINE_AICORE, kAIcoreEngine}, {ge::ENGINE_VECTOR, kVectorEngine}}; bool ContainsDynamicInpus(const ge::OpDesc &op_desc) { for (auto &tensor_desc : op_desc.GetAllInputsDescPtr()) { if (tensor_desc->MutableShape().IsUnknownShape()) { GELOGI("Contains unknown shape input. set is_dynamic_input to true."); return true; } } return false; } // if optional in/out, format is format_reserved and dtype is dt_undefined bool IsOptional(const ge::GeTensorDesc &tensor_desc) { return tensor_desc.GetFormat() == ge::FORMAT_RESERVED && tensor_desc.GetDataType() == ge::DT_UNDEFINED; } } // namespace namespace ge { static Status CheckEngineTypeSupport(const NodePtr &node, OpEngineType engine_type) { const OpDescPtr &op_desc = node->GetOpDesc(); GE_CHECK_NOTNULL_EXEC(op_desc, return PARAM_INVALID); if (engine_type == ENGINE_SYS) { GELOGI("CheckEngineType: use default engine."); return SUCCESS; } // get op engine name string op_engine_name; auto iter = engine_type_map.find(engine_type); if (iter != engine_type_map.end()) { op_engine_name = iter->second; GELOGI("CheckEngineType: engine type: %d", static_cast<int>(engine_type)); } else { ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"}, {op_desc->GetName(), op_desc->GetType(), "engine type", "it only support default/AIcoreEngine/VectorEngine"}); GELOGE(FAILED, "[Check][Param] value:%d not support, " "only support default/AIcoreEngine/VectorEngine now", static_cast<int>(engine_type)); return FAILED; } if (op_desc->HasAttr(ATTR_NAME_UNREGST_OPPATH)) { op_desc->SetOpEngineName(op_engine_name); op_desc->SetOpKernelLibName(op_engine_name); return SUCCESS; } // set op engine name and opkernelLib. when engine support std::shared_ptr<GELib> instance_ptr = ge::GELib::GetInstance(); if ((instance_ptr == nullptr) || (!instance_ptr->InitFlag())) { REPORT_INNER_ERROR("E19999", "get gelib failed, as get instance failed or initflag failed."); GELOGE(GE_CLI_GE_NOT_INITIALIZED, "[Get][GELib] CheckEngineType failed, as get gelib failed."); return FAILED; } OpsKernelManager &ops_kernel_manager = instance_ptr->OpsKernelManagerObj(); std::vector<OpInfo> op_infos = ops_kernel_manager.GetOpsKernelInfo(op_desc->GetType()); if (op_infos.empty()) { ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"}, {op_desc->GetName(), op_desc->GetType(), "optype", "it can not find"}); GELOGE(FAILED, "[Get][OpInfo] by op type %s failed.", op_desc->GetType().c_str()); return FAILED; } string kernel_name; for (const auto &it : op_infos) { if (it.engine == op_engine_name) { kernel_name = it.opKernelLib; break; } } if (kernel_name.empty()) { ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"}, {op_desc->GetName(), op_desc->GetType(), "engine name" + FmtToStr(op_engine_name), "it can not find"}); GELOGE(FAILED, "[Check][Param] Can not find ops kernel, engine name:%s. op:%s(%s)", op_engine_name.c_str(), op_desc->GetName().c_str(), op_desc->GetType().c_str()); return FAILED; } auto &kernel_map = ops_kernel_manager.GetAllOpsKernelInfoStores(); auto kernel_info_store = kernel_map.find(kernel_name); if (kernel_info_store != kernel_map.end()) { std::string unsupported_reason; if (kernel_info_store->second->CheckSupported(node, unsupported_reason)) { op_desc->SetOpEngineName(op_engine_name); op_desc->SetOpKernelLibName(kernel_name); GELOGI("CheckEngineType:Set OpKernelLibName %s and engine name %s into op_desc %s", kernel_name.c_str(), op_engine_name.c_str(), op_desc->GetName().c_str()); return SUCCESS; } else { ErrorManager::GetInstance().ATCReportErrMessage( "E13002", {"optype", "opskernel", "reason"}, {op_desc->GetType(), kernel_name, unsupported_reason}); GELOGE(FAILED, "[Call][CheckSupported] failed, Op type %s of ops kernel %s is unsupported, reason:%s", op_desc->GetType().c_str(), kernel_name.c_str(), unsupported_reason.c_str()); return FAILED; } } else { ErrorManager::GetInstance().ATCReportErrMessage( "E13003", {"opname", "optype"}, {op_desc->GetName(), op_desc->GetType()}); GELOGE(FAILED, "[Check][Param] Can not find any supported ops kernel info store by kernel_name %s," "op type is %s, op name is %s", kernel_name.c_str(), op_desc->GetType().c_str(), op_desc->GetName().c_str()); } return FAILED; } static Status AddInputs(const ComputeGraphPtr &graph, const NodePtr &node, const GeTensorDesc &tensor, int32_t index, bool attr, int32_t &data_index) { GE_CHECK_NOTNULL_EXEC(graph, return PARAM_INVALID); GE_CHECK_NOTNULL_EXEC(node, return PARAM_INVALID); auto format = tensor.GetFormat(); auto data_type = tensor.GetDataType(); if (format == FORMAT_RESERVED && data_type == DT_UNDEFINED) { return SUCCESS; } string op_type; bool is_const = false; (void)AttrUtils::GetBool(tensor, CONST_ATTR_NAME_INPUT, is_const); if (is_const) { GELOGD("Get input[%d] is const", index); op_type = CONSTANTOP; } else if (!AttrUtils::GetStr(tensor, kAttrOpType, op_type) || op_type.empty()) { op_type = DATA; } string op_name = node->GetName() + "_in_" + std::to_string(index); OpDescPtr data_op = MakeShared<ge::OpDesc>(op_name, op_type); if (data_op == nullptr) { REPORT_CALL_ERROR("E19999", "create OpDesc failed, name:%s", op_name.c_str()); GELOGE(FAILED, "[Create][OpDesc] failed, name:%s", op_name.c_str()); return FAILED; } if (is_const) { ConstGeTensorPtr tensor_value; if (!AttrUtils::GetTensor(tensor, ge::ATTR_NAME_WEIGHTS, tensor_value)) { REPORT_CALL_ERROR("E19999", "get attr %s failed, tensor:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), tensor.GetName().c_str()); GELOGE(FAILED, "[Get][Attr] %s failed, tensor:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), tensor.GetName().c_str()); return FAILED; } if (!AttrUtils::SetTensor(data_op, ge::ATTR_NAME_WEIGHTS, tensor_value)) { REPORT_CALL_ERROR("E19999", "set attr %s failed, op:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), op_name.c_str()); GELOGE(FAILED, "[Set][Attr] %s failed, op:%s.", ge::ATTR_NAME_WEIGHTS.c_str(), op_name.c_str()); return FAILED; } } (void)AttrUtils::SetBool(data_op, "_is_single_op", true); (void)AttrUtils::SetBool(data_op, ATTR_NAME_IS_ORIGINAL_INPUT, true); GE_CHK_BOOL_EXEC(data_op->AddInputDesc(tensor) == GRAPH_SUCCESS, REPORT_CALL_ERROR("E19999", "AddInputDesc failed for node:%s", data_op->GetName().c_str()); return FAILED, "[Add][InputDesc] fail for node:%s", data_op->GetName().c_str()); GE_CHK_BOOL_EXEC(data_op->AddOutputDesc(tensor) == GRAPH_SUCCESS, REPORT_CALL_ERROR("E19999", "AddOutputDesc failed for node:%s", data_op->GetName().c_str()); return FAILED, "[Add][OutputDesc] fail for node:%s", data_op->GetName().c_str()); if (attr && !is_const) { GE_CHK_BOOL_EXEC(AttrUtils::SetInt(data_op, ATTR_NAME_INDEX, data_index), REPORT_CALL_ERROR("E19999", "set attr %s failed for node:%s", ATTR_NAME_INDEX.c_str(), data_op->GetName().c_str()); return FAILED, "[Set][Attr:%s] fail for node:%s", ATTR_NAME_INDEX.c_str(), data_op->GetName().c_str()); ++data_index; } ge::NodePtr arg_node = graph->AddNode(data_op); GE_CHK_BOOL_EXEC(arg_node != nullptr, REPORT_CALL_ERROR("E19999", "add node:%s to graph:%s failed", data_op->GetName().c_str(), graph->GetName().c_str()); return FAILED, "[Add][Node] Insert Data node:%s fail", data_op->GetName().c_str()); GE_CHK_STATUS(GraphUtils::AddEdge(arg_node->GetOutDataAnchor(0), node->GetInDataAnchor(index)), "[Add][Edge]fail from node:%s to node:%s", data_op->GetName().c_str(), node->GetName().c_str()); return SUCCESS; } static Status AddOutputs(const ComputeGraphPtr &graph, const NodePtr &node, const vector<GeTensor> &outputs) { OpDescPtr op_desc = MakeShared<ge::OpDesc>(graph->GetName() + "_" + NODE_NAME_NET_OUTPUT, NETOUTPUT); if (op_desc == nullptr) { REPORT_CALL_ERROR("E19999", "create OpDesc failed, graph:%s", graph->GetName().c_str()); GELOGE(FAILED, "[Create][OpDesc] failed, graph:%s", graph->GetName().c_str()); return FAILED; } (void)AttrUtils::SetBool(op_desc, "_is_single_op", true); int32_t count = 0; for (const auto &out_desc : outputs) { GeTensorDesc tensor = out_desc.GetTensorDesc(); TensorUtils::SetInputTensor(tensor, true); GE_CHK_BOOL_EXEC(op_desc->AddInputDesc(tensor) == GRAPH_SUCCESS, REPORT_CALL_ERROR("E19999", "AddInputDesc failed for node:%s", op_desc->GetName().c_str()); return FAILED, "[Add][InputDesc]fail for node:%s", op_desc->GetName().c_str()); TensorUtils::SetInputTensor(tensor, false); TensorUtils::SetOutputTensor(tensor, true); GE_CHK_BOOL_EXEC(op_desc->AddOutputDesc(tensor) == GRAPH_SUCCESS, REPORT_CALL_ERROR("E19999", "AddOutputDesc failed for node:%s", op_desc->GetName().c_str()); return FAILED, "[Add][OutputDesc]fail for node:%s", op_desc->GetName().c_str()); count++; } GE_CHECK_NOTNULL_EXEC(graph, return PARAM_INVALID); ge::NodePtr out_node = graph->AddNode(op_desc); GE_CHK_BOOL_EXEC(out_node != nullptr, REPORT_CALL_ERROR("E19999", "add node:%s to graph:%u failed.", op_desc->GetName().c_str(), graph->GetGraphID()); return FAILED, "[Add][Node:%s]fail in graph:%u", op_desc->GetName().c_str(), graph->GetGraphID()); GE_CHECK_NOTNULL_EXEC(node, return PARAM_INVALID); for (int32_t i = 0; i < count; ++i) { GE_CHK_STATUS(GraphUtils::AddEdge(node->GetOutDataAnchor(i), out_node->GetInDataAnchor(i)), "[Add][Edge]fail from node:%s to node:%s", node->GetName().c_str(), out_node->GetName().c_str()); } return SUCCESS; } static void GetOpsProtoPath(string &opsproto_path) { const char *path_env = std::getenv("ASCEND_OPP_PATH"); if (path_env != nullptr) { string path = path_env; string file_path = RealPath(path.c_str()); if (file_path.empty()) { REPORT_CALL_ERROR("E19999", "File path %s is invalid.", path.c_str()); GELOGE(FAILED, "[Call][RealPath] File path %s is invalid.", path.c_str()); return; } opsproto_path = (path + "/op_proto/custom/" + ":") + (path + "/op_proto/built-in/"); GELOGI("Get opsproto so path from env : %s", path.c_str()); return; } string path_base = PluginManager::GetPath(); GELOGI("path_base is %s", path_base.c_str()); path_base = path_base.substr(0, path_base.rfind('/')); path_base = path_base.substr(0, path_base.rfind('/') + 1); opsproto_path = (path_base + "ops/op_proto/custom/" + ":") + (path_base + "ops/op_proto/built-in/"); } static Status ResetTensorVecShape(const vector<GeTensor> &inputs, vector<GeTensor> &inputs_dynamic) { for (auto input : inputs) { auto input_desc = input.GetTensorDesc(); GeShape shape_ori = input_desc.GetShape(); std::vector<int64_t> dynamic_shape_dims = {kDynamicDimValue}; GeShape dynamic_shape(dynamic_shape_dims); std::vector<std::pair<int64_t, int64_t>> dynamic_shape_range; ge::GeTensor inputTensor; ge::GeTensorDesc desc(input_desc); bool is_const = false; (void)AttrUtils::GetBool(input_desc, CONST_ATTR_NAME_INPUT, is_const); if (!is_const) { int64_t storage_format = FORMAT_NCHW; if (ge::AttrUtils::GetInt(desc, ge::ATTR_NAME_STORAGE_FORMAT, storage_format) && !ge::AttrUtils::SetListInt(desc, ge::ATTR_NAME_STORAGE_SHAPE, dynamic_shape_dims)) { REPORT_CALL_ERROR("E19999", "Set attr ATTR_NAME_STORAGE_SHAPE failed to op:%s.", desc.GetName().c_str()); GELOGE(FAILED, "[Set][Attr] ATTR_NAME_STORAGE_SHAPE fail."); return FAILED; } desc.SetShape(dynamic_shape); desc.SetShapeRange(dynamic_shape_range); } inputTensor.SetTensorDesc(desc); inputs_dynamic.push_back(inputTensor); } return SUCCESS; } static Status GetFuzzBuildAttrs(const OpDescPtr &op_desc, const GeRootModelPtr &ge_root_model, GeAttrValue::LIST_NAMED_ATTRS &fuzz_build_attrs) { GELOGD("Start get fuzz build attrs of %s.", op_desc->GetName().c_str()); GE_CHECK_NOTNULL(ge_root_model->GetRootGraph()); for (const auto &node : ge_root_model->GetRootGraph()->GetAllNodes()) { GE_CHECK_NOTNULL(node); GE_CHECK_NOTNULL(node->GetOpDesc()); GELOGD("Delete fuzz build attr of %s after build.", node->GetName().c_str()); node->GetOpDesc()->DelAttr(ATTR_NAME_FUZZ_BUILD); } (void)AttrUtils::GetListNamedAttrs(op_desc, ATTR_NAME_FUZZ_BUILD_RES_ATTRS, fuzz_build_attrs); if (!fuzz_build_attrs.empty()) { GELOGD("%s has split, get ATTR_NAME_FUZZ_BUILD_RES_ATTRS directly.", op_desc->GetName().c_str()); return SUCCESS; } else { GELOGW("%s build with fuzz build pattern, but not set ATTR_NAME_FUZZ_BUILD_RES_ATTRS.", op_desc->GetName().c_str()); } return SUCCESS; } static bool HasShapeRange(const vector<GeTensor> &inputs) { for (const auto &input : inputs) { vector<pair<int64_t, int64_t>> shape_range; (void)input.GetTensorDesc().GetShapeRange(shape_range); if (!shape_range.empty()) { GELOGD("Has set shape range."); return true; } } return false; } class GeGenerator::Impl { public: Impl(OmgContext &omg_context) : omg_context_(omg_context) {} ~Impl() = default; Status BuildModel(const Graph &graph, const vector<GeTensor> &inputs, GeRootModelPtr &ge_models); Status SaveModel(const string &file_name_prefix, GeModelPtr &models, ModelBufferData &model); Status SaveRootModel(const string &file_name_prefix, GeRootModelPtr &model, ModelBufferData &model_buff); Status SaveParams(GeModelPtr &ge_model, const string &type, const map<string, GeAttrValue> &attrs, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs); Status GenerateInfershapeGraph(const Graph &graph); OmgContext &omg_context_; GraphManager graph_manager_; SaveParam save_param_; bool is_offline_ = true; bool is_singleop_unregistered_ = false; std::string build_mode_; std::string build_step_; static std::mutex mutex_; private: static std::string Trim(const std::string &str); bool ParseVersion(const std::string &line, std::string &version); bool GetVersionFromPath(const std::string &file_path, std::string &version); bool SetAtcVersionInfo(AttrHolder &obj); bool SetOppVersionInfo(AttrHolder &obj); bool SetOmSystemInfo(AttrHolder &obj); }; Status GeGenerator::Initialize(const map<string, string> &options) { return Initialize(options, domi::GetContext()); } Status GeGenerator::Initialize(const map<string, string> &options, OmgContext &omg_context) { impl_ = ge::MakeShared<Impl>(omg_context); if (impl_ == nullptr) { REPORT_CALL_ERROR("E19999", "create Impl failed."); GELOGE(MEMALLOC_FAILED, "[Create][Impl] Make shared failed"); return MEMALLOC_FAILED; } ErrorManager::GetInstance().SetStage(error_message::kInitialize, error_message::kOpsProtoInit); string opsproto_path; GetOpsProtoPath(opsproto_path); GELOGI("Get opsproto path is %s", opsproto_path.c_str()); OpsProtoManager *manager = OpsProtoManager::Instance(); map<string, string> option_tmp; option_tmp.emplace(std::pair<string, string>(string("ge.opsProtoLibPath"), opsproto_path)); (void)manager->Initialize(option_tmp); Status ret = impl_->graph_manager_.Initialize(options); if (ret != SUCCESS) { GELOGE(GE_GENERATOR_GRAPH_MANAGER_INIT_FAILED, "[Call][Initialize] Graph manager initialize failed."); return GE_GENERATOR_GRAPH_MANAGER_INIT_FAILED; } // get ek file auto iter = options.find(EK_FILE); if (iter != options.end()) { impl_->save_param_.ek_file = iter->second; } // get cert file iter = options.find(CERT_FILE); if (iter != options.end()) { impl_->save_param_.cert_file = iter->second; } // get hw key file iter = options.find(HW_KEY_FILE); if (iter != options.end()) { impl_->save_param_.hw_key_file = iter->second; } // get private file iter = options.find(PRIVATE_KEY_FILE); if (iter != options.end()) { impl_->save_param_.pri_key_file = iter->second; } // get build mode iter = options.find(BUILD_MODE); if (iter != options.end()) { impl_->build_mode_ = iter->second; } // get build step iter = options.find(BUILD_STEP); if (iter != options.end()) { impl_->build_step_ = iter->second; } return SUCCESS; } Status GeGenerator::Finalize() { ErrorManager::GetInstance().SetStage(error_message::kFinalize, error_message::kFinalize); if (impl_ == nullptr) { return SUCCESS; } Status ret = impl_->graph_manager_.Finalize(); if (ret != SUCCESS) { GELOGE(GE_GENERATOR_GRAPH_MANAGER_FINALIZE_FAILED, "[Call][Finalize] Graph manager finalize failed."); return GE_GENERATOR_GRAPH_MANAGER_FINALIZE_FAILED; } return SUCCESS; } Status GeGenerator::GenerateOfflineModel(const Graph &graph, const string &file_name_prefix, const vector<GeTensor> &inputs) { ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); GELOGI("Start to generate offline model."); ModelBufferData model; return GenerateModel(graph, file_name_prefix, inputs, model, true); } Status GeGenerator::GenerateOnlineModel(const Graph &graph, const vector<GeTensor> &inputs, ModelBufferData &model) { ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); return GenerateModel(graph, "online", inputs, model, false); } Status GeGenerator::GenerateInfershapeGraph(const Graph &graph) { GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID); Status ret = impl_->GenerateInfershapeGraph(graph); if (ret != SUCCESS) { GELOGE(ret, "[Call][GenerateInfershapeGraph] Dump infershape json failed"); if (impl_->graph_manager_.Finalize() != SUCCESS) { GELOGE(FAILED, "[Call][Finalize] graph_manager finalize fail."); } return ret; } GELOGI("Generate infer shape graph success"); return SUCCESS; } std::mutex GeGenerator::Impl::mutex_; // Remove the space and tab before and after the string std::string GeGenerator::Impl::Trim(const std::string &str) { if (str.empty()) { return str; } std::string::size_type start = str.find_first_not_of(" \t\r\n"); if (start == std::string::npos) { return str; } std::string::size_type end = str.find_last_not_of(" \t\r\n") + 1; return str.substr(start, end); } // Parsing the command line bool GeGenerator::Impl::ParseVersion(const std::string &line, std::string &version) { std::string flag = "Version="; std::string temp = Trim(line); if (temp.empty()) { GELOGW("line is empty."); return false; } std::string::size_type pos = temp.find(flag); if (pos == std::string::npos) { GELOGW("Incorrect line [%s], it must include [%s].", line.c_str(), flag.c_str()); return false; } if (temp.size() == flag.size()) { GELOGW("version information is empty. %s", line.c_str()); return false; } version = temp.substr(pos + flag.size()); return true; } bool GeGenerator::Impl::GetVersionFromPath(const std::string &file_path, std::string &version) { // Normalize the path string resolved_file_path = RealPath(file_path.c_str()); if (resolved_file_path.empty()) { GELOGW("Invalid input file path [%s], make sure that the file path is correct.", file_path.c_str()); return false; } std::ifstream fs(resolved_file_path, std::ifstream::in); if (!fs.is_open()) { GELOGW("Open %s failed.", file_path.c_str()); return false; } std::string line; if (getline(fs, line)) { if (!ParseVersion(line, version)) { GELOGW("Parse version failed. content is [%s].", line.c_str()); fs.close(); return false; } } else { GELOGW("No version information found in the file path:%s", file_path.c_str()); fs.close(); return false; } fs.close(); // close the file return true; } // Set package version information in the model bool GeGenerator::Impl::SetAtcVersionInfo(AttrHolder &obj) { std::string path_base = ge::GELib::GetPath(); path_base = path_base.substr(0, path_base.rfind('/')); path_base = path_base.substr(0, path_base.rfind('/') + 1); std::string version_path = path_base + "version.info"; std::string version; if (!GetVersionFromPath(version_path, version)) { GELOGW("Get atc version information failed!"); return false; } // set version info if (!ge::AttrUtils::SetStr(obj, ATTR_MODEL_ATC_VERSION, version)) { GELOGW("Ge model set atc version failed!"); return false; } return true; } // Set package version information in the model bool GeGenerator::Impl::SetOppVersionInfo(AttrHolder &obj) { const char *path_env = std::getenv("ASCEND_OPP_PATH"); if (path_env == nullptr) { GELOGW("Get environment variable ASCEND_OPP_PATH failed!"); return false; } std::string version_path = path_env; version_path += "/version.info"; std::string version; if (!GetVersionFromPath(version_path, version)) { GELOGW("Get opp version information failed!"); return false; } // set version info if (!ge::AttrUtils::SetStr(obj, ATTR_MODEL_OPP_VERSION, version)) { GELOGW("Ge model set opp version failed!"); return false; } return true; } bool GeGenerator::Impl::SetOmSystemInfo(AttrHolder &obj) { std::string soc_version; (void)ge::GetContext().GetOption(ge::SOC_VERSION, soc_version); GELOGI("SetOmSystemInfo soc_version: %s", soc_version.c_str()); if (!ge::AttrUtils::SetStr(obj, "soc_version", soc_version)) { GELOGW("SetStr of soc_version failed."); return false; } std::string framework_type; (void)ge::GetContext().GetOption(ge::FRAMEWORK_TYPE, framework_type); GELOGI("SetOmSystemInfo framework_type: %s", framework_type.c_str()); auto iter = ge::kFwkTypeToStr.find(framework_type); if (iter == ge::kFwkTypeToStr.end()) { GELOGW("Can not find framework_type in the map."); return false; } if (!ge::AttrUtils::SetStr(obj, "framework_type", iter->second)) { GELOGW("SetStr of framework_type failed."); return false; } return true; } Status GeGenerator::SetModelNameForDump(const GeRootModelPtr &ge_root_model) { bool is_unknown_shape = false; Status ret = ge_root_model->CheckIsUnknownShape(is_unknown_shape); if (ret != SUCCESS) { GELOGE(FAILED, "[Check][IsUnknownShape]Check root model is unknown shape failed, model id:%u", ge_root_model->GetModelId()); REPORT_CALL_ERROR("E19999", "Check root model is unknown shape failed, model id:%u", ge_root_model->GetModelId()); return FAILED; } GeModelPtr model_root = nullptr; if (is_unknown_shape) { model_root = MakeShared<GeModel>(); GE_CHECK_NOTNULL(model_root); model_root->SetGraph(GraphUtils::CreateGraphFromComputeGraph(ge_root_model->GetRootGraph())); ge_root_model->SetSubgraphInstanceNameToModel(ge_root_model->GetRootGraph()->GetName(), model_root); } ModelHelper model_helper; string model_name; GE_CHECK_NOTNULL(ge_root_model->GetRootGraph()); Status name_ret = model_helper.GetModelNameFromMergedGraphName(ge_root_model->GetRootGraph()->GetName(), model_name); if (name_ret != SUCCESS) { ErrorManager::GetInstance().ATCReportErrMessage("E10000", {"parameter"}, {"output"}); GELOGE(FAILED, "[Check][GetModelNameStep]Get model_name failed. Param --output is invalid, root graph name: %s", ge_root_model->GetRootGraph()->GetName().c_str()); return PARAM_INVALID; } map<string, GeModelPtr> name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel(); GeModelPtr &ge_model = name_to_ge_model[ge_root_model->GetRootGraph()->GetName()]; GE_CHECK_NOTNULL(ge_model); ge_model->SetName(model_name); return SUCCESS; } Status GeGenerator::GenerateModel(const Graph &graph, const string &file_name_prefix, const vector<GeTensor> &inputs, ModelBufferData &model, bool is_offline) { rtContext_t ctx = nullptr; auto rt = rtCtxGetCurrent(&ctx); if (rt != RT_ERROR_NONE) { GELOGD("Current ctx is null."); ctx = nullptr; } std::function<void()> callback = [&]() { if (ctx != nullptr) { (void)rtCtxSetCurrent(ctx); } }; GE_MAKE_GUARD(restore, callback); GeRootModelPtr ge_root_model = nullptr; GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID); impl_->is_offline_ = is_offline; Status ret = impl_->BuildModel(graph, inputs, ge_root_model); if (ret != SUCCESS) { GELOGE(ret, "[Build][Model] failed, ret:%d.", ret); if (impl_->graph_manager_.Finalize() != SUCCESS) { GELOGE(FAILED, "[Call][Finalize] graph_manager finalize fail."); } return ret; } /// BUILD_MODE_TUNING with BUILD_STEP_BEFORE_UB_MATCH no need save model; /// BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER no need save model; /// BUILD_MODE_TUNING with BUILD_STEP_AFTER_BUILDER_SUB no need save model. if ((impl_->build_mode_ == BUILD_MODE_TUNING) && (impl_->build_step_ == BUILD_STEP_BEFORE_UB_MATCH || impl_->build_step_ == BUILD_STEP_AFTER_BUILDER || impl_->build_step_ == BUILD_STEP_AFTER_BUILDER_SUB)) { GELOGI("Build mode:%s with step:%s no need SaveModel.", impl_->build_mode_.c_str(), impl_->build_step_.c_str()); return SUCCESS; } GE_CHECK_NOTNULL(ge_root_model); ret = SetModelNameForDump(ge_root_model); if (ret != SUCCESS) { return ret; } ret = impl_->SaveRootModel(file_name_prefix, ge_root_model, model); if (ret != SUCCESS) { GELOGE(ret, "[Save][RootModel] failed, ret:%d, file:%s", ret, file_name_prefix.c_str()); if (impl_->graph_manager_.Finalize() != SUCCESS) { GELOGE(FAILED, "graph_manager finalize fail."); } return ret; } return SUCCESS; } namespace { bool IsNeedConnectInputOpForSingleOp(GeTensorDesc &tensor_desc) { bool is_need = true; // format and dtype is all reserved, stand for Optional input. When singleop scene if (tensor_desc.GetFormat() == FORMAT_RESERVED && tensor_desc.GetDataType() == DT_UNDEFINED) { is_need = false; } return is_need; } Status CheckDynamicSupport(GeModelPtr &ge_model, const ComputeGraphPtr &graph) { bool support_dynamic = true; bool is_dynamic = false; for (const auto &node : graph->GetDirectNode()) { GE_CHECK_NOTNULL(node); auto op_desc = node->GetOpDesc(); GE_CHECK_NOTNULL(op_desc); if (op_desc->GetOpEngineName() != kAIcoreEngine) { continue; } if (AttrUtils::HasAttr(op_desc, kAttrSupportDynamicShape)) { is_dynamic = true; (void) AttrUtils::GetBool(op_desc, kAttrSupportDynamicShape, support_dynamic); if (!support_dynamic) { GELOGW("Node[%s] doesn't support dynamic shape.", node->GetName().c_str()); break; } } } if (is_dynamic) { (void) AttrUtils::SetBool(ge_model, kAttrSupportDynamicShape, support_dynamic); } return SUCCESS; } } bool GeGenerator::CheckNoAicore(const ComputeGraphPtr &graph) { for (const auto &node : graph->GetDirectNode()) { if (node == nullptr) { continue; } auto op_desc = node->GetOpDesc(); if (op_desc == nullptr) { continue; } if (op_desc->GetOpEngineName() == kAIcoreEngine) { return false; } } return true; } void GeGenerator::RemoveConst(const vector<GeTensor> &inputs, vector<GeTensor> &outputs) { for (auto &input : inputs) { GeTensorDesc input_desc = input.GetTensorDesc(); bool is_const = false; (void)AttrUtils::GetBool(input_desc, CONST_ATTR_NAME_INPUT, is_const); bool is_optional = IsOptional(input_desc); if (!is_optional && !is_const) { outputs.emplace_back(input); } } } Status GeGenerator::CheckForSingleOp(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs) { GE_CHECK_NOTNULL_EXEC(op_desc, return PARAM_INVALID); if (!inputs.empty() && (inputs.size() != op_desc->GetAllInputsSize())) { ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"}, {op_desc->GetName(), op_desc->GetType(), "inputs size" + FmtToStr(op_desc->GetAllInputsSize()), "tensor size is " + FmtToStr(inputs.size())}); GELOGE(PARAM_INVALID, "[Check][Param] Tensor size: %zu, op:%s(%s) Inputs size: %zu, not equal", inputs.size(), op_desc->GetName().c_str(), op_desc->GetType().c_str(), op_desc->GetAllInputsSize()); return PARAM_INVALID; } if (!outputs.empty() && (outputs.size() != op_desc->GetOutputsSize())) { ErrorManager::GetInstance().ATCReportErrMessage("E14001", {"opname", "optype", "value", "reason"}, {op_desc->GetName(), op_desc->GetType(), "outputs size" + FmtToStr(op_desc->GetOutputsSize()), "tensor size is " + FmtToStr(outputs.size())}); GELOGE(PARAM_INVALID, "[Check][Param] Tensor size: %zu, op:%s(%s) Outputs size: %zu, not equal", outputs.size(), op_desc->GetName().c_str(), op_desc->GetType().c_str(), op_desc->GetOutputsSize()); return PARAM_INVALID; } return SUCCESS; } Status GeGenerator::InferFormatForSingleOp(OpDescPtr &op_desc, Graph &graph) { GE_CHECK_NOTNULL(op_desc); if (OperatorFactoryImpl::GetInferFormatFunc(op_desc->GetType()) != nullptr) { auto node_op = ge::OperatorFactoryImpl::CreateOperator("node_op", op_desc->GetType()); if (node_op.IsEmpty()) { GELOGW("get op from OperatorFactory fail. op type: %s", op_desc->GetType().c_str()); } else { GELOGD("get op from OperatorFactory success. op type: %s", op_desc->GetType().c_str()); auto temp_op_desc = ge::OpDescUtils::GetOpDescFromOperator(node_op); if (temp_op_desc == nullptr) { REPORT_INNER_ERROR("E19999", "GetOpDescFromOperator failed, as return nullptr, type:%s", op_desc->GetType().c_str()); GELOGE(FAILED, "[Get][OpDesc] temp op desc is null, type:%s", op_desc->GetType().c_str()); return FAILED; } if (!op_desc->UpdateInputName(temp_op_desc->GetAllInputName())) { GELOGW("InferFormatForSingleOp UpdateInputName failed"); } if (!op_desc->UpdateOutputName(temp_op_desc->GetAllOutputName())) { GELOGW("InferFormatForSingleOp UpdateOutputName failed"); } } node_op.BreakConnect(); } auto comp_graph = GraphUtils::GetComputeGraph(graph); GE_CHECK_NOTNULL(comp_graph); auto node = comp_graph->FindNode(op_desc->GetName()); GE_CHECK_NOTNULL(node); auto op = OpDescUtils::CreateOperatorFromNode(node); auto ret = op_desc->CallInferFormatFunc(op); if (ret != GRAPH_SUCCESS) { REPORT_INNER_ERROR("E19999", "call InferFormatFunc for single op:%s fail", op_desc->GetName().c_str()); GELOGE(FAILED, "[Call][InferFormatFunc] for single op:%s fail.", op_desc->GetName().c_str()); return FAILED; } return SUCCESS; } Status GeGenerator::BuildSingleOp(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs, const string &model_file_name, OpEngineType engine_type, ModelBufferData &model_buff, bool is_offline, int32_t compile_flag) { GELOGD("Inputs size is %zu, outputs size is %zu.", inputs.size(), outputs.size()); GE_CHECK_NOTNULL_EXEC(impl_, return PARAM_INVALID); impl_->is_offline_ = is_offline; (void)AttrUtils::SetBool(op_desc, ATTR_SINGLE_OP_SCENE, true); if (CheckForSingleOp(op_desc, inputs, outputs) != SUCCESS) { GELOGE(PARAM_INVALID, "[Check][Param] input param is invalid when build single op:%s!", op_desc->GetName().c_str()); return PARAM_INVALID; } OmgContext &omg_context = impl_->omg_context_; omg_context.is_dynamic_input = ContainsDynamicInpus(*op_desc); if (op_desc->HasAttr(ATTR_NAME_UNREGST_OPPATH)) { impl_->is_singleop_unregistered_ = true; } // 0. Save original attributes. OpDescPtr op_desc_tmp = AttrUtils::CloneOpDesc(op_desc); GE_CHECK_NOTNULL(op_desc_tmp); bool fuzz_compile_flag = false; if (!HasShapeRange(inputs) && compile_flag == kFuzzBuildPattern) { fuzz_compile_flag = true; } (void)AttrUtils::SetBool(op_desc, ATTR_NAME_FUZZ_BUILD, fuzz_compile_flag); impl_->omg_context_.fuzz_compile_flag = fuzz_compile_flag; // 1. Create ComputeGraph. string name = ge::CurrentTimeInStr() + "_" + model_file_name; Graph graph; GE_CHK_STATUS(BuildSingleOpGraph(op_desc, inputs, outputs, name, graph), "[Build][Graph] for single op:%s fail.", op_desc->GetName().c_str()); GE_CHK_STATUS_RET_NOLOG(InferFormatForSingleOp(op_desc, graph)); // 2. check engine type when compile online if (model_file_name == kFileNameSuffix) { auto comp_graph = GraphUtils::GetComputeGraph(graph); GE_CHECK_NOTNULL(comp_graph); auto node = comp_graph->FindNode(op_desc->GetName()); Status ret = CheckEngineTypeSupport(node, engine_type); if (ret != SUCCESS) { GELOGE(ret, "[Check][EngineType]not support node:%s with engine of %d.", node->GetName().c_str(), engine_type); return ret; } } GELOGI("ATC parser success in single op build."); GeRootModelPtr ge_root_model = nullptr; vector<GeTensor> data_inputs; RemoveConst(inputs, data_inputs); GE_CHK_STATUS_RET_NOLOG(impl_->BuildModel(graph, data_inputs, ge_root_model)); map<string, GeAttrValue> op_attrs = op_desc_tmp->GetAllAttrs(); GE_CHECK_NOTNULL(ge_root_model); GE_CHECK_NOTNULL(ge_root_model->GetRootGraph()); map<string, GeModelPtr> name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel(); if (name_to_ge_model.empty()) { REPORT_CALL_ERROR("E19999", "GetSubgraphInstanceNameToModel failed."); GELOGE(PARAM_INVALID, "[Get][Name] GetSubgraphInstanceNameToModel is empty."); return PARAM_INVALID; } const ComputeGraphPtr root_graph = ge_root_model->GetRootGraph(); GeModelPtr &ge_model = name_to_ge_model.begin()->second; GE_CHK_STATUS_RET_NOLOG(CheckDynamicSupport(ge_model, root_graph)); GELOGI("After build model, The opType in op_desc_tmp is [%s]", op_desc_tmp->GetType().c_str()); bool all_shape = false; (void)AttrUtils::GetBool(op_desc, kAicpuAllshape, all_shape); GELOGD("Node: %s, all_shape is %d, compile_flag is %d.", op_desc->GetName().c_str(), all_shape, compile_flag); (void)AttrUtils::SetInt(ge_model, ATTR_NAME_BUILD_MODE, fuzz_compile_flag); if (all_shape) { (void)AttrUtils::SetBool(ge_model, kAicpuAllshape, all_shape); } if (all_shape && CheckNoAicore(root_graph)) { GELOGD("Get aicpu all_shape kernel!"); vector<GeTensor> inputs_dynamic; vector<GeTensor> outputs_dynamic; GE_CHK_STATUS_RET_NOLOG(ResetTensorVecShape(inputs, inputs_dynamic)); GE_CHK_STATUS_RET_NOLOG(ResetTensorVecShape(outputs, outputs_dynamic)); GE_CHK_STATUS_RET_NOLOG( impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs_dynamic, outputs_dynamic)); } else if (fuzz_compile_flag) { GeAttrValue::LIST_NAMED_ATTRS fuzz_build_attrs; if (GetFuzzBuildAttrs(op_desc, ge_root_model, fuzz_build_attrs) != SUCCESS) { GELOGE(FAILED, "[Get][FuzzRet]Failed to get fuzz build result of %s.", op_desc->GetName().c_str()); return FAILED; } if (!fuzz_build_attrs.empty()) { GE_CHK_BOOL_EXEC(AttrUtils::SetListNamedAttrs(ge_model, ATTR_NAME_FUZZ_BUILD_RES_ATTRS, fuzz_build_attrs), REPORT_CALL_ERROR("E19999", "Set model:%s(id:%u) attr:%s failed.", ge_model->GetName().c_str(), ge_model->GetModelId(), ATTR_NAME_FUZZ_BUILD_RES_ATTRS.c_str()); return FAILED, "Set model:%s(id:%u) attr:%s failed.", ge_model->GetName().c_str(), ge_model->GetModelId(), ATTR_NAME_FUZZ_BUILD_RES_ATTRS.c_str()); } GE_CHK_STATUS_RET_NOLOG(impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs, outputs)); } else { GE_CHK_STATUS_RET_NOLOG(impl_->SaveParams(ge_model, op_desc_tmp->GetType(), op_attrs, inputs, outputs)); } GELOGI("Start save GeModel to Model buffer"); GE_CHK_STATUS_RET_NOLOG(impl_->SaveModel(model_file_name, ge_model, model_buff)); return SUCCESS; } /** * @ingroup ge * @brief Compiling a single operator into an offline model * @param [in] OpDescPtr &op_desc: Operator description info that needs to be compiled into an offline model file * @param [in] vector<GeTensor> &inputs: Operator input data description information. * @param [in] vector<GeTensor> &outputs: Operator output data description information. * @param [in] const string &model_file_name: Offline model filename. * @param [in] compile_flag: op build flag from atc * @return SUCCESS handle successfully / others handle failed */ Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs, const string &model_file_name, int32_t compile_flag) { ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); GELOGI("Start to build single op offline model, input size: %zu, output size: %zu", inputs.size(), outputs.size()); ModelBufferData model_buff; OpEngineType engine_type = ENGINE_SYS; Status status = BuildSingleOp(op_desc, inputs, outputs, model_file_name, engine_type, model_buff, true, compile_flag); GELOGI("Finish build single offline model, status: %u", status); return status; } /** * @ingroup ge * @brief Compiling a single operator into online buffer * @param [in] OpDescPtr &op_desc: Operator description info that needs to be compiled into an offline model file * @param [in] vector<GeTensor> &inputs: Operator input data description information. * @param [in] vector<GeTensor> &outputs: Operator output data description information. * @param [in] engine_type: specific engine. * @param [in] compile_flag: op build flag, compile flag by acl * @param [out] ModelBufferData &Model_buff: Model_buff: model buffer of the op. * @return SUCCESS handle successfully / others handle failed */ Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs, OpEngineType engine_type, ModelBufferData &model_buff) { ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); GELOGI("Start to build single op online, input size: %zu, output size: %zu", inputs.size(), outputs.size()); Status status = BuildSingleOp(op_desc, inputs, outputs, kFileNameSuffix, engine_type, model_buff, false); GELOGI("Finish build single online model, status: %u", status); return status; } Status GeGenerator::BuildSingleOpModel(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs, OpEngineType engine_type, int32_t compile_flag, ModelBufferData &model_buff) { ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); GELOGI("Start to build single op online, input size: %zu, output size: %zu", inputs.size(), outputs.size()); Status status = BuildSingleOp(op_desc, inputs, outputs, kFileNameSuffix, engine_type, model_buff, false, compile_flag); GELOGI("Finish build single online model, status: %u", status); return status; } Status GeGenerator::BuildSingleOpGraph(OpDescPtr &op_desc, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs, std::string graph_name, Graph &graph) { ge::ComputeGraphPtr compute_graph = MakeShared<ComputeGraph>(graph_name); GE_CHECK_NOTNULL_EXEC(compute_graph, return INTERNAL_ERROR); // 1. Add Node to ComputeGraph. NodePtr op_node = compute_graph->AddNode(op_desc); GE_CHECK_NOTNULL_EXEC(op_node, return INTERNAL_ERROR); // 2. Create InputData node. int32_t arg_index = 0; int32_t data_index = 0; if (inputs.empty()) { for (const auto &input_desc : op_desc->GetAllInputsDescPtr()) { GE_CHECK_NOTNULL_EXEC(input_desc, return INTERNAL_ERROR); if (!IsNeedConnectInputOpForSingleOp(*input_desc)) { continue; } GE_CHK_STATUS_RET_NOLOG(AddInputs(compute_graph, op_node, *input_desc, arg_index, false, data_index)); arg_index++; } } else { for (const auto &in_desc : inputs) { GE_CHK_STATUS_RET_NOLOG(AddInputs(compute_graph, op_node, in_desc.GetTensorDesc(), arg_index, true, data_index)); arg_index++; } } // 3. Create Output node. if (!outputs.empty()) { GE_CHK_STATUS_RET_NOLOG(AddOutputs(compute_graph, op_node, outputs)); } // dump ComputeGraph node. compute_graph->Dump(); graph = ge::GraphUtils::CreateGraphFromComputeGraph(compute_graph); return SUCCESS; } Status GeGenerator::Impl::SaveParams(GeModelPtr &ge_model, const string &type, const map<string, GeAttrValue> &attrs, const vector<GeTensor> &inputs, const vector<GeTensor> &outputs) { GE_CHECK_NOTNULL_EXEC(ge_model, return PARAM_INVALID); GE_CHK_BOOL_EXEC_NOLOG(graph_manager_.SaveParams(*ge_model, type, attrs, inputs, outputs) == SUCCESS, (void)graph_manager_.Finalize(); return FAILED); return SUCCESS; } Status GeGenerator::Impl::SaveModel(const string &file_name_prefix, GeModelPtr &model, ModelBufferData &model_buff) { // set atc version if (!SetAtcVersionInfo(*(model.get()))) { GELOGW("SetPackageVersionInfo of atc failed!"); } // set opp version if (!SetOppVersionInfo(*(model.get()))) { GELOGW("SetPackageVersionInfo of ops failed!"); } ModelHelper model_helper; model_helper.SetSaveMode(is_offline_); Status ret = model_helper.SaveToOmModel(model, save_param_, file_name_prefix, model_buff); if (ret != SUCCESS) { GELOGE(ret, "[Call][SaveToOmModel] Save to om model failed"); return ret; } return SUCCESS; } Status GeGenerator::Impl::SaveRootModel(const string &file_name_prefix, GeRootModelPtr &ge_root_model, ModelBufferData &model_buff) { bool is_unknown_shape = false; auto ret = ge_root_model->CheckIsUnknownShape(is_unknown_shape); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "root model(id:%u) CheckIsUnknownShape failed, ret:%d", ge_root_model->GetModelId(), ret); GELOGE(FAILED, "[Check][RootModel] is unkonwn shape failed, ret:%d", ret); return FAILED; } GELOGD("begin save root model, cur model is unkonwn shape model ? : %d", is_unknown_shape); GE_CHK_BOOL_EXEC(!ge_root_model->GetSubgraphInstanceNameToModel().empty(), REPORT_CALL_ERROR("E19999", "root model(id:%u) has no sub model.", ge_root_model->GetModelId()); return FAILED, "[Get][SubModel] ge root model has no sub model") GeModelPtr model_root = nullptr; if (is_unknown_shape) { auto name_to_ge_model = ge_root_model->GetSubgraphInstanceNameToModel(); model_root = name_to_ge_model[ge_root_model->GetRootGraph()->GetName()]; } else { model_root = ge_root_model->GetSubgraphInstanceNameToModel().begin()->second; } GE_CHECK_NOTNULL(model_root); // set atc version if (!SetAtcVersionInfo(*(model_root.get()))) { GELOGW("SetPackageVersionInfo of atc failed!"); } // set opp version if (!SetOppVersionInfo(*(model_root.get()))) { GELOGW("SetPackageVersionInfo of ops failed!"); } if (!SetOmSystemInfo(*(model_root.get()))) { GELOGW("SetOmsystemInfo failed!"); } ModelHelper model_helper; model_helper.SetSaveMode(is_offline_); ret = model_helper.SaveToOmRootModel(ge_root_model, save_param_, file_name_prefix, model_buff, is_unknown_shape); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "SaveToOmRootModel failed, ret:%d, model id:%u", ret, ge_root_model->GetModelId()); GELOGE(ret, "[Call][SaveToOmRootModel] failed, ret:%d, model id:%u", ret, ge_root_model->GetModelId()); return ret; } return SUCCESS; } Status GeGenerator::Impl::BuildModel(const Graph &graph, const vector<GeTensor> &inputs, GeRootModelPtr &ge_root_model) { static std::atomic<GraphId> atomic_graph_id(0); auto graph_id = atomic_graph_id.fetch_add(1); const std::map<std::string, std::string> options; Status ret = graph_manager_.AddGraph(graph_id, graph, options, omg_context_); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "add graph(id:%u) failed, ret:%d", graph_id, ret); GELOGE(GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED, "[Add][Graph] fail, graph id: %u", graph_id); (void)graph_manager_.Finalize(); return GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED; } graph_manager_.SetOptionsRunGraphFlag(false); static std::atomic<uint64_t> atomic_session_id(0); auto session_id = atomic_session_id.fetch_add(1); // This is a temporary add for graph with variable auto version = static_cast<int32_t>(SessionVersion::ClOUD_VERSION); ret = VarManager::Instance(session_id)->Init(version, session_id, kDefaultDeviceId, kDefaultJobId); GELOGI("Start init var instance, session_id %lu", session_id); if (ret != SUCCESS) { GELOGW("Failed init var instance, session_id %lu", session_id); } if (is_singleop_unregistered_) { ret = graph_manager_.BuildGraphForUnregisteredOp(graph_id, inputs, ge_root_model, session_id); } else { ret = graph_manager_.BuildGraph(graph_id, inputs, ge_root_model, session_id); } ErrorManager::GetInstance().SetStage(error_message::kModelCompile, error_message::kOther); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "build graph failed, graph id:%u, ret:%d", graph_id, ret); GELOGE(GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED, "[Build][Graph] fail, graph id: %u", graph_id); } RtContextUtil::GetInstance().DestroyRtContexts(session_id); Analyzer::GetInstance()->DestroySessionJsonObject(session_id); VarManagerPool::Instance().RemoveVarManager(session_id); return ret; } Status GeGenerator::Impl::GenerateInfershapeGraph(const Graph &graph) { static std::atomic<GraphId> atomic_graph_id(0); auto graph_id = atomic_graph_id.fetch_add(1); const std::map<std::string, std::string> options; Status ret = graph_manager_.AddGraph(graph_id, graph, options, omg_context_); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "add graph failed, graph id:%u, ret:%d", graph_id, ret); GELOGE(GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED, "[Add][Graph] failed, graph id: %u", graph_id); (void)graph_manager_.Finalize(); return GE_GENERATOR_GRAPH_MANAGER_ADD_GRAPH_FAILED; } ret = graph_manager_.GenerateInfershapeGraph(graph_id); if (ret != SUCCESS) { REPORT_CALL_ERROR("E19999", "GenerateInfershapeGraph failed, graph id:%u, ret:%d", graph_id, ret); GELOGE(GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED, "[Generate][Graph] failed, graph id:%u, ret:%d", graph_id, ret); return GE_GENERATOR_GRAPH_MANAGER_BUILD_GRAPH_FAILED; } return SUCCESS; } } // namespace ge
42.158557
120
0.692635
[ "shape", "vector", "model" ]
7c650efc3499bc8cdcb8ac6bfc5dbbe636a6b012
16,187
cpp
C++
main.cpp
anthonycherepkov/SuffixTreeSuffixAutomaton
621cb10cfec7db2bbd553ddd01b7b420c353d163
[ "MIT" ]
null
null
null
main.cpp
anthonycherepkov/SuffixTreeSuffixAutomaton
621cb10cfec7db2bbd553ddd01b7b420c353d163
[ "MIT" ]
null
null
null
main.cpp
anthonycherepkov/SuffixTreeSuffixAutomaton
621cb10cfec7db2bbd553ddd01b7b420c353d163
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <unordered_map> #include <vector> #include <cassert> #include <limits> template <char MIN_CHAR, char MAX_CHAR> class SuffixAutomaton { protected: const static size_t ALPHABET_SIZE = MAX_CHAR - MIN_CHAR + static_cast<size_t>(1); struct Node { int transition[ALPHABET_SIZE]; int suffixLink; size_t maximumLength; bool isTerminal; size_t numberOfEntries; Node() : suffixLink(-1), maximumLength(0), isTerminal(false), numberOfEntries(1) { std::fill(transition, transition + ALPHABET_SIZE, -1); } }; std::vector<Node> nodes; size_t nodesUsed; size_t finishState; private: void initialize(size_t strLength) { nodes.resize((strLength + 1) << 2); nodes[0].numberOfEntries = 0; nodesUsed = 1; finishState = 0; } size_t getNewNode() { return nodesUsed++; } size_t getClonedNode(size_t cloneOf) { size_t clone = getNewNode(); std::copy(nodes[cloneOf].transition, nodes[cloneOf].transition + ALPHABET_SIZE, nodes[clone].transition); nodes[clone].suffixLink = nodes[cloneOf].suffixLink; nodes[clone].maximumLength = nodes[cloneOf].maximumLength; nodes[clone].isTerminal = nodes[cloneOf].isTerminal; nodes[clone].numberOfEntries = 0; return clone; } /* * symbol must belong to range [0; ALPHABET_SIZE) */ void appendSymbol(unsigned char symbol) { size_t newNode = getNewNode(); nodes[newNode].maximumLength = nodes[finishState].maximumLength + 1; int i = finishState; finishState = newNode; while (i != -1 && nodes[i].transition[symbol] == -1) { nodes[i].transition[symbol] = newNode; i = nodes[i].suffixLink; } if (i == -1) { nodes[newNode].suffixLink = 0; return; } assert(nodes[i].transition[symbol] != -1); int j = nodes[i].transition[symbol]; if (nodes[j].maximumLength == nodes[i].maximumLength + 1) { nodes[newNode].suffixLink = j; return; } size_t clone = getClonedNode(j); nodes[clone].maximumLength = nodes[i].maximumLength + 1; nodes[j].suffixLink = clone; nodes[newNode].suffixLink = clone; while (i != -1 && nodes[i].transition[symbol] == j) { nodes[i].transition[symbol] = clone; i = nodes[i].suffixLink; } } void markTerminalNodes() { int i = finishState; while (i != -1) { nodes[i].isTerminal = true; i = nodes[i].suffixLink; } } void calculateNumbersOfEntries() { std::vector<size_t> vec(nodesUsed - 1); for (size_t i = 1; i < nodesUsed; ++i) { vec[i - 1] = i; } std::sort(vec.begin(), vec.end(), [this] (size_t a, size_t b) { return nodes[a].maximumLength > nodes[b].maximumLength; }); for (auto node: vec) { nodes[nodes[node].suffixLink].numberOfEntries += nodes[node].numberOfEntries; } } public: SuffixAutomaton() = delete; /* * str must contain characters from range [MIN_CHAR; MAX_CHAR] */ explicit SuffixAutomaton(const std::string& str) { initialize(str.length()); for (auto symbol: str) { appendSymbol(static_cast<unsigned char>(symbol - MIN_CHAR)); } markTerminalNodes(); calculateNumbersOfEntries(); } }; template <char MIN_CHAR, char MAX_CHAR> class SuffixTree { protected: const static size_t ALPHABET_SIZE = MAX_CHAR - MIN_CHAR + static_cast<size_t>(2); const static size_t INF = std::numeric_limits<size_t>::max() / 2; std::string str; struct Node { int transition[ALPHABET_SIZE]; int suffixLink; int parent; size_t left; size_t length; Node() = delete; explicit Node(size_t left, size_t length) : suffixLink(-1), parent(-1), left(left), length(length) { std::fill(transition, transition + ALPHABET_SIZE, -1); } }; std::vector<Node> nodes; size_t getNewNode(size_t left, size_t length) { nodes.push_back(Node(left, length)); return nodes.size() - 1; } void setChild(size_t parent, size_t child, unsigned char symbol) { nodes[parent].transition[symbol] = child; nodes[child].parent = parent; } char getChar(size_t node, size_t edgePosition) const { assert(node != root); assert(edgePosition < nodes[node].length); return str[nodes[node].left + edgePosition]; } bool canGo(size_t node, size_t edgePosition, unsigned char symbol) const { if (edgePosition + 1 < nodes[node].length) { return getChar(node, edgePosition + 1) == symbol; } return nodes[node].transition[symbol] != -1; } size_t splitEdge(size_t node, size_t edgePosition) { assert(edgePosition + 1 < nodes[node].length); size_t newNode = getNewNode(nodes[node].left, edgePosition + 1); size_t oldParent = nodes[node].parent; setChild(oldParent, newNode, str[nodes[node].left]); setChild(newNode, node, str[nodes[node].left + edgePosition + 1]); nodes[node].left += edgePosition + 1; if (nodes[node].length != INF) { nodes[node].length -= edgePosition + 1; } return newNode; } size_t getSuffixLink(size_t node) { if (nodes[node].suffixLink == -1) { int currentNode = nodes[nodes[node].parent].suffixLink; assert(currentNode != -1); size_t nextSymbolIndex = nodes[node].left; size_t symbolsRemain = nodes[node].length; unsigned char nextSymbol; while (true) { if (symbolsRemain == 0) { break; } nextSymbol = static_cast<unsigned char>(str[nextSymbolIndex]); int nextNode = nodes[currentNode].transition[nextSymbol]; assert(nextNode != -1); if (symbolsRemain < nodes[nextNode].length) { break; } nextSymbolIndex += nodes[nextNode].length; symbolsRemain -= nodes[nextNode].length; currentNode = nextNode; } if (symbolsRemain == 0) { nodes[node].suffixLink = currentNode; } else { nextSymbol = static_cast<unsigned char>(str[nextSymbolIndex]); nodes[node].suffixLink = splitEdge(nodes[currentNode].transition[nextSymbol], symbolsRemain - 1); } } return nodes[node].suffixLink; } void initialize() { nodes.reserve(str.length() << 1); root = getNewNode(0, 0); size_t empty = getNewNode(0, 0); nodes[root].suffixLink = empty; nodes[root].length = 1; nodes[empty].length = 0; std::fill(nodes[empty].transition, nodes[empty].transition + ALPHABET_SIZE, root); activeNode = root; activeEdgePosition = 0; } size_t root; size_t activeNode; size_t activeEdgePosition; void addSymbol(unsigned char symbol, size_t pos) { while (true) { if (canGo(activeNode, activeEdgePosition, symbol)) { if (activeEdgePosition + 1 < nodes[activeNode].length) { ++activeEdgePosition; } else { assert(nodes[activeNode].transition[symbol] != -1); activeNode = nodes[activeNode].transition[symbol]; activeEdgePosition = 0; } break; } if (activeEdgePosition + 1 < nodes[activeNode].length) { activeNode = splitEdge(activeNode, activeEdgePosition); assert(nodes[activeNode].length > 0); activeEdgePosition = nodes[activeNode].length - 1; } setChild(activeNode, getNewNode(pos, INF), symbol); activeNode = getSuffixLink(activeNode); activeEdgePosition = nodes[activeNode].length; } } void print(size_t v) const { if (v != root) { std::cout << (nodes[v].parent == root ? 1 : nodes[v].parent) << ' ' << v << ' ' << nodes[v].left + 1 << ' ' << std::min(nodes[v].left + nodes[v].length, str.length()) << '\n'; } for (char symbol = 0; symbol < ALPHABET_SIZE; ++symbol) { if (nodes[v].transition[symbol] != -1) { print(nodes[v].transition[symbol]); } } } public: SuffixTree() = delete; explicit SuffixTree(const std::string& str) : str(str) { initialize(); this->str = str; for (size_t i = 0; i < this->str.size(); ++i) { assert(this->str[i] >= MIN_CHAR && this->str[i] <= MAX_CHAR); this->str[i] -= MIN_CHAR; addSymbol(static_cast<unsigned char>(this->str[i]), i); } } //~SuffixTree() = default; void print() const { std::cout << nodes.size() - 1 << ' ' << nodes.size() - 2 << '\n'; print(root); } }; // The following code solves problem 'Refrain' // https://www.e-olymp.com/ru/problems/2469 class Refrain { std::vector<int> refrain; size_t numberOfEntries; public: Refrain() = delete; Refrain(std::vector<int> refrain, size_t numberOfEntries) : refrain(std::move(refrain)), numberOfEntries(numberOfEntries) {} ~Refrain() = default; std::vector<int> getRefrain() const { return refrain; } size_t getNumberOfEntries() const { return numberOfEntries; } long long getMetrics() const { return static_cast<long long>(getNumberOfEntries()) * getRefrain().size(); } void print(std::ostream& os) const { os << getMetrics() << '\n'; os << refrain.size() << '\n'; for (auto c: refrain) { os << c << ' '; } } }; class SuffixAutomatonRefrainFinder : SuffixAutomaton<0, 10> { std::vector<std::pair<int, char>> longestParent; std::vector<char> dfsVisited; void calculateLongestParents(int node) { if (node == -1) { return; } dfsVisited[node] = 1; for (unsigned char symbol = 0; symbol < ALPHABET_SIZE; ++symbol) { int nextNode = nodes[node].transition[symbol]; if (nextNode != -1 && longestParent[nextNode].first == -1 && nodes[nextNode].maximumLength == nodes[node].maximumLength + 1) { longestParent[nextNode].first = node; longestParent[nextNode].second = symbol; } if (!dfsVisited[nextNode]) { calculateLongestParents(nextNode); } } } Refrain findOnce() { longestParent.resize(nodesUsed, {-1, -1}); dfsVisited.resize(nodesUsed, 0); calculateLongestParents(0); int best = 0; for (size_t i = 0; i < nodesUsed; ++i) { if (static_cast<long long>(nodes[i].maximumLength) * nodes[i].numberOfEntries > static_cast<long long>(nodes[best].maximumLength) * nodes[best].numberOfEntries) { best = i; } } size_t numberOfEntries = nodes[best].numberOfEntries; std::vector<int> refrain(nodes[best].maximumLength); for (int i = refrain.size() - 1; i >= 0; --i, best = longestParent[best].first) { refrain[i] = longestParent[best].second; } return Refrain(refrain, numberOfEntries); } static std::string getNormalizedString(const std::vector<int>& source) { std::string res(source.size(), 0); for (size_t i = 0; i < res.size(); ++i) { res[i] = (char)source[i]; } return res; } public: SuffixAutomatonRefrainFinder() = delete; explicit SuffixAutomatonRefrainFinder(const std::vector<int>& source) : SuffixAutomaton(getNormalizedString(source)) {} ~SuffixAutomatonRefrainFinder() = default; Refrain find() { static Refrain refrain = findOnce(); longestParent.clear(); dfsVisited.clear(); longestParent.shrink_to_fit(); dfsVisited.shrink_to_fit(); return refrain; } }; class SuffixTreeRefrainFinder : SuffixTree<0, 11> { static const char DOLLAR_SIGN = 11; std::vector<size_t> numberOfEntries; std::vector<size_t> lengths; std::vector<int> res; long long calcNumberOfEntries(int node) { if (node == -1) { return 0; } for (int child : nodes[node].transition) { numberOfEntries[node] += calcNumberOfEntries(child); } if (numberOfEntries[node] == 0) { numberOfEntries[node] = 1; } return numberOfEntries[node]; } void calcLengths(int node, int currentLength = 0) { if (node != root) { currentLength += nodes[node].length; } bool isLeaf = true; for (int child: nodes[node].transition) { if (child != -1) { isLeaf = false; calcLengths(child, currentLength); } } if (isLeaf) { currentLength -= nodes[node].length; // give me my INF back currentLength += str.size() - nodes[node].left; currentLength -= 1; // throw away the '$' } lengths[node] = currentLength; } void restore(int node) { if (node == root) { return; } restore(nodes[node].parent); for (size_t i = 0; i < nodes[node].length && nodes[node].left + i < str.length(); ++i) { res.push_back(str[nodes[node].left + i]); } } Refrain findOnce() { numberOfEntries.resize(nodes.size(), 0); lengths.resize(nodes.size(), 0); calcNumberOfEntries(root); calcLengths(root); int best = 0; for (size_t node = 0; node < nodes.size(); ++node) { if (static_cast<long long>(lengths[node]) * numberOfEntries[node] > static_cast<long long>(lengths[best]) * numberOfEntries[best]) { best = node; } } restore(best); bool isLeaf = true; for (auto child: nodes[best].transition) { if (child != -1) { isLeaf = false; } } if (isLeaf) { res.pop_back(); } return Refrain(res, numberOfEntries[best]); } static std::string getNormalizedString(const std::vector<int>& source) { std::string res(source.size(), 0); for (size_t i = 0; i < res.size(); ++i) { res[i] = static_cast<char>(source[i]); } res.push_back(DOLLAR_SIGN); return res; } public: SuffixTreeRefrainFinder() = delete; explicit SuffixTreeRefrainFinder(const std::vector<int>& source) : SuffixTree(getNormalizedString(source)) {} ~SuffixTreeRefrainFinder() = default; Refrain find() { static Refrain refrain = findOnce(); numberOfEntries.clear(); lengths.clear(); res.clear(); lengths.shrink_to_fit(); res.shrink_to_fit(); return refrain; } }; int main() { std::ios_base::sync_with_stdio(false); size_t N, M; std::cin >> N >> M; std::vector<int> vec(N); for (size_t i = 0; i < N; ++i) { std::cin >> vec[i]; } SuffixTreeRefrainFinder suffixTreeRefrainFinder(vec); SuffixAutomatonRefrainFinder suffixAutomatonRefrainFinder(vec); auto refrain1 = suffixAutomatonRefrainFinder.find(); auto refrain2 = suffixTreeRefrainFinder.find(); assert(refrain1.getMetrics() == refrain2.getMetrics()); refrain1.print(std::cout); return 0; }
30.369606
128
0.556867
[ "vector" ]
7c670d61cc19473b5c02e0e5beeccb06c55a9a7a
3,318
hh
C++
include/sot/core/feature-joint-limits.hh
machines-in-motion/sot-core
9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5
[ "BSD-2-Clause" ]
12
2016-03-28T07:15:27.000Z
2022-01-05T13:41:06.000Z
include/sot/core/feature-joint-limits.hh
machines-in-motion/sot-core
9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5
[ "BSD-2-Clause" ]
121
2015-02-17T08:38:25.000Z
2021-12-01T10:54:05.000Z
include/sot/core/feature-joint-limits.hh
machines-in-motion/sot-core
9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5
[ "BSD-2-Clause" ]
24
2015-07-01T16:25:24.000Z
2021-11-08T15:06:58.000Z
/* * Copyright 2010, * François Bleibel, * Olivier Stasse, * * CNRS/AIST * */ #ifndef __SOT_FEATURE_JOINTLIMITS_HH__ #define __SOT_FEATURE_JOINTLIMITS_HH__ /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* SOT */ #include <sot/core/exception-task.hh> #include <sot/core/feature-abstract.hh> /* --------------------------------------------------------------------- */ /* --- API ------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ #if defined(WIN32) #if defined(feature_joint_limits_EXPORTS) #define SOTFEATUREJOINTLIMITS_EXPORT __declspec(dllexport) #else #define SOTFEATUREJOINTLIMITS_EXPORT __declspec(dllimport) #endif #else #define SOTFEATUREJOINTLIMITS_EXPORT #endif /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ namespace dynamicgraph { namespace sot { /*! \class FeatureJointLimits \brief Class that defines gradient vector for jl avoidance. */ class SOTFEATUREJOINTLIMITS_EXPORT FeatureJointLimits : public FeatureAbstract, FeatureReferenceHelper<FeatureJointLimits> { public: static const std::string CLASS_NAME; virtual const std::string &getClassName(void) const { return CLASS_NAME; } protected: double threshold; const static double THRESHOLD_DEFAULT; // = .9; /* unsigned int freeFloatingIndex,freeFloatingSize; */ /* static const unsigned int FREE_FLOATING_INDEX = 0; */ /* static const unsigned int FREE_FLOATING_SIZE = 5; */ /* --- SIGNALS ------------------------------------------------------------ */ public: dynamicgraph::SignalPtr<dynamicgraph::Vector, int> jointSIN; dynamicgraph::SignalPtr<dynamicgraph::Vector, int> upperJlSIN; dynamicgraph::SignalPtr<dynamicgraph::Vector, int> lowerJlSIN; dynamicgraph::SignalTimeDependent<dynamicgraph::Vector, int> widthJlSINTERN; using FeatureAbstract::selectionSIN; using FeatureAbstract::errorSOUT; using FeatureAbstract::jacobianSOUT; /*! \name Dealing with the reference value to be reach with this feature. @{ */ DECLARE_REFERENCE_FUNCTIONS(FeatureJointLimits); /*! @} */ public: FeatureJointLimits(const std::string &name); virtual ~FeatureJointLimits(void) {} virtual unsigned int &getDimension(unsigned int &dim, int time); virtual dynamicgraph::Vector &computeError(dynamicgraph::Vector &res, int time); virtual dynamicgraph::Matrix &computeJacobian(dynamicgraph::Matrix &res, int time); dynamicgraph::Vector &computeWidthJl(dynamicgraph::Vector &res, const int &time); /** Static Feature selection. */ inline static Flags selectActuated(void); virtual void display(std::ostream &os) const; }; } /* namespace sot */ } /* namespace dynamicgraph */ #endif // #ifndef __SOT_FEATURE_JOINTLIMITS_HH__ /* * Local variables: * c-basic-offset: 2 * End: */
30.440367
80
0.556962
[ "vector" ]
7c69949177bfa26c44d34a2113d9d144a5d32908
2,019
hpp
C++
include/api_dx11/device_dx11.hpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
7
2015-06-29T09:45:09.000Z
2017-06-06T08:14:09.000Z
include/api_dx11/device_dx11.hpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
null
null
null
include/api_dx11/device_dx11.hpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
null
null
null
#pragma once #include "i_device.hpp" // fwd declare struct DXGI_RATIONAL; struct ID3D11Device; struct ID3D11DeviceContext; struct IDXGISwapChain; struct ID3D11Debug; struct ID3D11DeviceChild; struct ID3DUserDefinedAnnotation; namespace AGN { class DeviceDX11 : public IDevice { public: DeviceDX11(); ~DeviceDX11() override; bool init(class WindowDX11* a_window); class IMesh* createMesh(const uint16_t a_aId, struct MeshData* a_meshData) override; class ITexture* createTexture(const uint16_t a_aId, struct TextureData* a_textureData) override; class IShader* createShader(const uint16_t a_aId, const char* a_shaderSource, EShaderType a_type) override; class IShaderPipeline* createShaderPipeline(const uint16_t a_aId, std::vector<class IShader*> a_shaders) override; void logLiveObjects(); void onWindowUpdated(glm::ivec2 a_dimensions); DXGI_RATIONAL queryRefreshRate(bool a_vsync); ID3D11Device* getD3D11Device() { return m_d3d11Device; } ID3D11DeviceContext* getD3D11DeviceContext() { return m_d3d11DeviceContext; } IDXGISwapChain* getD3D11SwapChain() { return m_d3d11SwapChain; } // debug functionality static void setDebugName(ID3D11DeviceChild* a_child, const std::string& a_name, const uint32_t a_lineNum = 0, const char* a_fileName = ""); void beginDebugEvent(const std::string& a_eventName); void setDebugMarker(const std::string& a_markerName); void endDebugEvent(); uint32_t getMSAALevel() { return m_MSAALevel; } uint32_t getMSAAQuality() { return m_MSAAQuality; } private: void cleanAndInitializeDevice(int a_numSamples, int a_quality); glm::ivec2 getMaxMSAASampleQuality(); class WindowDX11* m_window; ID3D11Device* m_d3d11Device; ID3D11DeviceContext* m_d3d11DeviceContext; IDXGISwapChain* m_d3d11SwapChain; ID3D11Debug* m_d3dDebug; ID3DUserDefinedAnnotation* m_debugUDA; uint32_t m_MSAALevel; uint32_t m_MSAAQuality; }; } #define D3D11_SET_DEBUG_NAME(child, name) AGN::DeviceDX11::setDebugName(child, name, __LINE__, __FILE__)
33.65
141
0.789995
[ "vector" ]
7c708410a8842d400344f7d11daaba6ce7a33b64
11,874
cpp
C++
Code/Engine/Resource/CompositorNode/Pass/GenerateMipmaps/CompositorInstancePassGenerateMipmaps.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
3
2020-05-12T04:36:38.000Z
2021-04-04T07:21:44.000Z
Code/Engine/Resource/CompositorNode/Pass/GenerateMipmaps/CompositorInstancePassGenerateMipmaps.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
null
null
null
Code/Engine/Resource/CompositorNode/Pass/GenerateMipmaps/CompositorInstancePassGenerateMipmaps.cpp
WarzesProject/Micro3DRPG
36604d51d5dd640836cad77995abbfecfe4bdccc
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Resource/CompositorNode/Pass/GenerateMipmaps/CompositorInstancePassGenerateMipmaps.h" #include "Resource/CompositorNode/Pass/GenerateMipmaps/CompositorResourcePassGenerateMipmaps.h" #include "Resource/CompositorNode/Pass/Compute/CompositorInstancePassCompute.h" #include "Resource/CompositorNode/Pass/Compute/CompositorResourcePassCompute.h" #include "Resource/CompositorNode/CompositorNodeInstance.h" #include "Resource/CompositorWorkspace/CompositorWorkspaceInstance.h" #include "Resource/CompositorWorkspace/CompositorContextData.h" #include "Resource/Material/MaterialResourceManager.h" #include "Resource/Material/MaterialResource.h" #include "Resource/Texture/TextureResourceManager.h" #include "Resource/Texture/TextureResource.h" #include "Core/IProfiler.h" #include "IRendererRuntime.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace RendererRuntime { //[-------------------------------------------------------] //[ Protected virtual RendererRuntime::ICompositorInstancePass methods ] //[-------------------------------------------------------] void CompositorInstancePassGenerateMipmaps::onFillCommandBuffer([[maybe_unused]] const Renderer::IRenderTarget* renderTarget, const CompositorContextData& compositorContextData, Renderer::CommandBuffer& commandBuffer) { const IRendererRuntime& rendererRuntime = getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime(); // Sanity check RENDERER_ASSERT(rendererRuntime.getContext(), nullptr == renderTarget, "The generate mipmaps compositor instance pass needs an invalid render target") // Handle texture mipmap generation via custom material blueprint const CompositorResourcePassGenerateMipmaps& compositorResourcePassGenerateMipmaps = static_cast<const CompositorResourcePassGenerateMipmaps&>(getCompositorResourcePass()); RENDERER_ASSERT(rendererRuntime.getContext(), isValid(compositorResourcePassGenerateMipmaps.getTextureAssetId()), "Invalid compositor resource pass generate mipmaps texture asset ID") const AssetId materialBlueprintAssetId = compositorResourcePassGenerateMipmaps.getMaterialBlueprintAssetId(); if (isValid(materialBlueprintAssetId)) { // Sanity check RENDERER_ASSERT(rendererRuntime.getContext(), isValid(compositorResourcePassGenerateMipmaps.getTextureMaterialBlueprintProperty()), "Invalid compositor resource pass generate mipmaps texture material blueprint property") { // Record reusable command buffer, if necessary const TextureResourceManager& textureResourceManager = rendererRuntime.getTextureResourceManager(); // TODO(co) "RendererRuntime::TextureResourceManager::getTextureResourceByAssetId()" is considered to be inefficient, don't use it in here TextureResource* textureResource = textureResourceManager.getTextureResourceByAssetId(compositorResourcePassGenerateMipmaps.getTextureAssetId()); if (nullptr != textureResource) { Renderer::ITexture* texture = textureResource->getTexturePtr(); if (nullptr != texture) { // Sanity check RENDERER_ASSERT(rendererRuntime.getContext(), texture->getResourceType() == Renderer::ResourceType::TEXTURE_2D, "The generate mipmaps compositor instance pass needs an 2D texture as texture") // Render target size changed? Renderer::ITexture2D* texture2D = static_cast<Renderer::ITexture2D*>(texture); const uint32_t renderTargetWidth = texture2D->getWidth(); const uint32_t renderTargetHeight = texture2D->getHeight(); const uint32_t numberOfMipmaps = Renderer::ITexture::getNumberOfMipmaps(renderTargetWidth, renderTargetHeight); if (mRenderTargetWidth != renderTargetWidth || mRenderTargetHeight != renderTargetHeight) { mRenderTargetWidth = renderTargetWidth; mRenderTargetHeight = renderTargetHeight; mFramebuffersPtrs.resize(numberOfMipmaps); Renderer::IRenderer& renderer = rendererRuntime.getRenderer(); Renderer::IRenderPass* renderPass = renderer.createRenderPass(0, nullptr, Renderer::TextureFormat::D32_FLOAT); // TODO(co) Make the texture format flexible, custom mipmap generation also makes sense for color textures for (uint32_t mipmapIndex = 1; mipmapIndex < numberOfMipmaps; ++mipmapIndex) { const Renderer::FramebufferAttachment depthFramebufferAttachment(texture, mipmapIndex, 0); mFramebuffersPtrs[mipmapIndex] = renderer.createFramebuffer(*renderPass, nullptr, &depthFramebufferAttachment); RENDERER_SET_RESOURCE_DEBUG_NAME(mFramebuffersPtrs[mipmapIndex], ("Compositor instance pass generate mipmap " + std::to_string(mipmapIndex)).c_str()) } } // Record reusable command buffer // TODO(co) Optimization: Make this hot-reloading ready and also listen to other critical compositor setting changes like number of multisamples, when done we can fill the following command buffer once and then just reuse it // TODO(co) There's certainly room for command buffer optimization here (e.g. the graphics pipeline state stays the same) mCommandBuffer.clear(); if (!mFramebuffersPtrs.empty()) { // Combined scoped profiler CPU and GPU sample as well as renderer debug event command RENDERER_SCOPED_PROFILER_EVENT_DYNAMIC(rendererRuntime.getContext(), mCommandBuffer, compositorResourcePassGenerateMipmaps.getDebugName()) // Basing on "Hierarchical-Z map based occlusion culling" - "Hi-Z map construction" - http://rastergrid.com/blog/2010/10/hierarchical-z-map-based-occlusion-culling/ uint32_t currentWidth = renderTargetWidth; uint32_t currentHeight = renderTargetHeight; for (uint32_t mipmapIndex = 1; mipmapIndex < numberOfMipmaps; ++mipmapIndex) { // Calculate next viewport size and ensure that the viewport size is always at least 1x1 currentWidth = Renderer::ITexture::getHalfSize(currentWidth); currentHeight = Renderer::ITexture::getHalfSize(currentHeight); // Set graphics render target Renderer::Command::SetGraphicsRenderTarget::create(mCommandBuffer, mFramebuffersPtrs[mipmapIndex]); // Set the graphics viewport and scissor rectangle Renderer::Command::SetGraphicsViewportAndScissorRectangle::create(mCommandBuffer, 0, 0, currentWidth, currentHeight); // Restrict fetches only to previous depth texture mipmap level Renderer::Command::SetTextureMinimumMaximumMipmapIndex::create(mCommandBuffer, *texture, mipmapIndex - 1, mipmapIndex - 1); // Execute the compute pass CompositorContextData localCompositorContextData(compositorContextData.getCompositorWorkspaceInstance(), nullptr); mCompositorInstancePassCompute->onFillCommandBuffer(mFramebuffersPtrs[mipmapIndex], localCompositorContextData, mCommandBuffer); mCompositorInstancePassCompute->onPostCommandBufferExecution(); } // Reset mipmap level range for the depth texture Renderer::Command::SetTextureMinimumMaximumMipmapIndex::create(mCommandBuffer, *texture, 0, numberOfMipmaps - 1); } } else { // Error! RENDERER_ASSERT(rendererRuntime.getContext(), false, "Texture resource has no renderer texture instance") } } else { // Error! RENDERER_ASSERT(rendererRuntime.getContext(), false, "Failed to get texture resource by asset ID") } } // Fill given command buffer, if necessary if (!mCommandBuffer.isEmpty()) { mCommandBuffer.submitToCommandBuffer(commandBuffer); } } else { // Sanity check RENDERER_ASSERT(rendererRuntime.getContext(), isInvalid(compositorResourcePassGenerateMipmaps.getTextureMaterialBlueprintProperty()), "Invalid compositor resource pass generate mipmaps texture material blueprint property") // Generate mipmaps // TODO(co) "RendererRuntime::TextureResourceManager::getTextureResourceByAssetId()" is considered to be inefficient, don't use it in here TextureResource* textureResource = getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime().getTextureResourceManager().getTextureResourceByAssetId(compositorResourcePassGenerateMipmaps.getTextureAssetId()); if (nullptr != textureResource) { Renderer::ITexture* texture = textureResource->getTexturePtr(); if (nullptr != texture) { Renderer::Command::GenerateMipmaps::create(commandBuffer, *texture); } } } } //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] CompositorInstancePassGenerateMipmaps::CompositorInstancePassGenerateMipmaps(const CompositorResourcePassGenerateMipmaps& compositorResourcePassGenerateMipmaps, const CompositorNodeInstance& compositorNodeInstance) : ICompositorInstancePass(compositorResourcePassGenerateMipmaps, compositorNodeInstance), mCompositorResourcePassCompute(nullptr), mCompositorInstancePassCompute(nullptr), mRenderTargetWidth(getInvalid<uint32_t>()), mRenderTargetHeight(getInvalid<uint32_t>()) { // Handle texture mipmap generation via custom material blueprint const AssetId materialBlueprintAssetId = compositorResourcePassGenerateMipmaps.getMaterialBlueprintAssetId(); if (isValid(materialBlueprintAssetId)) { // Sanity check RENDERER_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime().getContext(), isValid(compositorResourcePassGenerateMipmaps.getTextureMaterialBlueprintProperty()), "Invalid compositor resource pass generate mipmaps texture material blueprint property") // Create compositor pass compute MaterialProperties materialProperties; mCompositorResourcePassCompute = new CompositorResourcePassCompute(compositorResourcePassGenerateMipmaps.getCompositorTarget(), materialBlueprintAssetId, materialProperties); #if defined(_DEBUG) || defined(RENDERER_RUNTIME_PROFILER) mCompositorResourcePassCompute->setDebugName("Generate mipmap"); #endif mCompositorInstancePassCompute = new CompositorInstancePassCompute(*mCompositorResourcePassCompute, getCompositorNodeInstance()); getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime().getMaterialResourceManager().getById(mCompositorInstancePassCompute->getMaterialResourceId()).setPropertyById(compositorResourcePassGenerateMipmaps.getTextureMaterialBlueprintProperty(), MaterialPropertyValue::fromTextureAssetId(compositorResourcePassGenerateMipmaps.getTextureAssetId())); } else { // Sanity check RENDERER_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime().getContext(), isInvalid(compositorResourcePassGenerateMipmaps.getTextureMaterialBlueprintProperty()), "Invalid compositor resource pass generate mipmaps texture material blueprint property") } } CompositorInstancePassGenerateMipmaps::~CompositorInstancePassGenerateMipmaps() { // Handle texture mipmap generation via custom material blueprint: Destroy compositor pass compute, if there's one if (nullptr != mCompositorInstancePassCompute) { delete mCompositorInstancePassCompute; mCompositorInstancePassCompute = nullptr; RENDERER_ASSERT(getCompositorNodeInstance().getCompositorWorkspaceInstance().getRendererRuntime().getContext(), nullptr != mCompositorResourcePassCompute, "Invalid compositor resource pass compute") delete mCompositorResourcePassCompute; mCompositorResourcePassCompute = nullptr; } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // RendererRuntime
58.782178
374
0.752569
[ "render" ]
7c789ca1fc2cb6c69912caed6b7f04d501a6c1a9
2,751
cpp
C++
btcb/core_test/message.cpp
melnaquib/btcb
f55c9867113d403118c3028d5ba11a0debcd7609
[ "BSD-2-Clause" ]
8
2019-03-01T13:33:33.000Z
2019-06-02T04:42:38.000Z
btcb/core_test/message.cpp
melnaquib/btcb
f55c9867113d403118c3028d5ba11a0debcd7609
[ "BSD-2-Clause" ]
null
null
null
btcb/core_test/message.cpp
melnaquib/btcb
f55c9867113d403118c3028d5ba11a0debcd7609
[ "BSD-2-Clause" ]
5
2019-04-03T14:27:56.000Z
2019-12-22T17:14:28.000Z
#include <gtest/gtest.h> #include <btcb/node/common.hpp> TEST (message, keepalive_serialization) { btcb::keepalive request1; std::vector<uint8_t> bytes; { btcb::vectorstream stream (bytes); request1.serialize (stream); } auto error (false); btcb::bufferstream stream (bytes.data (), bytes.size ()); btcb::message_header header (error, stream); ASSERT_FALSE (error); btcb::keepalive request2 (error, stream, header); ASSERT_FALSE (error); ASSERT_EQ (request1, request2); } TEST (message, keepalive_deserialize) { btcb::keepalive message1; message1.peers[0] = btcb::endpoint (boost::asio::ip::address_v6::loopback (), 10000); std::vector<uint8_t> bytes; { btcb::vectorstream stream (bytes); message1.serialize (stream); } btcb::bufferstream stream (bytes.data (), bytes.size ()); auto error (false); btcb::message_header header (error, stream); ASSERT_FALSE (error); ASSERT_EQ (btcb::message_type::keepalive, header.type); btcb::keepalive message2 (error, stream, header); ASSERT_FALSE (error); ASSERT_EQ (message1.peers, message2.peers); } TEST (message, publish_serialization) { btcb::publish publish (std::make_shared<btcb::send_block> (0, 1, 2, btcb::keypair ().prv, 4, 5)); ASSERT_EQ (btcb::block_type::send, publish.header.block_type ()); std::vector<uint8_t> bytes; { btcb::vectorstream stream (bytes); publish.header.serialize (stream); } ASSERT_EQ (8, bytes.size ()); ASSERT_EQ (0x52, bytes[0]); ASSERT_EQ (0x41, bytes[1]); ASSERT_EQ (btcb::protocol_version, bytes[2]); ASSERT_EQ (btcb::protocol_version, bytes[3]); ASSERT_EQ (btcb::protocol_version_min, bytes[4]); ASSERT_EQ (static_cast<uint8_t> (btcb::message_type::publish), bytes[5]); ASSERT_EQ (0x00, bytes[6]); // extensions ASSERT_EQ (static_cast<uint8_t> (btcb::block_type::send), bytes[7]); btcb::bufferstream stream (bytes.data (), bytes.size ()); auto error (false); btcb::message_header header (error, stream); ASSERT_FALSE (error); ASSERT_EQ (btcb::protocol_version_min, header.version_min); ASSERT_EQ (btcb::protocol_version, header.version_using); ASSERT_EQ (btcb::protocol_version, header.version_max); ASSERT_EQ (btcb::message_type::publish, header.type); } TEST (message, confirm_ack_serialization) { btcb::keypair key1; auto vote (std::make_shared<btcb::vote> (key1.pub, key1.prv, 0, std::make_shared<btcb::send_block> (0, 1, 2, key1.prv, 4, 5))); btcb::confirm_ack con1 (vote); std::vector<uint8_t> bytes; { btcb::vectorstream stream1 (bytes); con1.serialize (stream1); } btcb::bufferstream stream2 (bytes.data (), bytes.size ()); bool error (false); btcb::message_header header (error, stream2); btcb::confirm_ack con2 (error, stream2, header); ASSERT_FALSE (error); ASSERT_EQ (con1, con2); }
31.988372
128
0.721556
[ "vector" ]
75a7bfeb5ad26f0e183131004aece81023ae0df3
11,532
cpp
C++
src/model_likelihood.cpp
geneprophet/BSDMR
81ff68646a8a304dd1241f8131041d0321d0e04b
[ "MIT" ]
null
null
null
src/model_likelihood.cpp
geneprophet/BSDMR
81ff68646a8a304dd1241f8131041d0321d0e04b
[ "MIT" ]
null
null
null
src/model_likelihood.cpp
geneprophet/BSDMR
81ff68646a8a304dd1241f8131041d0321d0e04b
[ "MIT" ]
null
null
null
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // we only include RcppArmadillo.h which pulls Rcpp.h in for us #include "RcppArmadillo.h" // via the depends attribute we tell Rcpp to create hooks for // RcppArmadillo so that the build process will know what to do // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; //' @name model_log_likelihood //' //' @title model_log_likelihood //' @param w a vector //' @param X a matrix //' @param H a matrix //' @param lambda a number //' @param is_nll boolean //' @export // [[Rcpp::export]] double bpr_log_likelihood(const arma::vec& w, const arma::mat& X, const arma::mat& H, const double lambda, const bool is_nll){ int nrows = X.n_rows; int ncols = X.n_cols; double ll = 0.0; // Predictions of the target variables Rcpp::NumericVector g = Rcpp::wrap(H * w); // Compute the cdf of N(0,1) distribution (i.e. probit function) Rcpp::NumericVector Phi = Rcpp::pnorm(g); for (int i = 0; i < nrows; i++){ // In extreme cases where probit is 0 or 1, subtract a tiny number // so we can evaluate the log(0) when computing the likelihood if (Phi[i] > (1 - 1e-15)){ Phi[i] = 1 - 1e-15; }else if (Phi[i] < 1e-15){ Phi[i] = 1e-15; } // Compute the log likelihood if (ncols == 3){ // If Binomial distributed data //ll += R::dbinom(X(i, 2), X(i, 1), Phi[i], true); ll += R::dbinom(X(i, 3), X(i, 2), Phi[i], true); }else{ // If Bernoulli distributed data //ll += R::dbinom(X(i, 1), 1, Phi[i], true); ll += R::dbinom(X(i, 2), 1, Phi[i], true); } } // Compute ridge regression likelihood ll = ll - lambda * arma::as_scalar(w.t() * w); // If we require the Negative Log Likelihood if (is_nll == true){ ll = (-1) * ll; } return ll; } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] Rcpp::NumericVector bpr_gradient(const arma::vec& w, const arma::mat& X, const arma::mat& H, const double lambda, const bool is_nll){ int nrows = X.n_rows; int ncols = X.n_cols; int M = w.size(); // Predictions of the target variables Rcpp::NumericVector g = Rcpp::wrap(H * w); // Compute the cdf of N(0,1) distribution (i.e. probit function) Rcpp::NumericVector Phi = Rcpp::pnorm(g); // Compute the density of a N(0,1) distribution Rcpp::NumericVector N = Rcpp::dnorm(g); Rcpp::NumericVector gr(M); for (int i = 0; i < nrows; i++){ // In extreme cases where probit is 0 or 1, subtract a tiny number // so we can evaluate the log(0) when computing the likelihood if (Phi[i] > (1 - 1e-15)){ Phi[i] = 1 - 1e-15; }else if (Phi[i] < 1e-15){ Phi[i] = 1e-15; } if (N[i] < 1e-15){ N[i] = 1e-15; } // Compute the gradient vector w.r.t the coefficients w if (ncols == 3){ // If Binomial distributed data for (int m = 0; m < M; m++){ gr[m] += N[i] * H(i, m) * (X(i, 2) / Phi[i] - (X(i, 1) - X(i, 2)) / (1 - Phi[i]) ); } }else{ // If Bernoulli distributed data for (int m = 0; m < M; m++){ gr[m] += N[i] * H(i, m) * (X(i, 1) / Phi[i] - (1 - X(i, 1)) / (1 - Phi[i]) ); } } } for (int m = 0; m < M; m++){ // Compute ridge regression likelihood gr[m] -= 2 * lambda * w[m]; // If we require the Negative Log Likelihood if (is_nll == true){ gr[m] *= -1; } } return gr; } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] double betareg_log_likelihood(const arma::vec& w, arma::mat& X, const arma::mat& H, const double lambda, const bool is_nll){ int nrows = X.n_rows; double ll = 0.0; // Predictions of the target variables Rcpp::NumericVector tmp = Rcpp::wrap(H * w); // Compute the cdf of N(0,1) distribution (i.e. probit function) Rcpp::NumericVector Phi = Rcpp::pnorm(tmp); for (int i = 0; i < nrows; i++){ // In extreme cases where probit is 0 or 1, subtract a tiny number // so we can evaluate the log(0) when computing the likelihood if (Phi[i] > (1 - 1e-15)){ Phi[i] = 1 - 1e-15; }else if (Phi[i] < 1e-15){ Phi[i] = 1e-15; } // Do the same for the actual observations if (X(i,1) > (1 - 1e-15)){ X(i,1) = 1 - 1e-15; }else if (X(i,1) < 1e-15){ X(i,1) = 1e-15; } ll += R::lgammafn(X(i,2)) - R::lgammafn(Phi[i]*X(i,2)) - R::lgammafn((1-Phi[i])*X(i,2)) + (Phi[i]*X(i,2)-1)*log(X(i,1)) + ((1-Phi[i])*X(i,2)-1)*log(1-X(i,1)); } // Compute ridge regression likelihood ll = ll - lambda * arma::as_scalar(w.t() * w); // If we require the Negative Log Likelihood if (is_nll == true){ ll = (-1) * ll; } return ll; } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] Rcpp::NumericVector betareg_gradient(const arma::vec& w, arma::mat& X, const arma::mat& H, const double lambda, const bool is_nll){ int nrows = X.n_rows; int M = w.size(); // Predictions of the target variables Rcpp::NumericVector g = Rcpp::wrap(H * w); // Compute the cdf of N(0,1) distribution (i.e. probit function) Rcpp::NumericVector Phi = Rcpp::pnorm(g); // Compute the density of a N(0,1) distribution Rcpp::NumericVector N = Rcpp::dnorm(g); Rcpp::NumericVector gr(M); for (int i = 0; i < nrows; i++){ // In extreme cases where probit is 0 or 1, subtract a tiny number // so we can evaluate the log(0) when computing the likelihood if (Phi[i] > (1 - 1e-15)){ Phi[i] = 1 - 1e-15; }else if (Phi[i] < 1e-15){ Phi[i] = 1e-15; } // Do the same for the actual observations if (X(i,1) > (1 - 1e-15)){ X(i,1) = 1 - 1e-15; }else if (X(i,1) < 1e-15){ X(i,1) = 1e-15; } if (N[i] < 1e-15){ N[i] = 1e-15; } // Compute the gradient vector w.r.t the coefficients w for (int m = 0; m < M; m++){ gr[m] += N[i] * X(i,2) * ( log(X(i,1)) - log(1-X(i,1)) - R::digamma(Phi[i]*X(i,2)) + R::digamma((1-Phi[i])*X(i,2)) ) * H(i,m); } } for (int m = 0; m < M; m++){ // Compute ridge regression likelihood gr[m] -= 2 * lambda * w[m]; // If we require the Negative Log Likelihood if (is_nll == true){ gr[m] *= -1; } } return gr; } //' @rdname model_log_likelihood //' @param X_list a list //' @param H_list a list //' @param r_nk a vector //' @export // [[Rcpp::export]] double sum_weighted_bpr_lik(const arma::vec& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const arma::vec& r_nk, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); Rcpp::NumericVector res(N); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Compute BPR likelihood res[i] = bpr_log_likelihood(w, X, H, lambda, is_nll); } // Inner product with the weight vector of posterior probabilities arma::vec ll = as<arma::vec>(res); return arma::as_scalar(r_nk.t() * ll); } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] arma::rowvec sum_weighted_bpr_grad(const arma::vec& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const arma::vec& r_nk, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); // Number of basis functions int M = w.size(); Rcpp::NumericMatrix res(N, M); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Compute the gradient of BPR model res(i, _) = bpr_gradient(w, X, H, lambda, is_nll); } // Inner product with the weight vector of posterior probabilities arma::mat ll = as<arma::mat>(res); arma::rowvec w_lik = r_nk.t() * ll; return w_lik; } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] double sum_weighted_betareg_lik(const arma::vec& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const arma::vec& r_nk, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); Rcpp::NumericVector res(N); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Compute Beta regression likelihood res[i] = betareg_log_likelihood(w, X, H, lambda, is_nll); } // Inner product with the weight vector of posterior probabilities arma::vec ll = as<arma::vec>(res); return arma::as_scalar(r_nk.t() * ll); } //' @rdname model_log_likelihood //' //' @export // [[Rcpp::export]] arma::rowvec sum_weighted_betareg_grad(const arma::vec& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const arma::vec& r_nk, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); // Number of basis functions int M = w.size(); Rcpp::NumericMatrix res(N, M); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Compute the gradient of Beta regression model res(i, _) = betareg_gradient(w, X, H, lambda, is_nll); } // Inner product with the weight vector of posterior probabilities arma::mat ll = as<arma::mat>(res); arma::rowvec w_lik = r_nk.t() * ll; return w_lik; } // @rdname model_log_likelihood // // @export // TODO [[Rcpp::export]] Rcpp::NumericVector bpr_lik_region(const arma::vec& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); Rcpp::NumericVector res(N); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Rcpp::List des_obj = H_list[i]; // arma::mat H = as<arma::mat>(des_obj["H"]); // Compute BPR likelihood res[i] = bpr_log_likelihood(w, X, H, lambda, is_nll); } return res; } // @rdname model_log_likelihood // // @export // TODO [[Rcpp::export]] Rcpp::NumericMatrix bpr_lik_resp(const arma::mat& w, const Rcpp::List& X_list, const Rcpp::List& H_list, const arma::vec pi_k, const double lambda, const bool is_nll){ // Number of regions int N = X_list.size(); int K = w.n_cols; int k; Rcpp::NumericMatrix res(N, K); for (int i = 0; i < N; i++){ // Extract observations in each region arma::mat X = X_list[i]; // Extract deisgn matrix of each region arma::mat H = H_list[i]; // Compute BPR likelihood for (k = 0; k < K; k++){ arma::vec ww = w.col(k); res(i, k) = pi_k[k] + bpr_log_likelihood(ww, X, H, lambda, is_nll); } } return res; }
33.32948
84
0.563822
[ "vector", "model" ]
75aa775473829d44036879f50c1c02552d4725a2
3,524
hpp
C++
Include/Rover/ScalarView.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
null
null
null
Include/Rover/ScalarView.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
30
2019-02-05T23:18:13.000Z
2019-07-05T14:19:04.000Z
Include/Rover/ScalarView.hpp
kranar/rover
a4a824321859e34478fec0924c0b76144b3fc20e
[ "Apache-2.0" ]
1
2020-06-01T06:32:05.000Z
2020-06-01T06:32:05.000Z
#ifndef ROVER_SCALAR_VIEW_HPP #define ROVER_SCALAR_VIEW_HPP #include <functional> #include <optional> #include <type_traits> #include <vector> #include "Rover/TrialIterator.hpp" namespace Rover { //! Representation of a sample using a single numeric type. template<typename T> struct ScalarSample { //! The type of the result. using Result = T; //! The type of the arguments. using Arguments = std::vector<T>; //! The result of the trial's function. Result m_result; //! The arguments passed to the trial's function. Arguments m_arguments; }; //! Interface to pass adapted Trial Samples to typed Algorithms. /*! \tparam G The type of a function returning adapted samples by index. */ template<typename G> class ScalarView { public: //! The type of a function returning adapted samples by index. using SampleGetter = G; //! Type used by the algorithm. using Type = typename std::invoke_result_t<SampleGetter, std::size_t>::Result; //! The type representing a sample. using Sample = ScalarSample<Type>; //! The type of the iterator. using Iterator = TrialIterator<ScalarView>; //! Creates a ScalarView. /*! \param get The function taking an index i and returning the ith adapted sample. \param size The total number of samples. */ template<typename SampleGetterFwd> ScalarView(SampleGetterFwd&& get, std::size_t size); //! Constructs a ScalarView using another ScalarView parameterized with a //! different getter function but returning the same Sample type. /*! \param view ScalarView returning the same Sample type. */ template<typename OtherScalarView, std::enable_if_t< !std::is_convertible_v<std::decay_t<OtherScalarView>, ScalarView>>* = nullptr> ScalarView(OtherScalarView&& view); //! Returns an input iterator to the beginning of the trial. Iterator begin() const; //! Returns an input iterator to the end of the trial. Iterator end() const; //! Returns ith adapted sample. Sample operator [](std::size_t i) const; //! Returns the number of the samples. std::size_t size() const; private: std::size_t m_size; SampleGetter m_getter; }; template<typename G> ScalarView(G&&, std::size_t) -> ScalarView<std::decay_t<G>>; template<typename G> template<typename SampleGetterFwd> ScalarView<G>::ScalarView(SampleGetterFwd&& getter, std::size_t size) : m_size(size), m_getter(std::forward<SampleGetterFwd>(getter)) {} template<typename G> template<typename OtherScalarView, std::enable_if_t< !std::is_convertible_v<std::decay_t<OtherScalarView>, ScalarView<G>>>*> ScalarView<G>::ScalarView(OtherScalarView&& view) : m_size(view.size()), m_getter([view = std::forward<OtherScalarView>(view)]( std::size_t index) { return view[index]; }) {} template<typename G> typename ScalarView<G>::Iterator ScalarView<G>::begin() const { return Iterator(*this, 0); } template<typename G> typename ScalarView<G>::Iterator ScalarView<G>::end() const { return Iterator(*this, m_size); } template<typename G> typename ScalarView<G>::Sample ScalarView<G>::operator []( std::size_t i) const { return m_getter(i); } template<typename G> std::size_t ScalarView<G>::size() const { return m_size; } } #endif
27.748031
79
0.661748
[ "vector" ]
75bd60f1899d3d3410b1fbb34ed5f670b34bb0c0
6,889
cpp
C++
aws-cpp-sdk-sagemaker/source/model/FeatureGroup.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-sagemaker/source/model/FeatureGroup.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-sagemaker/source/model/FeatureGroup.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sagemaker/model/FeatureGroup.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SageMaker { namespace Model { FeatureGroup::FeatureGroup() : m_featureGroupArnHasBeenSet(false), m_featureGroupNameHasBeenSet(false), m_recordIdentifierFeatureNameHasBeenSet(false), m_eventTimeFeatureNameHasBeenSet(false), m_featureDefinitionsHasBeenSet(false), m_creationTimeHasBeenSet(false), m_onlineStoreConfigHasBeenSet(false), m_offlineStoreConfigHasBeenSet(false), m_roleArnHasBeenSet(false), m_featureGroupStatus(FeatureGroupStatus::NOT_SET), m_featureGroupStatusHasBeenSet(false), m_offlineStoreStatusHasBeenSet(false), m_failureReasonHasBeenSet(false), m_descriptionHasBeenSet(false), m_tagsHasBeenSet(false) { } FeatureGroup::FeatureGroup(JsonView jsonValue) : m_featureGroupArnHasBeenSet(false), m_featureGroupNameHasBeenSet(false), m_recordIdentifierFeatureNameHasBeenSet(false), m_eventTimeFeatureNameHasBeenSet(false), m_featureDefinitionsHasBeenSet(false), m_creationTimeHasBeenSet(false), m_onlineStoreConfigHasBeenSet(false), m_offlineStoreConfigHasBeenSet(false), m_roleArnHasBeenSet(false), m_featureGroupStatus(FeatureGroupStatus::NOT_SET), m_featureGroupStatusHasBeenSet(false), m_offlineStoreStatusHasBeenSet(false), m_failureReasonHasBeenSet(false), m_descriptionHasBeenSet(false), m_tagsHasBeenSet(false) { *this = jsonValue; } FeatureGroup& FeatureGroup::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("FeatureGroupArn")) { m_featureGroupArn = jsonValue.GetString("FeatureGroupArn"); m_featureGroupArnHasBeenSet = true; } if(jsonValue.ValueExists("FeatureGroupName")) { m_featureGroupName = jsonValue.GetString("FeatureGroupName"); m_featureGroupNameHasBeenSet = true; } if(jsonValue.ValueExists("RecordIdentifierFeatureName")) { m_recordIdentifierFeatureName = jsonValue.GetString("RecordIdentifierFeatureName"); m_recordIdentifierFeatureNameHasBeenSet = true; } if(jsonValue.ValueExists("EventTimeFeatureName")) { m_eventTimeFeatureName = jsonValue.GetString("EventTimeFeatureName"); m_eventTimeFeatureNameHasBeenSet = true; } if(jsonValue.ValueExists("FeatureDefinitions")) { Array<JsonView> featureDefinitionsJsonList = jsonValue.GetArray("FeatureDefinitions"); for(unsigned featureDefinitionsIndex = 0; featureDefinitionsIndex < featureDefinitionsJsonList.GetLength(); ++featureDefinitionsIndex) { m_featureDefinitions.push_back(featureDefinitionsJsonList[featureDefinitionsIndex].AsObject()); } m_featureDefinitionsHasBeenSet = true; } if(jsonValue.ValueExists("CreationTime")) { m_creationTime = jsonValue.GetDouble("CreationTime"); m_creationTimeHasBeenSet = true; } if(jsonValue.ValueExists("OnlineStoreConfig")) { m_onlineStoreConfig = jsonValue.GetObject("OnlineStoreConfig"); m_onlineStoreConfigHasBeenSet = true; } if(jsonValue.ValueExists("OfflineStoreConfig")) { m_offlineStoreConfig = jsonValue.GetObject("OfflineStoreConfig"); m_offlineStoreConfigHasBeenSet = true; } if(jsonValue.ValueExists("RoleArn")) { m_roleArn = jsonValue.GetString("RoleArn"); m_roleArnHasBeenSet = true; } if(jsonValue.ValueExists("FeatureGroupStatus")) { m_featureGroupStatus = FeatureGroupStatusMapper::GetFeatureGroupStatusForName(jsonValue.GetString("FeatureGroupStatus")); m_featureGroupStatusHasBeenSet = true; } if(jsonValue.ValueExists("OfflineStoreStatus")) { m_offlineStoreStatus = jsonValue.GetObject("OfflineStoreStatus"); m_offlineStoreStatusHasBeenSet = true; } if(jsonValue.ValueExists("FailureReason")) { m_failureReason = jsonValue.GetString("FailureReason"); m_failureReasonHasBeenSet = true; } if(jsonValue.ValueExists("Description")) { m_description = jsonValue.GetString("Description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("Tags")) { Array<JsonView> tagsJsonList = jsonValue.GetArray("Tags"); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { m_tags.push_back(tagsJsonList[tagsIndex].AsObject()); } m_tagsHasBeenSet = true; } return *this; } JsonValue FeatureGroup::Jsonize() const { JsonValue payload; if(m_featureGroupArnHasBeenSet) { payload.WithString("FeatureGroupArn", m_featureGroupArn); } if(m_featureGroupNameHasBeenSet) { payload.WithString("FeatureGroupName", m_featureGroupName); } if(m_recordIdentifierFeatureNameHasBeenSet) { payload.WithString("RecordIdentifierFeatureName", m_recordIdentifierFeatureName); } if(m_eventTimeFeatureNameHasBeenSet) { payload.WithString("EventTimeFeatureName", m_eventTimeFeatureName); } if(m_featureDefinitionsHasBeenSet) { Array<JsonValue> featureDefinitionsJsonList(m_featureDefinitions.size()); for(unsigned featureDefinitionsIndex = 0; featureDefinitionsIndex < featureDefinitionsJsonList.GetLength(); ++featureDefinitionsIndex) { featureDefinitionsJsonList[featureDefinitionsIndex].AsObject(m_featureDefinitions[featureDefinitionsIndex].Jsonize()); } payload.WithArray("FeatureDefinitions", std::move(featureDefinitionsJsonList)); } if(m_creationTimeHasBeenSet) { payload.WithDouble("CreationTime", m_creationTime.SecondsWithMSPrecision()); } if(m_onlineStoreConfigHasBeenSet) { payload.WithObject("OnlineStoreConfig", m_onlineStoreConfig.Jsonize()); } if(m_offlineStoreConfigHasBeenSet) { payload.WithObject("OfflineStoreConfig", m_offlineStoreConfig.Jsonize()); } if(m_roleArnHasBeenSet) { payload.WithString("RoleArn", m_roleArn); } if(m_featureGroupStatusHasBeenSet) { payload.WithString("FeatureGroupStatus", FeatureGroupStatusMapper::GetNameForFeatureGroupStatus(m_featureGroupStatus)); } if(m_offlineStoreStatusHasBeenSet) { payload.WithObject("OfflineStoreStatus", m_offlineStoreStatus.Jsonize()); } if(m_failureReasonHasBeenSet) { payload.WithString("FailureReason", m_failureReason); } if(m_descriptionHasBeenSet) { payload.WithString("Description", m_description); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("Tags", std::move(tagsJsonList)); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws
25.420664
138
0.757585
[ "model" ]
75c4fcdc028d37091eb6064583f9b299eaa85e3d
5,245
cpp
C++
Source/SystemQOR/MSWindows/WinQAPI/src/MinGW32.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQAPI/src/MinGW32.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQAPI/src/MinGW32.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//MinGW32.cpp // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQAPI/WinQAPI.h" #include "WinQAPI/Kernel32.h" #ifdef __MINGW32__ //------------------------------------------------------------------------------ VOID TpInitializeCallbackEnviron( PTP_CALLBACK_ENVIRON CallbackEnviron ) { #if (_WIN32_WINNT >= _WIN32_WINNT_WIN7) CallbackEnviron->Version = 3; #else CallbackEnviron->Version = 1; #endif CallbackEnviron->Pool = NULL; CallbackEnviron->CleanupGroup = NULL; CallbackEnviron->CleanupGroupCancelCallback = NULL; CallbackEnviron->RaceDll = NULL; CallbackEnviron->ActivationContext = NULL; CallbackEnviron->FinalizationCallback = NULL; CallbackEnviron->u.Flags = 0; #if (_WIN32_WINNT >= _WIN32_WINNT_WIN7) CallbackEnviron->CallbackPriority = TP_CALLBACK_PRIORITY_NORMAL; CallbackEnviron->Size = sizeof(TP_CALLBACK_ENVIRON); #endif } //------------------------------------------------------------------------------ VOID InitializeThreadpoolEnvironment( PTP_CALLBACK_ENVIRON pcbe ) { TpInitializeCallbackEnviron(pcbe); } //------------------------------------------------------------------------------ VOID TpDestroyCallbackEnviron( PTP_CALLBACK_ENVIRON CallbackEnviron ) { // For the current version of the callback environment, no actions // need to be taken to tear down an initialized structure. This // may change in a future release. UNREFERENCED_PARAMETER(CallbackEnviron); } //------------------------------------------------------------------------------ VOID DestroyThreadpoolEnvironment( PTP_CALLBACK_ENVIRON pcbe ) { TpDestroyCallbackEnviron(pcbe); } //------------------------------------------------------------------------------ PVOID RtlSecureZeroMemory( PVOID ptr, SIZE_T cnt ) { volatile char *vptr = (volatile char *)ptr; #if defined(_M_AMD64) __stosb((PBYTE )((DWORD64)vptr), 0, cnt); #else while (cnt) { *vptr = 0; vptr++; cnt--; } #endif return ptr; } //------------------------------------------------------------------------------ VOID TpSetCallbackCleanupGroup( PTP_CALLBACK_ENVIRON CallbackEnviron, PTP_CLEANUP_GROUP CleanupGroup, PTP_CLEANUP_GROUP_CANCEL_CALLBACK CleanupGroupCancelCallback ) { CallbackEnviron->CleanupGroup = CleanupGroup; CallbackEnviron->CleanupGroupCancelCallback = CleanupGroupCancelCallback; } //------------------------------------------------------------------------------ VOID SetThreadpoolCallbackCleanupGroup( PTP_CALLBACK_ENVIRON pcbe, PTP_CLEANUP_GROUP ptpcg, PTP_CLEANUP_GROUP_CANCEL_CALLBACK pfng ) { TpSetCallbackCleanupGroup(pcbe, ptpcg, pfng); } //------------------------------------------------------------------------------ VOID TpSetCallbackRaceWithDll( PTP_CALLBACK_ENVIRON CallbackEnviron, PVOID DllHandle ) { CallbackEnviron->RaceDll = DllHandle; } //------------------------------------------------------------------------------ VOID SetThreadpoolCallbackLibrary( PTP_CALLBACK_ENVIRON pcbe, PVOID mod ) { TpSetCallbackRaceWithDll(pcbe, mod); } //------------------------------------------------------------------------------ VOID TpSetCallbackThreadpool( PTP_CALLBACK_ENVIRON CallbackEnviron, PTP_POOL Pool ) { CallbackEnviron->Pool = Pool; } //------------------------------------------------------------------------------ VOID SetThreadpoolCallbackPool( PTP_CALLBACK_ENVIRON pcbe, PTP_POOL ptpp ) { TpSetCallbackThreadpool(pcbe, ptpp); } //------------------------------------------------------------------------------ VOID TpSetCallbackLongFunction( PTP_CALLBACK_ENVIRON CallbackEnviron ) { CallbackEnviron->u.s.LongFunction = 1; } //------------------------------------------------------------------------------ VOID SetThreadpoolCallbackRunsLong( PTP_CALLBACK_ENVIRON pcbe ) { TpSetCallbackLongFunction(pcbe); } #endif//__MINGW32__
33.196203
164
0.612583
[ "object" ]
75c9940b76b9a9178f7b7e0ee93d79b1bcb02b85
4,610
hpp
C++
libadb/include/libadb/api/channel/data/channel.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/include/libadb/api/channel/data/channel.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/include/libadb/api/channel/data/channel.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <optional> #include <libadb/libadb.hpp> #include <nlohmann/json_fwd.hpp> #include <libadb/types/time.hpp> #include <libadb/types/snowflake.hpp> #include <libadb/types/nullable.hpp> #include <libadb/resource/image.hpp> #include <libadb/api/user/data/user.hpp> #include <libadb/api/channel/data/channel-type.hpp> #include <libadb/api/channel/data/overwrite.hpp> #include <libadb/api/channel/data/video-quality-mode.hpp> #include <libadb/api/channel/data/thread-metadata.hpp> #include <libadb/api/channel/data/thread-member.hpp> #include <libadb/api/permissions/permissions.hpp> namespace adb::api { /** * @brief Channel Object * @details https://discord.com/developers/docs/resources/channel#channel-object */ struct Channel { /// the id of this channel adb::types::SFID id; /// the type of channel ChannelType type; /// the id of the guild (may be missing for some channel objects received over gateway guild dispatches) std::optional<adb::types::SFID> guildId; /// sorting position of the channel std::optional<int> position; /// explicit permission overwrites for members and roles std::optional<std::vector<Overwrite>> permissionOverwrites; /// the name of the channel (1-100 characters) std::optional<std::string> name; /// the channel topic (0-1024 characters) std::optional<adb::types::Nullable<std::string>> topic; /// whether the channel is nsfw std::optional<bool> nsfw; /// the id of the last message sent in this channel (may not point to an existing or valid message) std::optional<adb::types::Nullable<adb::types::SFID>> lastMessageId; /// the bitrate (in bits) of the voice channel std::optional<int> bitrate; /// the user limit of the voice channel std::optional<int> userLimit; /// amount of seconds a user has to wait before sending another message (0-21600); /// bots, as well as users with the permission manage_messages or manage_channel, are unaffected std::optional<int> rateLimitPerUser; /// the recipients of the DM std::optional<std::vector<User>> recipients; /// icon hash of the group DM std::optional<adb::types::Nullable<adb::resource::Image>> icon; /// id of the creator of the group DM or thread std::optional<adb::types::SFID> ownerId; /// application id of the group DM creator if it is bot-created std::optional<adb::types::SFID> applicationId; /// for guild channels: id of the parent category for a channel /// (each parent category can contain up to 50 channels), // for threads: id of the text channel this thread was created std::optional<adb::types::Nullable<adb::types::SFID>> parentId; /// when the last pinned message was pinned. /// This may be null in events such as GUILD_CREATE when a message is not pinned. std::optional<adb::types::Nullable<adb::types::TimePoint>> lastPinTimestamp; /// voice region id for the voice channel, automatic when set to null std::optional<adb::types::Nullable<std::string>> rtcRegion; /// the camera video quality mode of the voice channel, 1 when not present std::optional<VideoQualityMode> videoQualityMode; /// an approximate count of messages in a thread, stops counting at 50 std::optional<size_t> messageCount; /// an approximate count of users in a thread, stops counting at 50 std::optional<size_t> memberCount; /// thread-specific fields not needed by other channels std::optional<ThreadMetadata> threadMetadata; /// thread member object for the current user, if they have joined the thread, only included on certain API endpoints std::optional<ThreadMember> threadMember; /// default duration that the clients (not the API) will use for newly created threads, in minutes, /// to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 std::optional<size_t> defailtAutoArchiveDuration; /// computed permissions for the invoking user in the channel, including overwrites /// only included when part of the `resolved` data received on a slash command interaction std::optional<Permissions> permissions; }; LIBADB_API void to_json(nlohmann::json& j, const Channel& channel); LIBADB_API void from_json(const nlohmann::json& j, Channel& channel); }
52.386364
125
0.681128
[ "object", "vector" ]
75cd810c9314f9f870ab821b71ed7cc0e7cd51ca
2,343
hpp
C++
include/Interop/ComCastor3D/CastorUtils/ComQuaternion.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
include/Interop/ComCastor3D/CastorUtils/ComQuaternion.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
include/Interop/ComCastor3D/CastorUtils/ComQuaternion.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
/* See LICENSE file in root folder */ #ifndef __COMC3D_COM_QUATERNION_H__ #define __COMC3D_COM_QUATERNION_H__ #include "ComCastor3D/ComCastor3DPrerequisites.hpp" #include "ComCastor3D/ComAtlObject.hpp" #include "ComCastor3D/CastorUtils/ComMatrix4x4.hpp" #include <CastorUtils/Math/Quaternion.hpp> namespace CastorCom { /*! \author Sylvain DOREMUS \version 0.7.0 \date 10/09/2014 \~english \brief This class defines a CQuaternion object accessible from COM. \~french \brief Cette classe définit un CQuaternion accessible depuis COM */ class ATL_NO_VTABLE CQuaternion : COM_ATL_OBJECT( Quaternion ) , public castor::Quaternion { public: /** *\~english *\brief Default constructor. *\~french *\brief Constructeur par défaut. */ CQuaternion(); /** *\~english *\brief Destructor. *\~french *\brief Destructeur. */ virtual ~CQuaternion(); typedef VariablePutter< castor::Quaternion, castor::Matrix4x4f const & > MtxPutter; COM_PROPERTY_GET( RotationMatrix, IMatrix4x4 *, makeGetter( this, &castor::Quaternion::toMatrix ) ); STDMETHOD( Transform )( /* [in] */ IVector3D * val, /* [out, retval] */ IVector3D ** pVal ); STDMETHOD( ToAxisAngle )( /* [out] */ IVector3D ** pAxis, /* [out] */ IAngle ** pAngle ); STDMETHOD( FromAxisAngle )( /* [in] */ IVector3D * axis, /* [in] */ IAngle * angle ); STDMETHOD( ToAxes )( /* [out] */ IVector3D ** pX, /* [out] */ IVector3D ** pY, /* [out] */ IVector3D ** pZ ); STDMETHOD( FromAxes )( /* [in] */ IVector3D * x, /* [in] */ IVector3D * y, /* [in] */ IVector3D * z ); STDMETHOD( GetMagnitude )( /* [out, retval] */ float * pVal ); STDMETHOD( Conjugate )(); STDMETHOD( Slerp )( /* [in] */ IQuaternion * quat, /* [in] */ float percent, /* [out, retval] */ IQuaternion ** pQuat ); STDMETHOD( Mix )( /* [in] */ IQuaternion * quat, /* [in] */ float percent, /* [out, retval] */ IQuaternion ** pQuat ); }; //!\~english Enters the ATL object into the object map, updates the registry and creates an instance of the object \~french Ecrit l'objet ATL dans la table d'objets, met à jour le registre et crée une instance de l'objet OBJECT_ENTRY_AUTO( __uuidof( Quaternion ), CQuaternion ); DECLARE_VARIABLE_REF_GETTER( Quaternion, castor, Quaternion ); DECLARE_VARIABLE_REF_PUTTER( Quaternion, castor, Quaternion ); } #endif
36.609375
221
0.67563
[ "object", "transform" ]
75d1c1ce225e53a0194538a827e4bb8dd26cf8f6
5,014
hh
C++
src/IPStackSimulator.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
src/IPStackSimulator.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
src/IPStackSimulator.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
#include <stdint.h> #include <netinet/in.h> #include <deque> #include <string> #include <phosg/Process.hh> #include <phosg/Filesystem.hh> #include "IPFrameInfo.hh" #include "Server.hh" #include "ProxyServer.hh" #include "ServerState.hh" class IPStackSimulator { public: IPStackSimulator( std::shared_ptr<struct event_base> base, std::shared_ptr<ServerState> state); ~IPStackSimulator(); void listen(const std::string& socket_path); void listen(const std::string& addr, int port); void listen(int port); void add_socket(int fd); static uint32_t connect_address_for_remote_address(uint32_t remote_addr); private: static PrefixedLogger log; std::shared_ptr<struct event_base> base; std::shared_ptr<ServerState> state; using unique_listener = std::unique_ptr<struct evconnlistener, void(*)(struct evconnlistener*)>; using unique_bufferevent = std::unique_ptr<struct bufferevent, void(*)(struct bufferevent*)>; using unique_evbuffer = std::unique_ptr<struct evbuffer, void(*)(struct evbuffer*)>; using unique_event = std::unique_ptr<struct event, void(*)(struct event*)>; struct IPClient { IPStackSimulator* sim; unique_bufferevent bev; uint8_t mac_addr[6]; uint32_t ipv4_addr; struct TCPConnection { std::weak_ptr<IPClient> client; // The PSO protocol begins with the server sending a command, but we // shouldn't send a PSH immediately after the SYN+ACK, so the connection // isn't handed to the Server object until after the 3-way handshake // (receive SYN, send SYN+ACK, receive ACK). This means server_bev is null // during the first part of the connection phase. unique_bufferevent server_bev; // TODO: Get rid of pending_data and just use server_bev's input buffer in // its place unique_evbuffer pending_data; unique_event resend_push_event; bool awaiting_first_ack; uint32_t server_addr; uint16_t server_port; uint16_t client_port; uint32_t next_client_seq; uint32_t acked_server_seq; size_t resend_push_usecs; size_t max_frame_size; size_t bytes_received; size_t bytes_sent; TCPConnection(); }; std::unordered_map<uint64_t, TCPConnection> tcp_connections; IPClient(struct bufferevent* bev); }; std::unordered_set<unique_listener> listeners; std::unordered_map<struct bufferevent*, std::shared_ptr<IPClient>> bev_to_client; uint8_t host_mac_address_bytes[6]; uint8_t broadcast_mac_address_bytes[6]; FILE* pcap_text_log_file; static uint64_t tcp_conn_key_for_connection( const IPClient::TCPConnection& conn); static uint64_t tcp_conn_key_for_client_frame( const IPv4Header& ipv4, const TCPHeader& tcp); static uint64_t tcp_conn_key_for_client_frame(const FrameInfo& fi); static std::string str_for_ipv4_netloc(uint32_t addr, uint16_t port); static std::string str_for_tcp_connection(std::shared_ptr<const IPClient> c, const IPClient::TCPConnection& conn); static void dispatch_on_listen_accept(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr *address, int socklen, void* ctx); void on_listen_accept(struct evconnlistener* listener, evutil_socket_t fd, struct sockaddr *address, int socklen); static void dispatch_on_listen_error(struct evconnlistener* listener, void* ctx); void on_listen_error(struct evconnlistener* listener); static void dispatch_on_client_input(struct bufferevent* bev, void* ctx); void on_client_input(struct bufferevent* bev); static void dispatch_on_client_error(struct bufferevent* bev, short events, void* ctx); void on_client_error(struct bufferevent* bev, short events); void on_client_frame(std::shared_ptr<IPClient> c, const std::string& frame); void on_client_arp_frame(std::shared_ptr<IPClient> c, const FrameInfo& fi); void on_client_udp_frame(std::shared_ptr<IPClient> c, const FrameInfo& fi); void on_client_tcp_frame(std::shared_ptr<IPClient> c, const FrameInfo& fi); static void dispatch_on_resend_push(evutil_socket_t fd, short events, void* ctx); void on_resend_push(std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn); static void dispatch_on_server_input(struct bufferevent* bev, void* ctx); void on_server_input(std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn); static void dispatch_on_server_error(struct bufferevent* bev, short events, void* ctx); void on_server_error(std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn, short events); void send_pending_push_frame( std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn); void send_tcp_frame( std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn, uint16_t flags = 0, struct evbuffer* src_buf = nullptr, size_t src_bytes = 0); void open_server_connection( std::shared_ptr<IPClient> c, IPClient::TCPConnection& conn); void log_frame(const std::string& data) const; };
35.814286
98
0.744515
[ "object" ]
75d5127c348fa41769376161ff7e943f80f86520
21,593
cpp
C++
isis/src/qisis/objs/ShapeList/ShapeList.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/qisis/objs/ShapeList/ShapeList.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/qisis/objs/ShapeList/ShapeList.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "ShapeList.h" #include <QDebug> #include <QDir> #include <QFile> #include <QFuture> #include <QInputDialog> #include <QLabel> #include <QProgressDialog> #include <QtConcurrentMap> #include <QXmlStreamWriter> #include "FileName.h" #include "IException.h" #include "IString.h" #include "Project.h" #include "XmlStackedHandlerReader.h" namespace Isis { /** * Creates an shape list from an shape list name and path (does not read Shapes). * * @param name The ShapeList's name (i.e. import1, import2, ...). * @param path The ShapeList's folder name (i.e. import1, import2, ...). * @param parent The Qt-relationship parent. */ ShapeList::ShapeList(QString name, QString path, QObject *parent) : QObject(parent) { m_name = name; m_path = path; } /** * Creates a blank shape list. * * @param parent The Qt-relationship parent. */ ShapeList::ShapeList(QObject *parent) : QObject(parent) { } /** * Creates an shape list from a list of shapes. * * @param shapes The list of shapes. * @param parent The Qt-relationship parent. */ ShapeList::ShapeList(QList<Shape *> shapes, QObject *parent) : QObject(parent) { append(shapes); } /** * Creates an shape list from XML. * * @param project The project with the shape list. * @param xmlReader The XML reader currently at an <shapeList /> tag. * @param parent The Qt-relationship parent. */ ShapeList::ShapeList(Project *project, XmlStackedHandlerReader *xmlReader, QObject *parent) : QObject(parent) { xmlReader->pushContentHandler(new XmlHandler(this, project)); } /** * Copy constructor. * * @param other The shape list to copy. */ ShapeList::ShapeList(const ShapeList &other) : QList<Shape *>(other) { m_name = other.m_name; m_path = other.m_path; } /** * Creates an shape list from a list of cube file names. This is slow (serial) and not recommended. * * @param fileNames The list of cube fileNames. */ ShapeList::ShapeList(QStringList &fileNames) { foreach (QString fileName, fileNames) { try { Shape *shape = new Shape(fileName); append(shape); } catch (IException &) { } } } /** * Destructor. This does not free the Shapes from memory. */ ShapeList::~ShapeList() { } /** * Creates a SerialNumberList from the shape list. * * @return @b SerialNumberList The list of serial numbers for the cubes in the ShapeList. */ SerialNumberList ShapeList::serialNumberList() { SerialNumberList result; for (int i = 0; i < count(); i++) { result.add((*this)[i]->fileName()); } return result; } /** * Appends an shape to the shape list. * * @param value The shape to be appended. * * @see QList<Shape *>::append(). */ void ShapeList::append(Shape * const &value) { QList<Shape *>::append(value); emit countChanged(count()); } /** * Appends a list of shapes to the shape list. * * @param value the list of shapes to be appened. * * @see QList<Shape *>::append(). */ void ShapeList::append(const QList<Shape *> &value) { QList<Shape *>::append(value); emit countChanged(count()); } /** * Clears the shape list. * * @see QList<Shape *>::clear(). */ void ShapeList::clear() { bool countChanging = count(); QList<Shape *>::clear(); if (countChanging) { emit countChanged(count()); } } /** * Erases a single shape from the shape list. * * @param pos An iterator pointing to the shape to be erased. * * @return @b QList::iterator An iterator pointing to the shape after the shape that was removed. * * @see QList<Shape *>::erase() */ QList<Shape *>::iterator ShapeList::erase(iterator pos) { iterator result = QList<Shape *>::erase(pos); emit countChanged(count()); return result; } /** * Erases a range of shapes from the shape list. * Erases all shapes from begin up to (but not including) end. * * @param begin An iterator pointing to the first shape to be erased. * @param end An iterator pointing to the shape just after the last shape to be erased. * Will be invalid after the call. * * @return @b QList::iterator An iterator pointing to the shape end refered to before the call. * * @see QList<Shape *>::erase() */ QList<Shape *>::iterator ShapeList::erase(iterator begin, iterator end) { iterator result = QList<Shape *>::erase(begin, end); emit countChanged(count()); return result; } /** * Inserts an shape into the shape list at an index * * @param i The index at which to insert the shape. * @param value the shape to be inserted. * * @see QList<Shape *>::insert() */ void ShapeList::insert(int i, Shape * const &value) { QList<Shape *>::insert(i, value); emit countChanged(count()); } /** * Inserts an shape into the shape list after an iterator. * * @param before An iterator pointing to the shape that value will be inserted after * @param value The shape to be inserted. * * @return @b QList::iterator An iterator pointing to the inserted shape. * * @see QList<Shape *>::insert() */ QList<Shape *>::iterator ShapeList::insert(iterator before, Shape * const &value) { iterator result = QList<Shape *>::insert(before, value); emit countChanged(count()); return result; } /** * Inserts an shape at the beginning of the shape list. * * @param value The shape to be inserted. * * @see QList<Shape *>::prepend() */ void ShapeList::prepend(Shape * const &value) { QList<Shape *>::prepend(value); emit countChanged(count()); } /** * Appends an shape to the end of the shape list. * Equivalent to append(). * * @param value The shape to be appended. * * @see QList<Shape *>::push_back() */ void ShapeList::push_back(Shape * const &value) { QList<Shape *>::push_back(value); emit countChanged(count()); } /** * Prepends an shape to the beginning of the shape list. * Equivalent to prepend(). * * @param value The shape to be appended. * * @see QList<Shape *>::push_front() */ void ShapeList::push_front(Shape * const &value) { QList<Shape *>::push_front(value); emit countChanged(count()); } /** * Removes all occurances of an shape. * * @param value The shape to be removed. * * @return @b int The number of occurances of the shape. * * @see QList<Shape *>::removeAll() */ int ShapeList::removeAll(Shape * const &value) { int result = QList<Shape *>::removeAll(value); if (result != 0) { emit countChanged(count()); } return result; } /** * Removes the shape at an index. * * @param i The index of the shape to be removed. * * @see QList<Shape *>::removeAt() */ void ShapeList::removeAt(int i) { QList<Shape *>::removeAt(i); emit countChanged(count()); } /** * Removes the shape at the front of the shape list. * * @see QList<Shape *>::removeFirst() */ void ShapeList::removeFirst() { QList<Shape *>::removeFirst(); emit countChanged(count()); } /** * Removes the shape at the end of the shape list. * * @see QList<Shape *>::removeLast() */ void ShapeList::removeLast() { QList<Shape *>::removeLast(); emit countChanged(count()); } /** * Removes the first occurance of an shape. * * @param value The shape to be removed. * * @return @b bool True if successful, otherwise false. * * @see QList<Shape *>::removeOne() */ bool ShapeList::removeOne(Shape * const &value) { bool result = QList<Shape *>::removeOne(value); if (result) { emit countChanged(count()); } return result; } /** * Swaps the shape list with another list of shapes. * * @param other The list of shapes to swapped with. * * @see QList<Shape *>::swap() */ void ShapeList::swap(QList<Shape *> &other) { QList<Shape *>::swap(other); if (count() != other.count()) { emit countChanged(count()); } } /** * Removes the shape at an index and returns it. * * @param i The index of the shape to be removed and returned. * * @return @b Shape * The removed shape. * * @see QList<Shape *>::takeAt() */ Shape *ShapeList::takeAt(int i) { Shape * result = QList<Shape *>::takeAt(i); emit countChanged(count()); return result; } /** * Removes and returns the first shape. * * @return @b Shape * The first shape. * * @see QList<Shape *>::takeFirst() */ Shape *ShapeList::takeFirst() { Shape *result = QList<Shape *>::takeFirst(); emit countChanged(count()); return result; } /** * Removes and returns the last shape. * * @return @b Shape * The last shape. * * @see QList<Shape *>::takeLast() */ Shape *ShapeList::takeLast() { Shape *result = QList<Shape *>::takeLast(); emit countChanged(count()); return result; } /** * Appends a list of shapes to the end of the shape list. * * @param other The list of shapes to be appended. * * @return @b ShapeList & A reference to the shapeList. * * @see append() * @see QList<Shape *>::operator+=() */ ShapeList &ShapeList::operator+=(const QList<Shape *> &other) { QList<Shape *>::operator+=(other); if (other.count()) { emit countChanged(count()); } return *this; } /** * Appends a single shape to the end of the shape list. * * @param other The shape to be appended. * * @return @b ShapeList & A reference to the shapeList. * * @see append() * @see QList<Shape *>::operator+=() */ ShapeList &ShapeList::operator+=(Shape * const &other) { QList<Shape *>::operator+=(other); emit countChanged(count()); return *this; } /** * Appends a list of shapes to the end of the shape list. * * @param other The list of shapes to be appended. * * @return @b ShapeList & A reference to the shapeList. * * @see append() * @see QList<Shape *>::operator<<() */ ShapeList &ShapeList::operator<<(const QList<Shape *> &other) { QList<Shape *>::operator<<(other); if (other.count()) { emit countChanged(count()); } return *this; } /** * Appends a single shape to the end of the shape list. * * @param other The shape to be appended. * * @return @b ShapeList & A reference to the shapeList. * * @see append() * @see QList<Shape *>::operator<<() */ ShapeList &ShapeList::operator<<(Shape * const &other) { QList<Shape *>::operator<<(other); emit countChanged(count()); return *this; } /** * Assigns another list of shapes to the shape list. * * @param rhs The list of shapes that shapeList will become a copy of. * * @return @b ShapeList & A reference to the shapeList. * * @see QList<Shape *>::operator=() */ ShapeList &ShapeList::operator=(const QList<Shape *> &rhs) { bool countChanging = (rhs.count() != count()); QList<Shape *>::operator=(rhs); if (countChanging) { emit countChanged(count()); } return *this; } /** * Assignment operator * * @param rhs The right hand side of the '=' operator * * @return @b ShapeList & This shape list. */ ShapeList &ShapeList::operator=(const ShapeList &rhs) { bool countChanging = (rhs.count() != count()); QList<Shape *>::operator=(rhs); m_name = rhs.m_name; m_path = rhs.m_path; if (countChanging) { emit countChanged(count()); } return *this; } /** * Set the human-readable name of this shape list. This is really only useful for project * shape lists (not anonymous temporary ones). * * @param newName The name to give this shape list */ void ShapeList::setName(QString newName) { m_name = newName; } /** * Set the relative path (from the project root) to this shape list's folder. This is really only * useful for project shape lists (not anonymous temporary ones). * * @param newPath The path to the shapes in this shape list */ void ShapeList::setPath(QString newPath) { m_path = newPath; } /** * Get the human-readable name of this shape list * * @return @b Qstring The name of the shape list (or an empty string if anonymous). */ QString ShapeList::name() const { return m_name; } /** * Get the path to the shapes in the shape list (relative to project root). This only applies to * an shape list from the project. * * @return @b QString The path to the shapes in the shape list (or an empty string if unknown). */ QString ShapeList::path() const { return m_path; } /** * Delete all of the contained Shapes from disk. * * @param project The project the shapes in the shape list belong to. * * @see Shape::deleteFromDisk() */ void ShapeList::deleteFromDisk(Project *project) { foreach (Shape *shape, *this) { shape->deleteFromDisk(); } if (!m_path.isEmpty()) { QFile::remove(project->shapeDataRoot() + "/" + m_path + "/shapes.xml"); QDir dir; dir.rmdir(project->shapeDataRoot() + "/" + m_path); } } /** * Convert this shape list into XML format for saving/restoring capabilities. * * This writes: * <pre> * <shapeList name="..." path="..."/> * </pre> * to the given xml stream, and creates an 'shapes.xml' inside the folder with the shapes. * Inside the shapes.xml, this writes: * * <pre> * <shapes> * ... * </shapes> * </pre> * * @param stream XmlStream to write out the document. * @param project The project the shape list will be saved to. * @param newProjectRoot The path to the root directory for the new project. * * @throws iException::Io "Failed to create directory" * @throws iException::Io "Unable to save shape information because new file could not be opened for writing" */ void ShapeList::save(QXmlStreamWriter &stream, const Project *project, FileName newProjectRoot) const { stream.writeStartElement("shapeList"); stream.writeAttribute("name", m_name); stream.writeAttribute("path", m_path); FileName settingsFileName( Project::shapeDataRoot(newProjectRoot.toString()) + "/" + m_path + "/shapes.xml"); if (!settingsFileName.dir().mkpath(settingsFileName.path())) { throw IException(IException::Io, QString("Failed to create directory [%1]") .arg(settingsFileName.path()), _FILEINFO_); } QFile shapeListContentsFile(settingsFileName.toString()); if (!shapeListContentsFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) { throw IException(IException::Io, QString("Unable to save shape information for [%1] because [%2] could not be opened for " "writing") .arg(m_name).arg(settingsFileName.original()), _FILEINFO_); } QXmlStreamWriter shapeDetailsWriter(&shapeListContentsFile); shapeDetailsWriter.setAutoFormatting(true); shapeDetailsWriter.writeStartDocument(); int countWidth = QString("%1L").arg(count()).size() - 1; QChar paddingChar('0'); QLabel *progressLabel = new QLabel; QProgressDialog progressDialog; progressDialog.setLabel(progressLabel); progressDialog.setRange(-1, count()); progressDialog.setValue(-1); shapeDetailsWriter.writeStartElement("shapes"); // Mapped is way faster than hundreds/thousands of run() calls... so use mapped for performance QFuture<void *> future = QtConcurrent::mapped(*this, CopyShapeDataFunctor(project, newProjectRoot)); for (int i = 0; i < count(); i++) { int newProgressValue = progressDialog.value() + 1; progressLabel->setText( tr("Saving Shape Information for [%1] - %L2/%L3 done") .arg(m_name) .arg(newProgressValue, countWidth, 10, paddingChar) .arg(count())); progressDialog.setValue(newProgressValue); future.resultAt(i); } progressLabel->setText(tr("Finalizing...")); progressDialog.setRange(0, 0); progressDialog.setValue(0); foreach (Shape *shape, *this) { shape->save(shapeDetailsWriter, project, newProjectRoot); } shapeDetailsWriter.writeEndElement(); shapeDetailsWriter.writeEndDocument(); stream.writeEndElement(); } /** * Constructor for CopyShapeDataFunctor. * * @param project The project that the shape data will be saved to when the functor is used * @param newProjectRoot The path to the project root */ ShapeList::CopyShapeDataFunctor::CopyShapeDataFunctor(const Project *project, FileName newProjectRoot) { m_project = project; m_newProjectRoot = newProjectRoot; } /** * Copy constructor for CopyShapeDataFunctor. * * @param other The functor to copy from */ ShapeList::CopyShapeDataFunctor::CopyShapeDataFunctor(const CopyShapeDataFunctor &other) { m_project = other.m_project; m_newProjectRoot = other.m_newProjectRoot; } /** * Destructor for CopyShapeDataFunctor. */ ShapeList::CopyShapeDataFunctor::~CopyShapeDataFunctor() { } /** * Copies the cub/ecub files for an shape into m_project. * Used by save to copy the shapeList into a new project. * * @param shapeToCopy The shape to copy into m_project. * * @see save */ void *ShapeList::CopyShapeDataFunctor::operator()(Shape * const &shapeToCopy) { shapeToCopy->copyToNewProjectRoot(m_project, m_newProjectRoot); return NULL; } /** * Assignment operator for CopyShapeDataFunctor. * * @param rhs The functor to assign from * * @return @b ShapeList::CopyShapeDataFunctor & A reference to a copy of the functor */ ShapeList::CopyShapeDataFunctor &ShapeList::CopyShapeDataFunctor::operator=( const CopyShapeDataFunctor &rhs) { m_project = rhs.m_project; m_newProjectRoot = rhs.m_newProjectRoot; return *this; } /** * Create an XML Handler (reader) that can populate the Shape list class data. * * @param shapeList The shape list we're going to be initializing * @param project The project that contains the shape list * * @see ShapeList::save() */ ShapeList::XmlHandler::XmlHandler(ShapeList *shapeList, Project *project) { m_shapeList = shapeList; m_project = project; } /** * Handle an XML start element. This expects <shapeList/> and <shape/> elements (it reads both * the project XML and the shapes.xml file). * * @return @b bool If we should continue reading the XML (usually true). */ bool ShapeList::XmlHandler::startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts) { if (XmlStackedHandler::startElement(namespaceURI, localName, qName, atts)) { if (localName == "shapeList") { QString name = atts.value("name"); QString path = atts.value("path"); if (!name.isEmpty()) { m_shapeList->setName(name); } if (!path.isEmpty()) { m_shapeList->setPath(path); } } else if (localName == "shape") { m_shapeList->append(new Shape(m_project->shapeDataRoot() + "/" + m_shapeList->path(), reader())); } } return true; } /** * Handle an XML end element. This handles <shapeList /> by opening and reading the shapes.xml * file. * * @return @b bool If we should continue reading the XML (usually true). * * @throws IException::Io "Unable to open with read access" * @throws IException::Io "Failed to open shape list XML" */ bool ShapeList::XmlHandler::endElement(const QString &namespaceURI, const QString &localName, const QString &qName) { if (localName == "shapeList") { XmlHandler handler(m_shapeList, m_project); XmlStackedHandlerReader reader; reader.pushContentHandler(&handler); reader.setErrorHandler(&handler); QString shapeListXmlPath = m_project->shapeDataRoot() + "/" + m_shapeList->path() + "/shapes.xml"; QFile file(shapeListXmlPath); if (!file.open(QFile::ReadOnly)) { throw IException(IException::Io, QString("Unable to open [%1] with read access") .arg(shapeListXmlPath), _FILEINFO_); } QXmlInputSource xmlInputSource(&file); if (!reader.parse(xmlInputSource)) throw IException(IException::Io, tr("Failed to open shape list XML [%1]").arg(shapeListXmlPath), _FILEINFO_); } return XmlStackedHandler::endElement(namespaceURI, localName, qName); } }
25.984356
111
0.62122
[ "shape" ]
75d7573ded0d17ca8470b44fc4bdcc0e9a7802e8
6,892
hh
C++
include/vkhr/input_map.hh
clayne/vkhr
ffcc0394c0991049337011e45ff3da9f3bd1bbe5
[ "MIT" ]
403
2019-05-27T20:17:12.000Z
2022-03-19T17:32:16.000Z
include/vkhr/input_map.hh
tangxianbo/vkhr
22713d0d9a7d42f207a86fac1d02f626e6007217
[ "MIT" ]
5
2019-06-19T15:46:41.000Z
2021-11-26T00:12:39.000Z
include/vkhr/input_map.hh
tangxianbo/vkhr
22713d0d9a7d42f207a86fac1d02f626e6007217
[ "MIT" ]
31
2019-06-05T02:32:17.000Z
2022-02-04T04:13:29.000Z
#ifndef VKHR_INPUT_MAP_HH #define VKHR_INPUT_MAP_HH #include <vkhr/window.hh> #include <imgui.h> #include <imgui_impl_glfw.h> #include <glm/glm.hpp> #include <string> #include <vector> #include <unordered_map> namespace vkhr { namespace Input { enum class State { Pressed = GLFW_PRESS, Released = GLFW_RELEASE, Repeat = GLFW_REPEAT, JustPressed, JustReleased }; enum class Key { Unknown = GLFW_KEY_UNKNOWN, Space = GLFW_KEY_SPACE, Apostrophe = GLFW_KEY_APOSTROPHE, Comma = GLFW_KEY_COMMA, Minus = GLFW_KEY_MINUS, Period = GLFW_KEY_PERIOD, Slash = GLFW_KEY_SLASH, Zero = GLFW_KEY_0, One = GLFW_KEY_1, Two = GLFW_KEY_2, Three = GLFW_KEY_3, Four = GLFW_KEY_4, Five = GLFW_KEY_5, Six = GLFW_KEY_6, Seven = GLFW_KEY_7, Eight = GLFW_KEY_8, Nine = GLFW_KEY_9, Semicolon = GLFW_KEY_SEMICOLON, Equal = GLFW_KEY_EQUAL, A = GLFW_KEY_A, B = GLFW_KEY_B, C = GLFW_KEY_C, D = GLFW_KEY_D, E = GLFW_KEY_E, F = GLFW_KEY_F, G = GLFW_KEY_G, H = GLFW_KEY_H, I = GLFW_KEY_I, J = GLFW_KEY_J, K = GLFW_KEY_K, L = GLFW_KEY_L, M = GLFW_KEY_M, N = GLFW_KEY_N, O = GLFW_KEY_O, P = GLFW_KEY_P, Q = GLFW_KEY_Q, R = GLFW_KEY_R, S = GLFW_KEY_S, T = GLFW_KEY_T, U = GLFW_KEY_U, V = GLFW_KEY_V, W = GLFW_KEY_W, X = GLFW_KEY_X, Y = GLFW_KEY_Y, Z = GLFW_KEY_Z, LeftBracket = GLFW_KEY_LEFT_BRACKET, Backslash = GLFW_KEY_BACKSLASH, RightBracket = GLFW_KEY_RIGHT_BRACKET, GraveAccent = GLFW_KEY_GRAVE_ACCENT, World1 = GLFW_KEY_WORLD_1, World2 = GLFW_KEY_WORLD_2, Escape = GLFW_KEY_ESCAPE, Enter = GLFW_KEY_ENTER, Tab = GLFW_KEY_TAB, Backspace = GLFW_KEY_BACKSPACE, Insert = GLFW_KEY_INSERT, Delete = GLFW_KEY_DELETE, Right = GLFW_KEY_RIGHT, Left = GLFW_KEY_LEFT, Down = GLFW_KEY_DOWN, Up = GLFW_KEY_UP, PageUp = GLFW_KEY_PAGE_UP, PageDown = GLFW_KEY_PAGE_DOWN, Home = GLFW_KEY_HOME, End = GLFW_KEY_END, CapsLock = GLFW_KEY_CAPS_LOCK, ScrollLock = GLFW_KEY_SCROLL_LOCK, NumLock = GLFW_KEY_NUM_LOCK, PrintScreen = GLFW_KEY_PRINT_SCREEN, Pause = GLFW_KEY_PAUSE, F1 = GLFW_KEY_F1, F2 = GLFW_KEY_F2, F3 = GLFW_KEY_F3, F4 = GLFW_KEY_F4, F5 = GLFW_KEY_F5, F6 = GLFW_KEY_F6, F7 = GLFW_KEY_F7, F8 = GLFW_KEY_F8, F9 = GLFW_KEY_F9, F10 = GLFW_KEY_F10, F11 = GLFW_KEY_F11, F12 = GLFW_KEY_F12, F13 = GLFW_KEY_F13, F14 = GLFW_KEY_F14, F15 = GLFW_KEY_F15, F16 = GLFW_KEY_F16, F17 = GLFW_KEY_F17, F18 = GLFW_KEY_F18, F19 = GLFW_KEY_F19, F20 = GLFW_KEY_F20, F21 = GLFW_KEY_F21, F22 = GLFW_KEY_F22, F23 = GLFW_KEY_F23, F24 = GLFW_KEY_F24, F25 = GLFW_KEY_F25, Keypad0 = GLFW_KEY_KP_0, Keypad1 = GLFW_KEY_KP_1, Keypad2 = GLFW_KEY_KP_2, Keypad3 = GLFW_KEY_KP_3, Keypad4 = GLFW_KEY_KP_4, Keypad5 = GLFW_KEY_KP_5, Keypad6 = GLFW_KEY_KP_6, Keypad7 = GLFW_KEY_KP_7, Keypad8 = GLFW_KEY_KP_8, Keypad9 = GLFW_KEY_KP_9, KeypadDecimal = GLFW_KEY_KP_DECIMAL, KeypadDivide = GLFW_KEY_KP_DIVIDE, KeypadMultiply = GLFW_KEY_KP_MULTIPLY, KeypadSubtract = GLFW_KEY_KP_SUBTRACT, KeypadAdd = GLFW_KEY_KP_ADD, KeypadEnter = GLFW_KEY_KP_ENTER, KeypadEqual = GLFW_KEY_KP_EQUAL, LeftShift = GLFW_KEY_LEFT_SHIFT, LeftControl = GLFW_KEY_LEFT_CONTROL, LeftAlt = GLFW_KEY_LEFT_ALT, LeftSuper = GLFW_KEY_LEFT_SUPER, RightShift = GLFW_KEY_RIGHT_SHIFT, RightControl = GLFW_KEY_RIGHT_CONTROL, RightAlt = GLFW_KEY_RIGHT_ALT, RightSuper = GLFW_KEY_RIGHT_SUPER, Menu = GLFW_KEY_MENU }; enum class MouseButton { Left = GLFW_MOUSE_BUTTON_LEFT, Middle = GLFW_MOUSE_BUTTON_MIDDLE, Right = GLFW_MOUSE_BUTTON_RIGHT }; } class InputMap final { public: InputMap(Window& window); void unbind(const std::string& id); void bind(const std::string& id, Input::Key key); void bind(const std::string& id, const std::vector<Input::Key>& keys); void bind(const std::string& id, Input::MouseButton mouse_button); void bind(const std::string& id, const std::vector<Input::MouseButton>& mouse_buttons); std::vector<Input::MouseButton> get_mouse_button_map(const std::string& id) const; std::vector<Input::Key> get_key_map(const std::string& id) const; bool pressed(Input::Key key) const; bool just_pressed(Input::Key key); bool just_released(Input::Key key); bool released(Input::Key key) const; bool pressed(Input::MouseButton key) const; bool just_pressed(Input::MouseButton key); bool just_released(Input::MouseButton key); bool released(Input::MouseButton key) const; bool pressed(const std::string& id) const; bool just_pressed(const std::string& id); bool just_released(const std::string& id); bool released(const std::string& id) const; glm::vec2 get_mouse_position() const; glm::vec2 get_scroll_offset() const; void reset_scrolling_offset(); void freeze_cursor(); void unlock_cursor(); void toggle_mouse_lock(); bool is_mouse_locked() const; private: // FIXME: Since we can't pass around private member functions // to the GLFW callback functions, we do a hack and map these // window pointers to their specific input mappers on create. // static void mouse_button_callback(GLFWwindow*, int, int, int); static std::unordered_map<GLFWwindow*, InputMap*> callback_map; static void scroll_callback(GLFWwindow*, double, double); static void key_callback(GLFWwindow*, int, int, int, int); static void char_callback(GLFWwindow*, unsigned int); std::unordered_map<Input::Key, Input::State> key_state_map; std::unordered_map<Input::MouseButton, Input::State> mouse_button_state; std::unordered_multimap<std::string, Input::MouseButton> mouse_button_map; std::unordered_multimap<std::string, Input::Key> key_map; glm::vec2 scroll_offsets { 0.0f }; bool mouse_locked { false }; GLFWwindow* handle; }; } #endif
36.855615
90
0.610273
[ "vector" ]
75d7b41bb8da12de7494c0e4c310b77b7765f651
3,188
hpp
C++
master/core/third/RCF/include/RCF/util/Scan.hpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/RCF/include/RCF/util/Scan.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/RCF/include/RCF/util/Scan.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
//***************************************************************************** // Copyright (c) 2003. All rights reserved. // Developed by Jarl Lindrud. // Contact: jlindrud@hotmail.com . //***************************************************************************** #ifndef _UTIL_SCAN_HPP_ #define _UTIL_SCAN_HPP_ #include <sstream> #include <string> #include <utility> #include <vector> namespace util { class Scan { public: Scan( std::string s, std::string format ) : i_(0), ok_(true) { int n = 0; std::string::size_type pos = 0; std::string::size_type prev_pos = 0; std::string::size_type npos = std::string::npos; // Extract format string literals std::vector< std::pair<std::string, std::string> > literals; while(pos != npos) { n++; std::string specifier1 = makeSpecifier(n); std::string specifier2 = makeSpecifier(n+1); pos = format.find(specifier1, prev_pos); std::string literal1 = (pos == npos) ? format.substr(prev_pos) : format.substr(prev_pos, pos - prev_pos); if (pos != npos) pos += specifier1.length(); prev_pos = pos; pos = format.find(specifier2, prev_pos); std::string literal2 = (pos == npos) ? format.substr(prev_pos) : format.substr(prev_pos, pos - prev_pos); literals.push_back( std::make_pair( literal1, literal2 ) ); } // Extract arg string values pos = 0; for (std::vector< std::pair<std::string, std::string> >::iterator it = literals.begin(); it != literals.end(); it++) { if (pos != npos && pos == s.find( (*it).first, pos)) { std::string::size_type a = pos + (*it).first.length(); std::string::size_type b = s.find( (*it).second, a ); values_.push_back( s.substr( a , (b == a) ? npos : b-a ) ); pos = b; } else { ok_ = false; } } } template<typename T> Scan &operator()(T &t) { std::istringstream istr( getNextValue() ); istr >> t; return *this; } operator bool() const { return ok(); } bool ok() const { return ok_; } private: std::string makeSpecifier( int n ) { std::ostringstream ostr; ostr << "%" << n; return ostr.str(); } std::string getNextValue() { if (i_<values_.size()) return values_[ i_++ ]; else { ok_ = false; return ""; } } std::vector<std::string> values_; unsigned int i_; bool ok_; }; } // namespace util #endif // ! _UTIL_SCAN_HPP_
30.653846
131
0.4266
[ "vector" ]
75d856e5364735ebf0e8697868997e17c210aad5
2,823
cpp
C++
Insipid3D/engine.cpp
thehugh100/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
90
2017-04-10T20:08:53.000Z
2022-03-28T19:16:04.000Z
Insipid3D/engine.cpp
CristianRodrigoGuarachiIbanez/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
2
2019-11-29T04:00:26.000Z
2021-05-29T10:39:24.000Z
Insipid3D/engine.cpp
CristianRodrigoGuarachiIbanez/Insipid3D
429a9e6022c1a0bca842209310f949647f4c441e
[ "MIT" ]
15
2017-10-02T03:15:03.000Z
2022-03-28T20:46:34.000Z
#include "engine.h" #include "FlyCam.h" #include <algorithm> #include <thread> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include "EntityClientCam.h" #include "Client_UDP.h" #include "NetworkClient.h" #include "NetworkServer.h" #include "MeshManager.h" Engine::Engine() { networkClient = new NetworkClient(this); networkServer = new NetworkServer(this); variables = new Variables(); shaderManager = new ShaderManager(); entityManger = new EntityManager(this); textureManager = new TextureManager(); map = nullptr; screen = glm::vec2(640, 480); camera = new Camera(this); cameraController = new FlyCam(this); meshManager = new MeshManager(this); editor = new Editor(this); input = new Input(this); fontManager = new FontManager(); console = new Console(this); netEvents = new NetEvents(this); deltaTime = 0.01; fps = 1; averageFps = 1; frameNum = 0; engineStart = std::chrono::high_resolution_clock::now(); frameStart = engineStart; } bool Engine::loadMap(std::string fname) { map = new Map(fname, this); return true; } Map* Engine::getMap() { if (map == nullptr) { //std::cout << "Warning: Map is nullptr" << std::endl; } return map; } void Engine::setScreenSize(glm::vec2 screenSize) { screen = screenSize; } void Engine::startFrame() { frameStart = std::chrono::high_resolution_clock::now(); } void Engine::endFrame() { std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - frameStart); deltaTime = time_span.count(); } void Engine::tick() { if (deltaTime != 0.0f) fps = 1.0f / deltaTime; averageFps += (fps - averageFps) * 0.01f; if (console != nullptr) console->tick(); if (input != nullptr) input->tick(frameNum); if (camera != nullptr) camera->update(); if (cameraController != nullptr) cameraController->control(); if (entityManger != nullptr) entityManger->tick(); if (editor != nullptr) editor->tick(); if(networkServer != nullptr) networkServer->tick(deltaTime); if (networkClient != nullptr) networkClient->tick(deltaTime); if (netEvents != nullptr) netEvents->tick(); ++frameNum; } void Engine::render() { if (entityManger != nullptr) entityManger->render(); if (editor != nullptr) editor->render(); if (console != nullptr) console->render(); } void Engine::drawDebugText(Font* f, float x, float y, std::string text, glm::vec3 col) { f->renderText(shaderManager->getShader("shaders/font"), text, x, y, 1, col, glm::ortho(0.f, screen.x, 0.f, screen.y)); } float Engine::getElapsedTimeMS() { std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::high_resolution_clock::now() - engineStart); return time_span.count() * 1000.0f; }
21.225564
158
0.69288
[ "render" ]
75e7572e44d8908155909a7929712419044b1fad
9,780
cpp
C++
github/polylogarithm/v322/src/Li.cpp
gxusthjw/JPolylogarithm
fd5f4e82815d87793dc9099eaa8acbf4be89e8c2
[ "Apache-2.0" ]
null
null
null
github/polylogarithm/v322/src/Li.cpp
gxusthjw/JPolylogarithm
fd5f4e82815d87793dc9099eaa8acbf4be89e8c2
[ "Apache-2.0" ]
null
null
null
github/polylogarithm/v322/src/Li.cpp
gxusthjw/JPolylogarithm
fd5f4e82815d87793dc9099eaa8acbf4be89e8c2
[ "Apache-2.0" ]
null
null
null
// ==================================================================== // This file is part of Polylogarithm. // // Polylogarithm is licenced under the GNU Lesser General Public // License (GNU LGPL) version 3. // ==================================================================== #include "Li.hpp" #include <array> #include <cmath> #include <limits> #include <vector> namespace polylogarithm { namespace { //等价于 1e-15 const double epsilon = std::pow(10., -std::floor(std::numeric_limits<double>::digits10)); const double inf = std::numeric_limits<double>::infinity(); /// expansion order static const long N = 50; /// Bernoulli numbers B0, ..., B49 /// Table[BernoulliB[n], {n,0,49}] const double bernoulli[N] = { 1, -0.5 , 1./6. , 0, -3.333333333333333e-02, 0, 2.380952380952381e-02, 0, -3.333333333333333e-02, 0, 7.575757575757576e-02, 0, -2.531135531135531e-01, 0, 1.166666666666667e+00, 0, -7.092156862745098e+00, 0, 5.497117794486215e+01, 0, -5.291242424242424e+02, 0, 6.192123188405797e+03, 0, -8.658025311355312e+04, 0, 1.425517166666667e+06, 0, -2.729823106781609e+07, 0, 6.015808739006424e+08, 0, -1.511631576709215e+10, 0, 4.296146430611667e+11, 0, -1.371165520508833e+13, 0, 4.883323189735932e+14, 0, -1.929657934194006e+16, 0, 8.416930475736827e+17, 0, -4.033807185405945e+19, 0, 2.115074863808199e+21, 0, -1.208662652229652e+23, 0 }; /// 1/n! for n = 1, ..., 50 /// Table[1/Factorial[n], {n,1,50}] const double fac_inv[N] = { 1 , 0.5 , 1./6. , 4.166666666666666e-02, 8.333333333333333e-03, 1.388888888888889e-03, 1.984126984126984e-04, 2.480158730158730e-05, 2.755731922398589e-06, 2.755731922398589e-07, 2.505210838544172e-08, 2.087675698786810e-09, 1.605904383682161e-10, 1.147074559772973e-11, 7.647163731819816e-13, 4.779477332387385e-14, 2.811457254345521e-15, 1.561920696858623e-16, 8.220635246624330e-18, 4.110317623312165e-19, 1.957294106339126e-20, 8.896791392450574e-22, 3.868170170630684e-23, 1.611737571096118e-24, 6.446950284384474e-26, 2.479596263224797e-27, 9.183689863795546e-29, 3.279889237069838e-30, 1.130996288644772e-31, 3.769987628815905e-33, 1.216125041553518e-34, 3.800390754854744e-36, 1.151633562077195e-37, 3.387157535521162e-39, 9.677592958631890e-41, 2.688220266286636e-42, 7.265460179153071e-44, 1.911963205040282e-45, 4.902469756513544e-47, 1.225617439128386e-48, 2.989310827142405e-50, 7.117406731291439e-52, 1.655210867742195e-53, 3.761842881232262e-55, 8.359650847182804e-57, 1.817315401561479e-58, 3.866628513960594e-60, 8.055476070751238e-62, 1.643974708316579e-63, 3.287949416633158e-65 }; bool is_close(double a, double b, double eps = epsilon) { return std::abs(a - b) < eps; } bool is_close(const std::complex<double>& a, const std::complex<double>& b, double eps = epsilon) { return is_close(std::real(a), std::real(b), eps) && is_close(std::imag(a), std::imag(b), eps); } bool is_even(long n) { return n % 2 == 0; } /// complex logarithm, converts -0.0 to 0.0 std::complex<double> clog(std::complex<double> z) noexcept { if (std::real(z) == 0.0) z.real(0.0); if (std::imag(z) == 0.0) z.imag(0.0); return std::log(z); } /// Binomial coefficients /// https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/ double binomial(long n, long k) { double result = 1.; // (n, k) = (n, n-k) if (k > n - k) k = n - k; for (long i = 0; i < k; i++) { result *= (n - i); result /= (i + 1); } return result; } /// Bernoulli polynomial std::complex<double> bernoulli_p(long m, const std::complex<double>& z) { std::complex<double> result; for (long n = 0; n <= m; n++) { std::complex<double> sum; for (long k = 0; k <= n; k++) { const double sgn = is_even(k) ? 1. : -1.; sum += sgn*binomial(n,k)*std::pow(z + static_cast<double>(k), m); } result += sum/(n + 1.); } return result; } /// factorial double fac(double n) { double result = 1.; for (long i = 1; i <= n; ++i) result *= i; return result; } /// Riemann zeta function for integer s (positive or negative) double zeta(long s) { #if __cpp_lib_math_special_functions >= 201603 return std::riemann_zeta(s); #else if (s == 1) return inf; double sum = 0., sum_old = 0.; long n = 0; do { sum_old = sum; double sub_sum = 0.; for (long k = 0; k <= n; k++) { const long sgn = is_even(k) ? 1 : -1; sub_sum += binomial(n,k)*sgn*std::pow(k+1,-s); } sum += sub_sum*std::pow(2.,-(n+1)); n++; } while (!is_close(sum_old, sum) && n < std::numeric_limits<long>::max() - 2); return sum/(1. - std::pow(2.,1-s)); #endif } /// Dirichlet eta function double eta(long n) { return (1. - std::pow(2.,1-n))*zeta(n); } /// calculates X(p,n) for all possible n < N, p >= 0 std::vector<std::array<double,N>> Xn(long p) { using TArray = std::array<double,N>; std::vector<TArray> xn(p+1); // calculate X(0,n) for p = 0 { TArray ar; for (long ni = 0; ni < N; ni++) { ar[ni] = bernoulli[ni]; } xn[0] = ar; } for (long pi = 1; pi <= p; pi++) { // calculate X(pi,n) for all n < N TArray ar; for (long ni = 0; ni < N; ni++) { double sum = 0.; for (long k = 0; k <= ni; k++) { sum += binomial(ni,k)*bernoulli[ni-k]/(k+1)*xn[pi-1][k]; } ar[ni] = sum; } xn[pi] = ar; } return xn; } /// series expansion of Li_n(z) for n <= 0 std::complex<double> Li_negative(long n, const std::complex<double>& z) { if (is_close(z, {1.,0.})) return {inf, inf}; std::complex<double> result; for (long k = 0; k <= -n; k++) { double sum = 0.; for (long j = 0; j <= k; j++) { const long sgn = is_even(j) ? -1 : 1; sum += sgn*binomial(k,j)*std::pow(j+1,-n); } result += std::pow(-z/(1. - z),k+1)*sum; } if (is_close(std::imag(z), 0.)) result.imag(0.); return result; } /// Series expansion of Li_n(z) in terms of powers of z. /// Fast convergence for large n >= 12. std::complex<double> Li_naive_sum(long n, const std::complex<double>& z) { std::complex<double> sum, sum_old; std::complex<double> pz(1.,0.); long k = 0; do { k++; pz *= z; sum_old = sum; sum += pz/std::pow(k,n); } while (!is_close(sum, sum_old) && k < std::numeric_limits<long>::max() - 2); return sum; } /// Harmonic number n double H(long n) { double sum = 0.; for (long h = 1; h <= n; h++) sum += 1./h; return sum; } /// Series expansion of Li_n(z) around z ~ 1, n > 0 std::complex<double> Li_expand_around_unity(long n, const std::complex<double>& z) { const std::complex<double> mu = clog(z); std::complex<double> sum, sum_old; long k = 0; do { if (k == n-1) { k++; continue; } sum_old = sum; sum += zeta(n-k)/fac(k)*std::pow(mu,k); k++; } while (!is_close(sum, sum_old) && k < std::numeric_limits<long>::max() - 2); return std::pow(mu,n-1)/fac(n-1)*(H(n-1) - clog(-mu)) + sum; } } // anonymous namespace /** * @brief Clausen function \f$\mathrm{Cl}_n(\theta)\f$ * @param n degree of Clausen function * @param x real angle * @return \f$\mathrm{Cl}_n(\theta)\f$ */ double Cl(long n, double x) { using std::exp; const double PI = 3.141592653589793; const std::complex<double> i(0.,1.); const std::complex<double> li = Li(n, exp(i*x)); while (x >= 2*PI) x -= 2*PI; while (x < 0.) x += 2*PI; if (is_even(n)) return std::imag(li); return std::real(li); } /** * @brief Complex polylogarithm \f$\mathrm{Li}_n(z)\f$ * @param n degree of the polylogarithm * @param z complex argument * @return \f$\mathrm{Li}_n(z)\f$ */ std::complex<double> Li(long n, const std::complex<double>& z) { if (n < 0) return Li_negative(n,z); if (n == 0) { if (is_close(z, {1.,0.})) return {inf, inf}; return z/(1. - z); } if (n == 1) return -clog(1. - z); if (is_close(z, 0.)) return 0.; if (is_close(z, 1.)) return zeta(n); if (is_close(z, -1.)) return -eta(n); if (n >= 12) return Li_naive_sum(n, z); if (is_close(z, 1., 2e-2)) return Li_expand_around_unity(n,z); std::complex<double> u, r; double sgn = 1.; if (std::abs(z) <= 1.) { u = -clog(1. - z); } else { // az > 1. const double PI = 3.141592653589793; const std::complex<double> IPI2(0.,2*PI); const std::complex<double> lnz = clog(-z); u = -clog(1. - 1./z); r = -std::pow(IPI2, n)/fac(n)*bernoulli_p(n, 0.5 + lnz/IPI2); sgn = is_even(n) ? -1. : 1.; } std::complex<double> p = 1., sum; const auto xn = Xn(n-2); for (long k = 0; k < N; k++) { p *= u; sum += xn[n-2][k]*p*fac_inv[k]; } return sgn*sum + r; } } // namespace polylogarithm
27.318436
92
0.530164
[ "vector" ]
75eadbc90e5afacfc3dbf5cd0cf42df2313a42b8
7,863
cpp
C++
tao/x11/dynamic_any/dynenum_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tao/x11/dynamic_any/dynenum_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tao/x11/dynamic_any/dynenum_i.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file dynenum_i.cpp * @author Marijke Henstmengel * * @brief CORBA C++11 TAOX11 DynamicAny::DynAny implementation * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "tao/AnyTypeCode/Marshal.h" #include "tao/x11/anytypecode/typecode_impl.h" #include "tao/x11/anytypecode/any_unknown_type.h" #include "tao/x11/dynamic_any/dynenum_i.h" #include "tao/x11/dynamic_any/dynanyutils_t.h" namespace TAOX11_NAMESPACE { namespace DynamicAny { DynEnum_i::DynEnum_i (bool allow_truncation) : TAOX11_DynCommon (allow_truncation) , value_ (0) { TAOX11_LOG_TRACE ("DynEnum_i::DynEnum_i"); } void DynEnum_i::init_common () { this->ref_to_component_ = false; this->container_is_destroying_ = false; this->has_components_ = false; this->destroyed_ = false; this->current_position_ = -1; this->component_count_ = 0; } IDL::traits< DynamicAny::DynAny>::ref_type DynEnum_i::init (const CORBA::Any &any) { TAOX11_LOG_TRACE ("DynEnum_i::init with any"); IDL::traits<CORBA::TypeCode>::ref_type tc = any.type (); CORBA::TCKind kind = DynAnyFactory_i::unalias (tc); if (kind != CORBA::TCKind::tk_enum) { throw DynamicAny::DynAnyFactory::InconsistentTypeCode (); } this->type_ = tc; TAOX11_CORBA::Any::impl_ref_type impl = any.impl (); if (impl->encoded ()) { std::shared_ptr<Unknown_IDL_Type> const unk = std::dynamic_pointer_cast<Unknown_IDL_Type> (impl); if (!unk) throw CORBA::INTERNAL (); // We don't want unk's rd_ptr to move, in case we are shared by // another Any, so we use this to copy the state, not the buffer. TAO_InputCDR for_reading (unk->_tao_get_cdr ()); for_reading.read_ulong (this->value_); } else { TAO_OutputCDR out; impl->marshal_value (out); TAO_InputCDR in (out); in.read_ulong (this->value_); } this->init_common (); return this->_this(); } IDL::traits< DynamicAny::DynAny>::ref_type DynEnum_i::init (IDL::traits<CORBA::TypeCode>::ref_type tc) { TAOX11_LOG_TRACE ("DynEnum_i::init with typecode"); CORBA::TCKind kind = DynAnyFactory_i::unalias (tc); if (kind != CORBA::TCKind::tk_enum) { throw DynamicAny::DynAnyFactory::InconsistentTypeCode (); } this->type_ = tc; this->value_ = 0; this->init_common (); return this->_this(); } std::string DynEnum_i::get_as_string () { TAOX11_LOG_TRACE ("DynEnum_i::get_as_string"); IDL::traits<CORBA::TypeCode>::ref_type ct = DynAnyFactory_i::strip_alias (this->type_); const std::string retval = ct->member_name (this->value_); return retval; } void DynEnum_i::set_as_string (const std::string &value_as_string) { TAOX11_LOG_TRACE ("DynEnum_i::set_as_string"); IDL::traits<CORBA::TypeCode>::ref_type ct = DynAnyFactory_i::strip_alias (this->type_); uint32_t count = ct->member_count (); uint32_t i; std::string temp {}; for (i = 0; i < count; ++i) { temp = ct->member_name (i); if (value_as_string == temp) { break; } } if (i < count) { this->value_ = i; } else { throw DynamicAny::DynAny::InvalidValue (); } } uint32_t DynEnum_i::get_as_ulong () { TAOX11_LOG_TRACE ("DynEnum_i::DynEnum_i"); return this->value_; } void DynEnum_i::set_as_ulong (uint32_t value_as_ulong) { TAOX11_LOG_TRACE ("DynEnum_i::set_as_ulong"); IDL::traits<CORBA::TypeCode>::ref_type ct = DynAnyFactory_i::strip_alias (this->type_); uint32_t const max = ct->member_count (); if (value_as_ulong < max) { this->value_ = value_as_ulong; } else { throw DynamicAny::DynAny::InvalidValue (); } } void DynEnum_i::from_any (const CORBA::Any& any) { TAOX11_LOG_TRACE ("DynEnum_i::from_any"); IDL::traits<CORBA::TypeCode>::ref_type tc = any.type (); CORBA::TCKind kind = DynAnyFactory_i::unalias (tc); if (kind == CORBA::TCKind::tk_enum) { // Get the CDR stream of the Any, if there isn't one, make one. TAOX11_CORBA::Any::impl_ref_type impl = any.impl (); if (impl->encoded ()) { std::shared_ptr<Unknown_IDL_Type> const unk = std::dynamic_pointer_cast<Unknown_IDL_Type> (impl); if (!unk) throw CORBA::INTERNAL (); // We don't want unk's rd_ptr to move, in case we are shared by // another Any, so we use this to copy the state, not the buffer. TAO_InputCDR for_reading (unk->_tao_get_cdr ()); for_reading.read_ulong (this->value_); } else { TAO_OutputCDR out; impl->marshal_value (out); TAO_InputCDR in (out); in.read_ulong (this->value_); } } else { throw DynamicAny::DynAny::TypeMismatch (); } } CORBA::Any DynEnum_i::to_any () { TAOX11_LOG_TRACE ("DynEnum_i::to_any"); TAO_OutputCDR out_cdr; out_cdr.write_ulong (this->value_); CORBA::Any retval {}; try { TAO_InputCDR in_cdr (out_cdr); TAOX11_NAMESPACE::Unknown_IDL_Type::ref_type safe_impl = std::make_shared<TAOX11_NAMESPACE::Unknown_IDL_Type> (this->type_, in_cdr); retval.replace (safe_impl); } catch (const std::bad_alloc&) { throw CORBA::NO_MEMORY (); } return retval; } bool DynEnum_i::equal (IDL::traits< DynamicAny::DynAny>::ref_type rhs) { TAOX11_LOG_TRACE ("DynEnum_i::equal"); IDL::traits<CORBA::TypeCode>::ref_type tc = rhs->type (); bool equivalent = tc->equivalent (this->type_); if (!equivalent) { return false; } CORBA::Any any = rhs->to_any (); TAOX11_CORBA::Any::impl_ref_type impl = any.impl (); uint32_t value; if (impl->encoded ()) { std::shared_ptr<Unknown_IDL_Type> const unk = std::dynamic_pointer_cast<Unknown_IDL_Type> (impl); if (!unk) throw CORBA::INTERNAL (); // We don't want unk's rd_ptr to move, in case we are shared by // another Any, so we use this to copy the state, not the buffer. TAO_InputCDR for_reading (unk->_tao_get_cdr ()); for_reading.read_ulong (value); } else { TAO_OutputCDR out; impl->marshal_value (out); TAO_InputCDR in (out); in.read_ulong (value); } return value == this->value_; } void DynEnum_i::destroy () { if (this->destroyed_) { throw CORBA::OBJECT_NOT_EXIST (); } if (!this->ref_to_component_ || this->container_is_destroying_) { this->destroyed_ = true; } } IDL::traits< DynamicAny::DynAny>::ref_type DynEnum_i::current_component () { TAOX11_LOG_TRACE ("DynEnum_i::current_component"); if (this->destroyed_) { throw CORBA::OBJECT_NOT_EXIST (); } throw DynamicAny::DynAny::TypeMismatch (); } } namespace CORBA { template<> TAOX11_DynamicAny_Export object_traits<DynamicAny::DynEnum>::ref_type object_traits<DynamicAny::DynEnum>::narrow ( object_reference<CORBA::Object> obj) { if (obj) { if (obj->_is_local ()) { return ref_type::_narrow (std::move(obj)); } } return nullptr; } } }
23.471642
85
0.580694
[ "object" ]
75ebc9eeeab0dd856bcd8d663b76675803422f5a
15,562
cpp
C++
src/gui/rendering/Load3ds.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
1
2018-09-18T07:09:36.000Z
2018-09-18T07:09:36.000Z
src/gui/rendering/Load3ds.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
null
null
null
src/gui/rendering/Load3ds.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
2
2020-06-18T04:45:30.000Z
2021-07-20T02:11:54.000Z
//------------------------------------------------------------------------------ // Load3ds //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // ** Legal ** // // Author: Phillip Silvia, Jr. // Created: 2009/06/24 /** * Loads a .3ds file and stores the information in a ModelObject */ //------------------------------------------------------------------------------ #include <stdio.h> #include <stdlib.h> //#include <conio.h> //#include <io.h> #include "ModelObject.hpp" #include "Load3ds.hpp" #include "MessageInterface.hpp" #define CHUNK_MAIN 0x4d4d #define CHUNK_OBJMESH 0x3d3d #define CHUNK_OBJBLOCK 0x4000 #define CHUNK_TRIMESH 0x4100 #define CHUNK_VERTLIST 0x4110 #define CHUNK_FACELIST 0x4120 #define CHUNK_FACEMAT 0x4130 #define CHUNK_MAPLIST 0x4140 #define CHUNK_SMOOLIST 0x4150 #define CHUNK_MATERIAL 0xAFFF #define CHUNK_MATNAME 0xA000 #define CHUNK_MATACOL 0xA010 #define CHUNK_SUBCOLOR 0x0011 #define CHUNK_MATDIFF 0xA020 #define CHUNK_MATSPEC 0xA030 #define CHUNK_MATSHINE 0xA040 #define CHUNK_SUBSHINE 0x0030 #define CHUNK_TEXMAP 0xA200 #define CHUNK_MATTEXT 0xA300 //------------------------------------------------------------------------------ // char Load3DS(ModelObject *p_object, const std::string &p_filename) //------------------------------------------------------------------------------ /** * This function loads a mesh from a 3ds file. * * It takes in only the vertices, polygons, and mapping lists. Other * information, such as lightings, materials, etc. must be added in * * @param p_object pointer to a ModelObject * * @return 1 if the object loaded correctly, 0 otherwise (char) */ //------------------------------------------------------------------------------ char Load3DS(ModelObject *p_object, const std::string &p_filename) { int i, chunk = 0; // Index int vert_index[MAX_LISTS]; // The starting index of a particular list of vertices int poly_index[MAX_LISTS]; // The starting index of a particular list of polygons int vert_list = 0, poly_list = 0, map_list = 0; int index = 0; FILE *l_file; // File pointer unsigned short l_chunk_id; // Chunk id unsigned int l_chunk_length; // Chunk length char l_char; // Char unsigned char r,g,b; unsigned short l_qty; // Numbers of elements in each chunk unsigned short l_face_flags; // Flag storing some face info long size; // length of the file // Make we have a file name if (p_filename[0] == '\0') return 0; if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("Loading 3ds object: %s\n", p_filename.c_str()); // Load the file, print an error message if we couldn't find the file or it failed for any reason if ((l_file = fopen(p_filename.c_str(), "rb")) == NULL) { MessageInterface::ShowMessage("File %s not found!", p_filename.c_str()); return 0; } fseek(l_file, 0, SEEK_END); // seek to end of file size = ftell(l_file); // get current file pointer fseek(l_file, 0, SEEK_SET); // seek back to beginning of file p_object->num_vertices = 0; p_object->num_polygons = 0; p_object->num_materials = 0; // Loop through the whole file while(ftell(l_file) < size){//filelength(fileno(l_file))){ // Read in chunk header fread(&l_chunk_id, 2, 1, l_file); if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("ChunkID: %x\n", l_chunk_id); // Read in the length of the chunk fread(&l_chunk_length, 4, 1, l_file); if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("Chunk Length: %x\n", l_chunk_length); // How we proceed depends on the chunk we are examining switch (l_chunk_id) { // Main Chunk, which contains all other chunks // We do not need to do anything here except skip it case CHUNK_MAIN: break; // 3D Editor Chunk, contains editor information and flags // We ignore it case CHUNK_OBJMESH: break; // Object Block chunk, contains information on each object in the model // We extract the names case CHUNK_OBJBLOCK: i = 0; do { fread(&l_char, 1, 1, l_file); p_object->name += l_char; i++; } while (l_char != '\0' && i < 20); break; // Triangular Mesh chunk, contains the chunks detailing mesh info // Just a header for the sub-chunks, we skip it case CHUNK_TRIMESH: break; // Vertices List chunk, has all of the vertices for the object // We want these case CHUNK_VERTLIST: float v; // Retrieve the number of vertices fread(&l_qty, sizeof(unsigned short), 1, l_file); vert_index[vert_list] = p_object->num_vertices; p_object->num_vertices += l_qty; if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("Number of vertices: %d\n", l_qty); // If the number of vertices is beyond our max, we bug out if (p_object->num_vertices > MAX_VERTICES) { MessageInterface::ShowMessage("Number of vertices too high!\n"); return 0; } // Then we loop through all vertices and store them for (i = p_object->num_vertices - l_qty; i < p_object->num_vertices; i++) { fread(&v, sizeof(float), 1, l_file); p_object->vertex[i].x = v; fread(&v, sizeof(float), 1, l_file); p_object->vertex[i].y = v; fread(&v, sizeof(float), 1, l_file); p_object->vertex[i].z = v; if (LOAD3DS_DEBUG) { MessageInterface::ShowMessage("Vertices List x: %f\n", p_object->vertex[i].x); MessageInterface::ShowMessage("Vertices List y: %f\n", p_object->vertex[i].y); MessageInterface::ShowMessage("Vertices List z: %f\n", p_object->vertex[i].z); } } vert_list++; break; // Faces list chunk, stores indices of vertices that make up the faces // We extract this information case CHUNK_FACELIST: // Retrieve the number of faces fread(&l_qty, sizeof(unsigned short), 1, l_file); poly_index[poly_list] = p_object->num_polygons; p_object->num_polygons += l_qty; if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("Number of polygons: %d\n", l_qty); // Ensure we don't have more polygons than we can handle if (p_object->num_polygons > MAX_POLYGONS) { MessageInterface::ShowMessage("Number of polygons is too high!\n"); return 0; } // Loop through file and extract all of the face information for (i = p_object->num_polygons-l_qty; i < p_object->num_polygons; i++){ fread(&p_object->polygon[i].a, sizeof(unsigned short), 1, l_file); p_object->polygon[i].a += vert_index[poly_list]; fread(&p_object->polygon[i].b, sizeof(unsigned short), 1, l_file); p_object->polygon[i].b += vert_index[poly_list]; fread(&p_object->polygon[i].c, sizeof(unsigned short), 1, l_file); p_object->polygon[i].c += vert_index[poly_list]; fread(&l_face_flags, sizeof(unsigned short), 1, l_file); if (LOAD3DS_DEBUG) { MessageInterface::ShowMessage("Polygon point a: %d\n", p_object->polygon[i].a); MessageInterface::ShowMessage("Polygon point b: %d\n", p_object->polygon[i].b); MessageInterface::ShowMessage("Polygon point c: %d\n", p_object->polygon[i].c); MessageInterface::ShowMessage("Face Flags: %x\n", l_face_flags); } } poly_list++; break; // The chunk defining which materials belong to which face. We // use this information to build our mat_map that maps a polygon index to // a material index case CHUNK_FACEMAT: unsigned short value; char str[255]; i = 0; do { fread(&l_char, 1, 1, l_file); str[i] = l_char; i++; } while (l_char != '\0' && i < 255); for (i = 0; i < p_object->num_materials; i++) { if (strcmp(p_object->material[i].name, str) == 0) { index = i; break; } else if (i == p_object->num_materials-1) { fprintf(stdout, "Material %s not found!\n", str); index = -1; return 0; } } fread(&l_qty, sizeof(unsigned short), 1, l_file); if (index != -1) p_object->material[index].num_faces += l_qty; for (i = p_object->material[index].num_faces - l_qty; i < p_object->material[index].num_faces; i++) { fread(&value, sizeof(unsigned short), 1, l_file); if (index != -1) p_object->material[index].faces[i] = value + poly_index[map_list]; } map_list++; break; // Texture mapping chunk, has the u,v coordinates for each vertex // We extract this information case CHUNK_MAPLIST: // Retrieve the number of mappings fread(&l_qty, sizeof(unsigned short), 1, l_file); // Go through all of the mappings and store them for (i = p_object->num_vertices-l_qty; i < p_object->num_vertices; i++) { fread(&p_object->mapcoord[i], sizeof(float), 2, l_file); // p_object->mapcoord[i].u = p_object->mapcoord[i].u; p_object->mapcoord[i].v = -p_object->mapcoord[i].v; if (LOAD3DS_DEBUG) { MessageInterface::ShowMessage("Mapping list u,v: %f,%f\n", p_object->mapcoord[i].u, p_object->mapcoord[i].v); } } break; // Start of the Materials chunk. Contains no data, so we move on case CHUNK_MATERIAL: p_object->num_materials++; break; // The name of the material. We extract and store case CHUNK_MATNAME: i = 0; do { fread(&l_char, 1, 1, l_file); p_object->material[p_object->num_materials-1].name[i] = l_char; i++; } while (l_char != '\0' && i < 255); p_object->material[p_object->num_materials-1].num_faces = 0; break; // The ambient color of the material. Extract and store case CHUNK_MATACOL: chunk = l_chunk_id; break; case CHUNK_SUBCOLOR: fread(&r, sizeof(unsigned char), 1, l_file); fread(&g, sizeof(unsigned char), 1, l_file); fread(&b, sizeof(unsigned char), 1, l_file); if (chunk == CHUNK_MATACOL) { p_object->material[p_object->num_materials-1].mat_ambient.r = (float)r/255; p_object->material[p_object->num_materials-1].mat_ambient.g = (float)g/255; p_object->material[p_object->num_materials-1].mat_ambient.b = (float)b/255; p_object->material[p_object->num_materials-1].mat_ambient.a = (float)(r+g+b)/3/255; } else if (chunk == CHUNK_MATDIFF) { p_object->material[p_object->num_materials-1].mat_diffuse.r = (float)r/255; p_object->material[p_object->num_materials-1].mat_diffuse.g = (float)g/255; p_object->material[p_object->num_materials-1].mat_diffuse.b = (float)b/255; p_object->material[p_object->num_materials-1].mat_diffuse.a = (float)(r+g+b)/3/255; } else if (chunk == CHUNK_MATSPEC) { p_object->material[p_object->num_materials-1].mat_specular.r = (float)r/255; p_object->material[p_object->num_materials-1].mat_specular.g = (float)g/255; p_object->material[p_object->num_materials-1].mat_specular.b = (float)b/255; p_object->material[p_object->num_materials-1].mat_specular.a = (float)(r+g+b)/3/255; } break; // The diffuse color of the material. Extract and store case CHUNK_MATDIFF: chunk = l_chunk_id; break; // The specular color of the material. Extract and store case CHUNK_MATSPEC: chunk = l_chunk_id; break; // The shininess of the material. Extract and store case CHUNK_MATSHINE: break; case CHUNK_SUBSHINE: unsigned short s; fread(&s, sizeof(unsigned short), 1, l_file); p_object->material[p_object->num_materials-1].mat_shininess = (float)s/255.0f; break; // The header chunk containing the material's texture. Skip it. case CHUNK_TEXMAP: break; // The file name of the material's texture. Extract and store. We will load // and bind the textures in the object. case CHUNK_MATTEXT: i = 0; do { fread(&l_char, 1, 1, l_file); p_object->material[p_object->num_materials-1].texture_name[i] = l_char; i++; } while (l_char != '\0' && i < 255); break; // We skip all unknown chunks. // Since they all begin with the chunk length, we use that information to skip. // If you want to add other information to the model (materials info, for example), // then add their cases here default: fseek(l_file, l_chunk_length-6, SEEK_CUR); } } fclose(l_file); // Close the file if (LOAD3DS_DEBUG) MessageInterface::ShowMessage("Vertex count: %d Face count: %d\n", p_object->num_vertices, p_object->num_polygons); return 1; // Return successfully }
42.98895
112
0.546652
[ "mesh", "object", "model", "3d" ]
75f11bc3a66243d7527b1445490609ea16539e6f
4,379
cpp
C++
src/kite_estimation/kiteEKF.cpp
jowaibel/openkite
165e4fc8e3e01934a36543be03e34a8cfa5b9926
[ "MIT" ]
4
2019-05-21T20:40:49.000Z
2021-01-19T19:28:17.000Z
src/kite_estimation/kiteEKF.cpp
jowaibel/openkite
165e4fc8e3e01934a36543be03e34a8cfa5b9926
[ "MIT" ]
1
2019-12-04T14:00:12.000Z
2019-12-04T14:00:12.000Z
src/kite_estimation/kiteEKF.cpp
jowaibel/openkite
165e4fc8e3e01934a36543be03e34a8cfa5b9926
[ "MIT" ]
4
2019-07-11T09:53:26.000Z
2020-05-06T13:01:12.000Z
#include "kiteEKF.h" using namespace casadi; /** experimentaly defined values */ const DM KiteEKF::SIGMA_Q = DM::diag(DMVector{0.01, 0.05, 0.05, 0.05}); const DM KiteEKF::SIGMA_V = DM::diag(DMVector{0.5, 0.5, 0.5}); const DM KiteEKF::SIGMA_W = DM::diag(casadi::DMVector{0.5, 0.5, 0.5}); const DM KiteEKF::SIGMA_R = DM::diag(casadi::DMVector{0.5, 0.1, 0.1}); const DM KiteEKF::DEFAULT_PROCESS_COVARIANCE = pow(DM::diagcat({SIGMA_V, SIGMA_W, SIGMA_R, SIGMA_Q}), 2); const DM KiteEKF::DEFAULT_MEASUREMENT_COVARIANCE = pow(DM::diag(DMVector{0.01,0.01,0.01, 0.0001,0.005,0.005,0.005}), 2); const DM KiteEKF::DEFAULT_MEASUREMENT_MATRIX = DM::horzcat(DMVector{DM::zeros(7,6), DM::eye(7)}); KiteEKF::KiteEKF(const KiteProperties &KiteProps, const AlgorithmProperties &AlgoProps) { /** instantiate kite object */ Kite = std::make_shared<KiteDynamics>(KiteProps, AlgoProps); this->m_Integrator = Kite->getNumericIntegrator(); this->m_Jacobian = Kite->getNumericJacobian(); this->W = DEFAULT_PROCESS_COVARIANCE; this->V = DEFAULT_MEASUREMENT_COVARIANCE; this->H = DEFAULT_MEASUREMENT_MATRIX; this->Cov_Est = 10 * this->W; /** initialize time */ std::chrono::time_point<std::chrono::system_clock> t_now = kite_utils::get_time(); auto duration = t_now.time_since_epoch(); auto microsec = std::chrono::duration_cast<std::chrono::microseconds>(duration).count(); this->tstamp = static_cast<double>(microsec) * 1e-6; } KiteEKF::KiteEKF(std::shared_ptr<KiteDynamics> obj_Kite) { Kite = obj_Kite; this->m_Integrator = Kite->getNumericIntegrator(); this->m_Jacobian = Kite->getNumericJacobian(); this->W = DEFAULT_PROCESS_COVARIANCE; this->V = DEFAULT_MEASUREMENT_COVARIANCE; this->H = DEFAULT_MEASUREMENT_MATRIX; this->Cov_Est = 10 * this->W; /** initialize time */ std::chrono::time_point<std::chrono::system_clock> t_now = kite_utils::get_time(); auto duration = t_now.time_since_epoch(); auto microsec = std::chrono::duration_cast<std::chrono::microseconds>(duration).count(); this->tstamp = static_cast<double>(microsec) * 1e-6; } KiteEKF::KiteEKF(const Function &_Dynamics, const Function &_Jacobian) { /** instantiate model */ this->m_Integrator = _Dynamics; this->m_Jacobian = _Jacobian; this->W = DEFAULT_PROCESS_COVARIANCE; this->V = DEFAULT_MEASUREMENT_COVARIANCE; this->H = DEFAULT_MEASUREMENT_MATRIX; this->Cov_Est = 10 * this->W; /** initialize time */ std::chrono::time_point<std::chrono::system_clock> t_now = kite_utils::get_time(); auto duration = t_now.time_since_epoch(); auto microsec = std::chrono::duration_cast<std::chrono::microseconds>(duration).count(); this->tstamp = static_cast<double>(microsec) * 1e-6; std::cout << tstamp << "\n"; } void KiteEKF::propagate(const double &_dt) { DM new_state; if (m_Integrator.name().find("RK4") != std::string::npos) { DMVector out = m_Integrator(DMVector{State_Est, Control, _dt}); new_state = out[0]; } else if (m_Integrator.name().find("CVODES") != std::string::npos) { DMDict args = {{"x0", State_Est}, {"p", Control}}; DMDict out = m_Integrator(args); new_state = out["xf"]; } else std::cout << "WARNING: Unknown intergrator! \n"; /** propagate covariance */ DM A = m_Jacobian(DMVector{State_Est, Control})[0] * _dt + DM::eye(13); DM P_new = DM::mtimes(DM::mtimes(A, Cov_Est), A.T()) + W; State_Est = new_state; Cov_Est = P_new; } void KiteEKF::estimate(const DM &measurement, const double &_tstamp) { /** prediction step */ double dt = _tstamp - this->tstamp; std::cout << "Time lapse in Kalman: " << dt << "\n"; _estimate(measurement, dt); } void KiteEKF::_estimate(const DM &measurement, const double &_dt) { this->propagate(_dt); /** update step */ DM y = measurement - DM::mtimes(H, State_Est); /** innovation covariance */ DM S = DM::mtimes(DM::mtimes(H, Cov_Est), H.T()) + V; /** Kalman gain */ DM K = DM::mtimes(DM::mtimes(Cov_Est, H.T()), DM::solve(S, SX::eye(7))); /** updated state estimate */ DM x_est = State_Est + DM::mtimes(K, y); /** estimate covariance update */ DM P_est = DM::mtimes((DM::eye(13) - DM::mtimes(K, H)), Cov_Est); State_Est = x_est; Cov_Est = P_est; }
34.480315
120
0.658826
[ "object", "model" ]
75f130dbcb07e71cfad1f4c0564202034af53e87
2,446
cc
C++
android_webview/renderer/aw_execution_termination_filter.cc
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-01-16T03:57:39.000Z
2019-01-16T03:57:39.000Z
android_webview/renderer/aw_execution_termination_filter.cc
7kbird/chrome
f56688375530f1003e34c34f441321977c5af3c3
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
android_webview/renderer/aw_execution_termination_filter.cc
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:23:37.000Z
2020-11-04T07:23:37.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "android_webview/renderer/aw_execution_termination_filter.h" #include <v8.h> #include "android_webview/common/render_view_messages.h" #include "base/message_loop/message_loop_proxy.h" namespace { const int kTerminationTimeoutInSeconds = 3; } // namespace namespace android_webview { AwExecutionTerminationFilter::AwExecutionTerminationFilter( const scoped_refptr<base::MessageLoopProxy>& io_message_loop, const scoped_refptr<base::MessageLoopProxy>& main_message_loop) : io_message_loop_(io_message_loop), main_message_loop_(main_message_loop), render_thread_isolate_(NULL) { } AwExecutionTerminationFilter::~AwExecutionTerminationFilter() { } void AwExecutionTerminationFilter::SetRenderThreadIsolate( v8::Isolate* isolate) { render_thread_isolate_ = isolate; } bool AwExecutionTerminationFilter::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(AwExecutionTerminationFilter, message) IPC_MESSAGE_HANDLER(AwViewMsg_CheckRenderThreadResponsiveness, OnCheckRenderThreadResponsiveness) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void AwExecutionTerminationFilter::OnCheckRenderThreadResponsiveness() { termination_timer_.Start( FROM_HERE, base::TimeDelta::FromSeconds(kTerminationTimeoutInSeconds), base::Bind(&AwExecutionTerminationFilter::TerminateExecution, this)); // Post a request to stop the timer via render thread's message loop // to ensure that render thread is responsive. main_message_loop_->PostTask( FROM_HERE, base::Bind(&AwExecutionTerminationFilter::StopTimerOnMainThread, this)); } void AwExecutionTerminationFilter::StopTimerOnMainThread() { io_message_loop_->PostTask( FROM_HERE, base::Bind(&AwExecutionTerminationFilter::StopTimer, this)); } void AwExecutionTerminationFilter::StopTimer() { termination_timer_.Stop(); } void AwExecutionTerminationFilter::TerminateExecution() { if (render_thread_isolate_) { LOG(WARNING) << "Trying to terminate JavaScript execution because " "renderer is unresponsive"; v8::V8::TerminateExecution(render_thread_isolate_); } } } // namespace android_webview
31.766234
75
0.770646
[ "render" ]
75ff1e3fec892aec2c202800caed2900b04665e6
1,485
cpp
C++
DynamicProgramming/shortestcommonsupersequencei.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
4
2020-12-29T09:27:10.000Z
2022-02-12T14:20:23.000Z
DynamicProgramming/shortestcommonsupersequencei.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-27T06:15:28.000Z
2021-11-27T06:15:28.000Z
DynamicProgramming/shortestcommonsupersequencei.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
1
2021-11-17T21:42:57.000Z
2021-11-17T21:42:57.000Z
/* Shortest Common Supersequence https://practice.geeksforgeeks.org/problems/shortest-common-supersequence0322/1# */ class Solution { public: //Function to find length of shortest common supersequence of two strings. /*the basic idea is that find the lcs length from both the strings and concatenate both the string to make the third one and just remove the lcs length from concatenated string, we will get the output. Time: O(m*n), Space: O(m*n)*/ int lcs(string tempX, string tempY, int m, int n) { vector<vector<int> > dp(m + 1, vector<int>(n + 1)); //intializing for (int i = 0; i < m + 1; i++) for (int j = 0; j < n + 1; j++) if (i == 0 || j == 0) dp[i][j] = 0; //solving the subproblems for (int i = 1; i < m + 1; i++) { for (int j = 1; j < n + 1; j++) { if (tempX[i - 1] == tempY[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } int shortestCommonSupersequence(char *X, char *Y, int m, int n) { string tempX = ""; string tempY = ""; for (int i = 0; i < m; i++) tempX.push_back(X[i]); for (int i = 0; i < n; i++) tempY.push_back(Y[i]); return m + n - lcs(tempX, tempY, m, n); } };
29.117647
80
0.480808
[ "vector" ]
2f086681f7a4961a41d56b41038528aeb38128ec
3,012
cpp
C++
imaging/cv_mat/filters/hard_edge.cpp
mission-systems-pty-ltd/snark
2bc8a20292ee3684d3a9897ba6fee43fed8d89ae
[ "BSD-3-Clause" ]
1
2022-03-27T00:24:37.000Z
2022-03-27T00:24:37.000Z
imaging/cv_mat/filters/hard_edge.cpp
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
null
null
null
imaging/cv_mat/filters/hard_edge.cpp
NEU-LC/snark
db890f73f4c4bbe679405f3a607fd9ea373deb2c
[ "BSD-3-Clause" ]
1
2020-10-30T02:11:55.000Z
2020-10-30T02:11:55.000Z
// Copyright (c) 2019 Vsevolod Vlaskine /// @author vsevolod vlaskine #include <memory> #include <sstream> #include <vector> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <boost/date_time/posix_time/ptime.hpp> #include <tbb/parallel_for.h> #include <comma/base/exception.h> #include "hard_edge.h" #include "../utils.h" namespace snark { namespace cv_mat { namespace filters { template < typename H > std::pair< H, cv::Mat > hard_edge< H >::handle( std::pair< H, cv::Mat > m, float background ) { std::pair< H, cv::Mat > n; n.first = m.first; m.second.copyTo( n.second ); std::vector< unsigned char > background_pixel( m.second.elemSize() ); for( unsigned int i = 0; i < m.second.elemSize(); i += m.second.elemSize1() ) { set_channel( &background_pixel[i], background, m.second.depth() ); } auto is_background = [&]( int i, int j ) -> bool { return std::memcmp( m.second.ptr( i, j ), &background_pixel[0], m.second.elemSize() ) == 0; }; auto same = [&]( int i0, int j0, int i1, int j1 ) -> bool { if( i1 < 0 || i1 >= m.second.rows || j1 < 0 || j1 >= m.second.cols ) { return true; } return std::memcmp( m.second.ptr( i0, j0 ), m.second.ptr( i1, j1 ), m.second.elemSize() ) == 0; }; auto reset = [&]( int i, int j ) { std::memcpy( n.second.ptr( i, j ), &background_pixel[0], m.second.elemSize() ); }; tbb::parallel_for( tbb::blocked_range< std::size_t >( 0, m.second.rows, m.second.rows / 8 ), [&]( const tbb::blocked_range< std::size_t >& r ) { for( unsigned int i = r.begin(); i < r.end(); ++i ) { for( int j = 0; j < m.second.cols; ++ j ) { if( is_background( i, j ) ) { continue; } if( same( i, j, i - 1, j - 1 ) && same( i, j, i - 1, j ) && same( i, j, i - 1, j + 1 ) && same( i, j, i , j - 1 ) && same( i, j, i , j + 1 ) && same( i, j, i + 1, j - 1 ) && same( i, j, i + 1, j ) && same( i, j, i + 1, j + 1 ) ) { reset( i, j ); } } } } ); return n; } template < typename H > std::pair< typename hard_edge< H >::functor_t, bool > hard_edge< H >::make( const std::string& options ) { return std::make_pair( boost::bind( &hard_edge< H >::handle, _1, options.empty() ? 0. : boost::lexical_cast< float >( options ) ), true ); } template < typename H > std::string hard_edge< H >::usage( unsigned int indent ) { std::ostringstream oss; oss << std::string( indent, ' ' ) << "hard-edge[=<background>]: find hard edge (currently only single-channel images supported); set all non-edge pixels to <background>"; return oss.str(); } template struct hard_edge< boost::posix_time::ptime >; template struct hard_edge< std::vector< char > >; } } } // namespace snark { namespace cv_mat { namespace impl {
40.16
174
0.543825
[ "vector" ]
2f12e0ed81c448ad6913ccf6f93627b3f872577f
14,550
cpp
C++
src/generate/gen_codefiles.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
7
2021-10-22T02:43:12.000Z
2022-01-15T10:52:58.000Z
src/generate/gen_codefiles.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
288
2021-05-16T19:12:04.000Z
2022-03-30T13:22:31.000Z
src/generate/gen_codefiles.cpp
KeyWorksRW/wxUiEditor
fc58bb37284430fa5901579ae121d4482b588c75
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Purpose: Generate code files // Author: Ralph Walden // Copyright: Copyright (c) 2020-2021 KeyWorks Software (Ralph Walden) // License: Apache License -- see ../../LICENSE ///////////////////////////////////////////////////////////////////////////// #include "ttcwd.h" // cwd -- Class for storing and optionally restoring the current directory #include "mainframe.h" #include "gen_base.h" // BaseCodeGenerator -- Generate Base class #include "mainapp.h" // App -- Main application class #include "node.h" // Node class #include "write_code.h" // Write code to Scintilla or file bool GenerateCodeFiles(wxWindow* parent, bool NeedsGenerateCheck, std::vector<ttlib::cstr>* pClassList) { auto project = wxGetApp().GetProject(); if (project->GetChildCount() == 0) { if (NeedsGenerateCheck) return false; wxMessageBox("You cannot generate any code until you have added a top level form.", "Code Generation"); return false; } ttSaveCwd cwd; ttlib::ChangeDir(wxGetApp().getProjectPath()); ttlib::cstr path; std::vector<ttlib::cstr> results; ttlib::cstr source_ext(".cpp"); ttlib::cstr header_ext(".h"); if (auto& extProp = project->prop_as_string(prop_source_ext); extProp.size()) { source_ext = extProp; } if (auto& extProp = project->prop_as_string(prop_header_ext); extProp.size()) { header_ext = extProp; } size_t currentFiles = 0; if (WriteCMakeFile(NeedsGenerateCheck) != result::exists) { if (NeedsGenerateCheck && !pClassList) return true; ++currentFiles; results.emplace_back() << project->prop_as_string(prop_cmake_file) << " saved" << '\n'; } bool generate_result = true; for (size_t pos = 0; pos < project->GetChildCount(); ++pos) { auto form = project->GetChild(pos); if (auto& base_file = form->prop_as_string(prop_base_file); base_file.size()) { path = base_file; // "filename_base" is the default filename given to all form files. Unless it's changed, no code will be // generated. if (path == "filename_base") continue; path.make_absolute(); path.backslashestoforward(); } else { results.emplace_back() << "No filename specified for " << form->prop_as_string(prop_class_name) << '\n'; } try { BaseCodeGenerator codegen; path.replace_extension(header_ext); auto h_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetHdrWriteCode(h_cw.get()); path.replace_extension(source_ext); auto cpp_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetSrcWriteCode(cpp_cw.get()); codegen.GenerateBaseClass(project, form); path.replace_extension(header_ext); auto retval = h_cw->WriteFile(NeedsGenerateCheck); if (retval > 0) { if (!NeedsGenerateCheck) { results.emplace_back() << path << " saved" << '\n'; } else { if (pClassList) { pClassList->emplace_back(form->prop_as_string(prop_class_name)); continue; } else { return true; } } } else if (retval < 0) { results.emplace_back() << "Cannot create or write to the file " << path << '\n'; generate_result = false; } else // retval == result::exists) { ++currentFiles; } path.replace_extension(source_ext); retval = cpp_cw->WriteFile(NeedsGenerateCheck); if (retval > 0) { if (!NeedsGenerateCheck) { results.emplace_back() << path << " saved" << '\n'; } else { if (pClassList) { pClassList->emplace_back(form->prop_as_string(prop_class_name)); continue; } else { return generate_result; } } } else if (retval < 0) { results.emplace_back() << "Cannot create or write to the file " << path << '\n'; } else // retval == result::exists { ++currentFiles; } } catch (const std::exception& DBG_PARAM(e)) { MSG_ERROR(e.what()); wxMessageBox(ttlib::cstr("An internal error occurred generating code files for ") << form->prop_as_string(prop_base_file), "Code generation"); continue; } } if (NeedsGenerateCheck) { if (pClassList && pClassList->size()) return generate_result; else return false; } if (results.size()) { ttlib::cstr msg; for (auto& iter: results) { msg += iter; } if (currentFiles) { msg << '\n' << "The other " << currentFiles << " generated files are current"; } wxMessageBox(msg.wx_str(), "Code Generation", wxOK, parent); } else if (currentFiles && parent) { ttlib::cstr msg; msg << '\n' << "All " << currentFiles << " generated files are current"; wxMessageBox(msg, "Code Generation", wxOK, parent); } return generate_result; } void MainFrame::OnGenInhertedClass(wxCommandEvent& WXUNUSED(e)) { auto& project = wxGetApp().GetProjectPtr(); ttlib::cwd cwd; ttlib::ChangeDir(wxGetApp().getProjectPath()); ttlib::cstr path; std::vector<ttlib::cstr> results; ttlib::cstr source_ext(".cpp"); ttlib::cstr header_ext(".h"); if (auto& extProp = project->prop_as_string(prop_source_ext); extProp.size()) { source_ext = extProp; } if (auto extProp = project->prop_as_string(prop_header_ext); extProp.size()) { header_ext = extProp; } size_t currentFiles = 0; for (size_t pos = 0; pos < project->GetChildCount(); ++pos) { auto form = project->GetChildPtr(pos); if (auto& file = form->prop_as_string(prop_derived_file); file.size()) { path = file; if (path.empty()) continue; path.make_relative(wxGetApp().getProjectPath()); path.backslashestoforward(); path.replace_extension(source_ext); if (path.file_exists()) { // Count both source and header file currentFiles += 2; continue; } path.remove_extension(); } else { continue; } BaseCodeGenerator codegen; path.replace_extension(header_ext); auto h_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetHdrWriteCode(h_cw.get()); path.replace_extension(source_ext); auto cpp_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetSrcWriteCode(cpp_cw.get()); auto retval = codegen.GenerateDerivedClass(project.get(), form.get()); ASSERT_MSG(retval != result::exists, "this should be impossible since we checked above") if (retval == result::fail) { results.emplace_back() << "Cannot create or write to the file " << path << '\n'; continue; } else if (retval == result::exists) { ++currentFiles; continue; } else if (retval == result::ignored) { // Completely ignore this file continue; } path.replace_extension(header_ext); retval = h_cw->WriteFile(); if (retval == result::fail) { results.emplace_back() << "Cannot create or write to the file " << path << '\n'; } else if (retval == result::exists) { ++currentFiles; } else { results.emplace_back() << path << " saved" << '\n'; } path.replace_extension(source_ext); retval = cpp_cw->WriteFile(); if (retval == result::fail) { results.emplace_back() << "Cannot create or write to the file " << path << '\n'; } else if (retval == result::exists) { ++currentFiles; } else { results.emplace_back() << path << " saved" << '\n'; } } if (results.size()) { ttlib::cstr msg; for (auto& iter: results) { msg += iter; } if (currentFiles) { msg << '\n' << "The other " << currentFiles << " derived files have already been created"; } wxMessageBox(msg.wx_str(), "Code Generation", wxOK); } else if (currentFiles) { ttlib::cstr msg; msg << '\n' << "All " << currentFiles << " derived files have already been created"; wxMessageBox(msg, "Code Generation", wxOK); } else { wxMessageBox("There were no derived filenames specified -- nothing to generate.\n\nAdd a filename to the " "derived_filename property to generate a derived file.", "Code Generation", wxOK); } } #if defined(_DEBUG) #include "pugixml.hpp" void GenerateTmpFiles(const std::vector<ttlib::cstr>& ClassList, pugi::xml_node root) { auto project = wxGetApp().GetProject(); ttSaveCwd cwd; ttlib::ChangeDir(wxGetApp().getProjectPath()); ttlib::cstr path; std::vector<ttlib::cstr> results; ttlib::cstr source_ext(".cpp"); ttlib::cstr header_ext(".h"); if (auto& extProp = project->prop_as_string(prop_source_ext); extProp.size()) { source_ext = extProp; } if (auto& extProp = project->prop_as_string(prop_header_ext); extProp.size()) { header_ext = extProp; } for (auto& iter_class: ClassList) { for (size_t pos = 0; pos < project->GetChildCount(); ++pos) { auto form = project->GetChild(pos); if (form->prop_as_string(prop_class_name).is_sameas(iter_class)) { BaseCodeGenerator codegen; // At this point we know which form has changes, but we don't know if it's the src file, the header file, or // both, so we need to check again. ttlib::cstr base_file(form->prop_as_string(prop_base_file)); base_file.replace_extension(header_ext); base_file.make_absolute(); base_file.replace_extension(header_ext); auto h_cw = std::make_unique<FileCodeWriter>(base_file.wx_str()); codegen.SetHdrWriteCode(h_cw.get()); base_file.replace_extension(source_ext); auto cpp_cw = std::make_unique<FileCodeWriter>(base_file.wx_str()); codegen.SetSrcWriteCode(cpp_cw.get()); codegen.GenerateBaseClass(project, form); base_file.replace_extension(header_ext); bool new_hdr = (h_cw->WriteFile(true) > 0); base_file.replace_extension(source_ext); bool new_src = (cpp_cw->WriteFile(true) > 0); if (new_hdr) { path = base_file; if (auto pos_file = path.find_filename(); ttlib::is_found(pos_file)) { path.insert(pos_file, "~wxue_"); } path.replace_extension(header_ext); h_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetHdrWriteCode(h_cw.get()); path.replace_extension(source_ext); cpp_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetSrcWriteCode(cpp_cw.get()); codegen.GenerateBaseClass(project, form); path.replace_extension(header_ext); h_cw->WriteFile(); auto paths = root.append_child("paths"); base_file.replace_extension(header_ext); paths.append_child("left").text().set(base_file.c_str()); paths.append_child("left-readonly").text().set("0"); paths.append_child("right").text().set(path.c_str()); paths.append_child("right-readonly").text().set("1"); } if (new_src) { path = base_file; if (auto pos_file = path.find_filename(); ttlib::is_found(pos_file)) { path.insert(pos_file, "~wxue_"); } path.replace_extension(header_ext); h_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetHdrWriteCode(h_cw.get()); path.replace_extension(source_ext); cpp_cw = std::make_unique<FileCodeWriter>(path.wx_str()); codegen.SetSrcWriteCode(cpp_cw.get()); codegen.GenerateBaseClass(project, form); path.replace_extension(source_ext); cpp_cw->WriteFile(); auto paths = root.append_child("paths"); base_file.replace_extension(source_ext); paths.append_child("left").text().set(base_file.c_str()); paths.append_child("left-readonly").text().set("0"); paths.append_child("right").text().set(path.c_str()); paths.append_child("right-readonly").text().set("1"); } } } } } #endif // _DEBUG
32.119205
124
0.51354
[ "vector" ]
2f1b95207aa3259a730339b971aa60cb8acd6920
51,228
cpp
C++
applications/plugins/Compliant/Compliant_test/Assembly_test.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/Compliant/Compliant_test/Assembly_test.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/Compliant/Compliant_test/Assembly_test.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
#include "Compliant_test.h" #include "../assembly/AssemblyVisitor.h" #include <SofaBoundaryCondition/ConstantForceField.h> namespace sofa { using namespace modeling; using namespace component; using namespace simulation; using core::objectmodel::New; /** Test suite for matrix assembly. */ struct Assembly_test : public CompliantSolver_test { typedef odesolver::CompliantImplicitSolver OdeSolver; typedef linearsolver::LDLTSolver LinearSolver; typedef sofa::Vec3 Vec3; typedef forcefield::ConstantForceField<defaulttype::Vec3Types> ConstantForceField3; OdeSolver::SPtr complianceSolver; ///< Solver used to perform the test simulation, and which contains the actual results, to be compared with the expected ones. LinearSolver::SPtr linearSolver; ///< Auxiliary linear equation solver used by the ode solver /** Expected results of the different tests. */ struct { DenseMatrix M,C,J,P,K; Vector f,phi,dv,lambda; } expected; struct { SparseMatrix M , K; } assembled; /// assembling the system with the given params (useful to assemble the mass or stiffness matrices alone) /// @warning the scene must be initialized static SparseMatrix getAssembledImplicitMatrix( Node::SPtr node, const core::MechanicalParams* mparams ) { simulation::AssemblyVisitor assemblyVisitor(mparams); node->getContext()->executeVisitor( &assemblyVisitor ); component::linearsolver::AssembledSystem sys; assemblyVisitor.assemble(sys); // assemble system return sys.H; } /// assembling the mass matrix alone /// @warning the scene must be initialized static SparseMatrix getAssembledMassMatrix( Node::SPtr node, core::MechanicalParams mparams=*core::MechanicalParams::defaultInstance() ) { mparams.setMFactor( 1 ); mparams.setBFactor( 0 ); mparams.setKFactor( 0 ); return getAssembledImplicitMatrix( node, &mparams ); } /// assembling the stiffness matrix alone /// @warning the scene must be initialized static SparseMatrix getAssembledStiffnessMatrix( Node::SPtr node, core::MechanicalParams mparams=*core::MechanicalParams::defaultInstance() ) { mparams.setMFactor( 0 ); mparams.setBFactor( 0 ); mparams.setKFactor( 1 ); return getAssembledImplicitMatrix( node, &mparams ); } /** @defgroup ComplianceSolver_Unit_Tests ComplianceSolver Assembly Tests These methods create a scene, run a short simulation, and save the expected matrix and vector values in the expected member struct. Each test in performed by an external function which runs the test method, then compares the results with the expected results. This tests suite is designed to test assembly, and involves only unit masses and perfectly hard constraints. The following notations are used in the documentation : - \f$ I_{n} \f$ is the identity matrix of size \f$ n \times n \f$ - \f$ O_{n} \f$ is the null matrix of size \f$ n \times n \f$ */ ///@{ /** An object with internal constraints. String of particles with unit mass, connected with rigid links, undergoing two opposed forces at the ends. The particles remain at equilibrium, and the internal force is equal to the external force. The equation structure is: \f[ \left( \begin{array}{c|c} I_{3n} & -J^T \\ \hline J & O_{n-1} \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] where Jacobian J is a block-bidiagonal matrix with opposite unit vectors in each row. \param n the number of particles \post dv is null because equilibrium \post lambda intensities are all equal to the intensity of the external force */ void testHardString( unsigned n ) { Node::SPtr root = clearScene(); root->setGravity( Vec3(0,0,0) ); // The solver complianceSolver = addNew<OdeSolver>(root); // root->addObject( complianceSolver ); complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); // root->addObject( linearSolver); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // The string simulation::Node::SPtr string1 = createCompliantString( root, Vec3(0,0,0), Vec3(1,0,0), n, 1.0*n, 0. ); // Opposite forces applied to the ends ConstantForceField3::SPtr ff = New<ConstantForceField3>(); string1->addObject(ff); helper::vector<unsigned>* indices = ff->points.beginEdit(); // not managed to create a WriteAccessor with a resize function for a ConstantForceField::SetIndex helper::WriteAccessor< Data<helper::vector<Vec3> > > forces( ff->forces ); (*indices).resize(2); forces.resize(2); // pull the left-hand particle to the left (*indices)[0]= 0; forces[0]= Vec3(-1,0,0); // pull the right-hand particle to the right (*indices)[1]= n-1; forces[1]= Vec3(1,0,0); ff->points.endEdit(); sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( root ); sofa::simulation::getSimulation()->animate(root.get(),1.0); // actual results // cout<<"M = " << assembled.M << endl; // cout<<"J = " << complianceSolver->J() << endl; // cout<<"C = " << complianceSolver->C() << endl; // cout<<"P = " << complianceSolver->P() << endl; // cout<<"f = " << complianceSolver->getF().transpose() << endl; // cout<<"phi = " << complianceSolver->getPhi().transpose() << endl; // cout<<"dv = " << complianceSolver->getDv().transpose() << endl; // cout<<"lambda = " << complianceSolver->getLambda().transpose() << endl; // Expected results expected.M = expected.P = DenseMatrix::Identity( 3*n, 3*n ); expected.C = DenseMatrix::Zero(n-1,n-1); // null expected.phi = Vector::Zero(n-1); // null imposed constraint value expected.dv = Vector::Zero(3*n); // equilibrium expected.J = DenseMatrix::Zero(n-1,3*n); expected.lambda.resize(n-1); for(unsigned i=0; i<n-1; i++) { expected.J(i,3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,3*(i+1) ) = 1; expected.lambda(i) = -1; // internal forces intensity = external force } } /** An object with internal constraints, subject to a projective constraint. String of particles with unit mass, connected with rigid links, attached at one end using a FixedConstraint (projective constraint) and undergoing gravity parallel to the string The particles remain at equilibrium, and the internal force is decreasing along with the weight carried by each link. The equation structure is: \f[ \left( \begin{array}{c|c} I_{3n} & -J^T \\ \hline J & O_{n-1} \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] \param n the number of particles \post \f$ P = \left(\begin{array}{cc} O_3 \\ & I_{3(n-1)} \end{array}\right) \f$ \post dv is null because equilibrium \post lambda intensities are equal to g*(n-1), g*(n-2) ... , g */ void testAttachedHardString( unsigned n ) { Node::SPtr root = clearScene(); SReal g=10; root->setGravity( Vec3(g,0,0) ); // The solver complianceSolver = addNew<OdeSolver>(root); complianceSolver->storeDynamicsSolution(true); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); // complianceSolver->debug.setValue(true); linearSolver = addNew<LinearSolver>(root); // linearSolver->debug.setValue(true); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // The string simulation::Node::SPtr string1 = createCompliantString( root, Vec3(0,0,0), Vec3(1,0,0), n, 1.0*n, 0. ); // attached FixedConstraint3::SPtr fixed1 = addNew<FixedConstraint3>(string1); sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( root ); sofa::simulation::getSimulation()->animate(root.get(),1.0); // cerr<<"lambda = " << complianceSolver->getLambda().transpose() << endl; // cerr<<"f = " << complianceSolver->getF().transpose() << endl; // Expected results expected.M = expected.P = DenseMatrix::Identity( 3*n, 3*n ); for(unsigned i=0; i<3; i++) expected.P(i,i)=0; // fixed point expected.C = DenseMatrix::Zero(n-1,n-1); // null compliance expected.phi = Vector::Zero(n-1); // null imposed constraint value expected.dv = Vector::Zero(3*n); // equilibrium expected.J = DenseMatrix::Zero(n-1,3*n); expected.lambda.resize(n-1); for(unsigned i=0; i<n-1; i++) { expected.J(i,3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,3*(i+1) ) = 1; expected.lambda(i) = -g*(n-1-i); } } /** An object with internal constraints, subject to an additional constraint. String of particles with unit mass, connected with rigid links, attached at one end using a hard constraint and undergoing gravity parallel to the string The particles remain at equilibrium, and the internal force is decreasing along with the weight carried by each link. The equation structure is: \f[ \left( \begin{array}{c|c|c} I_{3n} & -J_1^T & -J_2^T\\ \hline J_1 & O_{n-1} & \\ \hline J_2 & & O_1 \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] where Jacobian \f$ J_1 \f$ corresponds to the string internal constraints, and Jacobian \f$J_2 \f$ corresponds to the attachment of the string to a fixed point. \param n the number of particles \post dv is null because equilibrium \post lambda intensities are decreasing within the string, then there is the weight of the string: -g*(n-1), ... , -g, g*n */ void testConstrainedHardString( unsigned n ) { Node::SPtr root = clearScene(); SReal g=10; root->setGravity( Vec3(g,0,0) ); // The solver complianceSolver = addNew<OdeSolver>(root); complianceSolver->storeDynamicsSolution(true); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearSolver = addNew<LinearSolver>(root); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // The string Vec3 startPoint(0,0,0); simulation::Node::SPtr string1 = createCompliantString( root, startPoint, Vec3(1,0,0), n, 1.0*n, 0. ); //-------- fix a particle using a constraint: map the distance of the particle to its initial position, and constrain this to 0 std::string nodeName = "fixDistance_"; Node::SPtr fixNode = string1->createChild(nodeName + "Node"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extensions->setName(nodeName+"DOF"); fixNode->addObject(extensions); DistanceFromTargetMapping31::SPtr distanceMapping = New<DistanceFromTargetMapping31>(); MechanicalObject3* DOF = down_cast<MechanicalObject3>(string1->getMechanicalState()); assert(DOF != NULL); distanceMapping->setModels(DOF,extensions.get()); fixNode->addObject( distanceMapping ); distanceMapping->setName(nodeName+"Mapping"); distanceMapping->createTarget( 0, startPoint, 0.0 ); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); fixNode->addObject(compliance); compliance->setName(nodeName+"Compliance"); compliance->compliance.setValue(0); // ================= Expected results expected.M = expected.P = DenseMatrix::Identity( 3*n, 3*n ); expected.C = DenseMatrix::Zero(n,n); // null expected.phi = Vector::Zero(n-1); // null imposed constraint value expected.dv = Vector::Zero(3*n); // equilibrium expected.J = DenseMatrix::Zero(n,3*n); expected.lambda.resize(n); for(unsigned i=0; i<n-1; i++) { expected.J(i,3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,3*(i+1) ) = 1; expected.lambda(i) = -g*(n-1-i); } expected.J(n-1,0 ) = 1; // the constrained endpoint expected.lambda(n-1) = -g*n; // cerr<<"expected C = " << endl << DenseMatrix(expected.C) << endl; // cerr<<"expected dv = " << expected.dv.transpose() << endl; // cerr<<"expected lambda = " << expected.lambda.transpose() << endl; // ================= Run sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( root ); sofa::simulation::getSimulation()->animate(root.get(),1.0); // actual results // cerr<<"M = " << endl << DenseMatrix(assembled.M) << endl; // cerr<<"result, J = " << endl << DenseMatrix(complianceSolver->J()) << endl; // cerr<<"result, C = " << endl << DenseMatrix(complianceSolver->C()) << endl; // cerr<<"P = " << endl << DenseMatrix(complianceSolver->P()) << endl; // cerr<<"f = " << complianceSolver->getF().transpose() << endl; // cerr<<"phi = " << complianceSolver->getPhi().transpose() << endl; // cerr<<"dv = " << complianceSolver->getDv().transpose() << endl; // cerr<<"lambda = " << complianceSolver->getLambda().transpose() << endl; // cerr<<"lambda - expected.lambda = " << (complianceSolver->getLambda()-expected.lambda).transpose() << endl; } /** An object with internal constraints, connected using an additional constraint to a fixed point out of the scope of the solver. In practical examples, a point out of the scope of the solver may be controlled by the user using the mouse tracker. String of particles with unit mass, connected with rigid links, attached at one end using a hard constraint and undergoing gravity parallel to the string The particles remain at equilibrium, and the internal force is decreasing along with the weight carried by each link. The equation structure is: \f[ \left( \begin{array}{c|c|c} I_{3n} & -J_1^T & -J_2^T\\ \hline J_1 & O_{n-1} & \\ \hline J_2 & & O_1 \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] where Jacobian \f$ J_1 \f$ corresponds to the string internal constraints, and Jacobian \f$J_2 \f$ corresponds to the attachment of the string to a fixed point. \param n the number of particles \post dv is null because equilibrium \post lambda intensities are decreasing within the string, then there is the total weight of the string: -g*(n-1),... , -g, g*n */ void testExternallyConstrainedHardString( unsigned n ) { Node::SPtr root = clearScene(); SReal g=10; root->setGravity( Vec3(g,0,0) ); // ======== object out of scope Node::SPtr outOfScope = root->createChild("outOfScope"); MechanicalObject3::SPtr outOfScopeDOF = addNew<MechanicalObject3>(outOfScope,"outOfScopeDOF"); outOfScopeDOF->resize(1); MechanicalObject3::WriteVecCoord x = outOfScopeDOF->writePositions(); x[0] = Vec3(-1,0,0); // ======== object controlled by the solver Node::SPtr solverObject = root->createChild("solverObject"); // The solver complianceSolver = addNew<OdeSolver>(solverObject); complianceSolver->storeDynamicsSolution(true); // complianceSolver->f_printLog.setValue(true); // complianceSolver->debug.setValue(true); linearSolver = addNew<LinearSolver>(solverObject); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(solverObject); (void) response; // ======== string Node::SPtr string1 = createCompliantString( solverObject, Vec3(0,0,0), Vec3(1,0,0), n, 1.0*n, 0 ); // .======= Node with multiple parents to create an interaction using a MultiMapping Node::SPtr commonChild = string1->createChild("commonChild"); outOfScope->addChild(commonChild); MechanicalObject3::SPtr mappedDOF = addNew<MechanicalObject3>(commonChild); // to contain particles from the two strings SubsetMultiMapping3_to_3::SPtr multimapping = New<SubsetMultiMapping3_to_3>(); multimapping->setName("ConnectionMultiMapping"); multimapping->addInputModel( string1->getMechanicalState() ); multimapping->addInputModel( outOfScope->getMechanicalState() ); multimapping->addOutputModel( mappedDOF.get() ); multimapping->addPoint( string1->getMechanicalState(), 0 ); // first particle of string1 multimapping->addPoint( outOfScope->getMechanicalState(), 0 ); // with out of scope particle commonChild->addObject(multimapping); // ..======== Node to handle the extension of the interaction link Node::SPtr extension_node = commonChild->createChild("ConnectionExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); extensions->setName("extensionsDOF"); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); edgeSet->addEdge(0,1); DistanceMapping31::SPtr extensionMapping = New<DistanceMapping31>(); extensionMapping->setModels(mappedDOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName("ConnectionExtension_mapping"); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->setName("connectionCompliance"); compliance->compliance.setValue(0); // ================= Expected results expected.M = expected.P = DenseMatrix::Identity( 3*n, 3*n ); expected.C = DenseMatrix::Zero(n,n); // null expected.phi = Vector::Zero(n-1); // null imposed constraint value expected.dv = Vector::Zero(3*n); // equilibrium expected.J = DenseMatrix::Zero(n,3*n); expected.lambda.resize(n); for(unsigned i=0; i<n-1; i++) { expected.J(i,3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,3*(i+1) ) = 1; expected.lambda(i) = -g*(n-1-i); } // the constrained endpoint expected.J( n-1, 0 ) = 1; expected.lambda(n-1) = -g*n; // cerr<<"expected J = " << endl << DenseMatrix(expected.J) << endl; // cerr<<"expected dv = " << expected.dv.transpose() << endl; // cerr<<"expected lambda = " << expected.lambda.transpose() << endl; // ================= Run sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( solverObject ); sofa::simulation::getSimulation()->animate(root.get(),1.0); // actual results // cerr<<"M = " << endl << DenseMatrix(assembled.M) << endl; // cerr<<"result, J = " << endl << DenseMatrix(complianceSolver->J()) << endl; // cerr<<"result, C = " << endl << DenseMatrix(complianceSolver->C()) << endl; // cerr<<"P = " << endl << DenseMatrix(complianceSolver->P()) << endl; // cerr<<"f = " << complianceSolver->getF().transpose() << endl; // cerr<<"phi = " << complianceSolver->getPhi().transpose() << endl; // cerr<<"dv = " << complianceSolver->getDv().transpose() << endl; // cerr<<"lambda = " << complianceSolver->getLambda().transpose() << endl; // cerr<<"lambda - expected.lambda = " << (complianceSolver->getLambda()-expected.lambda).transpose() << endl; } /** Two objects of the same type with internal constraints, connected by a constraint. String of particles with unit mass, connected with rigid links, attached at one end using a FixedConstraint (projective constraint) and undergoing gravity parallel to the string The string is composed of two strings connected by a constraint using MultiMapping. The particles remain at equilibrium, and the internal force is decreasing along with the weight carried by each link. The equation structure is: \f[ \left( \begin{array}{c|c|c|c|c} I_{3n} \\ \hline & I_{3n} \\ \hline J_1 & & O_{n-1} \\ \hline & J_2 & & O_{n-1} \\ \hline \multicolumn{2}{c|}{J_3} & & & O_1 \\ \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] where Jacobian \f$ J_1 \f$ corresponds to the internal constraints of the first string, Jacobian \f$ J_2 \f$ corresponds to the internal constraints of the second string, and Jacobian \f$J_3 \f$ corresponds to the attachment of the strings together, and the (anti-)symmetric upper part is skipped for convenience. \param n the number of particles in each sub-string. The total number is 2*n. \post \f$ P= \left( \begin{array}{c|c|c} O_3 & & \\ \hline & I_{3(n-1)} & \\ \hline & & I_{3(n-1)} \end{array} \right)\f$ \post dv is null because equilibrium \post lambda intensities are: (1) decreasing within first string, (2) decreasing within second string, (3) weight of the second string to connect it to the first string: g*(2*n-1),... g*(n), g*(*n-2),... g, g*(*n-1) */ void testAttachedConnectedHardStrings( unsigned n ) { Node::SPtr root = clearScene(); SReal g=10; root->setGravity( Vec3(g,0,0) ); // The solver complianceSolver = New<OdeSolver>(); root->addObject( complianceSolver ); complianceSolver->storeDynamicsSolution(true); linearSolver = New<LinearSolver>(); root->addObject( linearSolver); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // ======== strings Node::SPtr string1 = createCompliantString( root, Vec3(0,0,0), Vec3(1,0,0), n, 1.0*n, 0 ); Node::SPtr string2 = createCompliantString( root, Vec3(2,0,0), Vec3(3,0,0), n, 1.0*n, 0 ); // string1 is attached FixedConstraint3::SPtr fixed1 = New<FixedConstraint3>(); string1->addObject( fixed1 ); // ======== Node with multiple parents to create an interaction using a MultiMapping Node::SPtr commonChild = string1->createChild("commonChild"); string2->addChild(commonChild); MechanicalObject3::SPtr mappedDOF = New<MechanicalObject3>(); // to contain particles from the two strings commonChild->addObject(mappedDOF); mappedDOF->setName("multiMappedDOF"); SubsetMultiMapping3_to_3::SPtr multimapping = New<SubsetMultiMapping3_to_3>(); multimapping->setName("ConnectionMultiMapping"); multimapping->addInputModel( string1->getMechanicalState() ); multimapping->addInputModel( string2->getMechanicalState() ); multimapping->addOutputModel( mappedDOF.get() ); multimapping->addPoint( string1->getMechanicalState(), n-1 ); // last particle of string1 multimapping->addPoint( string2->getMechanicalState(), 0 ); // with first of string2 commonChild->addObject(multimapping); // ======== Node to handle the extension of the interaction link Node::SPtr extension_node = commonChild->createChild("ConnectionExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); extensions->setName("extensionsDOF"); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); edgeSet->addEdge(0,1); DistanceMapping31::SPtr extensionMapping = New<DistanceMapping31>(); extensionMapping->setModels(mappedDOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName("ConnectionExtension_mapping"); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->compliance.setName("connectionCompliance"); compliance->compliance.setValue(0); // Expected results expected.M = expected.P = DenseMatrix::Identity( 6*n, 6*n ); for(unsigned i=0; i<3; i++) expected.P(i,i)=0; // fixed point expected.C = DenseMatrix::Zero(2*n-1,2*n-1); // null expected.phi = Vector::Zero(2*n-1); // null imposed constraint value expected.dv = Vector::Zero(6*n); // equilibrium expected.J = DenseMatrix::Zero(2*n-1,6*n); expected.lambda.resize(2*n-1); // first string for(unsigned i=0; i<n-1; i++) { expected.J(i,3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,3*(i+1) ) = 1; expected.lambda(i) = -g*(2*n-1-i); } // second string for(unsigned i=0; i<n-1; i++) { expected.J((n-1)+i,3*(n+i ) ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J((n-1)+i,3*(n+i+1) ) = 1; expected.lambda((n-1)+i) = -g*(n-1-i); } // the connection constraint between the two strings is the last constraint expected.J(2*n-2,3*(n-1) ) = -1; // last particle of the first string expected.J(2*n-2,3*(n ) ) = 1; // with first particle of the second string expected.lambda(2*n-2) = -g*(n); // weight of the second string // cerr<<"expected J = " << endl << DenseMatrix(expected.J) << endl; // cerr<<"expected lambda = " << expected.lambda.transpose() << endl; sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( root ); // for( unsigned i=0; i<multimapping->getJs()->size(); i++ ){ // cerr<<"multimapping Jacobian " << i << ": " << endl << *(*multimapping->getJs())[i] << endl; // } sofa::simulation::getSimulation()->animate(root.get(),1.0); // actual results // cerr<<"M = " << endl << DenseMatrix(assembled.M) << endl; // cerr<<"J = " << endl << DenseMatrix(complianceSolver->J()) << endl; // cerr<<"C = " << endl << DenseMatrix(complianceSolver->C()) << endl; // cerr<<"P = " << endl << DenseMatrix(complianceSolver->P()) << endl; // cerr<<"f = " << endl << complianceSolver->getF().transpose() << endl; // cerr<<"phi = " << complianceSolver->getPhi().transpose() << endl; // cerr<<"actual dv = " << complianceSolver->getDv().transpose() << endl; // cerr<<"actual lambda = " << complianceSolver->getLambda().transpose() << endl; } /** Two objects of different types, connected by a constraint. Rigid connected to particles. A hard string of particles is attached on the left, and connected to a rigid body on the right. The connection is created using a point mapped from the rigid body and constraint between this point and the last point of the string. The equation structure is: \f[ \left( \begin{array}{c|c|c|c} I_{3n} \\ \hline & I_6 \\ \hline J_1 & & O_{n-1} \\ \hline \multicolumn{2}{c|}{J_2} & & O_3 \end{array} \right) \left( \begin{array}{c} dv \\ \lambda \end{array} \right) = \left( \begin{array}{c} f_e \\ \phi \end{array} \right) \f] where Jacobian \f$ J_1 \f$ corresponds to the internal constraints of the first string, Jacobian \f$ J_2 \f$ corresponds to the attachment of the string to the rigid object, and the (anti-)symmetric upper part is skipped for convenience. \post \f$ P= \left( \begin{array}{c|c|c} O_3 & & \\ \hline & I_{3(n-1)} & \\ \hline & & I_{6} \end{array} \right)\f$ \post dv is null because equilibrium \post lambda intensities are equal to g*(n-1), g*(n-2) ... , g */ void testRigidConnectedToString( unsigned n ) { Node::SPtr root = clearScene(); SReal g=10; root->setGravity( Vec3(g,0,0) ); // The solver complianceSolver = New<OdeSolver>(); root->addObject( complianceSolver ); complianceSolver->storeDynamicsSolution(true); linearSolver = New<LinearSolver>(); root->addObject( linearSolver); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // ========= The rigid object simulation::Node::SPtr rigid = root->createChild("rigid"); MechanicalObjectRigid3::SPtr rigidDOF = addNew<MechanicalObjectRigid3>(rigid); rigidDOF->resize(1); MechanicalObjectRigid3::WriteVecCoord x = rigidDOF->writePositions(); x[0].getCenter() = Vec3(n,0,0); UniformMassRigid3::SPtr rigidMass = addNew<UniformMassRigid3>(rigid); // .========= Particle attached to the rigid object simulation::Node::SPtr particleOnRigid = rigid->createChild("particleOnRigid"); MechanicalObject3::SPtr particleOnRigidDOF = addNew<MechanicalObject3>(particleOnRigid); particleOnRigidDOF->resize(1); RigidMappingRigid3_to_3::SPtr particleOnRigidMapping = addNew<RigidMappingRigid3_to_3>(particleOnRigid); particleOnRigidMapping->setModels(rigidDOF.get(),particleOnRigidDOF.get()); // ========= The string simulation::Node::SPtr string1 = createCompliantString( root, Vec3(0,0,0), Vec3(1,0,0), n, 1.0*n, 0. ); // Fix the first particle of the string FixedConstraint3::SPtr fixed1 = New<FixedConstraint3>(); string1->addObject( fixed1 ); // ..======== Mixed subset containing the last particle of the string and the particle attached to the rigid object simulation::Node::SPtr pointPair = particleOnRigid->createChild("pointPair"); string1->addChild(pointPair); // two parents: particleOnRigid and string1 MechanicalObject3::SPtr pointPairDOF = addNew<MechanicalObject3>(pointPair); SubsetMultiMapping3_to_3::SPtr pointPairMapping = addNew<SubsetMultiMapping3_to_3>(pointPair); pointPairMapping->addInputModel(string1->mechanicalState); pointPairMapping->addInputModel(particleOnRigid->mechanicalState); pointPairMapping->addOutputModel(pointPair->mechanicalState); pointPairMapping->addPoint(string1->mechanicalState,n-1 ); // last particle pointPairMapping->addPoint(particleOnRigid->mechanicalState,0 ); // ...======== Distance between the particles in pointPair Node::SPtr extension = pointPair->createChild("extension"); MechanicalObject1::SPtr extensionDOF = addNew<MechanicalObject1>(extension); EdgeSetTopologyContainer::SPtr extensionEdgeSet = addNew<EdgeSetTopologyContainer>(extension); extensionEdgeSet->addEdge(0,1); DistanceMapping31::SPtr extensionMapping = addNew<DistanceMapping31>(extension); extensionMapping->setModels(pointPairDOF.get(),extensionDOF.get()); // helper::WriteAccessor< Data< vector< Real > > > restLengths( extensionMapping->f_restLengths ); // restLengths.resize(1); // restLengths[0] = 1.0; rigidDOF->forceMask.assign( rigidDOF->getSize(), true ); particleOnRigidDOF->forceMask.assign( particleOnRigidDOF->getSize(), true ); pointPairDOF->forceMask.assign( pointPairDOF->getSize(), true ); extensionDOF->forceMask.assign( extensionDOF->getSize(), true ); UniformCompliance1::SPtr extensionCompliance = addNew<UniformCompliance1>(extension); extensionCompliance->compliance.setValue(0); // ***** Expected results unsigned nM = 3*n+6; // n particles + 1 rigid unsigned nC = n; // n-1 in the string + 1 to connect the string to the rigid expected.M = expected.P = DenseMatrix::Identity( nM,nM ); for(unsigned i=0; i<3; i++) expected.P(6+i,6+i)=0; // fixed point expected.dv = Vector::Zero(nM); // equilibrium expected.C = DenseMatrix::Zero(nC,nC); // null compliance expected.phi = Vector::Zero(nC); // null imposed constraint value expected.J = DenseMatrix::Zero(nC,nM); expected.lambda.resize(nC); // string for(unsigned i=0; i<nC-1; i++) { expected.J(i,6+3* i ) = -1; // block-bidiagonal matrix with opposite unit vectors in each row expected.J(i,6+3*(i+1) ) = 1; expected.lambda(i) = -g*(nC-i); // weight: nC-i-1 particle + the rigid } // the connection constraint between the two strings is the last constraint expected.J( nC-1, 6+3*(n-1) ) = -1; // last particle of the first string expected.J( nC-1, 0 ) = 1; // with the rigid translation expected.lambda(nC-1) = -g; // weight of the rigid // cerr<<"expected J = " << endl << DenseMatrix(expected.J) << endl; // cerr<<"expected P = " << endl << DenseMatrix(expected.P) << endl; // cerr<<"expected lambda = " << expected.lambda.transpose() << endl; // ***** Perform simulation sofa::simulation::getSimulation()->init(root.get()); assembled.M = getAssembledMassMatrix( root ); sofa::simulation::getSimulation()->animate(root.get(),1.0); // actual results // cerr<<"M = " << endl << DenseMatrix(assembled.M) << endl; // cerr<<"J = " << endl << DenseMatrix(complianceSolver->J()) << endl; // cerr<<"C = " << endl << DenseMatrix(complianceSolver->C()) << endl; // cerr<<"P = " << endl << DenseMatrix(complianceSolver->P()) << endl; // cerr<<"f = " << endl << complianceSolver->getF().transpose() << endl; // cerr<<"phi = " << complianceSolver->getPhi().transpose() << endl; // cerr<<"actual dv = " << complianceSolver->getDv().transpose() << endl; // cerr<<"actual lambda = " << complianceSolver->getLambda().transpose() << endl; } ///@} /** A spring composed by two independent dofs + subsetMapping to bring them in the same mechanical object + extensionMapping + uniformCompliance Do we obtain the same stiffness matrix as a regular spring? */ void testDecomposedString( SReal stiffness = 1e4 ) { /////// SUBSETMULTIMAPPING + DISTANCEMAPPING Node::SPtr root = clearScene(); root->setGravity( Vec3(0,0,0) ); const Vec3 p0(0,0,0), p1(2,0,0); // make it deformed at start, such as it creates a force and geometric stiffness // The solver complianceSolver = addNew<OdeSolver>(root); complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); linearsolver::LDLTResponse::SPtr response = addNew<linearsolver::LDLTResponse>(root); (void) response; // ========= DOF1 simulation::Node::SPtr node1 = root->createChild("node1"); MechanicalObject3::SPtr dof1 = addNew<MechanicalObject3>(node1); dof1->resize(1); MechanicalObject3::WriteVecCoord x1 = dof1->writePositions(); x1[0] = p0; UniformMass3::SPtr mass1 = addNew<UniformMass3>(node1); mass1->setTotalMass( 1 ); // ========= DOF2 simulation::Node::SPtr node2 = root->createChild("node2"); MechanicalObject3::SPtr dof2 = addNew<MechanicalObject3>(node2); dof2->resize(1); MechanicalObject3::WriteVecCoord x2 = dof2->writePositions(); x2[0] = p1; UniformMass3::SPtr mass2 = addNew<UniformMass3>(node2); mass1->setTotalMass( 1 ); // =========== common DOFs simulation::Node::SPtr subset_node = node1->createChild( "SubsetNode"); node2->addChild( subset_node ); MechanicalObject3::SPtr allDofs = addNew<MechanicalObject3>(subset_node); SubsetMultiMapping3_to_3::SPtr subsetMapping = addNew<SubsetMultiMapping3_to_3>(subset_node); subsetMapping->addInputModel( dof1.get() ); subsetMapping->addInputModel( dof2.get() ); subsetMapping->addOutputModel( allDofs.get() ); subsetMapping->addPoint( dof1.get(), 0 ); subsetMapping->addPoint( dof2.get(), 0 ); // ========= extension simulation::Node::SPtr extension_node = subset_node->createChild( "ExtensionNode"); MechanicalObject1::SPtr extensions = addNew<MechanicalObject1>(extension_node); EdgeSetTopologyContainer::SPtr edgeSet = addNew<EdgeSetTopologyContainer>(extension_node); edgeSet->addEdge(0,1); DistanceMapping31::SPtr extensionMapping = addNew<DistanceMapping31>(extension_node); extensionMapping->setModels( allDofs.get(), extensions.get() ); helper::vector<SReal> restLengths(1); restLengths[0]=1; // make it deformed at start, such as it creates a force and geometric stiffness extensionMapping->f_restLengths.setValue( restLengths ); UniformCompliance1::SPtr compliance = addNew<UniformCompliance1>(extension_node); compliance->compliance.setValue(1.0/stiffness); compliance->isCompliance.setValue(false); // ***** Perform initialization sofa::simulation::getSimulation()->init(root.get()); // ***** Perform simulation sofa::simulation::getSimulation()->animate(root.get(),1.0); // after animation, the force has been computed as well as the geometric stiffness SparseMatrix SubsetMultimapping_H = complianceSolver->H(); /////// DISTANCEMULTIMAPPING root = clearScene(); root->setGravity( Vec3(0,0,0) ); // The solver complianceSolver = addNew<OdeSolver>(root); // complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); response = addNew<linearsolver::LDLTResponse>(root); // ========= DOF1 node1 = root->createChild("node1"); dof1 = addNew<MechanicalObject3>(node1); dof1->resize(1); MechanicalObject3::WriteVecCoord x3 = dof1->writePositions(); x3[0] = p0; mass1 = addNew<UniformMass3>(node1); mass1->setTotalMass( 1 ); // ========= DOF2 node2 = root->createChild("node2"); dof2 = addNew<MechanicalObject3>(node2); dof2->resize(1); MechanicalObject3::WriteVecCoord x4 = dof2->writePositions(); x4[0] = p1; mass2 = addNew<UniformMass3>(node2); mass1->setTotalMass( 1 ); // =========== common DOFs extension_node = node1->createChild( "ExtensionNode"); node2->addChild( extension_node ); extensions = addNew<MechanicalObject1>(extension_node); edgeSet = addNew<EdgeSetTopologyContainer>(extension_node); edgeSet->addEdge(0,1); DistanceMultiMapping31::SPtr distanceMultiMapping = addNew<DistanceMultiMapping31>(extension_node); distanceMultiMapping->addInputModel( dof1.get() ); distanceMultiMapping->addInputModel( dof2.get() ); distanceMultiMapping->addOutputModel( extensions.get() ); distanceMultiMapping->addPoint( dof1.get(), 0 ); distanceMultiMapping->addPoint( dof2.get(), 0 ); distanceMultiMapping->f_restLengths.setValue( restLengths ); compliance = addNew<UniformCompliance1>(extension_node); compliance->compliance.setValue(1.0/stiffness); compliance->isCompliance.setValue(false); // ***** Perform initialization sofa::simulation::getSimulation()->init(root.get()); // ***** Perform simulation sofa::simulation::getSimulation()->animate(root.get(),1.0); // after animation, the force has been computed as well as the geometric stiffness SparseMatrix DistanceMultiMapping_H = complianceSolver->H(); ///////// SIMPLE FORCEFIELD SPRING root = clearScene(); root->setGravity( Vec3(0,0,0) ); complianceSolver = addNew<OdeSolver>(root); complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); response = addNew<linearsolver::LDLTResponse>(root); dof1 = addNew<MechanicalObject3>(root); dof1->resize(2); MechanicalObject3::WriteVecCoord x5 = dof1->writePositions(); x5[0] = p0; x5[1] = p1; mass1 = addNew<UniformMass3>(root); mass1->setMass( 1 ); StiffSpringForceField3::SPtr ff = addNew<StiffSpringForceField3>(root); ff->addSpring(0,1,stiffness,0,1); sofa::simulation::getSimulation()->init(root.get()); sofa::simulation::getSimulation()->animate(root.get(),1.0); SparseMatrix SimpleForceField_H = complianceSolver->H(); ///////// INTERACTIONFORCEFIELD SPRING root = clearScene(); root->setGravity( Vec3(0,0,0) ); // The solver complianceSolver = addNew<OdeSolver>(root); // complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); response = addNew<linearsolver::LDLTResponse>(root); // ========= DOF1 node1 = root->createChild("node1"); dof1 = addNew<MechanicalObject3>(node1); dof1->setName("dof1"); dof1->resize(1); MechanicalObject3::WriteVecCoord x6 = dof1->writePositions(); x6[0] = p0; mass1 = addNew<UniformMass3>(node1); mass1->setTotalMass( 1 ); // ========= DOF2 node2 = root->createChild("node2"); dof2 = addNew<MechanicalObject3>(node2); dof2->setName("dof2"); dof2->resize(1); MechanicalObject3::WriteVecCoord x7 = dof2->writePositions(); x7[0] = p1; mass2 = addNew<UniformMass3>(node2); mass1->setTotalMass( 1 ); ff = New<StiffSpringForceField3>(dof1.get(), dof2.get()); root->addObject(ff); ff->addSpring(0,0,stiffness,0,1); sofa::simulation::getSimulation()->init(root.get()); sofa::simulation::getSimulation()->animate(root.get(),1.0); SparseMatrix InteractionForceField_H = complianceSolver->H(); ///////// SIMPLE DISTANCE MAPPING // build a spring stiffness matrix from a simple mapping to test the values root = clearScene(); root->setGravity( Vec3(0,0,0) ); complianceSolver = addNew<OdeSolver>(root); complianceSolver->storeDynamicsSolution(true); linearSolver = addNew<LinearSolver>(root); complianceSolver->alpha.setValue(1.0); complianceSolver->beta.setValue(1.0); response = addNew<linearsolver::LDLTResponse>(root); createCompliantString( root, p0, p1, 2, 2, 1.0/stiffness, false, 1 ); sofa::simulation::getSimulation()->init(root.get()); sofa::simulation::getSimulation()->animate(root.get(),1.0); SparseMatrix SimpleDistanceMapping_H = complianceSolver->H(); ///////// COMPARISONS ASSERT_TRUE( matricesAreEqual( SimpleForceField_H, SubsetMultimapping_H ) ); ASSERT_TRUE( matricesAreEqual( SimpleForceField_H, DistanceMultiMapping_H ) ); ASSERT_TRUE( matricesAreEqual( SimpleForceField_H, SimpleDistanceMapping_H ) ); ASSERT_TRUE( matricesAreEqual( SimpleForceField_H, InteractionForceField_H ) ); } ///@} }; //**************************************************************************************************** TEST_F( Assembly_test, testHardString ) { unsigned numParticles=3; ::testing::Message() << "Assembly_test: hard string of " << numParticles << " particles"; testHardString(numParticles); ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // cout<<"testHardString results compared"<< endl; } TEST_F( Assembly_test, testAttachedHardString ) { unsigned numParticles=3; ::testing::Message() << "Assembly_test: hard string of " << numParticles << " particles attached using a projective constraint (FixedConstraint)"; testAttachedHardString(numParticles); ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // cout<<"testAttachedHardString results compared"<< endl; } TEST_F( Assembly_test, testConstrainedHardString ) { unsigned numParticles=4; ::testing::Message() << "Assembly_test: hard string of " << numParticles << " particles attached using a distance constraint"; testConstrainedHardString(numParticles); ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // cout<<"testConstrainedHardString results compared"<< endl; } TEST_F( Assembly_test, testExternallyConstrainedHardString ) { unsigned numParticles=2; ::testing::Message() << "Assembly_test: hard string of " << numParticles << " particles attached using a constraint with an out-of-scope particle"; testExternallyConstrainedHardString(numParticles); ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // // cout<<"testExternallyConstrainedHardString results compared"<< endl; } TEST_F( Assembly_test, testAttachedConnectedHardStrings ) { unsigned numParticles=2; ::testing::Message() << "Assembly_test: hard strings of " << numParticles << " particles connected using a MultiMapping"; testAttachedConnectedHardStrings(numParticles); ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // cout<<"testAttachedConnectedHardString results compared"<< endl; } TEST_F( Assembly_test, testRigidConnectedToString ) { unsigned numParticles=2; ::testing::Message() << "Assembly_test: hard string of " << numParticles << " particles connected to a rigid"; testRigidConnectedToString(numParticles); // cerr<<"expected.M = " << endl << expected.M << endl; // cerr<<"assembled.M = " << endl << assembled.M << endl; ASSERT_TRUE(matricesAreEqual( expected.M, assembled.M )); ASSERT_TRUE(matricesAreEqual( expected.P, complianceSolver->P() )); ASSERT_TRUE(matricesAreEqual( expected.J, complianceSolver->J() )); ASSERT_TRUE(matricesAreEqual( expected.C, complianceSolver->C() )); ASSERT_TRUE(vectorsAreEqual( expected.dv, complianceSolver->getDv() )); ASSERT_TRUE(vectorsAreEqual( expected.lambda, complianceSolver->getLambda() )); // cout<<"testRigidConnectedToString results compared"<< endl; // cout<<"all tests done" << endl; } TEST_F( Assembly_test, testDecomposedString ) { testDecomposedString(); } } // sofa
43.561224
224
0.624034
[ "object", "vector" ]
2f208cc339448fd445ec530962bf809aec079f8d
17,532
hpp
C++
ntree/ntree.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
1
2015-06-14T15:54:27.000Z
2015-06-14T15:54:27.000Z
ntree/ntree.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
ntree/ntree.hpp
degarashi/boomstick
55dc5bfcfad6119d8401f578f91df7bbd44c192b
[ "MIT" ]
null
null
null
#pragma once #include "spinner/bits.hpp" #include "spinner/common.hpp" #include "spinner/resmgr.hpp" #include "../common.hpp" #include <stack> namespace boom { namespace ntree { using MortonId = uint32_t; using MortonId_OP = spn::Optional<MortonId>; using PositionId = uint32_t; using CacheId = uint32_t; struct VolEntry { CacheId cacheId; //! 各軸の数値をビットフィールドで記録 (Dim依存) PositionId posMin, posMax; }; using VolVec = spn::noseq_vec<VolEntry>; class CTreeObjStack; //! シングルラインCTreeエントリ class CTreeEntry { private: VolVec _olist; //!< セルに内包されたオブジェクトリスト int _nLower; //!< このセルより下に幾つオブジェクトが存在するか protected: void _remObj(VolVec& v, CacheId cid); public: //! 巡回時にはこのスタックを使う using ItrStack = CTreeObjStack; CTreeEntry(); void clear(); void addObj(CMask mask, const VolEntry& ve); bool remObj(CMask mask, CacheId cid); bool isNodeEmpty() const; //!< このノード単体が空か? bool isEmpty() const; //!< 下位ノードを含めて空か? const VolVec& getObjList() const; int getLowerCount() const; void incrementLowerCount(); void decrementLowerCount(); }; //! 木を巡回する際に手持ちのオブジェクトを保持 class CTreeObjStack { struct Ent { int nPop; //!< pop時に幾つpopするか int baseIdx; }; using Stack = std::stack<Ent>; Stack _nstk; VolVec _obj; public: CTreeObjStack(); void addBlock(const CTreeEntry& ent, bool bAdd); void addBlock(const VolVec& ol, bool bAdd); /*! \param[in] bWirte 下層レイヤーのマス目有効フラグ \param[in] centerId */ template <class DIM> void classify(const bool (&bWrite)[DIM::N_LayerSize], typename DIM::Id centerId) { auto cur = getObj(); const int stride = std::get<1>(cur); // 処理途中で配列が再アロケートされることを防ぐ int wcur = _obj.size(); // 実際に書き込まれたオブジェクトを示すカーソル _obj.resize(wcur + stride * DIM::N_LayerSize); // 振り分けるポインタを一本の配列に一時的に格納 std::unique_ptr<const VolEntry*> da(new const VolEntry*[stride * DIM::N_LayerSize]); const VolEntry** daP[DIM::N_LayerSize]; for(int i=0 ; i<DIM::N_LayerSize ; i++) daP[i] = &da.get()[i*stride]; // オブジェクトを振り分け cur = getObj(); DIM::Classify(daP, std::get<0>(cur), stride, centerId); // 枝の有効リストを見ながらVolEntry実体をコピー, タグ付け for(int i=0 ; i<DIM::N_LayerSize ; i++) { if(bWrite[i]) { auto base = da.get() + i*stride; // daPに幾つオブジェクトが割り振られたか int nObj = daP[i] - base; _nstk.push(Ent{nObj, wcur}); for(int j=0 ; j<nObj ; j++) _obj[wcur++] = *(*base++); } } // 本来の配列の長さに設定 AssertP(Trap, wcur <= static_cast<int>(_obj.size())) _obj.resize(wcur); } bool isTopEmpty() const; void popBlock(); //! スタックトップのVolEntryリストを受け取る std::tuple<const VolEntry*, int> getObj() const; }; class CTreeObjStackM; //! マップ用オブジェクトを含むCTreeエントリ class CTreeEntryM : public CTreeEntry { private: VolVec _mlist; using base_t = CTreeEntry; public: using ItrStack = CTreeObjStackM; static bool IsTypeB(CMask mask); void addObj(CMask mask, const VolEntry& v); bool remObj(CMask mask, CacheId cid); void clear(); bool isNodeEmpty() const; bool isEmpty() const; const VolVec& getMapList() const; }; class CTreeObjStackM { CTreeObjStack _stk, _stkM; public: void addBlock(const CTreeEntryM& ent, bool bAdd); void popBlock(); std::tuple<const VolEntry*, int> getObj() const; std::tuple<const VolEntry*, int> getMap() const; bool isTopEmpty() const; template <class DIM> void classify(const bool (&bWrite)[DIM::N_LayerSize], typename DIM::Id centerId) { _stk.classify<DIM>(bWrite, centerId), _stkM.classify<DIM>(bWrite, centerId); } }; //! broad-phase collision manager (N-tree) /*! \tparam CTDim (モートンID変換などを担当する)次元クラス \tparam CTEnt エントリ管理クラステンプレート \tparam NDiv 分割数 \tparam Ent エントリーの中身 \tparam Self 継承先のクラス */ template <class CTDim, template<class,int,int> class CTEnt, int NDiv, class Ent, class Self> class _NTree { public: using this_t = Self; constexpr static int NDim = CTDim::N_Dim, N_LayerSize = CTDim::N_LayerSize; using Entry_t = Ent; using CTDim_t = CTDim; using CTEnt_t = CTEnt<Entry_t, NDiv, NDim>; using BVolume = typename CTDim_t::BVolume; using IDType = spn::SHandle; using IDTypeV = std::vector<IDType>; int _saturateW(float w) const { return Saturate(static_cast<int>(w*_unitSizeInv), 0, CTEnt_t::N_Width-1); } private: struct Cache { spn::SHandle hObj; CMask mask; BVolume bvolume; MortonId mortonId; PositionId posMin, posMax; }; CTDim_t _dim; CTEnt_t _ent; const float _unitSizeInv, _fieldOffset; using FGetBV = std::function<BVolume (spn::SHandle)>; //! BVolumeをSHandleから計算する為にCtorで与えられるファンクタ const FGetBV _fGetBV; using CacheNS = spn::noseq_list<Cache, std::allocator, CacheId>; CacheNS _cache; using MortonCache = std::unordered_map<spn::SHandle, CacheId>; //! オブジェクト削除でCacheIdを検索するのに使用 MortonCache _mmap; template <class Notify> int iterateChk(CMask mask, const BVolume& bv, const Notify& ntf) const { if(getEntry(0).isEmpty()) return 0; using Id = typename this_t::CTDim_t::Id; auto mid = CTDim_t::ToMortonId(bv, CTEnt_t::N_Width, _unitSizeInv, _fieldOffset); VolEntry ve{CacheId(0), std::get<2>(mid).value, std::get<3>(mid).value}; int count = 0; struct Pair { int toProc; Id center; }; std::stack<Pair> stkId; // ルートノードをプッシュ int curWidth = this_t::CTEnt_t::N_Width/2; // 現在の走査幅 (常に2の乗数) stkId.push(Pair{0, Id(curWidth)}); while(!stkId.empty()) { auto p = stkId.top(); stkId.pop(); if(p.toProc < 0) { if(p.toProc == -2) { curWidth *= 2; if(curWidth == 0) curWidth = 1; } continue; } const auto& curEnt = getEntry(p.toProc); // 判定を行うかの判断 (assert含む) if(!curEnt.isNodeEmpty()) { count += static_cast<const this_t&>(*this)._doCollision(mask, bv, curEnt, ntf); } else { AssertP(Trap, curEnt.getLowerCount() > 0) } // 下に枝があればそれを処理 if(curEnt.getLowerCount() > 0) { stkId.push(Pair{-2, 0}); curWidth /= 2; // 手持ちリストをOctave個のリストに分類(重複あり)にしてスタックに積む Id lowerCenterId[this_t::N_LayerSize]; this_t::CTDim_t::CalcLowerCenterId(lowerCenterId, p.center, curWidth); // 先に枝が有効かどうか確認 int tcount = 0; for(int i=0 ; i<this_t::N_LayerSize ; i++) { int idx = p.toProc*this_t::N_LayerSize+1+i; // 子ノードのインデックス if(hasEntry(idx)) { auto& ent = getEntry(idx); if(!ent.isEmpty()) { this_t::CTDim_t::Classify(ve, lowerCenterId[i], [i, idx2=idx, &lowerCenterId, &stkId](const VolEntry& /*ve*/, int /*idx*/){ stkId.push(Pair{idx2, lowerCenterId[i]}); }); ++tcount; continue; } } } AssertP(Trap, tcount>0) } } return count; } //! コリジョン判定の為に木を巡る /*! \return コリジョンと判定された回数 */ template <class Notify> int iterate(const Notify& ntf) const { if(getEntry(0).isEmpty()) return 0; int count = 0; typename this_t::CTEnt_t::Entry::ItrStack stk; // 現在持っているオブジェクト集合 using Id = typename this_t::CTDim_t::Id; struct Pair { int toProc; // これから処理する枝ノード. 負数は一段上に上がる Id center; // 中心座標(ノードが負数の時は無効) Pair(int toproc, Id cent): toProc(toproc), center(cent) {} }; std::stack<Pair> stkId; int curWidth = this_t::CTEnt_t::N_Width/2; // 現在の走査幅 (常に2の乗数) // ルートノードをプッシュ stkId.push(Pair(0, Id(curWidth))); while(!stkId.empty()) { auto p = stkId.top(); stkId.pop(); if(p.toProc < 0) { if(p.toProc == -2) { stk.popBlock(); // オブジェクト集合の状態を1つ戻す curWidth *= 2; if(curWidth == 0) curWidth = 1; } continue; } const auto& curEnt = getEntry(p.toProc); // 判定を行うかの判断 (assert含む) if(!curEnt.isNodeEmpty()) { count += static_cast<const this_t&>(*this)._doCollision(stk, curEnt, ntf); // オブジェクト集合を加える stk.addBlock(curEnt, true); } else { AssertP(Trap, curEnt.getLowerCount() > 0) } // 下に枝があればそれを処理 if(curEnt.getLowerCount() > 0) { stkId.push(Pair(-2, 0)); curWidth /= 2; // 手持ちリストをOctave個のリストに分類(重複あり)にしてスタックに積む Id lowerCenterId[this_t::N_LayerSize]; bool bWrite[this_t::N_LayerSize] = {}; this_t::CTDim_t::CalcLowerCenterId(lowerCenterId, p.center, curWidth); // 先に枝が有効かどうか確認 int tcount = 0; for(int i=0 ; i<this_t::N_LayerSize ; i++) { int idx = p.toProc*this_t::N_LayerSize+1+i; // 子ノードのインデックス if(hasEntry(idx)) { auto& ent = getEntry(idx); if(!ent.isEmpty()) { stkId.push(Pair(idx, lowerCenterId[i])); ++tcount; bWrite[i] = true; continue; } } } stk.template classify<typename this_t::CTDim_t>(bWrite, p.center); AssertP(Trap, tcount>0) } else stk.popBlock(); // オブジェクト集合の状態を1つ戻す } return count; } //! 上位セルのカウンタをインクリメント void _incrementUpper(MortonId num) { while(num != 0) { num = (num-1)>>(CTDim_t::N_Dim); AssertP(Trap, _ent.refEntry(num).getLowerCount() >= 0) _ent.increment(num); } } //! 上位セルのカウンタをデクリメント void _decrementUpper(MortonId num) { while(num != 0) { num = (num-1)>>(CTDim::N_Dim); AssertP(Trap, _ent.refEntry(num).getLowerCount() > 0) _ent.decrement(num); } } protected: //! リスト総当たり判定 template <class Itr, class T1, class Chk, class Notify> static int _HitCheck(Itr itr0, Itr itrE0, const T1& oL1, const Chk& chk, const Notify& ntf) { int count = 0; while(itr0 != itrE0) { auto& o0 = *itr0; for(auto& o1 : oL1) { if(chk(o0, o1)) { // 通知など ntf(o0, o1); } } ++itr0; count += oL1.size(); } return count; } //! 1つのリスト内で当たり判定 template <class T0, class Chk, class Notify> static int _HitCheck(const T0& oL0, const Chk& chk, const Notify& ntf) { int count = 0; for(auto itr0=oL0.cbegin() ; itr0!=oL0.cend() ; ++itr0) { auto itr1=itr0; ++itr1; for( ; itr1!=oL0.cend() ; ++itr1) { ++count; if(chk(*itr0, *itr1)) { // 通知など ntf(*itr0, *itr1); } } } return count; } template <class Notify> int _doCollision(CMask mask, const BVolume& bv, const CTreeEntry& cur, const Notify& ntf) const { int count = 0; for(auto& obj : cur.getObjList()) { auto& c = _getCache(obj.cacheId); if((mask & c.mask) && bv.hit(c.bvolume)) { ntf(c.hObj); ++count; } } return count; } template <class Notify> int _doCollision(const typename Entry_t::ItrStack& stk, const CTreeEntry& cur, const Notify& ntf) const { const VolVec& ol = cur.getObjList(); // Objリストとブロック内Objとの判定 auto ret = stk.getObj(); auto* bgn = std::get<0>(ret); auto nObj = std::get<1>(ret); auto fnNtf = [this, &ntf](const VolEntry& v0, const VolEntry& v1){ auto &c0 = _getCache(v0.cacheId), &c1 = _getCache(v1.cacheId); ntf(c0.hObj, c1.hObj); }; auto fnChk = [this](const VolEntry& v0, const VolEntry& v1){ auto &c0 = _getCache(v0.cacheId), &c1 = _getCache(v1.cacheId); return (c0.mask & c1.mask) && c0.bvolume.hit(c1.bvolume); }; int count = _HitCheck(bgn, bgn+nObj, ol, fnChk, fnNtf); // ブロック内同士の判定 count += _HitCheck(ol, fnChk, fnNtf); return count; } const Cache& _getCache(CacheId cid) const { return _cache.get(cid); } private: //! バウンディングボリュームの更新 /*! \param[in] idv 非nullptrならリストに指定したオブジェクトのみの更新 */ void _refreshBV(const IDTypeV* idv) { if(idv) { for(auto& idt : *idv) { auto itr = _mmap.find(idt); AssertP(Trap, itr!=_mmap.end()) auto& cache = _cache.get(itr->second); auto bv = _fGetBV(itr->first); cache.bvolume = bv; auto mid = CTDim_t::ToMortonId(bv, CTEnt_t::N_Width, _unitSizeInv, _fieldOffset); if(std::get<2>(mid).value != cache.posMin || std::get<3>(mid).value != cache.posMax) { // エントリ間の移動 _moveObject(itr->first, false); cache.posMin = std::get<2>(mid).value; cache.posMax = std::get<3>(mid).value; cache.mortonId = ToMortonId(std::get<0>(mid), std::get<1>(mid)); } } } else { for(auto& m : _mmap) { // 新しくBVolumeを計算 auto bv = _fGetBV(m.first); auto& cache = _cache.get(m.second); auto mid = CTDim_t::ToMortonId(bv, CTEnt_t::N_Width, _unitSizeInv, _fieldOffset); cache.bvolume = bv; if(std::get<2>(mid).value != cache.posMin || std::get<3>(mid).value != cache.posMax) { // エントリ間の移動 _moveObject(m.first, false); cache.posMin = std::get<2>(mid).value; cache.posMax = std::get<3>(mid).value; cache.mortonId = ToMortonId(std::get<0>(mid), std::get<1>(mid)); } } } } MortonId _moveObject(const IDType& idt, bool bAddRem) { _remObject(idt, bAddRem); CacheId cid = _mmap.at(idt); auto& cache = _cache.get(cid); return _addObject(cache.mask, idt, bAddRem); } MortonId _addObject(CMask mask, spn::SHandle hObj, bool bAddMM) { AssertP(Trap, hObj.valid()) auto bv = _fGetBV(hObj); auto mid = CTDim_t::ToMortonId(bv, CTEnt_t::N_Width, _unitSizeInv, _fieldOffset); MortonId num = ToMortonId(std::get<0>(mid), std::get<1>(mid)); CacheId cid; if(bAddMM) { cid = _cache.add(Cache{hObj, mask, bv, num, std::get<2>(mid).value, std::get<3>(mid).value}); _mmap[hObj] = cid; } else cid = _mmap.at(hObj); // まだエントリがリストを持っていなければ自動的に作成 auto& entry = _ent.refEntry(num); VolEntry ve{cid, std::get<2>(mid).value, std::get<3>(mid).value}; entry.addObj(mask, std::move(ve)); _incrementUpper(num); // LogOutput("Add(%1%) %2%", hObj.getIndex(), num); return num; } MortonId _remObject(const IDType& idt, bool bRemMM) { AssertP(Trap, idt.valid()) auto itr = _mmap.find(idt); AssertP(Trap, itr != _mmap.end()) CacheId cid = itr->second; auto& cache = _cache.get(cid); MortonId num = cache.mortonId; AssertP(Trap, _ent.hasEntry(num)) auto& e = _ent.refEntry(num); // リストが空になったらエントリを削除 if(e.remObj(cache.mask, cid)) _ent.remEntry(num); _decrementUpper(num); if(bRemMM) { _cache.rem(itr->second); _mmap.erase(itr); } // LogOutput("Rem(%1%) %2%", idt.getIndex(), num); return num; } public: /*! \param[in] fieldSize 当たり判定対象の一片サイズ */ _NTree(const FGetBV& f, float fsize, float fofs): _unitSizeInv(CTEnt_t::N_Width / fsize), _fieldOffset(fofs), _fGetBV(f) {} void clear() { _ent.clear(); } IDType add(spn::SHandle hObj, CMask mask) { AssertP(Trap, hObj.valid()) _addObject(mask, hObj, true); return hObj; } void rem(const IDType& idt) { _remObject(idt, true); } template <class CB> void checkCollision(CMask mask, const BVolume& bv, CB&& cb) { _refreshBV(nullptr); iterateChk(mask, bv, std::forward<CB>(cb)); } template <class CB> int broadCollision(CB&& cb, const IDTypeV* idv=nullptr) { _refreshBV(idv); return iterate(std::forward<CB>(cb)); } //! モートンIDとレベルから配列インデックスを計算 static int MortonIdtoIndex(MortonId num, int level) { return static_cast<int>((std::pow(int(N_LayerSize), level)-1) / (N_LayerSize-1) + num); } //! BBox最小、最大地点のモートンIdからエントリを格納する場所を算出 static MortonId ToMortonId(MortonId num0, MortonId num1) { auto diff = num0 ^ num1; num0 = MortonIdtoIndex(num0, CTEnt_t::N_Size); if(diff != 0) { auto upLv = (spn::Bit::MSB_N(diff) / CTDim_t::N_Dim)+1; do { num0 = (num0-1) >> CTDim_t::N_Dim; } while(--upLv != 0); } AssertP(Trap, num0 < (CTEnt_t::N_Ent)) return num0; } const Entry_t& getEntry(MortonId num) const { return _ent.getEntry(num); } bool hasEntry(MortonId num) const { return _ent.hasEntry(num); } }; template <class CTDim, template<class,int,int> class CTEnt, int NDiv> class NTree : public _NTree<CTDim, CTEnt, NDiv, CTreeEntry, NTree<CTDim, CTEnt, NDiv>> { private: using base_t = _NTree<CTDim, CTEnt, NDiv, CTreeEntry, NTree<CTDim, CTEnt, NDiv>>; public: using base_t::base_t; }; // -------- <<エントリ実装テンプレートクラス>> -------- /*! \tparam NDiv 分割度 \tparam Dim 次元数(2 or 3) */ template <int NDiv, int Dim> class CTEnt_Base { public: constexpr static int N_Size = NDiv, N_Width = spn::NPow<2,N_Size>::result, N_LayerSize = spn::NPow<2,Dim>::result, N_Ent = (spn::NPow<N_LayerSize, NDiv>::result - 1) / (N_LayerSize-1) + spn::NPow<N_Width, Dim>::result; protected: CTEnt_Base() { // 2D木なら4, 3D木なら8. それ以外はエラー static_assert(N_LayerSize==4||N_LayerSize==8, "invalid dimension"); } }; } }
29.715254
133
0.589836
[ "vector" ]
2f20cd61fb9ab4903c75517fa364d9f3ae738555
4,284
cpp
C++
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkConfigPreferencePage.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkConfigPreferencePage.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Plugins/org.mitk.gui.qt.ext/src/internal/QmitkConfigPreferencePage.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkConfigPreferencePage.h" #include "ui_QmitkConfigPreferencePage.h" #include <vector> #include <berryIWorkbenchPage.h> #include <ConfigManager.h> namespace { struct ConfigSaver : config::IParamSaver { explicit ConfigSaver(Ui::QmitkConfigPreferencePage* ui, const std::unordered_set<std::string>& deletedParams) : ui(ui) , m_deletedParams(deletedParams) { ui->configTableWidget->setColumnCount(2); ui->configTableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem(QObject::tr("key"))); ui->configTableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem(QObject::tr("value"))); } virtual ~ConfigSaver() { m_params.erase(std::remove_if(m_params.begin(), m_params.end(), [this](const std::pair<QString, QString>& item) -> bool { return !item.first.indexOf(INTERNAL_PARAM_PREFIX) || m_deletedParams.end() != m_deletedParams.find(item.first.toStdString()); }), m_params.end()); ui->configTableWidget->setRowCount(m_params.size()); for (auto i = 0; i < m_params.size(); ++i) { set(i, 0, m_params[i].first); set(i, 1, m_params[i].second); } ui->deleteButton->setEnabled(!m_params.empty()); } virtual void Put(const char* key, const QString& value) { m_params.push_back(std::make_pair(key, value)); } virtual void Put(const char* key, double value) { m_params.push_back(std::make_pair(key, QString::number(value))); } virtual void Put(const char* key, int value) { m_params.push_back(std::make_pair(key, QString::number(value))); } virtual void Put(const char* key, bool value) { m_params.push_back(std::make_pair(key, value ? QObject::tr("true") : QObject::tr("false"))); } private: void set(int row, int column, const QString& text) { QTableWidgetItem* item = new QTableWidgetItem; item->setText(text); ui->configTableWidget->setItem(row, column, item); } Ui::QmitkConfigPreferencePage* ui; const std::unordered_set<std::string>& m_deletedParams; std::vector<std::pair<QString, QString>> m_params; }; } QmitkConfigPreferencePage::QmitkConfigPreferencePage() : ui(nullptr) , pageWidget(nullptr) , workbench(nullptr) { } QmitkConfigPreferencePage::~QmitkConfigPreferencePage() { } void QmitkConfigPreferencePage::Init(berry::IWorkbench::Pointer workbench) { ui.reset(new Ui::QmitkConfigPreferencePage); this->workbench = workbench.GetPointer(); } void QmitkConfigPreferencePage::CreateQtControl(QWidget* parent) { pageWidget = new QWidget(parent); ui->setupUi(pageWidget); ui->configTableWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->configTableWidget->setIconSize(QSize(16, 16)); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(DeleteSelectedParam())); this->Update(); } QWidget* QmitkConfigPreferencePage::GetQtControl() const { return pageWidget; } bool QmitkConfigPreferencePage::PerformOk() { auto& configManager = config::ConfigManager::GetInstance(); for (auto& key : m_deletedParams) { configManager.Delete(key.c_str()); } return true; } void QmitkConfigPreferencePage::PerformCancel() { } void QmitkConfigPreferencePage::Update() { ConfigSaver uiListInitializer(ui.get(), m_deletedParams); config::ConfigManager::GetInstance().SaveParams(uiListInitializer); } void QmitkConfigPreferencePage::DeleteSelectedParam() { auto selection = ui->configTableWidget->selectedItems(); if (selection.isEmpty()) { return; } for (auto item : selection) { auto row = ui->configTableWidget->row(item); if (row > -1) { auto key = ui->configTableWidget->item(row, 0); m_deletedParams.emplace(key->text().toStdString()); } } Update(); }
27.286624
133
0.679272
[ "vector" ]
2f2338a98ab219e9ea3c3b53cdfe6f998dc199c1
1,973
hh
C++
include/introvirt/util/HexDump.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
include/introvirt/util/HexDump.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
include/introvirt/util/HexDump.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <introvirt/core/memory/guest_ptr.hh> #include <cstdint> #include <iostream> #include <ostream> #include <string> namespace introvirt { /** * @brief A class for outputting formatted hex dumps */ class HexDump { public: /** * @brief Write the formatted hex output * * @param os The output stream to write to */ void write(std::ostream& os = std::cout) const; /** * @brief Construct a new HexDump object using the given buffer * * @param buf The buffer to read from * @param len The number of bytes to read * @param start_address The address to label the output data as * @param prepend A prefix to add before each line */ HexDump(const void* buf, std::size_t len, std::size_t start_address = 0, std::string prepend = ""); /** * @brief Construct a HexDump object using guest memory at the specified address * * @param ptr The address to read * @param len The number of bytes to read * @param prepend A prefix to add before each line */ HexDump(const guest_ptr<void>& ptr, size_t len, std::string prepend = ""); private: guest_ptr<uint8_t[]> guest_data_; const uint8_t* buf_; std::size_t len_; std::size_t start_address_; const std::string prepend_; }; } // namespace introvirt
29.014706
84
0.676128
[ "object" ]
2f2ac082c5074b42a11868b048cb1b89a91fd6b0
3,419
cpp
C++
client/client-multi/client-cpp/impl/event/registration/UserTransport.cpp
acHefei/anteater_hf
2d8cc2041b7f9a394541052f4c4c27e79af515d3
[ "ECL-2.0", "Apache-2.0" ]
1
2017-08-24T08:53:32.000Z
2017-08-24T08:53:32.000Z
client/client-multi/client-cpp/impl/event/registration/UserTransport.cpp
acHefei/anteater_hf
2d8cc2041b7f9a394541052f4c4c27e79af515d3
[ "ECL-2.0", "Apache-2.0" ]
2
2019-11-13T02:57:27.000Z
2020-12-02T18:34:01.000Z
client/client-multi/client-cpp/impl/event/registration/UserTransport.cpp
acHefei/anteater_hf
2d8cc2041b7f9a394541052f4c4c27e79af515d3
[ "ECL-2.0", "Apache-2.0" ]
1
2017-08-24T08:53:38.000Z
2017-08-24T08:53:38.000Z
/** * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kaa/event/registration/UserTransport.hpp" #ifdef KAA_USE_EVENTS #include "kaa/logging/Log.hpp" namespace kaa { UserTransport::UserTransport(IRegistrationProcessor& manager, IKaaChannelManager& channelManager, IKaaClientContext &context) : AbstractKaaTransport(channelManager, context) , manager_(manager) { } std::shared_ptr<UserSyncRequest> UserTransport::createUserRequest() { auto attachUsr = manager_.getUserAttachRequest(); auto attachEps = manager_.getEndpointsToAttach(); auto detachEps = manager_.getEndpointsToDetach(); std::shared_ptr<UserSyncRequest> request(new UserSyncRequest); if (attachUsr.get() == nullptr) { request->userAttachRequest.set_null(); } else { request->userAttachRequest.set_UserAttachRequest(*attachUsr); } if (attachEps.empty()) { request->endpointAttachRequests.set_null(); } else { std::vector<EndpointAttachRequest> requests; for (const auto& idToTokenPair : attachEps) { EndpointAttachRequest subRequest; subRequest.requestId = idToTokenPair.first; subRequest.endpointAccessToken = idToTokenPair.second; requests.push_back(subRequest); } request->endpointAttachRequests.set_array(requests); } if (detachEps.empty()) { request->endpointDetachRequests.set_null(); } else { std::vector<EndpointDetachRequest> requests; for (const auto& idToHashPair : detachEps) { EndpointDetachRequest subRequest; subRequest.requestId = idToHashPair.first; subRequest.endpointKeyHash = idToHashPair.second; requests.push_back(subRequest); } request->endpointDetachRequests.set_array(requests); } return request; } void UserTransport::onUserResponse(const UserSyncResponse& response) { if (!response.userAttachResponse.is_null()) { manager_.onUserAttach(response.userAttachResponse.get_UserAttachResponse()); } if (!response.endpointAttachResponses.is_null()) { manager_.onEndpointsAttach(response.endpointAttachResponses.get_array()); } if (!response.endpointDetachResponses.is_null()) { manager_.onEndpointsDetach(response.endpointDetachResponses.get_array()); } if (!response.userAttachNotification.is_null()) { manager_.onCurrentEndpointAttach(response.userAttachNotification.get_UserAttachNotification()); } if (!response.userDetachNotification.is_null()) { manager_.onCurrentEndpointDetach(response.userDetachNotification.get_UserDetachNotification()); } } void UserTransport::sync() { syncByType(); } void UserTransport::syncProfile() { syncByType(TransportType::PROFILE); } } // namespace kaa #endif
30.526786
125
0.710442
[ "vector" ]
2f2d2dd86ddd6146e85486f0d4fc15c64281e1cc
7,232
cpp
C++
src/api/ConfigurationBavieca.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
src/api/ConfigurationBavieca.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
src/api/ConfigurationBavieca.cpp
atk-/bavieca-0014
031216739b4800285af717f22f44ecda54675139
[ "Apache-2.0" ]
null
null
null
/*---------------------------------------------------------------------------------------------* * Copyright (C) 2012 Daniel Bolaños - www.bltek.com - Boulder Language Technologies * * * * www.bavieca.org is the website of the Bavieca Speech Recognition Toolkit * * * * 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 "ConfigurationBavieca.h" namespace Bavieca { // define the parameters void ConfigurationBavieca::defineParameters() { // feature extraction defineParameter("feature.configurationFile","",PARAMETER_TYPE_FILE,false); defineParameter("feature.cepstralNormalization.mode","cepstral normalization mode", PARAMETER_TYPE_STRING,false,"utterance|stream|session"); defineParameter("feature.cepstralNormalization.method","cepstral normalization method", PARAMETER_TYPE_STRING,false,"none|CMN|CMVN"); defineParameter("feature.cepstralNormalization.bufferSize","cepstral buffer size (in bytes)", PARAMETER_TYPE_INTEGER,false); defineParameter("feature.warpFactor","warp factor for VTLN", PARAMETER_TYPE_FLOAT,false); defineParameter("feature.transformFile","list of feature transforms", PARAMETER_TYPE_FILE,true); // phonetic symbol set defineParameter("phoneticSymbolSet.file","set of phonetic symbols",PARAMETER_TYPE_FILE,false); // acoustic models defineParameter("acousticModels.file","acoustic models",PARAMETER_TYPE_FILE,false); // speech activity detection defineParameter("sad.maxGaussianSilence","max Gaussian components for silence model",PARAMETER_TYPE_INTEGER,true); defineParameter("sad.maxGaussianSpeech","max Gaussian components for speech model",PARAMETER_TYPE_INTEGER,true); defineParameter("sad.speechPadding","speech padding",PARAMETER_TYPE_INTEGER,true); defineParameter("sad.speechPenalty","speech insertion penalty",PARAMETER_TYPE_FLOAT,true); // lexicon defineParameter("lexicon.file","pronunciation lexicon",PARAMETER_TYPE_FILE,true); // language model defineParameter("languageModel.file","language model",PARAMETER_TYPE_FILE,true); defineParameter("languageModel.format","language model format",PARAMETER_TYPE_STRING,true); defineParameter("languageModel.type","language model type",PARAMETER_TYPE_STRING,true); defineParameter("languageModel.scalingFactor","language model scaling factor",PARAMETER_TYPE_FLOAT,true); defineParameter("languageModel.ngram","language model n-gram",PARAMETER_TYPE_STRING,true); defineParameter("languageModel.crossUtterance","language model",PARAMETER_TYPE_BOOLEAN,true,"yes|no","no"); // insertion penalty defineParameter("insertionPenalty.standard","",PARAMETER_TYPE_FLOAT,true); defineParameter("insertionPenalty.filler","",PARAMETER_TYPE_FLOAT,true); defineParameter("insertionPenalty.filler.file","",PARAMETER_TYPE_FILE,true); // pruning defineParameter("pruning.likelihoodBeam","likelihood beam used for pruning arcs", PARAMETER_TYPE_FLOAT,true); defineParameter("pruning.likelihoodBeamWE","likelihood beam used for pruning word-end arcs", PARAMETER_TYPE_FLOAT,true); defineParameter("pruning.likelihoodBeamTokensArc","likelihood beam used for pruning tokens within an arc", PARAMETER_TYPE_FLOAT,true); defineParameter("pruning.maxActiveArcs","maximum number of active arcs", PARAMETER_TYPE_INTEGER,true); defineParameter("pruning.maxActiveArcsWE","maximum number of active word-end arcs", PARAMETER_TYPE_INTEGER,true); defineParameter("pruning.maxActiveTokensArc","maximum number of active tokens per arc", PARAMETER_TYPE_INTEGER,true); // decoder output defineParameter("output.lattice.maxWordSequencesState", "maximum number of different word sequences exiting a state", PARAMETER_TYPE_INTEGER,true,"[2|100]","5"); } // load the configuration parameters void ConfigurationBavieca::load() { // load pairs parameter-value from the file ConfigurationFile::load(); // get the data VParameterValue vParameterValue; for(MParameterValue::iterator it = m_mParameterValue.begin() ; it != m_mParameterValue.end() ; ++it) { ParameterValue parameterValue; parameterValue.strParameter = it->first; parameterValue.strValue = it->second; vParameterValue.push_back(parameterValue); } //ConfigurationFile::print(); // make the parameter definitiones defineParameters(); // parse the parameter-value pairs parse(vParameterValue); } // check whether SAD configuration parameters are set bool ConfigurationBavieca::areSADParametersSet() { // make sure required configuration parameters are defined if (isParameterSet("sad.maxGaussianSilence") && isParameterSet("sad.maxGaussianSpeech") && isParameterSet("sad.speechPadding") && isParameterSet("sad.speechPenalty")) { return true; } return false; } // check whether alignment configuration parameters are set bool ConfigurationBavieca::areAlignerParametersSet() { // make sure required configuration parameters are defined if (isParameterSet("lexicon.file")) { return true; } return false; } // check whether decoding configuration parameters are set bool ConfigurationBavieca::areDecodingParametersSet() { // make sure required configuration parameters are defined if (isParameterSet("languageModel.file") && isParameterSet("languageModel.format") && isParameterSet("languageModel.type") && isParameterSet("languageModel.scalingFactor") && isParameterSet("languageModel.ngram") && isParameterSet("languageModel.crossUtterance") && isParameterSet("insertionPenalty.standard") && isParameterSet("insertionPenalty.filler") && isParameterSet("insertionPenalty.filler.file") && isParameterSet("pruning.likelihoodBeam") && isParameterSet("pruning.likelihoodBeamWE") && isParameterSet("pruning.likelihoodBeamTokensArc") && isParameterSet("pruning.maxActiveArcs") && isParameterSet("pruning.maxActiveArcsWE") && isParameterSet("pruning.maxActiveTokensArc")) { return true; } return false; } }; // end-of-namespace
44.097561
115
0.684458
[ "model" ]
2f3120ca5f38f3121c65e30f1d9a045d1284573d
4,826
hpp
C++
include/camera.hpp
namelessvoid/nparticles
6a113d201b726c7f06eae1ffd965f8b2041a683d
[ "Zlib" ]
1
2016-05-31T11:29:18.000Z
2016-05-31T11:29:18.000Z
include/camera.hpp
namelessvoid/nparticles
6a113d201b726c7f06eae1ffd965f8b2041a683d
[ "Zlib" ]
1
2016-09-03T13:18:53.000Z
2016-09-03T13:18:53.000Z
include/camera.hpp
namelessvoid/nparticles
6a113d201b726c7f06eae1ffd965f8b2041a683d
[ "Zlib" ]
null
null
null
/* * Copyright (C) 2015 Simon Kerler * * This file is part of the "Nameless Particle Engine". * For conditions of distribution and use, see the copyright notice you should * have recievied with this software. I not, see: * http://opensource.org/licenses/Zlib */ #ifndef NP_CAMERA_HPP #define NP_CAMERA_HPP #include <glm/glm.hpp> namespace nparticles { /** * The Camera class is a basic camera implementation. * * The vector based Camera is used to navigate through a scene. */ class Camera { public: /** * Enum rotations defines valid Camera rotations. * * This rotations are passed to rotate() to specify the axis of rotation. * The axes are relative to the strafe (x), up (y) and direction (z) vectors * of the Camera. */ enum rotations { NP_ROT_PITCH, /**< rotation around strafe / x axis */ NP_ROT_YAW, /**< rotation around up / y axis */ NP_ROT_ROLL /**< rotation around direction / z axis */ }; /** * Enum directions defines valid Camera movements. * * This directions are passed to setMovementSpeed() to set the movement * in the given direction. The movement is relative to the strafe (x), up (y) and * direction (z) vectors of the Camera. */ enum directions { NP_DIR_FOREWARD, /**< Move foreward along the direction (z) axis */ NP_DIR_BACKWARD, /**< Move backards along the direction (z) axis */ NP_DIR_STRAFE_RIGHT, /**< Move to the right along the strafe (x) axis */ NP_DIR_STRAFE_LEFT, /**< Move to the left along the strafe (x) axis */ NP_DIR_UP, /**< Move up along the up (y) axis */ NP_DIR_DOWN /**< Move down along the up (y) axis */ }; /** * Camera constructor. */ Camera(); /** * Camera destructor. */ ~Camera(); /** * Set the perspective projection. * * Set the perspective projection matrix for projecting the scene. * * @param fieldOfView The field of view in radians. * @param screenWidth The width of the view plane. * @param screenHeight The height of the view plane. * @param nearClippingPlane Distance of the near clipping plane. * @param farClippingPlane Distance of the far clipping plane. */ void setPerspective(float fieldOfView, float screenWidth, float screenHeight, float nearClippingPlane, float farClippingPlane); /** * Set movement speed in a given @p direction. * * This sets the movement speed in a given @p direction to guarantee uniform movement. * * @param speed The speed. * @param direction The direction which is one of available Camera::directions */ void setMovementSpeed(float speed, directions direction); /** * Rotate the Camera around a given @p rotation axis. * * This rotates the camera aroud a given @p rotation axis. * * @param angle The angle (in radians) to rotate. * @param rotation One of the available Camera::rotations. */ void rotate(float angle, rotations rotation); /** * Move the Camera in a direction. * * Move the Camera by given distances. The order of directions of the vector is NP_DIR_STRAFE_RIGHT, NP_DIR_UP, NP_DIR_FOREWARD. * * @param distance Vector which indicates the distances to move. */ void move(glm::vec3 distance); /** * Updates the Camera position. * * This udpates the position of the Camera according the current movement speed set via setMovementSpeed(). */ void updatePosition(); /** * Get the view projection matrix. * * Get view and projection matrix combined to a single matrix. This can be used for view projection transformations * in a shader. * * @return The combined view and projection matrix. */ glm::mat4 getViewProjectionMatrix(); /** * Get the normal matrix. * * This returns the normal matrix retrieved by the current transformation of the camera. This can be used for * normal transformations. * * @return The normal matrix. */ glm::mat3 getNormalMatrix(); private: /** * The up vector. */ glm::vec3 mUpVector; /** * The directon or "look at" vector. */ glm::vec3 mDirectionVector; /** * The strafe vector pointing to the right. */ glm::vec3 mStrafeVector; /** * Current speed in x, y and z direction. */ glm::vec3 mSpeed; /** * The current camera postion. */ glm::vec3 mPosition; /** * The perspective projection matrix calculated by intputs of setPerspective(). */ glm::mat4 mProjectionMatrix; }; } // namespace nparticles #endif // NP_CAMERA_HPP
28.222222
132
0.631786
[ "vector" ]
2f31a9a1952899dc4a64881b215b05ce26b708c5
3,089
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoTextureCoordinateDefault.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoTextureCoordinateDefault.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoTextureCoordinateDefault.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoTextureCoordinateDefault SoTextureCoordinateDefault.h Inventor/nodes/SoTextureCoordinateDefault.h \brief The SoTextureCoordinateDefault class removes texture coordinates from the state. \ingroup nodes Shapes below this node in the scenegraph will have to use its default texture coordinates as SoTextureCoordinateDefault cleans out all previously defined texture coordinates and texture coordinate functions. <b>FILE FORMAT/DEFAULTS:</b> \code TextureCoordinateDefault { } \endcode */ // ************************************************************************* #include <Inventor/nodes/SoTextureCoordinateDefault.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/elements/SoGLTextureCoordinateElement.h> #include "nodes/SoSubNodeP.h" // ************************************************************************* SO_NODE_SOURCE(SoTextureCoordinateDefault); /*! Constructor. */ SoTextureCoordinateDefault::SoTextureCoordinateDefault() { SO_NODE_INTERNAL_CONSTRUCTOR(SoTextureCoordinateDefault); } /*! Destructor. */ SoTextureCoordinateDefault::~SoTextureCoordinateDefault() { } // doc in super void SoTextureCoordinateDefault::initClass(void) { SO_NODE_INTERNAL_INIT_CLASS(SoTextureCoordinateDefault, SO_FROM_INVENTOR_1); } // doc from parent void SoTextureCoordinateDefault::doAction(SoAction * action) { SoTextureCoordinateElement::setDefault(action->getState(), this); } // doc from parent void SoTextureCoordinateDefault::GLRender(SoGLRenderAction * action) { SoGLTextureCoordinateElement::setTexGen(action->getState(), this, NULL); SoTextureCoordinateDefault::doAction((SoAction *)action); } // doc from parent void SoTextureCoordinateDefault::callback(SoCallbackAction * action) { SoTextureCoordinateDefault::doAction((SoAction *)action); } // doc from parent void SoTextureCoordinateDefault::pick(SoPickAction * action) { SoTextureCoordinateDefault::doAction((SoAction *)action); }
29.701923
108
0.688249
[ "3d" ]
2f334190fe37b3e4f7f82e58600a9ded4004e6bd
37,827
hh
C++
EnergyPlus/PackagedTerminalHeatPump.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
EnergyPlus/PackagedTerminalHeatPump.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
1
2020-07-08T13:32:09.000Z
2020-07-08T13:32:09.000Z
EnergyPlus/PackagedTerminalHeatPump.hh
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // The Regents of the University of California, through Lawrence Berkeley National Laboratory // (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. As such, the U.S. Government has been // granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, // worldwide license in the Software to reproduce, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // 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 PackagedTerminalHeatPump_hh_INCLUDED #define PackagedTerminalHeatPump_hh_INCLUDED // ObjexxFCL Headers #include <ObjexxFCL/Array1D.hh> #include <ObjexxFCL/Optional.hh> // EnergyPlus Headers #include <DataGlobals.hh> #include <EnergyPlus.hh> #include <VariableSpeedCoils.hh> namespace EnergyPlus { namespace PackagedTerminalHeatPump { // Using/Aliasing using VariableSpeedCoils::MaxSpedLevels; // Data // MODULE PARAMETER DEFINITIONS // Compressor operation extern int const On; // normal compressor operation extern int const Off; // signal DXCoil that compressor shouldn't run // Last mode of operation extern int const CoolingMode; // last compressor operating mode was in cooling extern int const HeatingMode; // last compressor operating mode was in heating // Airflow control for contant fan mode extern int const UseCompressorOnFlow; // set compressor OFF air flow rate equal to compressor ON air flow rate extern int const UseCompressorOffFlow; // set compressor OFF air flow rate equal to user defined value // Unit type extern int const PTHPUnit; // equivalent to PackagedTerminal:HeatPump:AirToAir extern int const PTACUnit; // equivalent to PackagedTerminal:AirConditioner extern int const PTWSHPUnit; // equivalent to WaterToAirHeatPump // DERIVED TYPE DEFINITIONS // MODULE VARIABLE DECLARATIONS: extern Array1D_bool CheckEquipName; extern Real64 SupHeaterLoad; // load to be met by supplemental heater [W] extern int NumPTHP; // total number of PTHP's extern int NumPTAC; // total number of PTAC's extern int NumPTWSHP; // total number of PTWSHP's extern int NumPTUs; // total number of PTHP and PTAC units extern Real64 CompOnMassFlow; // Supply air mass flow rate w/ compressor ON extern Real64 OACompOnMassFlow; // OA mass flow rate w/ compressor ON extern Real64 CompOffMassFlow; // Supply air mass flow rate w/ compressor OFF extern Real64 OACompOffMassFlow; // OA mass flow rate w/ compressor OFF extern Real64 CompOnFlowRatio; // fan flow ratio when coil on extern Real64 CompOffFlowRatio; // fan flow ratio when coil off extern Real64 FanSpeedRatio; // ratio of air flow ratio passed to fan object extern bool GetPTUnitInputFlag; // First time, input is "gotten" extern Real64 SaveCompressorPLR; // holds compressor PLR from active DX coil extern Real64 SteamDensity; // density of steam at 100C, used for steam heating coils extern bool HeatingLoad; // defines a heating load on PTUnit extern bool CoolingLoad; // defines a cooling load on PTUnit extern Real64 MinWaterFlow; // minimum water flow for heating [kg/s] extern Real64 TempSteamIn; // steam coil steam inlet temperature // SUBROUTINE SPECIFICATIONS FOR MODULE // modules for variable speed heat pump // Types struct PTUnitData { // Members // input data int UnitType_Num; // paramter equivalent to type of unit int ZoneEquipType; // Type of PT unit bool useVSCoilModel; // does PT use VS coil models int SchedPtr; // index number to availability schedule Real64 MaxCoolAirVolFlow; // supply air volumetric flow rate during cooling operation [m3/s] Real64 MaxHeatAirVolFlow; // supply air volumetric flow rate during heating operation [m3/s] Real64 MaxNoCoolHeatAirVolFlow; // supply air volumetric flow rate when no cooling or heating [m3/s] Real64 CoolOutAirVolFlow; // OA volumetric flow rate during cooling operation [m3/s] Real64 HeatOutAirVolFlow; // OA volumetric flow rate during heating operation [m3/s] Real64 NoCoolHeatOutAirVolFlow; // OA volumetric flow rate when no cooling or heating [m3/s] Real64 CoolOutAirMassFlow; // OA mass flow rate during cooling operation [kg/s] Real64 HeatOutAirMassFlow; // OA mass flow rate during heating operation [kg/s] Real64 NoCoolHeatOutAirMassFlow; // OA mass flow rate when no cooling or heating [kg/s] int OutsideAirNode; // OAmixer outside air node number int AirReliefNode; // OAmixer relief air node number std::string OAMixType; // type of outside air mixer std::string OAMixName; // name of OAmixer int OAMixIndex; std::string FanName; // name of fan std::string FanType; // type of fan int FanType_Num; // fan type number (see DataHVACGlobals) int FanIndex; // index number to fan int FanSchedPtr; // index number to fan operating mode schedule int FanAvailSchedPtr; // index to fan availability schedule std::string DXCoolCoilName; // name of DX cooling coil std::string DXCoolCoilType; // type of DX cooling coil,Coil:DX:CoolingBypassFactorEmpirical or // 'CoilSystem:Cooling:DX:HeatExchangerAssisted' int DXCoolCoilType_Num; // numeric equivalent for DX cooling coil type int CoolCoilCompIndex; // cooling coil index number (index for DX coil or HX Assisted object) int DXCoolCoilIndexNum; // actual DX cooling coil index number int CondenserNodeNum; // DX cooling coil condenser node number int DXHeatCoilIndexNum; // actual DX heating coil index number std::string DXHeatCoilName; // name of DX heating coil std::string DXHeatCoilType; // type of DX heating coil,Coil:DX:HeatingEmpirical int DXHeatCoilType_Num; // numeric equivalent for DX heating coil type std::string ACHeatCoilName; // name of heating coil for PTAC std::string ACHeatCoilType; // type of heating coil for PTAC Real64 ACHeatCoilCap; // heating coil capacity for PTAC int ACHeatCoilIndex; // heating coil index number for PTAC int SuppCoilFluidInletNode; // steam inlet node number of HW coil for PTAC and HP int HWCoilSteamOutletNode; // steam inlet node number of HW coil for PTAC and HP std::string SuppHeatCoilName; // name of supplemental heating coil int SuppHeatCoilType_Num; // numeric equivalent for supplemental heating coil type int ACHeatCoilType_Num; // numeric equivalent for PTAC heating coil type int SuppHeatCoilIndex; // supplemental heater index number int SupHeatCoilCap; // supplemental heater coil capacity [W] int SupCoilAirInletNode; // air inlet node for supplemental coil for HP std::string SuppHeatCoilType; // supplemental heater coil type Real64 MaxSATSupHeat; // maximum supply air temperature from supplemental heater [C] Real64 MaxOATSupHeat; // maximum outdoor air temp for supplemental heater operation [C] int OpMode; // mode of operation; 1=cycling fan, cycling compressor, 2=continuous fan, cycling compresor int FanPlace; // fan placement; 1=blow through, 2=draw through Real64 CoolConvergenceTol; // Convergence tolerance, fraction (ZoneLoad - Equip Output)/ZoneLoad Real64 HeatConvergenceTol; // Convergence tolerance, fraction (ZoneLoad - Equip Output)/ZoneLoad Real64 MinOATCompressorCooling; // Minimum OAT for compressor operation in cooling mode [C] Real64 MinOATCompressorHeating; // Minimum OAT for compressor operation in heating mode [C] int IterErrIndex; // index for recurring warnings std::string AvailManagerListName; // Name of an availability manager list object int WaterCyclingMode; // Heat Pump Coil water flow mode; See definitions in DataHVACGlobals, // 1=water cycling, 2=water constant, 3=water constant on demand (old mode) int PTObjectIndex; // index for PT unit // Water source HP specific variables Real64 MaxONOFFCyclesperHour; // Maximum ON/OFF Cycling Rate [cycles/hr] Real64 HPTimeConstant; // Heat Pump Time Constant [s] Real64 OnCyclePowerFraction; // Fraction of on-cycle power use [~] // supplemental heating coil operation Real64 FanDelayTime; // Fan delay time, time delay for the HP's fan to // shut off after compressor cycle off [s] Real64 DesignHeatingCapacity; // Nominal Capacity of Heating Coil [W] Real64 DesignCoolingCapacity; // Nominal Capacity of Cooling Coil [W] Real64 DesignSuppHeatingCapacity; // Nominal Capacity of Supplemental Heating Coil [W] // addition for OA to Zone Units bool ATMixerExists; // True if there is an ATMixer std::string ATMixerName; // name of air terminal mixer int ATMixerIndex; // index to the air terminal mixer int ATMixerType; // 1 = inlet side mixer, 2 = supply side mixer int ATMixerPriNode; // primary inlet air node number for the air terminal mixer int ATMixerSecNode; // secondary air inlet node number for the air terminal mixer int ATMixerOutNode; // outlet air node number for the air terminal mixer // Report data Real64 TotHeatEnergyRate; // total heating output [W] Real64 TotHeatEnergy; // total heating output [J] Real64 TotCoolEnergyRate; // total cooling output [W] Real64 TotCoolEnergy; // total cooling output [J] Real64 SensHeatEnergyRate; // sensible heating output [W] Real64 SensHeatEnergy; // sensible heating output [J] Real64 SensCoolEnergyRate; // sensible cooling output [W] Real64 SensCoolEnergy; // sensible cooling output [J] Real64 LatHeatEnergyRate; // latent heating output [W] Real64 LatHeatEnergy; // latent heating output [J] Real64 LatCoolEnergyRate; // latent cooling output [W] Real64 LatCoolEnergy; // latent cooling output [J] Real64 ElecPower; // electricity consumed [W] Real64 ElecConsumption; // electricity consumed [J] Real64 CompPartLoadRatio; // compressor part-load ratio for time step int LastMode; // last mode of operation, coolingmode or heatingmode int AirFlowControl; // fan control mode, UseCompressorOnFlow or UseCompressorOffFlow int ControlType; // Setpoint, Load based or ASHRAE (SZVAV) control bool validASHRAECoolCoil; // cooling coil model that conforms to ASHRAE 90.1 requirements and methodology bool validASHRAEHeatCoil; // heating coil model that conforms to ASHRAE 90.1 requirements and methodology bool simASHRAEModel; // flag denoting that ASHRAE model (SZVAV) should be used Real64 CompPartLoadFrac; // compressor part load ratio int PlantCoilOutletNode; // outlet node for water coil int SuppCoilLoopNum; // plant loop index for water heating coil int SuppCoilLoopSide; // plant loop side index for water heating coil int SuppCoilBranchNum; // plant loop branch index for water heating coil int SuppCoilCompNum; // plant loop component index for water heating coil Real64 MaxSuppCoilFluidFlow; // water or steam mass flow rate supp. heating coil [kg/s] int HotWaterCoilMaxIterIndex; // Index to recurring warning message int HotWaterCoilMaxIterIndex2; // Index to recurring warning message Real64 ActualFanVolFlowRate; // Volumetric flow rate from fan object Real64 HeatingSpeedRatio; // Fan speed ratio in heating mode Real64 CoolingSpeedRatio; // Fan speed ratio in cooling mode Real64 NoHeatCoolSpeedRatio; // Fan speed ratio when no cooling or heating int AvailStatus; // starting added varibles for variable speed water source heat pump, Bo Shen, ORNL, March 2012 int HeatCoolMode; // System operating mode (0 = floating, 1 = cooling, 2 = heating) int NumOfSpeedCooling; // The number of speeds for cooling int NumOfSpeedHeating; // The number of speeds for heating Real64 IdleSpeedRatio; // idle air fan ratio Real64 IdleVolumeAirRate; // idle air flow rate Real64 IdleMassFlowRate; // idle air flow rate Real64 FanVolFlow; // fan volumetric flow rate bool CheckFanFlow; // Supply airflow check Array1D<Real64> HeatVolumeFlowRate; // Supply air volume flow rate during heating operation Array1D<Real64> HeatMassFlowRate; // Supply air mass flow rate during heating operation Array1D<Real64> CoolVolumeFlowRate; // Supply air volume flow rate during cooling operation Array1D<Real64> CoolMassFlowRate; // Supply air mass flow rate during cooling operation Array1D<Real64> MSHeatingSpeedRatio; // Fan speed ratio in heating mode Array1D<Real64> MSCoolingSpeedRatio; // Fan speed ratio in cooling mode int CompSpeedNum; Real64 CompSpeedRatio; int ErrIndexCyc; int ErrIndexVar; int ZonePtr; // pointer to a zone served by a fancoil unit int HVACSizingIndex; // index of a HVACSizing object for a fancoil unit bool FirstPass; // used to reset sizing flags Real64 HeatCoilWaterFlowRate; // Real64 ControlZoneMassFlowFrac; // // variables used in SZVAV model: std::string Name; // name of unit std::string UnitType; // type of unit int MaxIterIndex; // used in PLR calculations for sensible load int NodeNumOfControlledZone; // node number of control zone int RegulaFalsiFailedIndex; // used in PLR calculations for sensible load Real64 FanPartLoadRatio; // fan part-load ratio for time step Real64 CoolCoilWaterFlowRatio; // holds ratio of max cool coil water flow rate, may be < 1 when FlowLock is true Real64 HeatCoilWaterFlowRatio; // holds ratio of max heat coil water flow rate, may be < 1 when FlowLock is true int ControlZoneNum; // index of unit in ZoneEquipConfig int AirInNode; // Parent inlet air node number int AirOutNode; // Parent outlet air node number Real64 MaxCoolAirMassFlow; // Maximum coil air mass flow for cooling [kg/s] Real64 MaxHeatAirMassFlow; // Maximum coil air mass flow for heating [kg/s] Real64 MaxNoCoolHeatAirMassFlow; // Maximum coil air mass flow for no cooling or heating [kg/s] Real64 DesignMinOutletTemp; // DOAS DX Cooling or SZVAV coil outlet air minimum temperature [C] Real64 DesignMaxOutletTemp; // Maximum supply air temperature from heating coil [C] Real64 LowSpeedCoolFanRatio; // cooling mode ratio of low speed fan flow to full flow rate Real64 LowSpeedHeatFanRatio; // heating mode ratio of low speed fan flow to full flow rate Real64 MaxCoolCoilFluidFlow; // water flow rate for cooling coil [kg/s] - NOT USED in PTHP Real64 MaxHeatCoilFluidFlow; // water or steam mass flow rate for heating coil [kg/s] int CoolCoilLoopNum; // plant loop index for water cooling coil - NOT USED in PTHP int CoolCoilLoopSide; // plant loop side index for water cooling coil - NOT USED in PTHP int CoolCoilBranchNum; // plant loop branch index for water cooling coil - NOT USED in PTHP int CoolCoilCompNum; // plant loop component index for water cooling coil - NOT USED in PTHP int HeatCoilLoopNum; // plant loop index for water heating coil int HeatCoilLoopSide; // plant loop side index for water heating coil int HeatCoilBranchNum; // plant loop branch index for water heating coil int HeatCoilCompNum; // plant loop component index for water heating coil int CoolCoilFluidInletNode; // water cooling coil water inlet node number NOT USED in PTHP int CoolCoilFluidOutletNodeNum; // water cooling coil water outlet node number NOT USED in PTHP int CoolCoilInletNodeNum; // cooling coil air inlet node number int CoolCoilOutletNodeNum; // cooling coil air outlet node number int HeatCoilFluidInletNode; // heating coil fluid (e.g., water or steam) inlet node number int HeatCoilFluidOutletNodeNum; // heating coil fluid (e.g., water or steam) outlet node number int HeatCoilInletNodeNum; // heating coil air inlet node number int HeatCoilOutletNodeNum; // heating coil air outlet node number // end of the additional variables for variable speed water source heat pump // Default Constructor PTUnitData() : UnitType_Num(0), ZoneEquipType(0), useVSCoilModel(false), SchedPtr(0), MaxCoolAirVolFlow(0.0), MaxHeatAirVolFlow(0.0), MaxNoCoolHeatAirVolFlow(0.0), CoolOutAirVolFlow(0.0), HeatOutAirVolFlow(0.0), NoCoolHeatOutAirVolFlow(0.0), CoolOutAirMassFlow(0.0), HeatOutAirMassFlow(0.0), NoCoolHeatOutAirMassFlow(0.0), OutsideAirNode(0), AirReliefNode(0), OAMixIndex(0), FanType_Num(0), FanIndex(0), FanSchedPtr(0), FanAvailSchedPtr(0), DXCoolCoilType_Num(0), CoolCoilCompIndex(0), DXCoolCoilIndexNum(0), CondenserNodeNum(0), DXHeatCoilIndexNum(0), DXHeatCoilType_Num(0), ACHeatCoilCap(0.0), ACHeatCoilIndex(0), SuppCoilFluidInletNode(0), HWCoilSteamOutletNode(0), SuppHeatCoilType_Num(0), ACHeatCoilType_Num(0), SuppHeatCoilIndex(0), SupHeatCoilCap(0), SupCoilAirInletNode(0), MaxSATSupHeat(0.0), MaxOATSupHeat(0.0), OpMode(0), FanPlace(0), CoolConvergenceTol(0.0), HeatConvergenceTol(0.0), MinOATCompressorCooling(0.0), MinOATCompressorHeating(0.0), IterErrIndex(0), WaterCyclingMode(0), PTObjectIndex(0), MaxONOFFCyclesperHour(0.0), HPTimeConstant(0.0), OnCyclePowerFraction(0.0), FanDelayTime(0.0), DesignHeatingCapacity(0.0), DesignCoolingCapacity(0.0), DesignSuppHeatingCapacity(0.0), ATMixerExists(false), ATMixerIndex(0), ATMixerType(0), ATMixerPriNode(0), ATMixerSecNode(0), ATMixerOutNode(0), TotHeatEnergyRate(0.0), TotHeatEnergy(0.0), TotCoolEnergyRate(0.0), TotCoolEnergy(0.0), SensHeatEnergyRate(0.0), SensHeatEnergy(0.0), SensCoolEnergyRate(0.0), SensCoolEnergy(0.0), LatHeatEnergyRate(0.0), LatHeatEnergy(0.0), LatCoolEnergyRate(0.0), LatCoolEnergy(0.0), ElecPower(0.0), ElecConsumption(0.0), CompPartLoadRatio(0.0), LastMode(0), AirFlowControl(0), CompPartLoadFrac(0.0), PlantCoilOutletNode(0), SuppCoilLoopNum(0), SuppCoilLoopSide(0), SuppCoilBranchNum(0), SuppCoilCompNum(0), MaxSuppCoilFluidFlow(0.0), HotWaterCoilMaxIterIndex(0), HotWaterCoilMaxIterIndex2(0), ActualFanVolFlowRate(0.0), HeatingSpeedRatio(1.0), CoolingSpeedRatio(1.0), NoHeatCoolSpeedRatio(1.0), AvailStatus(0), HeatCoolMode(0), NumOfSpeedCooling(0), NumOfSpeedHeating(0), IdleSpeedRatio(0.0), IdleVolumeAirRate(0.0), IdleMassFlowRate(0.0), FanVolFlow(0.0), CheckFanFlow(true), HeatVolumeFlowRate(MaxSpedLevels, 0.0), HeatMassFlowRate(MaxSpedLevels, 0.0), CoolVolumeFlowRate(MaxSpedLevels, 0.0), CoolMassFlowRate(MaxSpedLevels, 0.0), MSHeatingSpeedRatio(MaxSpedLevels, 0.0), MSCoolingSpeedRatio(MaxSpedLevels, 0.0), CompSpeedNum(0), CompSpeedRatio(0.0), ErrIndexCyc(0), ErrIndexVar(0), ZonePtr(0), HVACSizingIndex(0), FirstPass(true), HeatCoilWaterFlowRate(0.0), ControlZoneMassFlowFrac(1.0), // variables used in SZVAV model: MaxIterIndex(0), NodeNumOfControlledZone(0), RegulaFalsiFailedIndex(0), FanPartLoadRatio(0.0), CoolCoilWaterFlowRatio(0.0), HeatCoilWaterFlowRatio(0.0), ControlZoneNum(0), AirInNode(0), AirOutNode(0), MaxCoolAirMassFlow(0.0), MaxHeatAirMassFlow(0.0), MaxNoCoolHeatAirMassFlow(0.0), DesignMinOutletTemp(0.0), DesignMaxOutletTemp(0.0), LowSpeedCoolFanRatio(0.0), LowSpeedHeatFanRatio(0.0), MaxCoolCoilFluidFlow(0.0), MaxHeatCoilFluidFlow(0.0), CoolCoilLoopNum(0), CoolCoilLoopSide(0), CoolCoilBranchNum(0), CoolCoilCompNum(0), HeatCoilLoopNum(0), HeatCoilLoopSide(0), HeatCoilBranchNum(0), HeatCoilCompNum(0), CoolCoilFluidInletNode(0), CoolCoilFluidOutletNodeNum(0), CoolCoilInletNodeNum(0), CoolCoilOutletNodeNum(0), HeatCoilFluidInletNode(0), HeatCoilFluidOutletNodeNum(0), HeatCoilInletNodeNum(0), HeatCoilOutletNodeNum(0) { } }; struct PTUnitNumericFieldData { // Members Array1D_string FieldNames; // Default Constructor PTUnitNumericFieldData() { } }; // Object Data extern Array1D<PTUnitData> PTUnit; extern Array1D<PTUnitNumericFieldData> PTUnitUNumericFields; // holds PT unit numeric input fields character field name // Functions void clear_state(); void SimPackagedTerminalUnit(std::string const &CompName, // name of the packaged terminal heat pump int const ZoneNum, // number of zone being served bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep Real64 &QUnitOut, // sensible capacity delivered to zone Real64 &LatOutputProvided, // Latent add/removal by packaged terminal unit (kg/s), dehumid = negative int const PTUnitType, // indicates whether PTAC, PTHP or PTWSHP int &CompIndex // index to Packaged Terminal Heat Pump ); void SimPTUnit(int const PTUnitNum, // number of the current Packaged Terminal Heat Pump being simulated int const ZoneNum, // number of zone being served bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep Real64 &QSensUnitOut, // sensible delivered capacity [W] Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep Real64 const QZnReq, // cooling/heating needed by zone [W] Real64 &QLatUnitOut // Latent delivered capacity [kg/s], dehumidification = negative ); void GetPTUnit(); void InitPTUnit(int const PTUnitNum, // number of the current PTHP unit being simulated int const ZoneNum, // zone number where the current PTHP unit is located bool const FirstHVACIteration, // TRUE on first HVAC iteration Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to average airflow over timestep Real64 &ZoneLoad // cooling or heating needed by zone [watts] ); void SetOnOffMassFlowRate(int const PTUnitNum, // number of the current PTHP unit being simulated Real64 const PartLoadFrac, // coil operating part-load ratio Real64 &OnOffAirFlowRatio // ratio of coil on to coil off air flow rate ); void SizePTUnit(int const PTUnitNum); void ControlPTUnitOutput(int const PTUnitNum, // Unit index in fan coil array bool const FirstHVACIteration, // flag for 1st HVAC iteration in the time step int const OpMode, // operating mode: CycFanCycCoil | ContFanCycCoil Real64 const QZnReq, // cooling or heating output needed by zone [W] int const ZoneNum, // Index to zone number Real64 &PartLoadFrac, // unit part load fraction Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep Real64 &SupHeaterLoad, // Supplemental heater load [W] bool &HXUnitOn // flag to enable heat exchanger ); void CalcPTUnit(int const PTUnitNum, // Unit index in fan coil array bool const FirstHVACIteration, // flag for 1st HVAC iteration in the time step Real64 const PartLoadFrac, // compressor part load fraction Real64 &LoadMet, // load met by unit (W) Real64 const QZnReq, // Zone load (W) unused1208 Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep Real64 &SupHeaterLoad, // supplemental heater load (W) bool const HXUnitOn // flag to enable heat exchanger ); void HeatPumpRunFrac(int const PTUnitNum, // PTAC Index Number Real64 const PLR, // part load ratio bool &errFlag, // part load factor out of range flag Real64 &RuntimeFrac // the required run time fraction to meet part load ); Real64 HotWaterCoilResidual(Real64 const HWFlow, // hot water flow rate in kg/s Array1<Real64> const &Par // Par(5) is the requested coil load ); Real64 SupSATResidual(Real64 &TempSupHeater, // supplemental heater load at maximum SAT Array1<Real64> const &Par // par(1) = PTUnitNum ); Real64 PLRResidual(Real64 const PartLoadFrac, // compressor cycling ratio (1.0 is continuous, 0.0 is off) Array1<Real64> const &Par // par(1) = PTUnitNum ); void SetAverageAirFlow(int const PTUnitNum, // Unit index Real64 const PartLoadRatio, // unit part load ratio Real64 &OnOffAirFlowRatio // ratio of compressor ON airflow to average airflow over timestep ); void ReportPTUnit(int const PTUnitNum); // number of the current AC unit being simulated int GetPTUnitZoneInletAirNode(int const PTUnitCompIndex, int const PTUnitType); int GetPTUnitOutAirNode(int const PTUnitCompIndex, int const PTUnitType); int GetPTUnitReturnAirNode(int const PTUnitCompIndex, int const PTUnitType); int GetPTUnitMixedAirNode(int const PTUnitCompIndex, int const PTUnitType); //****************************************************************************** void SimVariableSpeedHP(int const PTUnitNum, // number of the current engine driven Heat Pump being simulated int const ZoneNum, // Controlled zone number bool const FirstHVACIteration, // TRUE if 1st HVAC simulation of system timestep Real64 const QZnReq, // required zone load Real64 const QLatReq, // required latent load Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep int const OpMode, // operating mode: CycFanCycCoil | ContFanCycCoil bool const HXUnitOn // flag to enable heat exchanger ); //****************************************************************************** //****************************************************************************** void ControlVSHPOutput(int const PTUnitNum, // Unit index in fan coil array bool const FirstHVACIteration, // flag for 1st HVAC iteration in the time step int const CompOp, // compressor operation; 1=on, 0=off int const OpMode, // operating mode: CycFanCycCoil | ContFanCycCoil Real64 const QZnReq, // cooling or heating output needed by zone [W] Real64 const QLatReq, // latent cooling output needed by zone [W] int const ZoneNum, // Index to zone number int &SpeedNum, // Speed number Real64 &SpeedRatio, // unit speed ratio for DX coils Real64 &PartLoadFrac, // unit part load fraction Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep Real64 &SupHeaterLoad, // Supplemental heater load [W] bool const HXUnitOn // flag to enable heat exchanger ); //****************************************************************************** //****************************************************************************** Real64 VSHPCyclingResidual(Real64 const PartLoadFrac, // compressor cycling ratio (1.0 is continuous, 0.0 is off) Array1<Real64> const &Par // par(1) = FurnaceNum ); //****************************************************************************** Real64 VSHPSpeedResidual(Real64 const SpeedRatio, // compressor cycling ratio (1.0 is continuous, 0.0 is off) Array1<Real64> const &Par // par(1) = MSHPNum ); //****************************************************************************** void CalcVarSpeedHeatPump(int const PTUnitNum, // Unit index in fan coil array int const ZoneNum, // Zone index bool const FirstHVACIteration, // flag for 1st HVAC iteration in the time step int const CompOp, // Compressor on/off; 1=on, 0=off int const SpeedNum, // Speed number Real64 const SpeedRatio, // Compressor speed ratio Real64 const PartLoadFrac, // compressor part load fraction Real64 &LoadMet, // load met by unit (W) Real64 &LatentLoadMet, // Latent cooling load met (furnace outlet with respect to control zone humidity ratio) Real64 const QZnReq, // Zone load (W) unused1208 Real64 const QLatReq, // Zone latent load [] Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to AVERAGE airflow over timestep Real64 &SupHeaterLoad, // supplemental heater load (W) bool const HXUnitOn // flag to enable heat exchanger ); void SetVSHPAirFlow(int const PTUnitNum, // Unit index int const ZoneNum, // Zone index Real64 const PartLoadRatio, // unit part load ratio Real64 &OnOffAirFlowRatio, // ratio of compressor ON airflow to average airflow over timestep Optional_int_const SpeedNum = _, // Speed number Optional<Real64 const> SpeedRatio = _ // Speed ratio ); void SetOnOffMassFlowRateVSCoil(int const PTUnitNum, // index to furnace int const ZoneNum, // index to zone bool const FirstHVACIteration, // Flag for 1st HVAC iteration int const AirLoopNum, // index to air loop !unused1208 Real64 &OnOffAirFlowRatio, // ratio of coil on to coil off air flow rate int const OpMode, // fan operating mode Real64 const QZnReq, // sensible load to be met (W) !unused1208 Real64 const MoistureLoad, // moisture load to be met (W) Real64 &PartLoadRatio // coil part-load ratio ); void SetMinOATCompressor(int const FurnaceNum, // index to furnace std::string const FurnaceName, // name of furnace std::string const cCurrentModuleObject, // type of furnace std::string const CoolingCoilType, // type of cooling coil std::string const CoolingCoilName, // name of cooling coil std::string const HeatingCoilType, // type of heating coil std::string const HeatingCoilName, // name of heating coil bool &ErrorsFound // GetInput logical that errors were found ); Real64 CalcPTUnitWaterFlowResidual(Real64 const PartLoadRatio, // coil PLR Array1<Real64> const &Par // Function parameters ); Real64 CalcPTUnitAirAndWaterFlowResidual(Real64 const PartLoadRatio, // coil PLR Array1<Real64> const &Par // Function parameters ); } // namespace PackagedTerminalHeatPump } // namespace EnergyPlus #endif
69.153565
150
0.623179
[ "object", "model" ]
2f360ae61238cd4132ee431e0d0557d1796abd54
2,821
cpp
C++
Libraries/BulletAnimatSim/BlPlane.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
8
2015-01-09T21:59:50.000Z
2021-04-14T14:08:47.000Z
Libraries/BulletAnimatSim/BlPlane.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
null
null
null
Libraries/BulletAnimatSim/BlPlane.cpp
NeuroRoboticTech/AnimatLabPublicSource
c5b23f8898513582afb7891eb994a7bd40a89f08
[ "BSD-3-Clause" ]
2
2018-12-21T02:58:30.000Z
2020-08-12T11:44:39.000Z
/** \file BlPlane.cpp \brief Implements the vortex plane class. **/ #include "StdAfx.h" #include "BlJoint.h" #include "BlMotorizedJoint.h" #include "BlRigidBody.h" #include "BlPlane.h" #include "BlSimulator.h" namespace BulletAnimatSim { namespace Environment { namespace Bodies { /** \brief Default constructor. \author dcofer \date 4/17/2011 **/ BlPlane::BlPlane() { SetThisPointers(); m_bCullBackfaces = true; //we want back face culling on by default for planes. } /** \brief Destructor. \author dcofer \date 4/17/2011 **/ BlPlane::~BlPlane() { try { DeleteGraphics(); DeletePhysics(false); } catch(...) {Std_TraceMsg(0, "Caught Error in desctructor of BlPlane/\r\n", "", -1, false, true);} } void BlPlane::CreateGraphicsGeometry() { m_osgGeometry = CreatePlaneGeometry(CornerX(), CornerY(), m_ptSize.x, m_ptSize.y, GridX(), GridY(), false); } void BlPlane::CreatePhysicsGeometry() { if(IsCollisionObject()) { DeleteCollisionGeometry(); m_fltMass = 0; //Plane is always a static object. if(m_osgMT.valid()) OsgMovableItem::UpdatePositionAndRotationFromMatrix(m_osgMT->getMatrix()); CStdFPoint vPos = m_lpStructure->Position(); m_eBodyType = STATIC_PLANE_PROXYTYPE; m_btCollisionShape = new btStaticPlaneShape(btVector3(0,1,0), vPos.y); } } void BlPlane::CreateParts() { CreateGeometry(); //Create the geometry and osg drawable nodes. m_eControlType = DynamicsControlType::ControlNode; //This is not a dynamic part. BlRigidBody::CreateItem(); Plane::CreateParts(); } void BlPlane::CreateDynamicPart() { BlSimulator *lpSim = GetBlSimulator(); if(lpSim && m_lpThisRB && m_lpThisAB) { //m_btCollisionShape = new btStaticPlaneShape(btVector3(0,1,0), 1); btRigidBody::btRigidBodyConstructionInfo rbInfo( 0., NULL, m_btCollisionShape, btVector3(0,0,0) ); rbInfo.m_friction = m_lpMaterial->FrictionLinearPrimary(); rbInfo.m_rollingFriction = m_lpMaterial->FrictionAngularPrimaryConverted(); rbInfo.m_restitution = m_lpMaterial->Restitution(); rbInfo.m_linearDamping = m_lpThisRB->LinearVelocityDamping(); rbInfo.m_angularDamping = m_lpThisRB->AngularVelocityDamping(); m_btPart = new btRigidBody(rbInfo); if(!m_lpBulletData) m_lpBulletData = new BlBulletData(this, false); m_btPart->setUserPointer((void *) m_lpBulletData); lpSim->DynamicsWorld()->addRigidBody( m_btPart, AnimatCollisionTypes::RIGID_BODY, ALL_COLLISIONS ); m_osgbMotion = dynamic_cast<osgbDynamics::MotionState *>(m_btPart->getMotionState()); } } // //void BlPlane::ResizePhysicsGeometry() //{ //} //Planes can never have fluid interactions/dynamics. void BlPlane::Physics_FluidDataChanged() {} } //Bodies } // Environment } //BulletAnimatSim
23.122951
108
0.706133
[ "geometry", "object" ]
2f38e1c697dc1e8bff3c6097e5ef86295973dd6d
3,069
cpp
C++
2_1_11/2_1_11.cpp
navigatore/SedgewickWayne
8fe14c3516e60bf03a0ec3ceb7cc7d4e383fc42b
[ "MIT" ]
null
null
null
2_1_11/2_1_11.cpp
navigatore/SedgewickWayne
8fe14c3516e60bf03a0ec3ceb7cc7d4e383fc42b
[ "MIT" ]
null
null
null
2_1_11/2_1_11.cpp
navigatore/SedgewickWayne
8fe14c3516e60bf03a0ec3ceb7cc7d4e383fc42b
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> template <typename T> void shellsort(const T first, const T last) { static constexpr auto gaps = std::array{1L, 4L, 13L, 40L, 121L, 364L, 1093L, 3280L, 9841L, 29524L, 88573L, 265720L, 797161L, 2391484L, 7174453L, 21523360L, 64570081L, 193710244L, 581130733L, 1743392200L, 5230176601L, 15690529804L, 47071589413L, 141214768240L, 423644304721L, 1270932914164L, 3812798742493L, 11438396227480L, 34315188682441L, 102945566047324L, 308836698141973L, 926510094425920L, 2779530283277761L, 8338590849833284L, 25015772549499853L, 75047317648499560L, 225141952945498681L, 675425858836496044L, 2026277576509488133L, 6078832729528464400L}; auto n = last - first; auto hIter = gaps.cbegin(); while (*hIter < n / 3) { ++hIter; } for (; hIter >= gaps.cbegin(); --hIter) { for (auto i = first + *hIter; i < last; ++i) { for (auto k = i; k >= first + *hIter && *k < *(k - *hIter); k -= *hIter) { std::swap(*k, *(k - *hIter)); } } } } int main() { auto v1 = std::vector{44, 92, 10, 48, 34, 96, 58, 84, 57, 1, 58, 83, 60, 20, 73, 62, 96, 4, 18, 51, 44, 78, 76, 39, 21, 87, 29, 45, 81, 71, 89, 88, 24, 73, 89, 57, 27, 38, 75, 65, 70, 80, 64, 100, 24, 45, 62, 18, 34, 53}; auto v2 = v1; shellsort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); assert((v1 == v2)); }
42.625
80
0.284783
[ "vector" ]
2f3b4f3990d39db4c2d3df0ad781fed68a3f17c8
43,251
cpp
C++
interfaces/innerkits/huks_standard/test/moduletest/src/hks_rsa_ecb_oaep_sha256_mt.cpp
openharmony/security_huks
ad5c362e115ab39282b2b6b12c1232a6c54acb4c
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/huks_standard/test/moduletest/src/hks_rsa_ecb_oaep_sha256_mt.cpp
openharmony/security_huks
ad5c362e115ab39282b2b6b12c1232a6c54acb4c
[ "Apache-2.0" ]
null
null
null
interfaces/innerkits/huks_standard/test/moduletest/src/hks_rsa_ecb_oaep_sha256_mt.cpp
openharmony/security_huks
ad5c362e115ab39282b2b6b12c1232a6c54acb4c
[ "Apache-2.0" ]
2
2021-09-13T11:13:36.000Z
2021-12-15T15:10:55.000Z
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "openssl_rsa_helper.h" #include "hks_rsa_common_mt.h" #include <string> #include <vector> #include <gtest/gtest.h> #include "hks_api.h" #include "hks_mem.h" using namespace testing::ext; namespace OHOS { namespace Security { namespace Huks { namespace MT { namespace { const int SET_SIZE_4096 = 4096; const int KEY_SIZE_512 = 512; const int KEY_SIZE_768 = 768; const int KEY_SIZE_1024 = 1024; const int KEY_SIZE_2048 = 2048; const int KEY_SIZE_3072 = 3072; const GenerateKeyCaseParams HKS_RSA_MT_12100_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_512 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_FAILURE, .decryptResult = HKS_SUCCESS, }; const GenerateKeyCaseParams HKS_RSA_MT_12200_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_768 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_FAILURE, .decryptResult = HKS_SUCCESS, }; const GenerateKeyCaseParams HKS_RSA_MT_12300_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_1024 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const GenerateKeyCaseParams HKS_RSA_MT_12400_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_2048 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const GenerateKeyCaseParams HKS_RSA_MT_12500_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_3072 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const GenerateKeyCaseParams HKS_RSA_MT_12600_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_4096 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_12700_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_512 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_ERROR_INVALID_KEY_FILE, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_12800_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_512 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = KEY_SIZE_512, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_ERROR_INVALID_KEY_FILE, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_12900_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_768 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_13000_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_768 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = KEY_SIZE_768, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_13100_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_1024 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_13200_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_1024 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = KEY_SIZE_1024, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_13300_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_2048 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_13400_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_2048 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = KEY_SIZE_2048, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_13500_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_3072 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_13600_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_3072 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = KEY_SIZE_3072, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptLocalCaseParams HKS_RSA_MT_13700_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_4096 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const EncryptServiceCaseParams HKS_RSA_MT_13800_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_4096 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .keySize = SET_SIZE_4096, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_13900_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_512 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_FAILURE, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_14000_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_512 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_FAILURE, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_14100_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_768 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_14200_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_768 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_14300_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_1024 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_14400_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_1024 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_14500_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_2048 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_14600_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_2048 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_14700_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_3072 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_14800_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_3072 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptLocalCaseParams HKS_RSA_MT_14900_PARAMS = { .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_TEMP }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_4096 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = false }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; const DecryptServiceCaseParams HKS_RSA_MT_15000_PARAMS = { .alias = "This is a test auth id for OAEPWithSHA-256", .params = { { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_RSA }, { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_RSA_KEY_SIZE_4096 }, { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_SHA256 }, { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_OAEP }, { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_ECB }, }, .hexData = "00112233445566778899aabbccddeeff", .padding = RSA_PKCS1_OAEP_PADDING, .keyDigest = HKS_DIGEST_SHA256, .generateKeyResult = HKS_SUCCESS, .encryptResult = HKS_SUCCESS, .decryptResult = HKS_SUCCESS, }; } // namespace class HksRsaEcbOaepSha256Mt : public HksRsaCommonMt, public testing::Test {}; /** * @tc.number : HksRsaEcbOaepSha256Mt12100 * @tc.name : HksRsaEcbOaepSha256Mt12100 * @tc.desc : Test huks generate key (512_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12100, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12100_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12200 * @tc.name : HksRsaEcbOaepSha256Mt12200 * @tc.desc : Test huks generate key (768_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12200, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12200_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12300 * @tc.name : HksRsaEcbOaepSha256Mt12300 * @tc.desc : Test huks generate key (1024_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12300, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12300_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12400 * @tc.name : HksRsaEcbOaepSha256Mt12400 * @tc.desc : Test huks generate key (2048_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12400, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12400_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12500 * @tc.name : HksRsaEcbOaepSha256Mt12500 * @tc.desc : Test huks generate key (3072_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12500, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12500_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12600 * @tc.name : HksRsaEcbOaepSha256Mt12600 * @tc.desc : Test huks generate key (4096_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12600, TestSize.Level1) { GenerateKeyTestCase(HKS_RSA_MT_12600_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12700 * @tc.name : HksRsaEcbOaepSha256Mt12700 * @tc.desc : Test huks Encrypt (512_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12700, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_12700_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12800 * @tc.name : HksRsaEcbOaepSha256Mt12800 * @tc.desc : Test huks Encrypt (512_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12800, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_12800_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt12900 * @tc.name : HksRsaEcbOaepSha256Mt12900 * @tc.desc : Test huks Encrypt (768_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt12900, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_12900_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13000 * @tc.name : HksRsaEcbOaepSha256Mt13000 * @tc.desc : Test huks Encrypt (768_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13000, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_13000_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13100 * @tc.name : HksRsaEcbOaepSha256Mt13100 * @tc.desc : Test huks Encrypt (1024_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13100, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_13100_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13200 * @tc.name : HksRsaEcbOaepSha256Mt13200 * @tc.desc : Test huks Encrypt (1024_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13200, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_13200_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13300 * @tc.name : HksRsaEcbOaepSha256Mt13300 * @tc.desc : Test huks Encrypt (2048_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13300, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_13300_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13400 * @tc.name : HksRsaEcbOaepSha256Mt13400 * @tc.desc : Test huks Encrypt (2048_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13400, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_13400_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt00100 * @tc.name : HksRsaEcbOaepSha256Mt00100 * @tc.desc : Test huks Encrypt (3072_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13500, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_13500_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13600 * @tc.name : HksRsaEcbOaepSha256Mt13600 * @tc.desc : Test huks Encrypt (3072_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13600, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_13600_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13700 * @tc.name : HksRsaEcbOaepSha256Mt13700 * @tc.desc : Test huks Encrypt (4096_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13700, TestSize.Level1) { EncryptLocalTestCase(HKS_RSA_MT_13700_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13800 * @tc.name : HksRsaEcbOaepSha256Mt13800 * @tc.desc : Test huks Encrypt (4096_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13800, TestSize.Level1) { EncryptServiceTestCase(HKS_RSA_MT_13800_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt13900 * @tc.name : HksRsaEcbOaepSha256Mt13900 * @tc.desc : Test huks Decrypt (512_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt13900, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_13900_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14000 * @tc.name : HksRsaEcbOaepSha256Mt14000 * @tc.desc : Test huks Decrypt (512_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14000, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_14000_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14100 * @tc.name : HksRsaEcbOaepSha256Mt14100 * @tc.desc : Test huks Decrypt (768_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14100, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_14100_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14200 * @tc.name : HksRsaEcbOaepSha256Mt14200 * @tc.desc : Test huks Decrypt (768_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14200, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_14200_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14300 * @tc.name : HksRsaEcbOaepSha256Mt14300 * @tc.desc : Test huks Decrypt (1024_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14300, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_14300_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14400 * @tc.name : HksRsaEcbOaepSha256Mt14400 * @tc.desc : Test huks Decrypt (1024_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14400, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_14400_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14500 * @tc.name : HksRsaEcbOaepSha256Mt14500 * @tc.desc : Test huks Decrypt (2048_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14500, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_14500_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14600 * @tc.name : HksRsaEcbOaepSha256Mt14600 * @tc.desc : Test huks Decrypt (2048_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14600, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_14600_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14700 * @tc.name : HksRsaEcbOaepSha256Mt14700 * @tc.desc : Test huks Decrypt (3072_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14700, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_14700_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14800 * @tc.name : HksRsaEcbOaepSha256Mt14800 * @tc.desc : Test huks Decrypt (3072_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14800, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_14800_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt14900 * @tc.name : HksRsaEcbOaepSha256Mt14900 * @tc.desc : Test huks Decrypt (4096_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/TEMP) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt14900, TestSize.Level1) { DecryptLocalTestCase(HKS_RSA_MT_14900_PARAMS); } /** * @tc.number : HksRsaEcbOaepSha256Mt15000 * @tc.name : HksRsaEcbOaepSha256Mt15000 * @tc.desc : Test huks Decrypt (4096_RSA/ECB/RSA/ECB/OAEPWithSHA-256AndMGF1Padding/PERSISTENT) */ HWTEST_F(HksRsaEcbOaepSha256Mt, HksRsaEcbOaepSha256Mt15000, TestSize.Level1) { DecryptServiceTestCase(HKS_RSA_MT_15000_PARAMS); } } // namespace MT } // namespace Huks } // namespace Security } // namespace OHOS
43.468342
105
0.682597
[ "vector" ]
2f409fa2d076196827fc622823924c1aa6ac95b0
2,120
cc
C++
Delay_in_Networks/Dijkstra.cc
acmpesuecc/Simple_Algos
7d9e4b1b1b3b5d87c1acd4ca881116abcd47ec36
[ "MIT" ]
null
null
null
Delay_in_Networks/Dijkstra.cc
acmpesuecc/Simple_Algos
7d9e4b1b1b3b5d87c1acd4ca881116abcd47ec36
[ "MIT" ]
7
2020-10-23T18:18:27.000Z
2020-10-25T10:01:31.000Z
Delay_in_Networks/Dijkstra.cc
acmpesuecc/Simple_Algos
7d9e4b1b1b3b5d87c1acd4ca881116abcd47ec36
[ "MIT" ]
3
2020-10-24T05:37:09.000Z
2020-10-24T10:59:14.000Z
#include<iostream> #include<vector> #include<limits> #include<bits/stdc++.h> using pairType = std::pair<int, int>; using graphType = std::unordered_map<int, vector<pairType> >; using heapType = std::priority_queue<pairType, vector<pairType> >; int dijkstra(const int & K, const int &N, std::vector<int> &delay, graphType & graph, const int &TIMEOUT ) { int d = -1; heapType Q; delay[K]=0; Q.push(std::make_pair(0, K)); while(Q.size()>0){ const std::pair<int, int> dnode = Q.top(); int node = dnode.second; Q.pop(); const vector<pairType> vec_link = graph[node]; for(const auto & vw : vec_link) { int v = vw.first; int w = vw.second; if(delay[node] + w < delay[v]) { delay[v] = delay[node] + w; Q.push(std::make_pair(-w, v)); } } } for(const auto & it : delay) { if( it > d ) d = it; if( it == TIMEOUT) return -1; } return d; } int networkDelayTime(vector<vector<int>>& times, int N, int K) { const int TIMEOUT = 10000; std::vector<int> delay(N, TIMEOUT); graphType graph; for(int i=0; i < times.size(); i++) { int u = times[i][0] -1; int v = times[i][1] -1; int w = times[i][2]; graph[u].push_back(make_pair(v, w)); } return dijkstra(K-1, N, delay, graph, TIMEOUT); } int main() { int N, E, K; cout<<"Enter the number of Nodes in Network\n"; cin >> N; cout<<"Enter number of Edges in Network\n"; cin>>E; cout<<"Enter the starting Node ranging from 1 to N\n"; cin>>K; vector<vector<int>> times; cout<<"Enter source node , destination node and time taken to go from source to destination\n"; for (int i = 0; i < E; ++i) { int u, v, w; cin >> u >> v >> w; times.push_back(vector<int>({u,v,w})); } cout << "The Delay is :\n"<<networkDelayTime(times, N, K)<<"\n"; return 0; }
24.367816
107
0.511321
[ "vector" ]
2f43591dff729dcba381c1d29140bc0957360025
5,521
cpp
C++
src/ProcMonGUI/ProcMonGUIDlg.cpp
apriorit/windows-process-monitor
97197b898555daebe7a2a4a68e373dc5bea6da6b
[ "MIT" ]
100
2017-04-14T01:02:10.000Z
2022-02-10T07:42:33.000Z
src/ProcMonGUI/ProcMonGUIDlg.cpp
apriorit/windows-process-monitor
97197b898555daebe7a2a4a68e373dc5bea6da6b
[ "MIT" ]
1
2021-05-30T20:19:07.000Z
2021-05-30T20:19:07.000Z
src/ProcMonGUI/ProcMonGUIDlg.cpp
apriorit/windows-process-monitor
97197b898555daebe7a2a4a68e373dc5bea6da6b
[ "MIT" ]
44
2017-05-04T12:55:36.000Z
2021-12-09T08:21:44.000Z
// ProcMonGUIDlg.cpp : implementation file // #include "stdafx.h" #include "ProcMonGUI.h" #include "ProcMonGUIDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CProcMonGUIDlg dialog CProcMonGUIDlg::CProcMonGUIDlg(CWnd* pParent /*=NULL*/) : CDialog(CProcMonGUIDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CProcMonGUIDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CProcMonGUIDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_INSTALL_DRIVER, &CProcMonGUIDlg::OnBnClickedInstallDriver) ON_BN_CLICKED(IDC_START_DRIVER, &CProcMonGUIDlg::OnBnClickedStartDriver) ON_BN_CLICKED(IDC_STOP_DRIVER, &CProcMonGUIDlg::OnBnClickedStopDriver) ON_BN_CLICKED(IDC_UNINSTALL_DRIVER, &CProcMonGUIDlg::OnBnClickedUninstallDriver) ON_BN_CLICKED(IDC_START_MONITOR, &CProcMonGUIDlg::OnBnClickedStartMonitor) ON_BN_CLICKED(IDC_STOP_MONITOR, &CProcMonGUIDlg::OnBnClickedStopMonitor) ON_BN_CLICKED(IDOK, &CProcMonGUIDlg::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CProcMonGUIDlg::OnBnClickedCancel) END_MESSAGE_MAP() // CProcMonGUIDlg message handlers BOOL CProcMonGUIDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here RefreshDriverStatus(); return TRUE; // return TRUE unless you set the focus to a control } void CProcMonGUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CProcMonGUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CProcMonGUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CProcMonGUIDlg::OnBnClickedInstallDriver() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Install()); RefreshDriverStatus(); } void CProcMonGUIDlg::OnBnClickedStartDriver() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Start()); RefreshDriverStatus(); } void CProcMonGUIDlg::OnBnClickedStopDriver() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Stop()); RefreshDriverStatus(); } void CProcMonGUIDlg::OnBnClickedUninstallDriver() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Uninstall()); RefreshDriverStatus(); } void CProcMonGUIDlg::OnBnClickedStartMonitor() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Init(Callbacks::ListCallback)); } void CProcMonGUIDlg::OnBnClickedStopMonitor() { // TODO: Add your control notification handler code here ErrorDispatcher::Dispatch(Deinit()); } void CProcMonGUIDlg::OnBnClickedOk() { // TODO: Add your control notification handler code here OnOK(); } void CProcMonGUIDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here OnCancel(); } void CProcMonGUIDlg::RefreshDriverStatus() { int status = 0; ErrorDispatcher::Dispatch(GetStatus(&status)); DriverStatus::Type driverStatus = (DriverStatus::Type)status; if (driverStatus == DriverStatus::Running) { SetDlgItemText(IDC_LABEL_INFO, _T("Status: Driver is started")); } else if (driverStatus == DriverStatus::NotInstalled) { SetDlgItemText(IDC_LABEL_INFO, _T("Status: Drver is not installed")); } else if (driverStatus == DriverStatus::Installed) { SetDlgItemText(IDC_LABEL_INFO, _T("Status: Driver is installed")); } }
23.493617
86
0.751494
[ "model" ]
2f4f91dae0cb910214ae18b61a6276a021dc3011
10,394
cpp
C++
server.cpp
s25g5d4/netproghw2
05739f27eaae0a4436f753f6b03fc52d217118e4
[ "MIT" ]
null
null
null
server.cpp
s25g5d4/netproghw2
05739f27eaae0a4436f753f6b03fc52d217118e4
[ "MIT" ]
null
null
null
server.cpp
s25g5d4/netproghw2
05739f27eaae0a4436f753f6b03fc52d217118e4
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <exception> #include <cstdio> #include <cstdlib> #include <cstring> #include "commons.hpp" #include "my_huffman.hpp" extern "C" { #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <netdb.h> #include <signal.h> #include <errno.h> #include "my_send_recv.h" } #define LISTEN_PORT 1732 #define BUFLEN 65536 int sockfd = 0; int clientfd = 0; char welcome_msg[] = "Welcome to my netprog hw2 FTP server\n"; /** * Descrption: Clean exit when SIGINT received. */ static void sigint_safe_exit(int sig); /** * Descrption: Determine and return IPv4 or IPv6 address object. * Return: IPv4 or IPv6 address object (sin_addr or sin6_addr). */ static const void *get_in_addr(const struct sockaddr &sa); /** * Descrption: Get port number from sockaddr object. * Return: Unsigned short, host byte order port number. */ static uint16_t get_in_port(const struct sockaddr &sa); /** * Descrption: Start server and listening to clients. * Return: 0 if succeed, or -1 if fail. */ static int start_server(); /** * Descrption: Print client info and send welcome message to client. * Return: 0 if succeed, or -1 if fail. */ static int welcome(const struct sockaddr &client_addr); /** * Descrption: Receive file sent from client. * Return: 0 if succeed, or -1 if fail. */ static int receive_file(std::vector<std::string> &cmd, const char *orig_cmd); /** * Descrption: Read and serve client. * Return: 0 if succeed, or -1 if fail. */ static int serve_client(); int main() { // Handle SIGINT struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_handler = sigint_safe_exit; sa.sa_flags = 0; sigaction(SIGINT, &sa, NULL); using namespace std; // Start server int status = start_server(); if (status != 0) { if (sockfd > 2) { close(sockfd); } cerr << "Fail to start server." << endl; exit(1); } struct sockaddr_storage client_addr = {}; socklen_t client_addr_size = sizeof (client_addr); // Accept client connecting. clientfd = accept(sockfd, reinterpret_cast<struct sockaddr *>(&client_addr), &client_addr_size); while (clientfd > 0) { welcome(reinterpret_cast<struct sockaddr &>(client_addr)); serve_client(); close(clientfd); my_clean_buf(); // See my_send_recv.h cout << "Connection terminated." << endl; clientfd = accept(sockfd, reinterpret_cast<struct sockaddr *>(&client_addr), &client_addr_size); } // Abnormal exit. if (clientfd < 0) { perror("accept"); } close(sockfd); return 1; } static void sigint_safe_exit(int sig) { if (clientfd > 2) { close(clientfd); } if (sockfd > 2) { close(sockfd); } std::cerr << "Interrupt." << std::endl; exit(1); } static const void *get_in_addr(const struct sockaddr &sa) { if (sa.sa_family == AF_INET) { return &(reinterpret_cast<const struct sockaddr_in *>(&sa)->sin_addr); } return &(reinterpret_cast<const struct sockaddr_in6 *>(&sa)->sin6_addr); } static uint16_t get_in_port(const struct sockaddr &sa) { if (sa.sa_family == AF_INET) { return ntohs(reinterpret_cast<const struct sockaddr_in *>(&sa)->sin_port); } return ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&sa)->sin6_port); } static int start_server() { // Create socket int addr_family = AF_INET6; sockfd = socket(PF_INET6, SOCK_STREAM, 0); if (sockfd < 0) { std::cout << "Fail to open IPv6 socket. Fallback to IPv4 socket." << std::endl; addr_family = AF_INET; sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return -1; } } int status; // Set IPv6 dual stack socket if (addr_family == AF_INET6) { int no = 0; status = setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &no, sizeof (no)); if (status != 0) { std::cout << "Fail to set dual stack socket. Fallback to IPv4 socket." << std::endl; close(sockfd); addr_family = AF_INET; sockfd = socket(PF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); return -1; } } } if (addr_family == AF_INET6) { struct sockaddr_in6 any_addr = {}; any_addr.sin6_family = AF_INET6; any_addr.sin6_port = htons(LISTEN_PORT); status = bind(sockfd, reinterpret_cast<const struct sockaddr *>(&any_addr), sizeof (any_addr)); } else { struct sockaddr_in any_addr = {}; any_addr.sin_family = AF_INET; any_addr.sin_port = htons(LISTEN_PORT); status = bind(sockfd, reinterpret_cast<const struct sockaddr *>(&any_addr), sizeof (any_addr)); } if (status < 0) { perror("bind"); return -1; } status = listen(sockfd, 1); if (status < 0) { perror("listen"); return -1; } std::cout << "Start listening at port " << LISTEN_PORT << "." << std::endl; return 0; } static int welcome(const struct sockaddr &client_addr) { char client_addr_p[INET6_ADDRSTRLEN] = {}; if (inet_ntop(client_addr.sa_family, get_in_addr(client_addr), client_addr_p, sizeof (client_addr_p)) == NULL) { perror("inet_ntop"); return -1; } // Extract address from IPv4-mapped IPv6 address. int offset = (memcmp(client_addr_p, "::ffff:", 7) == 0) ? 7 : 0; std::cout << "Connection from " << (client_addr_p + offset) << " port " << get_in_port(client_addr) << " protocol SOCK_STREAM(TCP) accepted." << std::endl; int msglen = (int) strlen(welcome_msg); return my_send(clientfd, welcome_msg, &msglen); } static int receive_file(std::vector<std::string> &cmd, const char *orig_cmd) { using namespace std; if (cmd.size() < 3) { cout << "Invalid command received. Terminating connection..." << endl; return -1; } int filesize; try { filesize = stoi(cmd[1]); } catch (exception &e) { cout << "Invalid command received. Terminating connection..." << endl; return -1; } // Extract filename const char *filename_c_str = strstr(orig_cmd, cmd[2].c_str()); if (filename_c_str == NULL) { cout << "Invalid command received. Terminating connection..." << endl; return -1; } string filename = filename_c_str; string codefilename = filename + ".code"; fstream codefile(codefilename, fstream::out | fstream::binary | fstream::trunc); if (!codefile.is_open()) { cout << "Failed to open file " << codefilename << "." << endl; cout << "An error has occurred. Terminating connection..." << endl; return -1; } cout << "Receiving " << filename << " ..." << endl; // Write header and compressed data into codefile int status = -1; int received = 0; while (received < filesize) { uint8_t buf[BUFLEN]; int buflen = (filesize - received < BUFLEN) ? (filesize - received) : BUFLEN; status = my_recv_data(clientfd, buf, &buflen); if (status < 0) { perror("my_recv_data"); break; } if (buflen == 0) { cout << "Connection closed by peer." << endl; status = -1; break; } received += buflen; codefile.write(reinterpret_cast<const char *>(&buf), static_cast<streamsize>(buflen)); } if (status < 0) { cout << "An error has occurred. Terminating connection..." << endl; return -1; } string response = "OK " + to_string(filesize) + " bytes received.\n"; int reslen = static_cast<int>(response.size()); status = my_send(clientfd, response.c_str(), &reslen); if (status < 0) { perror("my_send"); cout << "An error has occurred. Terminating connection..." << endl; return -1; } cout << response; fstream file(filename, fstream::out | fstream::binary | fstream::trunc); if (!file.is_open()) { cout << "Failed to open file " << filename << "." << endl; cout << "An error has occurred. Terminating connection..." << endl; return -1; } // Decode file codefile.close(); codefile.open(codefilename, fstream::in | fstream::binary); my_huffman::huffman_decode decode(codefile); decode.write(file); // Write code table to codefile codefile.close(); codefile.open(codefilename, fstream::out | fstream::binary | fstream::trunc); int char_code = 0; for (auto &code : decode.char_table) { string s(code.size(), '0'); for (unsigned int i = 0; i < code.size(); ++i) { if (code[i]) { s[i] = '1'; } } codefile << char_code++ << ": " << s << endl; } cout << "Uncompressed file size: " << file.tellp() << " bytes. "; cout.precision(2); cout.setf(ios::fixed); cout << "Compression ratio: " << static_cast<double>(filesize) * 100.0 / static_cast<double>(file.tellp()) << "%." << endl; cout << "Huffman coding table is saved in " << codefilename << " ." << endl; return 0; } static int serve_client() { using namespace std; while (true) { char orig_cmd[MAX_CMD]; int cmdlen = MAX_CMD; int status = my_recv_cmd(clientfd, orig_cmd, &cmdlen); if (status > 0) { if (cmdlen == 0) { // cmdlen == 0 means connection closed by peer. break; } cout << "Invalid command received. Terminating connection..." << endl; return -1; } else if (status < 0) { perror("my_recv_cmd"); return -1; } orig_cmd[cmdlen - 1] = '\0'; vector<string> cmd = parse_command(orig_cmd); if (cmd.size() == 0) { continue; } if (cmd[0] == "send") { if (receive_file(cmd, orig_cmd) < 0) { return -1; } } else { cout << "Invalid command received. Terminating connection..." << endl; return -1; } } return 0; }
27.138381
127
0.583895
[ "object", "vector" ]
016dfc500ac2c1448625c1738449dd5818f6a211
593
cc
C++
minimal_cost.cc
jamie-jjd/oj
5c9b89c8b1455cc9c85233bac19eb866fd76e62a
[ "MIT" ]
null
null
null
minimal_cost.cc
jamie-jjd/oj
5c9b89c8b1455cc9c85233bac19eb866fd76e62a
[ "MIT" ]
null
null
null
minimal_cost.cc
jamie-jjd/oj
5c9b89c8b1455cc9c85233bac19eb866fd76e62a
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> int main () { uint64_t N {}; while (std::cin >> N && N) { std::priority_queue<uint64_t, std::vector<uint64_t>, std::greater<uint64_t>> min_heap; for (uint64_t i {}, x {}; i != N; ++i) { std::cin >> x; min_heap.push(x); } uint64_t cost {}; while (min_heap.size() != 1) { auto min {min_heap.top()}; min_heap.pop(); auto second_min {min_heap.top()}; min_heap.pop(); auto sum {min + second_min}; min_heap.push(sum); cost += sum; } std::cout << cost << "\n"; } return 0; }
21.962963
90
0.532884
[ "vector" ]
01758d8df79b9d2ec64c277a3f5ec9ee851efa81
2,732
cpp
C++
CFD/UI/Graphics3DAxes.cpp
shellshocked2003/WE-UQ
b5d296b604310ce49a01dcce91c8c05405146d88
[ "BSD-2-Clause" ]
5
2019-08-22T13:39:06.000Z
2021-08-22T15:44:51.000Z
CFD/UI/Graphics3DAxes.cpp
shellshocked2003/WE-UQ
b5d296b604310ce49a01dcce91c8c05405146d88
[ "BSD-2-Clause" ]
null
null
null
CFD/UI/Graphics3DAxes.cpp
shellshocked2003/WE-UQ
b5d296b604310ce49a01dcce91c8c05405146d88
[ "BSD-2-Clause" ]
11
2019-05-07T05:07:07.000Z
2021-08-22T15:44:53.000Z
#include "Graphics3DAxes.h" #include <Qt3DExtras/QPhongAlphaMaterial> #include <Qt3DExtras/QCuboidMesh> #include <Qt3DExtras/QCylinderMesh> #include <Qt3DExtras/QText2DEntity> Graphics3DAxes::Graphics3DAxes(Qt3DCore::QEntity* rootEntity, QObject *parent) : QObject(parent) { //Origin Cube auto cubeEntity = new Qt3DCore::QEntity(rootEntity); auto cubeMesh = new Qt3DExtras::QCuboidMesh(); cubeMesh->setXExtent(0.5); cubeMesh->setYExtent(0.5); cubeMesh->setZExtent(0.5); auto cubeMaterial = new Qt3DExtras::QPhongAlphaMaterial(cubeEntity); cubeMaterial->setAmbient(QColor(125, 125, 125)); cubeEntity->addComponent(cubeMesh); cubeEntity->addComponent(cubeMaterial); //X Axis auto xAxisTransform = new Qt3DCore::QTransform(); xAxisTransform->setRotationZ(90.0f); xAxisTransform->setTranslation(QVector3D(1.0f, 0.0f, 0.0f)); auto xAxisLabelTransform = new Qt3DCore::QTransform(); xAxisLabelTransform->setTranslation(QVector3D(1.5f, 0.0f, 0.0f)); addAxis(rootEntity, "X", QColor(255, 0, 0), xAxisTransform, xAxisLabelTransform); //Y Axis auto yAxisTransform = new Qt3DCore::QTransform(); yAxisTransform->setRotationX(90.0f); yAxisTransform->setTranslation(QVector3D(0.0f, 0.0f, 1.0f)); auto yAxisLabelTransform = new Qt3DCore::QTransform(); yAxisLabelTransform->setTranslation(QVector3D(-0.5f, 0.0f, 2.0f)); addAxis(rootEntity, "Y", QColor(0, 255, 0), yAxisTransform, yAxisLabelTransform); //X Axis auto zAxisTransform = new Qt3DCore::QTransform(); zAxisTransform->setTranslation(QVector3D(0.0f, 1.0f, 0.0f)); auto zAxisLabelTransform = new Qt3DCore::QTransform(); zAxisLabelTransform->setTranslation(QVector3D(-0.5f, 2.0f, 0.0f)); addAxis(rootEntity, "Z", QColor(0, 0, 255), zAxisTransform, zAxisLabelTransform); } void Graphics3DAxes::addAxis(Qt3DCore::QEntity* rootEntity, QString name, QColor color, Qt3DCore::QTransform* transform, Qt3DCore::QTransform* labelTransform) { auto axisEntity = new Qt3DCore::QEntity(rootEntity); auto axisMesh = new Qt3DExtras::QCylinderMesh(); axisMesh->setLength(2.0f); axisMesh->setRadius(0.2f); auto axisMaterial = new Qt3DExtras::QPhongAlphaMaterial(axisEntity); axisMaterial->setAmbient(color); axisEntity->addComponent(axisMesh); axisEntity->addComponent(axisMaterial); axisEntity->addComponent(transform); auto axisLabelEntity = new Qt3DExtras::QText2DEntity(rootEntity); axisLabelEntity->setFont(QFont("monospace", 1)); axisLabelEntity->setHeight(2); axisLabelEntity->setWidth(2); axisLabelEntity->setText(name); axisLabelEntity->setColor(color); axisLabelEntity->addComponent(labelTransform); }
37.944444
158
0.732064
[ "transform" ]
0177bd771db1cc1bf0d205bc65fb6453287b02f6
2,231
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/AdvancingFrontNode.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/AdvancingFrontNode.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/AdvancingFrontNode.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::ProBuilder::Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Forward declaring type: TriangulationPoint class TriangulationPoint; // Forward declaring type: DelaunayTriangle class DelaunayTriangle; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder.Poly2Tri namespace UnityEngine::ProBuilder::Poly2Tri { // Autogenerated type: UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode class AdvancingFrontNode : public ::Il2CppObject { public: // public UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode Next // Offset: 0x10 UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode* Next; // public UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode Prev // Offset: 0x18 UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode* Prev; // public System.Double Value // Offset: 0x20 double Value; // public UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint Point // Offset: 0x28 UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* Point; // public UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle Triangle // Offset: 0x30 UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* Triangle; // public System.Void .ctor(UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint point) // Offset: 0x191255C static AdvancingFrontNode* New_ctor(UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint* point); // public System.Boolean get_HasNext() // Offset: 0x19125A4 bool get_HasNext(); // public System.Boolean get_HasPrev() // Offset: 0x19125B4 bool get_HasPrev(); }; // UnityEngine.ProBuilder.Poly2Tri.AdvancingFrontNode } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Poly2Tri::AdvancingFrontNode*, "UnityEngine.ProBuilder.Poly2Tri", "AdvancingFrontNode"); #pragma pack(pop)
41.314815
136
0.737786
[ "object" ]
017ded569ee9eaca7071ce54426d1115bdee39fb
4,503
cpp
C++
First semester/Homework/3/dz3.2[icYFTL].cpp
icYFTL/Procedural_programming
438ce2a5cbaac68b9b628db03c4390a2e20eba42
[ "Apache-2.0" ]
3
2020-09-10T19:39:47.000Z
2020-09-24T16:10:11.000Z
First semester/Homework/3/dz3.2[icYFTL].cpp
icYFTL/MIREA_Programming
438ce2a5cbaac68b9b628db03c4390a2e20eba42
[ "Apache-2.0" ]
null
null
null
First semester/Homework/3/dz3.2[icYFTL].cpp
icYFTL/MIREA_Programming
438ce2a5cbaac68b9b628db03c4390a2e20eba42
[ "Apache-2.0" ]
1
2019-12-19T15:30:39.000Z
2019-12-19T15:30:39.000Z
/* * NOTICE: THIS SOLUTION PROBABLY WILL NOT WORK CORRECTLY * NOTICE: U NEED TO DOWNLOAD AND CONNECT BOOST LIBRARY TO THE PROJECT (GOOGLE IT) * */ #define _WIN32_WINNT 0x0A00 #define BOOST_DATE_TIME_NO_LIB #define BOOST_REGEX_NO_LIB #include <vector> #include <iostream> #include <string> #include <fstream> #include <boost/asio.hpp> #include <boost/format.hpp> #include <sstream> #include <regex> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string.hpp> #include <cstdlib> using namespace std; using boost::asio::ip::tcp; double m, S, n; string host = "api.wolframalpha.com"; string url = url = "/v2/query?input=m+%3D+%28S+*+p%2F100+*+pow%28%281+%2B+p%2F100%29%2C+n%29%29+%2F+%2812+*+%28%28pow%28%281+%2B+p%2F100%29%2C+n%29+-+1%29%29%29+for+m+%3D+" + to_string(m) + "%2C+S+%3D+" + to_string(S) + "%2C+n+%3D+" + to_string(n) + "&appid=" + this->app_id; string app_id = "VKQG3T-QE5HK5QU2Y"; string request() { try { boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(this->host, "http"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "GET " << this->url << " HTTP/1.0\r\n"; request_stream << "Host: " << this->host << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n\r\n"; boost::asio::write(socket, request); boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return "None"; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return "None"; } boost::asio::read_until(socket, response, "\r\n\r\n"); std::string header; //while (std::getline(response_stream, header) && header != "\r") //std::cout << header << "\n"; //std::cout << "\n"; stringstream answer; if (response.size() > 0) answer << &response; boost::system::error_code error; while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) answer << &response; return answer.str(); if (error != boost::asio::error::eof) throw boost::system::system_error(error); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return "None"; } void write_it(string ans) { ofstream fout("ans.txt"); fout << ans; fout.close(); } string get_p(string data) { string out = ""; smatch m; regex e("alt='p[ ]?\\D+[ ]?[0-9.]+'"); if (regex_search(data, m, e)) { for (string ans : m) { out += ans; break; } } vector<string> details; boost::split(details, out, boost::is_any_of(" ")); if (details[2].find("...'") != string::npos) out = regex_replace(details[2], regex("...'"), ""); else out = regex_replace(details[2], regex("'"), ""); return out; } class InputData { private: string filename = "request.txt"; public: bool file_exists() { ifstream fin(this->filename); return fin.good(); } vector<int> get_data() { ifstream fin(this->filename); string str; vector<int> out; while (fin >> str) out.push_back(stoi(str)); return out; } }; int main() { setlocale(LC_ALL, "Russian"); int m, S, n; InputData ID; if (ID.file_exists()) { vector<int> data = ID.get_data(); S = data[0]; m = data[1]; n = data[2]; } else { cout << "Give me the values: " << endl << "S: " << endl << "> "; cin >> S; cout << endl << "m: " << endl << "> "; cin >> m; cout << endl << "n: " << endl << "> "; cin >> n; cout << endl; } string data = get_p(request()); cout << endl << "ANSWER: " << endl << data; write_it(data); }
22.628141
275
0.577171
[ "vector", "3d" ]
017ea27c4fbc1528d7f690cf3682f11b8ad79fec
7,448
cc
C++
ns-allinone-2.35/qs/qsagent.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2020-05-29T13:04:42.000Z
2020-05-29T13:04:42.000Z
ns-allinone-2.35/qs/qsagent.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2019-01-20T17:35:23.000Z
2019-01-22T21:41:38.000Z
ns-allinone-2.35/qs/qsagent.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2021-09-29T16:06:57.000Z
2021-09-29T16:06:57.000Z
/* * qsagent.cc * Copyright (C) 2001 by the University of Southern California * $Id: qsagent.cc,v 1.9 2010/03/08 05:54:53 tom_henderson Exp $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. * * * The copyright of this module includes the following * linking-with-specific-other-licenses addition: * * In addition, as a special exception, the copyright holders of * this module give you permission to combine (via static or * dynamic linking) this module with free software programs or * libraries that are released under the GNU LGPL and with code * included in the standard release of ns-2 under the Apache 2.0 * license or under otherwise-compatible licenses with advertising * requirements (or modified versions of such code, with unchanged * license). You may copy and distribute such a system following the * terms of the GNU GPL for this module and the licenses of the * other code concerned, provided that you include the source code of * that other code when and as the GNU GPL requires distribution of * source code. * * Note that people who make modified versions of this module * are not obligated to grant this special exception for their * modified versions; it is their choice whether to do so. The GNU * General Public License gives permission to release a modified * version without this exception; this exception also makes it * possible to release a modified version which carries forward this * exception. * */ /* * Quick Start for TCP and IP. * A scheme for transport protocols to dynamically determine initial * congestion window size. * * http://www.ietf.org/internet-drafts/draft-amit-quick-start-02.ps * * This implements the Quick Start Agent at each of network element "Agent/QSAgent" * qsagent.cc * * Srikanth Sundarrajan, 2002 * sundarra@usc.edu */ #include <assert.h> #include <math.h> #include <stdio.h> #include <signal.h> #include <float.h> #include "object.h" #include "agent.h" #include "packet.h" #include "ip.h" #include "classifier.h" #include "connector.h" #include "delay.h" #include "queue.h" #include "scheduler.h" #include "random.h" #include "hdr_qs.h" #include "qsagent.h" #include <fstream> static class QSAgentClass : public TclClass { public: QSAgentClass() : TclClass("Agent/QSAgent") {} TclObject* create(int, const char*const*) { return (new QSAgent); } } class_QSAgent; int QSAgent::rate_function_ = 1; QSAgent::QSAgent():Agent(PT_TCP), old_classifier_(NULL), qs_enabled_(1), qs_timer_(this) { prev_int_aggr_ = 0; aggr_approval_ = 0; bind("qs_enabled_", &qs_enabled_); bind("old_classifier_", &old_classifier_); bind("state_delay_", &state_delay_); bind("alloc_rate_", &alloc_rate_); bind("threshold_", &threshold_); bind("max_rate_", &max_rate_); bind("mss_", &mss_); bind("rate_function_", &rate_function_); bind("algorithm_", &algorithm_); qs_timer_.resched(state_delay_); } QSAgent::~QSAgent() { } int QSAgent::command(int argc, const char*const* argv) { return (Agent::command(argc,argv)); } void QSAgent::recv(Packet* packet, Handler*) { double app_rate; //double avail_bw, util; Classifier * pkt_target; Tcl& tcl = Tcl::instance(); char qname[64], lname[64]; hdr_qs *qsh = hdr_qs::access(packet); hdr_ip *iph = hdr_ip::access(packet); assert (old_classifier_ != 0); pkt_target = (Classifier *)TclObject::lookup(old_classifier_->name()); if (qs_enabled_) { if (qsh->flag() == QS_REQUEST && qsh->rate() > 0 && iph->daddr() != addr()) { sprintf (qname, "[Simulator instance] get-queue %d %d", addr(), iph->daddr()); tcl.evalc (qname); Queue * queue = (Queue *) TclObject::lookup(tcl.result()); sprintf (lname, "[Simulator instance] get-link %d %d", addr(), iph->daddr()); tcl.evalc (lname); LinkDelay * link = (LinkDelay *) TclObject::lookup(tcl.result()); if (link != NULL && queue != NULL) { app_rate = process(link, queue, hdr_qs::rate_to_Bps(qsh->rate())); if (app_rate > 0) { qsh->ttl() -= 1; qsh->rate() = hdr_qs::Bps_to_rate(app_rate); //update rate } else { qsh->rate() = 0; //disable quick start, not enough bandwidth qsh->flag() = QS_DISABLE; } } } } pkt_target->recv(packet, 0); return; } double QSAgent::process(LinkDelay *link, Queue *queue, double ratereq) { double util, avail_bw, app_rate, util_bw; // PS: avail_bw is in units of bytes per sec. if (algorithm_ == 1) { /* */ util = queue->utilization(); avail_bw = link->bandwidth() / 8 * (1 - util); avail_bw -= (prev_int_aggr_ + aggr_approval_); avail_bw *= alloc_rate_; app_rate = (avail_bw < ratereq) ? (int) avail_bw : ratereq; app_rate = (app_rate < (max_rate_ * 1024)) ? app_rate : (max_rate_ * 1024); if (app_rate > 0) { // add approved to current bucket aggr_approval_ += app_rate; } } else if (algorithm_ == 2) { /* * Algorithm 2 checks if the utilized bandwidth is * less than some fraction (threshold_) of * the total bandwidth. If so, the approved rate * is at most some fraction (alloc_rate_) of the * link bandwidth. */ util = queue->utilization(); util_bw = link->bandwidth() / 8 * util; util_bw += (prev_int_aggr_ + aggr_approval_); if (util_bw < threshold_ * link->bandwidth() / 8) { app_rate = alloc_rate_ * link->bandwidth() / 8; if (ratereq < app_rate) app_rate = ratereq; } else { app_rate = 0; } aggr_approval_ += app_rate; } else if (algorithm_ == 3) { /* * Algorithm 3 checks if the utilized bandwidth is * less than some fraction (threshold_) of * the total bandwidth. If so, the approved rate * is at most the allowed allocated bandwidth minus * the utilized bandwidth. * * Algorithm 3 used queue->peak_utilization() instead of * queue->utilization(). This looks at the peak * utilization measures over a sub-interval of a * larger interval. */ util = queue->peak_utilization(); util_bw = link->bandwidth() / 8 * util; util_bw += (prev_int_aggr_ + aggr_approval_); if (util_bw < threshold_ * link->bandwidth() / 8) { app_rate = alloc_rate_ * link->bandwidth() / 8 - util_bw; if (ratereq < app_rate) app_rate = ratereq; if (app_rate < 0) app_rate = 0; } else { app_rate = 0; } aggr_approval_ += app_rate; } else if (algorithm_ == 4) { // a broken router: yes to all QS requests app_rate = ratereq; } else { app_rate = 0; } #ifdef QS_DEBUG printf("%d: requested = %f KBps, available = %f KBps, approved = %f KBps\n", addr(), ratereq/1024, free_bw/1024, app_rate/1024); #endif return app_rate; } void QSTimer::expire(Event *) { qs_handle_->prev_int_aggr_ = qs_handle_->aggr_approval_; qs_handle_->aggr_approval_ = 0; this->resched(qs_handle_->state_delay_); } /* Local Variables: c-basic-offset: 8 End: */
28.319392
130
0.684748
[ "object" ]
0189e28d4fcf903e713e86b49553caf691f594bb
4,553
cpp
C++
src/strongly-connected-component.cpp
yaozhongxiao/algorithm
657f22952a7ff9974e13c0627fa5923b69ab5487
[ "Apache-2.0" ]
null
null
null
src/strongly-connected-component.cpp
yaozhongxiao/algorithm
657f22952a7ff9974e13c0627fa5923b69ab5487
[ "Apache-2.0" ]
null
null
null
src/strongly-connected-component.cpp
yaozhongxiao/algorithm
657f22952a7ff9974e13c0627fa5923b69ab5487
[ "Apache-2.0" ]
null
null
null
/* * Strongly Conntected Component Generation for DAG */ #include <iostream> #include <vector> /* * Vector-Based stack_ extension for std::stack_ */ template <typename T> class SStack { public: SStack(bool flag = false) : dump_flag() {} ~SStack() = default; void push(const T &v) { container_.push_back(v); } void pop() { container_.pop_back(); } T top() { return container_.back(); } bool empty() { return container_.empty(); } bool contain(T v) { for (T &t : container_) { if (t == v) { return true; } } return false; } void dump() { if (dump_flag) { for (T &t : container_) { std::cout << t << " "; } std::cout << std::endl; } } private: std::vector<T> container_; bool dump_flag = false; }; /* * Matrix for Graph */ template <typename T> using GraphMatrix = std::vector<std::vector<T>>; template <typename T> void PrintMatrix(GraphMatrix<T> &matrix) { for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[i].size(); ++j) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } } /************************************************** * 1 -> 2 -> 3 * ^ | ^ * \ v \ * 4 -> 5 - > 6 * * Builder for generationg SCC for DAG, the above DAG will * Generate the following SCC sets * { 1 } * { 2, 3, 4, 5 } * { 6 } */ class SCCBuilder { private: int gvn = 1; // global nodes number for dfn std::vector<int> dfn; // the numbering by dfs algorighm std::vector<int> group; // the group number for earch node SStack<int> stack_; // stack_ for nodes GraphMatrix<int> dag; // dag represents with matrix GraphMatrix<int> SCCs; // the SCC sets bool dump_flag; public: SCCBuilder(bool flags = true) : dump_flag(flags), stack_(flags) {} ~SCCBuilder() = default; void SCCGen(int head) { std::vector<int> scc; stack_.dump(); while (!stack_.empty()) { if (stack_.top() == head) { scc.emplace_back(stack_.top()); stack_.pop(); break; } scc.emplace_back(stack_.top()); stack_.pop(); } stack_.dump(); if (!scc.empty()) { SCCs.emplace_back(scc); } } /* Pseudo Code void dfs(int current, int from) { dfn[current] = gvn; group[current] = gvn; ++gvn; stack_.push(current); for (reachable to : dag) { if (!dfn[to]) { dfs(to, current); if (dfn[to] == group[to]) { SCCGen(to); } } if (stack_.contain(to)) { group[current] = std::min(group[current], group[to]); } } }*/ void dfs(int current, int from) { dfn[current] = gvn; group[current] = gvn; ++gvn; stack_.push(current); if (dump_flag) { printf("node-%d[%d : %d]\n", current, dfn[current], group[current]); } for (int to = 1; to < dag.size(); ++to) { if (dag[current][to]) { if (dump_flag) { printf("%d -> %d\n", current, to); } if (!dfn[to]) { dfs(to, current); if (dfn[to] == group[to]) { SCCGen(to); } } if (stack_.contain(to)) { group[current] = std::min(group[current], group[to]); if (dump_flag) { printf("found group %d -> %d [%d : %d]\n", current, to, dfn[current], group[current]); } } } } } void SCCScan(int nums, std::vector<std::vector<int>> edges) { dfn.resize(nums + 1, 0); group.resize(nums + 1, 0); dag.resize(nums + 1, std::vector<int>(nums + 1, 0)); for (int i = 0; i < edges.size(); ++i) { std::vector<int> &edge = edges[i]; dag[edge[0]][edge[1]] = 1; } for (int i = 1; i <= nums; ++i) { if (!dfn[i]) { dfs(i, 0); if (!stack_.empty()) { SCCGen(i); } } } } void dump() { std::cout << "\n-----------------------------\n"; PrintMatrix(dag); std::cout << "\n-----------------------------\n"; for (int i = 1; i < dfn.size(); ++i) { printf("node-%d[%d : %d]\n", i, dfn[i], group[i]); } std::cout << "\n-----------------------------\n"; PrintMatrix(SCCs); } }; int main() { std::vector<std::vector<int>> edges = { {1, 2}, {2, 3}, {3, 4}, {4, 2}, {4, 5}, {5, 3}, {5, 6}, }; SCCBuilder builder; builder.SCCScan(7, edges); builder.dump(); } // g++ -std=c++11 strongly-connected-component.cpp -o scc
23.713542
74
0.486053
[ "vector" ]
018b59bf2e945ef7a376075db470e8c38461d5d5
1,401
hpp
C++
inc/taskdb.hpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
inc/taskdb.hpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
inc/taskdb.hpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- #ifndef __TASK_DB_HPP #define __TASK_DB_HPP #include <vector> #include <map> #include <fstream> #include "task.hpp" // ----------------------------------------------------------------------------- class TaskDB{ private: std::map<unsigned int, Task> task_list; std::map<std::string,int> tag_list; std::string db_file_name; unsigned int last_id; void initialize(); void add_tag(const std::string & tag); void del_tag(const std::string & tag); public: TaskDB(); TaskDB(const std::string & name); void set_name(const std::string & name); const Task & get_task( unsigned int id ) const; void get_task_list(std::vector<Task> & tasks) const; void get_task_list(std::vector<Task> & tasks, const std::string & tag) const; void add_task( Task & task ); void update_task(const Task & task); void delete_task(unsigned int id); bool finish_task(unsigned int id); bool finish_task(unsigned int id, bool status); void read(); void save() const; }; // ----------------------------------------------------------------------------- #endif
28.591837
102
0.455389
[ "vector" ]
018bb6d7eebe6bc00143992d2d31eb60b7fbeac3
1,554
cpp
C++
TIMUS-1471. Tree/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
TIMUS-1471. Tree/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
TIMUS-1471. Tree/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <iostream> #include <vector> using namespace std; const int maxn = 50005; const int maxlg = 22; int n, anc[maxlg][maxn], level[maxn]; vector <pair<int, int> > g[maxn]; long long sum[maxn]; inline void dfs(int node, int father) { level[node] = level[father] + 1; anc[0][node] = father; for(auto it : g[node]) if(it.first != father) { sum[it.first] = sum[node] + it.second; dfs(it.first, node); } } inline int lca(int x, int y) { if(level[x] < level[y]) swap(x, y); int diff = level[x] - level[y]; for(int i = 0 ; (1 << i) <= diff ; ++ i) if(diff & (1 << i)) x = anc[i][x]; if(x == y) return x; for(int i = maxlg - 1 ; i >= 0 ; -- i) if(anc[i][x] != anc[i][y]) { x = anc[i][x]; y = anc[i][y]; } return anc[0][x]; } int main() { #ifndef ONLINE_JUDGE freopen("input.in", "r", stdin); freopen("output.out", "w", stdout); #endif // ONLINE_JUDGE cin >> n; for(int i = 1 ; i < n ; ++ i) { int x, y, z; cin >> x >> y >> z; ++ x; ++ y; g[x].push_back(make_pair(y, z)); g[y].push_back(make_pair(x, z)); } dfs(1, 0); for(int i = 1 ; (1 << i) <= n ; ++ i) for(int j = 1 ; j <= n ; ++ j) anc[i][j] = anc[i - 1][anc[i - 1][j]]; int m; cin >> m; while(m -- ) { int x, y; cin >> x >> y; ++ x; ++ y; cout << sum[x] + sum[y] - 2LL * sum[lca(x, y)] << '\n'; } }
23.19403
63
0.432432
[ "vector" ]
01961d3d239270be73a52897361b149202045ed1
41,575
cpp
C++
third_party/reil/reil/aarch64/printer.cpp
avniculae/TinyInst
ca6ae41539a318b82d0365b91ea703fb3d9bad4e
[ "Apache-2.0" ]
802
2020-06-04T17:55:15.000Z
2022-03-31T08:47:56.000Z
third_party/reil/reil/aarch64/printer.cpp
avniculae/TinyInst
ca6ae41539a318b82d0365b91ea703fb3d9bad4e
[ "Apache-2.0" ]
47
2020-06-09T09:30:25.000Z
2022-03-08T10:45:14.000Z
third_party/reil/reil/aarch64/printer.cpp
avniculae/TinyInst
ca6ae41539a318b82d0365b91ea703fb3d9bad4e
[ "Apache-2.0" ]
80
2020-06-04T19:31:45.000Z
2022-03-28T15:08:06.000Z
// Copyright 2018 Google LLC // // 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 // // https://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 "reil/aarch64/decoder.h" #include <cassert> namespace reil { namespace aarch64 { namespace decoder { static void PrintImmediate(std::ostream& stream, const Immediate& opnd) { stream << "#0x" << std::hex << opnd.value; } static void PrintSignedImmediate(std::ostream& stream, const Immediate& opnd) { if (opnd.value & (1ull << (opnd.size - 1))) { stream << "#-0x" << std::hex << (~opnd.value) + 1ull; } else { stream << "#0x" << std::hex << opnd.value; } } static void PrintPcRelativeOffset(std::ostream& stream, const Instruction& insn, const Immediate& opnd) { if (opnd.value & (1ull << (opnd.size - 1))) { stream << "#0x" << std::hex << insn.address - ((~opnd.value) + 1ull); } else { stream << "#0x" << std::hex << insn.address + opnd.value; } } static void PrintRegister(std::ostream& stream, const Register& opnd) { if (Register::kX0 <= opnd.name && opnd.name <= Register::kXzr) { if (opnd.size <= 32) { stream << "w"; } else { stream << "x"; } if (opnd.name == Register::kXzr) { stream << "zr"; } else { stream << std::dec << (unsigned)(opnd.name - Register::kX0); } } else if (opnd.name == Register::kSp) { if (opnd.size <= 32) { stream << "wsp"; } else { stream << "sp"; } } else if (opnd.name == Register::kPc) { stream << "pc"; } else if (Register::kV0 <= opnd.name && opnd.name <= Register::kV31) { if (opnd.size == 8) { stream << "b"; } else if (opnd.size == 16) { stream << "h"; } else if (opnd.size == 32) { stream << "s"; } else if (opnd.size == 64) { stream << "d"; } else if (opnd.size == 128) { stream << "q"; } stream << std::dec << (unsigned)(opnd.name - Register::kV0); } else { stream << "<unsupported_reg>"; } } static void PrintSystemRegister(std::ostream& stream, const SystemRegister& opnd) { if (opnd.name == SystemRegister::kUnknown) { stream << "S" << std::dec << (int)opnd.op0; stream << "_" << std::dec << (int)opnd.op1; stream << "_C" << std::dec << (int)opnd.crn; stream << "_C" << std::dec << (int)opnd.crm; stream << "_" << std::dec << (int)opnd.op2; } else if (opnd.name == SystemRegister::kSPSel) { stream << "SPSel"; } else if (opnd.name == SystemRegister::kDAIFSet) { stream << "DAIFSet"; } else if (opnd.name == SystemRegister::kDAIFClr) { stream << "DAIFClr"; } else if (opnd.name == SystemRegister::kUAO) { stream << "UAO"; } else if (opnd.name == SystemRegister::kPAN) { stream << "PAN"; } } static void PrintShift(std::ostream& stream, const Shift& opnd) { if (opnd.type != Shift::kNone) { switch (opnd.type) { case Shift::kLsl: { if (opnd.count) { stream << ", lsl "; } else { return; } } break; case Shift::kLsr: { stream << ", lsr "; } break; case Shift::kAsr: { stream << ", asr "; } break; case Shift::kRor: { stream << ", ror "; } break; default: abort(); } stream << "#0x" << std::hex << (unsigned)opnd.count; } } static void PrintExtend(std::ostream& stream, const Extend& opnd) { if (opnd.type != Extend::kNone) { switch (opnd.type) { case Extend::kUxtb: { stream << ", uxtb"; } break; case Extend::kUxth: { stream << ", uxth"; } break; case Extend::kUxtw: { stream << ", uxtw"; } break; case Extend::kUxtx: { stream << ", uxtx"; } break; case Extend::kLsl: { if (opnd.count) { stream << ", lsl"; } } break; case Extend::kSxtb: { stream << ", sxtb"; } break; case Extend::kSxth: { stream << ", sxth"; } break; case Extend::kSxtw: { stream << ", sxtw"; } break; case Extend::kSxtx: { stream << ", sxtx"; } break; default: abort(); } if (opnd.count) { stream << ", #" << std::dec << (unsigned)opnd.count; } } } static void PrintImmediateOffset(std::ostream& stream, const ImmediateOffset& opnd) { stream << "[" << opnd.base; if (opnd.writeback && opnd.post_index) { stream << "]"; } if (opnd.offset.value) { stream << ", "; PrintSignedImmediate(stream, opnd.offset); stream << opnd.shift; } if (!opnd.writeback || !opnd.post_index) { stream << "]"; if (opnd.writeback) { stream << "!"; } } } static void PrintRegisterOffset(std::ostream& stream, const RegisterOffset& opnd) { stream << "[" << opnd.base; if (opnd.writeback && opnd.post_index) { stream << "]"; } stream << ", " << opnd.offset << opnd.extend; if (!opnd.writeback || !opnd.post_index) { stream << "]"; if (opnd.writeback) { stream << "!"; } } } static void PrintOperands(std::ostream& stream, const std::vector<Operand>& opnds) { for (size_t i = 0; i < opnds.size(); ++i) { if (i != 0 && !std::holds_alternative<Shift>(opnds[i])) { stream << ", "; } stream << opnds[i]; } } static void PrintConditionCode(std::ostream& stream, ConditionCode cc) { static std::vector<std::string> condition_codes = { "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", "al"}; stream << condition_codes[cc]; } static void PrintPrefetchOp(std::ostream& stream, uint8_t prfop) { if (((prfop & 0b11000) == 0b11000) || ((prfop & 0b00110) == 0b00110)) { stream << "#" << std::dec << (int)prfop; } else { switch (prfop & 0b11000) { case 0b00000: { stream << "PLD"; } break; case 0b01000: { stream << "PLI"; } break; case 0b10000: { stream << "PST"; } break; default: abort(); } switch (prfop & 0b00110) { case 0b00000: { stream << "L1"; } break; case 0b00010: { stream << "L2"; } break; case 0b00100: { stream << "L3"; } break; default: abort(); } switch (prfop & 0b1) { case 0: { stream << "KEEP"; } break; case 1: { stream << "STRM"; } break; } } } static void PrintBarrierType(std::ostream& stream, uint8_t option) { if (((option & 0b10) >> 1) == (option & 0b01)) { stream << "#" << std::dec << (int)option; } else { switch (option >> 2) { case 0b00: { stream << "os"; } break; case 0b01: { stream << "nsh"; } break; case 0b10: { stream << "ish"; } break; case 0b11: { if (option == 0b1111) { stream << "sy"; } } break; } switch (option & 0b11) { case 0b01: { stream << "ld"; } break; case 0b10: { stream << "st"; } break; default: abort(); } } } static void PrintPcRelativeAddressing(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Register rd = std::get<Register>(insn.operands[0]); Immediate imm = std::get<Immediate>(insn.operands[1]); Shift shift = std::get<Shift>(insn.operands[2]); if (insn.opcode == kAdr) { stream << "adr "; } else { stream << "adrp "; assert(shift.type == Shift::kLsl); assert(shift.count == 12); imm.value <<= 12; } stream << rd << ", " << imm; } static void PrintAddSubtractImmediate(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Immediate imm = std::get<Immediate>(insn.operands[2]); Shift shift = std::get<Shift>(insn.operands[3]); if ((imm.value == 0 && !insn.set_flags && rd.name == Register::kSp) || (imm.value == 0 && rn.name == Register::kSp)) { stream << "mov " << rd << ", " << rn; } else if (rd.name == Register::kXzr) { if (insn.opcode == kSubImmediate) { stream << "cmp "; } else { stream << "cmn "; } stream << rn << ", " << imm << shift; } else { if (insn.opcode == kSubImmediate) { stream << "sub"; } else { stream << "add"; } if (insn.set_flags) { stream << "s "; } else { stream << " "; } stream << rd << ", " << rn << ", " << imm << shift; } } static void PrintLogicalImmediate(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Immediate imm = std::get<Immediate>(insn.operands[2]); switch (insn.opcode) { case kAndImmediate: { if (!insn.set_flags) { stream << "and "; } else if (rd.name == Register::kXzr) { stream << "tst "; } else { stream << "ands "; } } break; case kOrrImmediate: { if (rn.name == Register::kXzr) { stream << "mov "; } else { stream << "orr "; } } break; case kEorImmediate: { stream << "eor "; } break; default: abort(); } if (insn.opcode != kAndImmediate || rd.name != Register::kXzr) { stream << rd << ", "; } if (insn.opcode != kOrrImmediate || rn.name != Register::kXzr) { stream << rn << ", "; } stream << imm; } static void PrintMoveWideImmediate(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Immediate imm = std::get<Immediate>(insn.operands[1]); Shift shift = std::get<Shift>(insn.operands[2]); switch (insn.opcode) { case kMovn: { stream << "mov "; imm.value <<= shift.count; imm.value = ~imm.value; } break; case kMovz: { stream << "mov "; imm.value <<= shift.count; } break; case kMovk: { stream << "movk "; } break; default: abort(); } if (imm.size == 32) { imm.value &= 0xfffffffful; } stream << insn.operands[0] << ", " << imm; if (insn.opcode == kMovk) { stream << shift; } } static void PrintBitfield(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Immediate immr = std::get<Immediate>(insn.operands[2]); Immediate imms = std::get<Immediate>(insn.operands[3]); if (insn.opcode == kBfm) { if (rn.name == Register::kXzr && imms.value < immr.value) { stream << "bfc " << rd; } else if (imms.value < immr.value) { stream << "bfi " << rd << ", " << rn; } else { stream << "bfxil " << rd << ", " << rn; } stream << ", #" << immr.size - immr.value << ", #" << imms.value + 1; } else if (insn.opcode == kSbfm) { if ((imms.size == 32 && imms.value == 0b011111) || (imms.size == 64 && imms.value == 0b111111)) { stream << "asr " << rd << ", " << rn << ", #" << immr.value; } else if (imms.value < immr.value) { stream << "sbfiz " << rd << ", " << rn; stream << ", #" << immr.size - immr.value << ", #" << imms.value + 1; } else if (immr.value == 0 && imms.value == 0b000111) { stream << "sxtb " << rd << ", " << rn; } else if (immr.value == 0 && imms.value == 0b001111) { stream << "sxth " << rd << ", " << rn; } else if (immr.value == 0 && imms.value == 0b011111) { stream << "sxtw " << rd << ", " << rn; } else { stream << "sbfx " << rd << ", " << rn; stream << ", #" << immr.value << ", #" << imms.value - immr.value + 1; } } else if (insn.opcode == kUbfm) { if ((imms.value + 1 == immr.value) && (imms.value != 0b011111 && imms.value != 0b111111)) { stream << "lsl " << rd << ", " << rn << ", #" << immr.size - immr.value; } else if (imms.value == 0b011111 || imms.value == 0b111111) { stream << "lsr " << rd << ", " << rn << ", #" << immr.value; } else if (imms.value < immr.value) { stream << "ubfiz " << rd << ", " << rn; stream << ", #" << immr.size - immr.value << ", #" << imms.value + 1; } else if (immr.value == 0 && imms.value == 0b000111) { stream << "uxtb " << rd << ", " << rn; } else if (immr.value == 0 && imms.value == 0b001111) { stream << "uxth " << rd << ", " << rn; } else if (immr.value == 0 && imms.value == 0b011111) { stream << "uxtw " << rd << ", " << rn; } else { stream << "ubfx " << rd << ", " << rn; stream << ", #" << immr.value << ", #" << imms.value - immr.value + 1; } } } static void PrintExtract(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); Immediate imm = std::get<Immediate>(insn.operands[3]); if (rn.name == rm.name) { stream << "ror "; stream << rd << ", " << rn; } else { stream << "extr "; stream << rd << ", " << rn << ", " << rm; } stream << ", #" << std::dec << imm.value; } static void PrintConditionalBranch(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 1); Immediate offset = std::get<Immediate>(insn.operands[0]); stream << "b."; PrintConditionCode(stream, insn.cc); stream << " "; PrintPcRelativeOffset(stream, insn, offset); } static void PrintExceptionGeneration(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 1); Immediate imm = std::get<Immediate>(insn.operands[0]); switch (insn.opcode) { case kSvc: { stream << "svc #" << std::dec << imm.value; } break; case kHvc: { stream << "hvc #" << std::dec << imm.value; } break; case kSmc: { stream << "smc #" << std::dec << imm.value; } break; case kBrk: { stream << "brk #" << std::dec << imm.value; } break; case kHlt: { stream << "hlt #" << std::dec << imm.value; } break; case kDcps1: { stream << "dcps1"; } break; case kDcps2: { stream << "dcps2"; } break; case kDcps3: { stream << "dcps3"; } break; default: abort(); } } static void PrintSystem(std::ostream& stream, const Instruction& insn) { switch (insn.opcode) { case kNop: { stream << "nop"; } break; case kYield: { stream << "yield"; } break; case kWfe: { stream << "wfe"; } break; case kWfi: { stream << "wfi"; } break; case kSev: { stream << "sev"; } break; case kSevl: { stream << "sevl"; } break; case kXpaclri: { stream << "xapclri"; } break; case kPacia1716: { stream << "pacia1716"; } break; case kPacib1716: { stream << "pacib1716"; } break; case kAutia1716: { stream << "autia1716"; } break; case kAutib1716: { stream << "autib1716"; } break; case kEsb: { stream << "esb"; } break; case kPsbCsync: { stream << "psb csync"; } break; case kPaciaz: { stream << "paciaz"; } break; case kPaciasp: { stream << "paciasp"; } break; case kPacibz: { stream << "pacibz"; } break; case kPacibsp: { stream << "pacibsp"; } break; case kAutiaz: { stream << "autiaz"; } break; case kAutiasp: { stream << "autiasp"; } break; case kAutibz: { stream << "autibz"; } break; case kAutibsp: { stream << "autibsp"; } break; case kHint: { stream << "hint " << insn.operands[0]; } break; case kClrex: { stream << "clrex"; } break; case kDsb: { Immediate imm = std::get<Immediate>(insn.operands[0]); stream << "dsb "; PrintBarrierType(stream, imm.value); } break; case kDmb: { Immediate imm = std::get<Immediate>(insn.operands[0]); stream << "dmb "; PrintBarrierType(stream, imm.value); } break; case kIsb: { Immediate imm = std::get<Immediate>(insn.operands[0]); stream << "isb"; if (imm.value != 0b1111) { stream << " #" << std::dec << imm.value; } } break; case kSys: { // TODO: handle AT etc. Immediate op1 = std::get<Immediate>(insn.operands[0]); Immediate crn = std::get<Immediate>(insn.operands[1]); Immediate crm = std::get<Immediate>(insn.operands[2]); Immediate op2 = std::get<Immediate>(insn.operands[3]); Register rt = std::get<Register>(insn.operands[4]); stream << "sys "; stream << "#" << std::dec << op1.value; stream << ", C" << std::dec << crn.value; stream << ", C" << std::dec << crm.value; stream << ", #" << std::dec << op2.value; if (rt.name != Register::kXzr) { stream << ", " << rt; } } break; case kMsr: { stream << "msr "; PrintOperands(stream, insn.operands); } break; case kSysl: { Register rt = std::get<Register>(insn.operands[0]); Immediate op1 = std::get<Immediate>(insn.operands[1]); Immediate crn = std::get<Immediate>(insn.operands[2]); Immediate crm = std::get<Immediate>(insn.operands[3]); Immediate op2 = std::get<Immediate>(insn.operands[4]); stream << "sysl "; stream << rt; stream << ", #" << std::dec << op1.value; stream << ", C" << std::dec << crn.value; stream << ", C" << std::dec << crm.value; stream << ", #" << std::dec << op2.value; } break; case kMrs: { stream << "mrs "; PrintOperands(stream, insn.operands); } break; default: abort(); } } static void PrintBranchRegister(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() >= 1); Register rn = std::get<Register>(insn.operands[0]); switch (insn.opcode) { case kBr: { stream << "br " << rn; } break; case kBraaz: { stream << "braaz " << rn; } break; case kBrabz: { stream << "brabz" << rn; } break; case kBlr: { stream << "blr " << rn; } break; case kBlraaz: { stream << "blraaz " << rn; } break; case kBlrabz: { stream << "blrabz " << rn; } break; case kRet: { stream << "ret"; if (rn.name != Register::kX30) { stream << " " << rn; } } break; case kRetaa: { stream << "retaa"; } break; case kRetab: { stream << "retab"; } break; case kEret: { stream << "eret"; } break; case kEretaa: { stream << "eretaa"; } break; case kEretab: { stream << "eretab"; } break; case kDrps: { stream << "drps"; } break; case kBraa: { stream << "braa " << rn << ", " << insn.operands[1]; } break; case kBrab: { stream << "brab " << rn << ", " << insn.operands[1]; } break; case kBlraa: { stream << "blraa " << rn << ", " << insn.operands[1]; } break; case kBlrab: { stream << "blrab " << rn << ", " << insn.operands[1]; } break; default: abort(); } } static void PrintBranchImmediate(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 1); Immediate offset = std::get<Immediate>(insn.operands[0]); if (insn.opcode == kBl) { stream << "bl "; } else { stream << "b "; } PrintPcRelativeOffset(stream, insn, offset); } static void PrintCompareAndBranch(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 2); Immediate offset = std::get<Immediate>(insn.operands[1]); if (insn.opcode == kCbz) { stream << "cbz "; } else { stream << "cbnz "; } stream << insn.operands[0] << ", "; PrintPcRelativeOffset(stream, insn, offset); } static void PrintTestAndBranch(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Immediate bit = std::get<Immediate>(insn.operands[1]); Immediate offset = std::get<Immediate>(insn.operands[2]); if (insn.opcode == kTbz) { stream << "tbz "; } else { stream << "tbnz "; } stream << insn.operands[0] << ", #" << std::dec << bit.value << ", "; PrintPcRelativeOffset(stream, insn, offset); } static void PrintLoadStoreExclusive(std::ostream& stream, const Instruction& insn) { bool pair = false; uint8_t size = 64; if (insn.opcode <= kLdxr) { if (insn.opcode == kCas) { stream << "cas"; } else if (insn.opcode == kCasa) { stream << "casa"; } else if (insn.opcode == kCasal) { stream << "casal"; } else if (insn.opcode == kCasl) { stream << "casl"; } else if (insn.opcode == kCasp) { stream << "casp "; pair = true; } else if (insn.opcode == kCaspa) { stream << "caspa "; pair = true; } else if (insn.opcode == kCaspal) { stream << "caspal "; pair = true; } else if (insn.opcode == kCaspl) { stream << "caspl "; pair = true; } else if (insn.opcode == kLdxr) { stream << "ldxr"; } else if (insn.opcode == kLdxp) { stream << "ldxp "; pair = true; } else if (insn.opcode == kLdaxr) { stream << "ldaxr"; } else if (insn.opcode == kLdaxp) { stream << "ldaxp "; pair = true; } else if (insn.opcode == kLdlar) { stream << "ldlar"; } else { stream << "ldar"; } size = std::get<Register>(insn.operands[0]).size; } else if (insn.opcode <= kStxr) { if (insn.opcode == kStxr) { stream << "stxr"; } else if (insn.opcode == kStxp) { stream << "stxp "; pair = true; } else if (insn.opcode == kStlxr) { stream << "stlxr"; } else if (insn.opcode == kStlxp) { stream << "stlxp "; pair = true; } else if (insn.opcode == kStllr) { stream << "stllr"; } else if (insn.opcode == kStlr) { stream << "stlr"; } if (insn.opcode != kStlr && insn.opcode != kStllr) { size = std::get<Register>(insn.operands[1]).size; } else { size = std::get<Register>(insn.operands[0]).size; } } if (!pair) { if (size == 8) { stream << "b "; } else if (size == 16) { stream << "h "; } else { stream << " "; } } PrintOperands(stream, insn.operands); } static void PrintLoadLiteral(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 2); ImmediateOffset imm_off = std::get<ImmediateOffset>(insn.operands[1]); if (insn.opcode == kSimdLdrLiteral || insn.opcode == kLdrLiteral) { stream << "ldr "; } else if (insn.opcode == kLdrsLiteral) { stream << "ldrsw "; } else if (insn.opcode == kPrfmLiteral) { stream << "prfm "; } else { abort(); } if (insn.opcode == kPrfmLiteral) { Immediate prfop = std::get<Immediate>(insn.operands[0]); PrintPrefetchOp(stream, prfop.value); } else { stream << insn.operands[0] << ", "; } PrintSignedImmediate(stream, imm_off.offset); } static void PrintLoadStorePair(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); if (insn.opcode == kSimdLdp || insn.opcode == kLdp) { stream << "ldp "; } else if (insn.opcode == kLdpsw) { stream << "ldpsw "; } else if (insn.opcode == kSimdLdnp || insn.opcode == kLdnp) { stream << "ldnp "; } else if (insn.opcode == kSimdStp || insn.opcode == kStp) { stream << "stp "; } else if (insn.opcode == kSimdStnp || insn.opcode == kStnp) { stream << "stnp "; } else { abort(); } PrintOperands(stream, insn.operands); } static void PrintLoadStore(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 2); uint8_t size = 0; if (std::holds_alternative<ImmediateOffset>(insn.operands[1])) { ImmediateOffset address = std::get<ImmediateOffset>(insn.operands[1]); size = address.size; } else if (std::holds_alternative<RegisterOffset>(insn.operands[1])) { RegisterOffset address = std::get<RegisterOffset>(insn.operands[1]); size = address.size; } else { abort(); } if (insn.opcode == kPrfm) { Immediate prfop = std::get<Immediate>(insn.operands[0]); stream << "prfm "; PrintPrefetchOp(stream, prfop.value); stream << ", " << insn.operands[1]; } else { if (insn.opcode == kSimdLdr || insn.opcode == kLdr) { stream << "ldr"; } else if (insn.opcode == kSimdLdur || insn.opcode == kLdur) { stream << "ldur"; } else if (insn.opcode == kLdtr) { stream << "ldtr"; } else if (insn.opcode == kLdrs) { stream << "ldrs"; } else if (insn.opcode == kLdurs) { stream << "ldurs"; } else if (insn.opcode == kLdtrs) { stream << "ldtrs"; } else if (insn.opcode == kSimdStr || insn.opcode == kStr) { stream << "str"; } else if (insn.opcode == kSimdStur || insn.opcode == kStur) { stream << "stur"; } else if (insn.opcode == kSttr) { stream << "sttr"; } else { abort(); } if (insn.opcode >= kLdr) { if (size == 8) { stream << "b "; } else if (size == 16) { stream << "h "; } else if (size == 32 && (insn.opcode == kLdrs || insn.opcode == kLdurs || insn.opcode == kLdtrs)) { stream << "w "; } else { stream << " "; } } else { stream << " "; } PrintOperands(stream, insn.operands); } } static void PrintDataProcessingTwoSource(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); switch (insn.opcode) { case kAsr: { stream << "asr "; } break; case kLsl: { stream << "lsl "; } break; case kLsr: { stream << "lsr "; } break; case kRor: { stream << "ror "; } break; case kSdiv: { stream << "sdiv "; } break; case kUdiv: { stream << "udiv "; } break; case kPacga: { stream << "pacga "; } break; case kCrc32b: { stream << "crc32b "; } break; case kCrc32h: { stream << "crc32h "; } break; case kCrc32w: { stream << "crc32w "; } break; case kCrc32x: { stream << "crc32x "; } break; case kCrc32cb: { stream << "crc32cb "; } break; case kCrc32ch: { stream << "crc32ch "; } break; case kCrc32cw: { stream << "crc32cw "; } break; case kCrc32cx: { stream << "crc32cx "; } break; default: abort(); } PrintOperands(stream, insn.operands); } static void PrintDataProcessingOneSource(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 2); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); switch (insn.opcode) { case kRbit: { stream << "rbit " << rd << ", " << rn; } break; case kRev16: { stream << "rev16 " << rd << ", " << rn; } break; case kRev32: { stream << "rev32 " << rd << ", " << rn; } break; case kRev: { stream << "rev " << rd << ", " << rn; } break; case kClz: { stream << "clz " << rd << ", " << rn; } break; case kCls: { stream << "cls " << rd << ", " << rn; } break; case kPacia: { if (rn.name == Register::kXzr) { stream << "paciza " << rd; } else { stream << "pacia " << rd << ", " << rn; } } break; case kPacib: { if (rn.name == Register::kXzr) { stream << "pacizb " << rd; } else { stream << "pacib " << rd << ", " << rn; } } break; case kPacda: { if (rn.name == Register::kXzr) { stream << "pacdza " << rd; } else { stream << "pacda " << rd << ", " << rn; } } break; case kPacdb: { if (rn.name == Register::kXzr) { stream << "pacdzb " << rd; } else { stream << "pacdb " << rd << ", " << rn; } } break; case kAutia: { if (rn.name == Register::kXzr) { stream << "autiza " << rd; } else { stream << "autia " << rd << ", " << rn; } } break; case kAutib: { if (rn.name == Register::kXzr) { stream << "autizb " << rd; } else { stream << "autib " << rd << ", " << rn; } } break; case kAutda: { if (rn.name == Register::kXzr) { stream << "autdza " << rd; } else { stream << "autda " << rd << ", " << rn; } } break; case kAutdb: { if (rn.name == Register::kXzr) { stream << "autdzb " << rd; } else { stream << "autda " << rd << ", " << rn; } } break; case kXpaci: { stream << "xpaci " << rd; } break; case kXpacd: { stream << "xpacd " << rd; } break; default: abort(); } } static void PrintLogicalShiftedRegister(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); Shift shift = std::get<Shift>(insn.operands[3]); switch (insn.opcode) { case kAndShiftedRegister: { if (insn.set_flags) { stream << "ands "; } else { stream << "and "; } } break; case kBicShiftedRegister: { if (insn.set_flags) { stream << "bics "; } else { stream << "bic "; } } break; case kOrrShiftedRegister: { if (rn.name == Register::kXzr) { stream << "mov " << rd << ", " << rm << shift; return; } else { stream << "orr "; } } break; case kOrnShiftedRegister: { if (rn.name == Register::kXzr) { stream << "mvn " << rd << ", " << rm << shift; return; } else { stream << "orn "; } } break; case kEorShiftedRegister: { stream << "eor "; } break; case kEonShiftedRegister: { stream << "eon "; } break; default: abort(); } PrintOperands(stream, insn.operands); } static void PrintAddSubtractShiftedRegister(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); Shift shift = std::get<Shift>(insn.operands[3]); if (insn.opcode == kSubShiftedRegister) { if (insn.set_flags) { if (rd.name == Register::kXzr) { stream << "cmp " << rn << ", " << rm << shift; } else if (rn.name == Register::kXzr) { stream << "negs " << rd << ", " << rm << shift; } else { stream << "subs " << rd << ", " << rn << ", " << rm << shift; } } else { if (rn.name == Register::kXzr) { stream << "neg " << rd << ", " << rm << shift; } else { stream << "sub " << rd << ", " << rn << ", " << rm << shift; } } } else { if (insn.set_flags) { if (rd.name == Register::kXzr) { stream << "cmn " << rn << ", " << rm << shift; } else { stream << "adds " << rd << ", " << rn << ", " << rm << shift; } } else { stream << "add " << rd << ", " << rn << ", " << rm << shift; } } } static void PrintAddSubtractExtendedRegister(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); Extend extend = std::get<Extend>(insn.operands[3]); if (insn.opcode == kSubExtendedRegister) { if (insn.set_flags) { if (rd.name == Register::kXzr) { stream << "cmp " << rn << ", " << rm << extend; } else { stream << "subs " << rd << ", " << rn << ", " << rm << extend; } } else { stream << "sub " << rd << ", " << rn << ", " << rm << extend; } } else { if (insn.set_flags) { if (rd.name == Register::kXzr) { stream << "cmn " << rn << ", " << rm << extend; } else { stream << "adds " << rd << ", " << rn << ", " << rm << extend; } } else { stream << "add " << rd << ", " << rn << ", " << rm << extend; } } } static void PrintAddSubtractWithCarry(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); if (insn.opcode == kSbc) { if (insn.set_flags) { if (rn.name == Register::kXzr) { stream << "ngcs " << rd << ", " << rm; } else { stream << "sbcs " << rd << ", " << rn << ", " << rm; } } else { if (rn.name == Register::kXzr) { stream << "ngc " << rd << ", " << rm; } else { stream << "sbc " << rd << ", " << rn << ", " << rm; } } } else { if (insn.set_flags) { stream << "adcs " << rd << ", " << rn << ", " << rm; } else { stream << "adc " << rd << ", " << rn << ", " << rm; } } } static void PrintConditionalCompare(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); if (insn.opcode == kCcmn) { stream << "ccmn "; } else { stream << "ccmp "; } PrintOperands(stream, insn.operands); stream << ", "; PrintConditionCode(stream, insn.cc); } static void PrintConditionalSelect(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 3); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); if (insn.opcode == kCsel) { stream << "csel " << rd << ", " << rn << ", " << rm; } else if (insn.opcode == kCsinc) { if (rn.name == Register::kXzr && rm.name == Register::kXzr) { stream << "cset " << rd; } else if (rn.name == rm.name) { stream << "cinc " << rd << ", " << rn; } else { stream << "csinc " << rd << ", " << rn << ", " << rm; } } else if (insn.opcode == kCsinv) { if (rn.name == Register::kXzr && rm.name == Register::kXzr) { stream << "csetm " << rd; } else if (rn.name == rm.name) { stream << "cinv " << rd << ", " << rn; } else { stream << "csinv " << rd << ", " << rn << ", " << rm; } } else if (insn.opcode == kCsneg) { if (rn.name == rm.name) { stream << "cneg " << rd << ", " << rn; } else { stream << "csneg " << rd << ", " << rn << ", " << rm; } } else { abort(); } stream << ", "; PrintConditionCode(stream, insn.cc); } static void PrintDataProcessingThreeSource(std::ostream& stream, const Instruction& insn) { assert(insn.operands.size() == 4); Register rd = std::get<Register>(insn.operands[0]); Register rn = std::get<Register>(insn.operands[1]); Register rm = std::get<Register>(insn.operands[2]); Register ra = std::get<Register>(insn.operands[3]); switch (insn.opcode) { case kMadd: { if (ra.name == Register::kXzr) { stream << "mul " << rd << ", " << rn << ", " << rm; } else { stream << "madd " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kMsub: { if (ra.name == Register::kXzr) { stream << "mneg " << rd << ", " << rn << ", " << rm; } else { stream << "msub " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kSmaddl: { if (ra.name == Register::kXzr) { stream << "smull " << rd << ", " << rn << ", " << rm; } else { stream << "smaddl " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kSmsubl: { if (ra.name == Register::kXzr) { stream << "smnegl " << rd << ", " << rn << ", " << rm; } else { stream << "smsubl " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kSmulh: { stream << "smulh " << rd << ", " << rn << ", " << rm; } break; case kUmaddl: { if (ra.name == Register::kXzr) { stream << "umull " << rd << ", " << rn << ", " << rm; } else { stream << "umaddl " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kUmsubl: { if (ra.name == Register::kXzr) { stream << "umnegl " << rd << ", " << rn << ", " << rm; } else { stream << "umsubl " << rd << ", " << rn << ", " << rm << ", " << ra; } } break; case kUmulh: { stream << "umulh " << rd << ", " << rn << ", " << rm; } break; default: abort(); } } std::ostream& operator<<(std::ostream& stream, const Instruction& insn) { if (insn.opcode <= kAdrp) { PrintPcRelativeAddressing(stream, insn); } else if (insn.opcode <= kSubImmediate) { PrintAddSubtractImmediate(stream, insn); } else if (insn.opcode <= kEorImmediate) { PrintLogicalImmediate(stream, insn); } else if (insn.opcode <= kMovz) { PrintMoveWideImmediate(stream, insn); } else if (insn.opcode <= kUbfm) { PrintBitfield(stream, insn); } else if (insn.opcode <= kExtr) { PrintExtract(stream, insn); } else if (insn.opcode <= kBCond) { PrintConditionalBranch(stream, insn); } else if (insn.opcode <= kSvc) { PrintExceptionGeneration(stream, insn); } else if (insn.opcode <= kYield) { PrintSystem(stream, insn); } else if (insn.opcode <= kRetabz) { PrintBranchRegister(stream, insn); } else if (insn.opcode <= kBl) { PrintBranchImmediate(stream, insn); } else if (insn.opcode <= kCbz) { PrintCompareAndBranch(stream, insn); } else if (insn.opcode <= kTbz) { PrintTestAndBranch(stream, insn); } else if (insn.opcode <= kStxr) { PrintLoadStoreExclusive(stream, insn); } else if (insn.opcode <= kPrfmLiteral) { PrintLoadLiteral(stream, insn); } else if (insn.opcode <= kStp) { PrintLoadStorePair(stream, insn); } else if (insn.opcode <= kStur) { PrintLoadStore(stream, insn); } else if (insn.opcode <= kUdiv) { PrintDataProcessingTwoSource(stream, insn); } else if (insn.opcode <= kXpaci) { PrintDataProcessingOneSource(stream, insn); } else if (insn.opcode <= kEonShiftedRegister) { PrintLogicalShiftedRegister(stream, insn); } else if (insn.opcode <= kSubShiftedRegister) { PrintAddSubtractShiftedRegister(stream, insn); } else if (insn.opcode <= kSubExtendedRegister) { PrintAddSubtractExtendedRegister(stream, insn); } else if (insn.opcode <= kSbc) { PrintAddSubtractWithCarry(stream, insn); } else if (insn.opcode <= kCcmp) { PrintConditionalCompare(stream, insn); } else if (insn.opcode <= kCsneg) { PrintConditionalSelect(stream, insn); } else if (insn.opcode <= kUmsubl) { PrintDataProcessingThreeSource(stream, insn); } else { stream << "invalid"; } return stream; } std::ostream& operator<<(std::ostream& stream, const Operand& opnd) { switch (opnd.index()) { case kImmediate: { PrintImmediate(stream, std::get<Immediate>(opnd)); } break; case kRegister: { PrintRegister(stream, std::get<Register>(opnd)); } break; case kSystemRegister: { PrintSystemRegister(stream, std::get<SystemRegister>(opnd)); } break; case kShift: { PrintShift(stream, std::get<Shift>(opnd)); } break; case kExtend: { PrintExtend(stream, std::get<Extend>(opnd)); } break; case kImmediateOffset: { PrintImmediateOffset(stream, std::get<ImmediateOffset>(opnd)); } break; case kRegisterOffset: { PrintRegisterOffset(stream, std::get<RegisterOffset>(opnd)); } break; default: stream << "invalid"; } return stream; } } // namespace decoder } // namespace aarch64 } // namespace reil
25.258202
80
0.509369
[ "vector" ]
019f080bd2ec5bb1deb1b4c19f517d845dba406d
1,683
cpp
C++
src/image_view.cpp
gasinvein/vkBasalt
2aad4245dd133feac80f80177dccba53c6cb2be5
[ "Zlib" ]
null
null
null
src/image_view.cpp
gasinvein/vkBasalt
2aad4245dd133feac80f80177dccba53c6cb2be5
[ "Zlib" ]
null
null
null
src/image_view.cpp
gasinvein/vkBasalt
2aad4245dd133feac80f80177dccba53c6cb2be5
[ "Zlib" ]
null
null
null
#include "image_view.hpp" namespace vkBasalt { std::vector<VkImageView> createImageViews(std::shared_ptr<LogicalDevice> pLogicalDevice, VkFormat format, std::vector<VkImage> images, VkImageViewType viewType, VkImageAspectFlags aspectMask, uint32_t mipLevels) { std::vector<VkImageView> imageViews(images.size()); VkImageViewCreateInfo imageViewCreateInfo; imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; imageViewCreateInfo.pNext = nullptr; imageViewCreateInfo.flags = 0; imageViewCreateInfo.image = VK_NULL_HANDLE; imageViewCreateInfo.viewType = viewType; imageViewCreateInfo.format = format; imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; imageViewCreateInfo.subresourceRange.aspectMask = aspectMask; imageViewCreateInfo.subresourceRange.baseMipLevel = 0; imageViewCreateInfo.subresourceRange.levelCount = mipLevels; imageViewCreateInfo.subresourceRange.baseArrayLayer = 0; imageViewCreateInfo.subresourceRange.layerCount = 1; for(uint32_t i = 0; i < images.size(); i++) { imageViewCreateInfo.image = images[i]; VkResult result = pLogicalDevice->vkd.CreateImageView(pLogicalDevice->device, &imageViewCreateInfo, nullptr, &(imageViews[i])); ASSERT_VULKAN(result); } return imageViews; } }
44.289474
215
0.715389
[ "vector" ]
01b0120fef585704d05ddac937e1e8b0f86df188
2,463
cpp
C++
src/Engine/Loaders/XmlLoader.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Engine/Loaders/XmlLoader.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Engine/Loaders/XmlLoader.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
#include "Base.h" #include "XmlLoader.h" #include "Parsers/Xml/tinyxml2.h" using namespace tinyxml2; namespace CasaEngine { XmlLoader::XmlLoader() { } XmlLoader::~XmlLoader() { } /** * */ void HandleXmlError(XMLError error_, const std::string& Filename = "") { if (error_ != XML_SUCCESS) { std::string msg = "tinyxml2 error : "; switch(error_) { case XML_NO_ATTRIBUTE: msg+= "XML_NO_ATTRIBUTE"; break; case XML_WRONG_ATTRIBUTE_TYPE: msg+= "XML_WRONG_ATTRIBUTE_TYPE"; break; case XML_ERROR_FILE_NOT_FOUND: msg+= "XML_ERROR_FILE_NOT_FOUND"; break; case XML_ERROR_FILE_COULD_NOT_BE_OPENED: msg+= "XML_ERROR_FILE_COULD_NOT_BE_OPENED"; break; case XML_ERROR_FILE_READ_ERROR: msg+= "XML_ERROR_FILE_READ_ERROR"; break; case XML_ERROR_ELEMENT_MISMATCH: msg+= "XML_ERROR_ELEMENT_MISMATCH"; break; case XML_ERROR_PARSING_ELEMENT: msg+= "XML_ERROR_PARSING_ELEMENT"; break; case XML_ERROR_PARSING_ATTRIBUTE: msg+= "XML_ERROR_PARSING_ATTRIBUTE"; break; case XML_ERROR_IDENTIFYING_TAG: msg+= "XML_ERROR_IDENTIFYING_TAG"; break; case XML_ERROR_PARSING_TEXT: msg+= "XML_ERROR_PARSING_TEXT"; break; case XML_ERROR_PARSING_CDATA: msg+= "XML_ERROR_PARSING_CDATA"; break; case XML_ERROR_PARSING_COMMENT: msg+= "XML_ERROR_PARSING_COMMENT"; break; case XML_ERROR_PARSING_DECLARATION: msg+= "XML_ERROR_PARSING_DECLARATION"; break; case XML_ERROR_PARSING_UNKNOWN: msg+= "XML_ERROR_PARSING_UNKNOWN"; break; case XML_ERROR_EMPTY_DOCUMENT: msg+= "XML_ERROR_EMPTY_DOCUMENT"; break; case XML_ERROR_MISMATCHED_ELEMENT: msg+= "XML_ERROR_MISMATCHED_ELEMENT"; break; case XML_ERROR_PARSING: msg+= "XML_ERROR_PARSING"; break; case XML_CAN_NOT_CONVERT_TEXT: msg+= "XML_CAN_NOT_CONVERT_TEXT"; break; case XML_NO_TEXT_NODE: msg+= "XML_NO_TEXT_NODE"; break; default: msg+= "unknown"; break; } throw NEW_AO CLoadingFailed(Filename, msg); } } tinyxml2::XMLDocument* XmlLoader::LoadFromFile(IFile *pFile_) { tinyxml2::XMLDocument *xmlDoc = new tinyxml2::XMLDocument(); //XMLError error = xmlDoc->LoadFile(Filename.c_str()); const char *xml = pFile_->GetBuffer(); XMLError error = xmlDoc->Parse(xml, pFile_->GetBufferLength()); HandleXmlError(error, pFile_->Filename()); return xmlDoc; } void XmlLoader::SaveToFile(const tinyxml2::XMLDocument* Object, const std::string& Filename) { XMLError error = const_cast<tinyxml2::XMLDocument *>(Object)->SaveFile(Filename.c_str()); HandleXmlError(error, Filename); } }
33.283784
93
0.761267
[ "object" ]
01b579cbdb46d9d107e9e7711500eec641dae39f
400
hpp
C++
include/wordprediction.hpp
afairon/markov-cpp-playground
cec0e3e27046a8da9b1e51ea93e1caf801dbafda
[ "MIT" ]
null
null
null
include/wordprediction.hpp
afairon/markov-cpp-playground
cec0e3e27046a8da9b1e51ea93e1caf801dbafda
[ "MIT" ]
null
null
null
include/wordprediction.hpp
afairon/markov-cpp-playground
cec0e3e27046a8da9b1e51ea93e1caf801dbafda
[ "MIT" ]
null
null
null
#ifndef WORD_PREDICTION_HPP_ #define WORD_PREDICTION_HPP_ #include <string> #include <vector> typedef std::vector<std::string> NGram; // WordPrediction abstract class for word prediction class WordPrediction { public: WordPrediction() {} ~WordPrediction() {} virtual void Add(const NGram& seq) = 0; virtual std::string Generate(const NGram& seq) = 0; }; #endif
22.222222
59
0.69
[ "vector" ]
01b9b88ea76efd28287db4cae3a79117d468f3a6
2,989
hpp
C++
include/hops/Model/MultivariateGaussianModel.hpp
modsim/hops
4285dd75a07dd844295440a0756b3ba25f5819ac
[ "MIT" ]
7
2020-11-26T05:13:03.000Z
2022-01-12T02:08:40.000Z
include/hops/Model/MultivariateGaussianModel.hpp
modsim/hops
4285dd75a07dd844295440a0756b3ba25f5819ac
[ "MIT" ]
1
2021-02-20T23:16:34.000Z
2021-02-20T23:16:34.000Z
include/hops/Model/MultivariateGaussianModel.hpp
modsim/hops
4285dd75a07dd844295440a0756b3ba25f5819ac
[ "MIT" ]
null
null
null
#ifndef HOPS_MULTIVARIATEGAUSSIANMODEL_HPP #define HOPS_MULTIVARIATEGAUSSIANMODEL_HPP #define _USE_MATH_DEFINES #include <math.h> #include <Eigen/Cholesky> #include <Eigen/Core> #include <Eigen/LU> #include <utility> namespace hops { template<typename Matrix, typename Vector> class MultivariateGaussianModel { public: using MatrixType = Matrix; using VectorType = Vector; MultivariateGaussianModel(VectorType mean, MatrixType covariance); /** * @brief Evaluates the negative log likelihood for input x. * @param x * @return */ typename MatrixType::Scalar computeNegativeLogLikelihood(const VectorType &x) const; MatrixType computeExpectedFisherInformation(const VectorType &) const; VectorType computeLogLikelihoodGradient(const VectorType &x) const; private: VectorType mean; MatrixType covariance; MatrixType inverseCovariance; typename MatrixType::Scalar logNormalizationConstant; }; template<typename MatrixType, typename VectorType> MultivariateGaussianModel<MatrixType, VectorType>::MultivariateGaussianModel(VectorType mean, MatrixType covariance) : mean(std::move(mean)), covariance(std::move(covariance)) { Eigen::LLT<MatrixType, Eigen::Upper> solver(this->covariance); Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixL = solver.matrixL(); Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> matrixU = solver.matrixU(); Eigen::Matrix<typename MatrixType::Scalar, Eigen::Dynamic, Eigen::Dynamic> inverseMatrixL = matrixL.inverse(); inverseCovariance = inverseMatrixL * inverseMatrixL.transpose(); logNormalizationConstant = -static_cast<typename MatrixType::Scalar>(this->mean.rows()) / 2 * std::log(2 * M_PI) - matrixL.diagonal().array().log().sum(); } template<typename MatrixType, typename VectorType> typename MatrixType::Scalar MultivariateGaussianModel<MatrixType, VectorType>::computeNegativeLogLikelihood(const VectorType &x) const { return -logNormalizationConstant + 0.5 * static_cast<typename MatrixType::Scalar>((x - mean).transpose() * inverseCovariance * (x - mean)); } template<typename MatrixType, typename VectorType> MatrixType MultivariateGaussianModel<MatrixType, VectorType>::computeExpectedFisherInformation(const VectorType &) const { return inverseCovariance; } template<typename MatrixType, typename VectorType> VectorType MultivariateGaussianModel<MatrixType, VectorType>::computeLogLikelihoodGradient(const VectorType &x) const { return -inverseCovariance * (x - mean); } } #endif //HOPS_MULTIVARIATEGAUSSIANMODEL_HPP
39.853333
119
0.680495
[ "vector" ]
01bb45b469f01440c61a0edcc791ccc248800c6e
104,146
cpp
C++
production/libs/fog/Fog/Src/Fog/G2d/Painting/RasterInit_SSE2.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/G2d/Painting/RasterInit_SSE2.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/G2d/Painting/RasterInit_SSE2.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
// [Fog-G2d] // // [License] // MIT, See COPYING file in package // [Precompiled Headers] #if defined(FOG_PRECOMP) #include FOG_PRECOMP #endif // FOG_PRECOMP // [Dependencies] #include <Fog/Core/Global/Global.h> #include <Fog/G2d/Painting/RasterApi_p.h> #include <Fog/G2d/Painting/RasterConstants_p.h> #include <Fog/G2d/Painting/RasterInit_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/BaseAccess_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/BaseConvert_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/BaseDefs_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/BaseHelpers_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/CompositeBase_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/CompositeClear_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/CompositeExt_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/CompositeSrc_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/CompositeSrcOver_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/GradientBase_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/GradientConical_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/GradientLinear_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/GradientRadial_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/GradientRectangular_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/TextureBase_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/TextureAffine_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/TextureProjection_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/TextureScale_p.h> #include <Fog/G2d/Painting/RasterOps_SSE2/TextureSimple_p.h> namespace Fog { // ============================================================================ // [Init / Fini] // ============================================================================ FOG_NO_EXPORT void RasterOps_init_SSE2(void) { ApiRaster& api = _api_raster; //return; // -------------------------------------------------------------------------- // [RasterOps - Convert - API] // -------------------------------------------------------------------------- RasterConvertFuncs& convert = api.convert; // -------------------------------------------------------------------------- // [RasterOps - Convert - Copy] // -------------------------------------------------------------------------- /* convert.copy[RASTER_COPY_8] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_8; convert.copy[RASTER_COPY_16] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_16; convert.copy[RASTER_COPY_24] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_24; convert.copy[RASTER_COPY_32] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_32; convert.copy[RASTER_COPY_48] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_48; convert.copy[RASTER_COPY_64] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::copy_64; // -------------------------------------------------------------------------- // [RasterOps - Convert - Fill] // -------------------------------------------------------------------------- */ convert.fill[RASTER_FILL_8] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::fill_8; convert.fill[RASTER_FILL_16] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::fill_16; /* // -------------------------------------------------------------------------- // [RasterOps - Convert - BSwap] // -------------------------------------------------------------------------- convert.bswap[RASTER_BSWAP_16] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::bswap_16; convert.bswap[RASTER_BSWAP_24] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::bswap_24; convert.bswap[RASTER_BSWAP_32] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::bswap_32; convert.bswap[RASTER_BSWAP_48] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::bswap_48; convert.bswap[RASTER_BSWAP_64] = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::bswap_64; // -------------------------------------------------------------------------- // [RasterOps - Convert - Premultiply / Demultiply] // -------------------------------------------------------------------------- convert.prgb32_from_argb32 = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::prgb32_from_argb32; convert.prgb64_from_argb64 = (ImageConverterBlitLineFunc)RasterOps_SSE2::Convert::prgb64_from_argb64; */ // -------------------------------------------------------------------------- // [RasterOps - Convert - ARGB32] // -------------------------------------------------------------------------- /* convert.argb32_from[RASTER_FORMAT_RGB16_555 ] = RasterOps_SSE2::Convert::argb32_from_rgb16_555; convert.argb32_from[RASTER_FORMAT_RGB16_555_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb16_555_bs; convert.argb32_from[RASTER_FORMAT_RGB16_565 ] = RasterOps_SSE2::Convert::argb32_from_rgb16_565; convert.argb32_from[RASTER_FORMAT_RGB16_565_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb16_565_bs; convert.argb32_from[RASTER_FORMAT_ARGB16_4444 ] = RasterOps_SSE2::Convert::argb32_from_argb16_4444; convert.argb32_from[RASTER_FORMAT_ARGB16_4444_BS ] = RasterOps_SSE2::Convert::argb32_from_argb16_4444_bs; convert.argb32_from[RASTER_FORMAT_ARGB16_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_argb16_custom; convert.argb32_from[RASTER_FORMAT_ARGB16_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_argb16_custom_bs; //convert.argb32_from[RASTER_FORMAT_RGB24_888 ] = SKIP; convert.argb32_from[RASTER_FORMAT_RGB24_888_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb24_888_bs; convert.argb32_from[RASTER_FORMAT_ARGB24_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_argb24_custom; convert.argb32_from[RASTER_FORMAT_ARGB24_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_argb24_custom_bs; //convert.argb32_from[RASTER_FORMAT_RGB32_888 ] = SKIP; convert.argb32_from[RASTER_FORMAT_RGB32_888_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb32_888_bs; //convert.argb32_from[RASTER_FORMAT_ARGB32_8888 ] = SKIP; convert.argb32_from[RASTER_FORMAT_ARGB32_8888_BS ] = RasterOps_SSE2::Convert::argb32_from_argb32_8888_bs; convert.argb32_from[RASTER_FORMAT_ARGB32_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_argb32_custom; convert.argb32_from[RASTER_FORMAT_ARGB32_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_argb32_custom_bs; //convert.argb32_from[RASTER_FORMAT_RGB48_161616 ] = SKIP; convert.argb32_from[RASTER_FORMAT_RGB48_161616_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb48_161616_bs; convert.argb32_from[RASTER_FORMAT_RGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_rgb48_custom; convert.argb32_from[RASTER_FORMAT_RGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_rgb48_custom_bs; convert.argb32_from[RASTER_FORMAT_ARGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_argb48_custom; convert.argb32_from[RASTER_FORMAT_ARGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_argb48_custom_bs; //convert.argb32_from[RASTER_FORMAT_ARGB64_16161616 ] = SKIP; convert.argb32_from[RASTER_FORMAT_ARGB64_16161616_BS ] = RasterOps_SSE2::Convert::argb32_from_argb64_16161616_bs; convert.argb32_from[RASTER_FORMAT_ARGB64_CUSTOM ] = RasterOps_SSE2::Convert::argb32_from_argb64_custom; convert.argb32_from[RASTER_FORMAT_ARGB64_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_from_argb64_custom_bs; //convert.argb32_from[RASTER_FORMAT_I8 ]; convert.from_argb32[RASTER_FORMAT_RGB16_555 ] = RasterOps_SSE2::Convert::rgb16_555_from_argb32; convert.from_argb32[RASTER_FORMAT_RGB16_555_BS ] = RasterOps_SSE2::Convert::rgb16_555_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_RGB16_565 ] = RasterOps_SSE2::Convert::rgb16_565_from_argb32; convert.from_argb32[RASTER_FORMAT_RGB16_565_BS ] = RasterOps_SSE2::Convert::rgb16_565_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB16_4444 ] = RasterOps_SSE2::Convert::argb16_4444_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB16_4444_BS ] = RasterOps_SSE2::Convert::argb16_4444_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB16_CUSTOM ] = RasterOps_SSE2::Convert::argb16_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB16_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb16_custom_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_RGB24_888 ] = SKIP; convert.from_argb32[RASTER_FORMAT_RGB24_888_BS ] = RasterOps_SSE2::Convert::rgb24_888_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB24_CUSTOM ] = RasterOps_SSE2::Convert::argb24_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB24_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb24_custom_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_RGB32_888 ] = SKIP; convert.from_argb32[RASTER_FORMAT_RGB32_888_BS ] = RasterOps_SSE2::Convert::rgb32_888_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_ARGB32_8888 ] = SKIP; convert.from_argb32[RASTER_FORMAT_ARGB32_8888_BS ] = RasterOps_SSE2::Convert::argb32_8888_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB32_CUSTOM ] = RasterOps_SSE2::Convert::argb32_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB32_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_custom_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_RGB48_161616 ] = SKIP; convert.from_argb32[RASTER_FORMAT_RGB48_161616_BS ] = RasterOps_SSE2::Convert::rgb48_161616_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_RGB48_CUSTOM ] = RasterOps_SSE2::Convert::rgb48_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_RGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::rgb48_custom_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb48_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb48_custom_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_ARGB64_16161616 ] = SKIP; convert.from_argb32[RASTER_FORMAT_ARGB64_16161616_BS ] = RasterOps_SSE2::Convert::argb64_16161616_bs_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB64_CUSTOM ] = RasterOps_SSE2::Convert::argb64_custom_from_argb32; convert.from_argb32[RASTER_FORMAT_ARGB64_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_custom_bs_from_argb32; //convert.from_argb32[RASTER_FORMAT_I8 ]; // -------------------------------------------------------------------------- //[RasterOps - Convert - ARGB64] // -------------------------------------------------------------------------- convert.argb64_from[RASTER_FORMAT_RGB16_555 ] = RasterOps_SSE2::Convert::argb64_from_rgb16_555; convert.argb64_from[RASTER_FORMAT_RGB16_555_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb16_555_bs; convert.argb64_from[RASTER_FORMAT_RGB16_565 ] = RasterOps_SSE2::Convert::argb64_from_rgb16_565; convert.argb64_from[RASTER_FORMAT_RGB16_565_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb16_565_bs; convert.argb64_from[RASTER_FORMAT_ARGB16_4444 ] = RasterOps_SSE2::Convert::argb64_from_argb16_4444; convert.argb64_from[RASTER_FORMAT_ARGB16_4444_BS ] = RasterOps_SSE2::Convert::argb64_from_argb16_4444_bs; convert.argb64_from[RASTER_FORMAT_ARGB16_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_argb16_custom; convert.argb64_from[RASTER_FORMAT_ARGB16_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_argb16_custom_bs; //convert.argb64_from[RASTER_FORMAT_RGB24_888 ] = SKIP; convert.argb64_from[RASTER_FORMAT_RGB24_888_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb24_888_bs; convert.argb64_from[RASTER_FORMAT_ARGB24_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_argb24_custom; convert.argb64_from[RASTER_FORMAT_ARGB24_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_argb24_custom_bs; //convert.argb64_from[RASTER_FORMAT_RGB32_888 ] = SKIP; convert.argb64_from[RASTER_FORMAT_RGB32_888_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb32_888_bs; //convert.argb64_from[RASTER_FORMAT_ARGB32_8888 ] = SKIP; convert.argb64_from[RASTER_FORMAT_ARGB32_8888_BS ] = RasterOps_SSE2::Convert::argb64_from_argb32_8888_bs; convert.argb64_from[RASTER_FORMAT_ARGB32_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_argb32_custom; convert.argb64_from[RASTER_FORMAT_ARGB32_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_argb32_custom_bs; //convert.argb64_from[RASTER_FORMAT_RGB48_161616 ] = SKIP; convert.argb64_from[RASTER_FORMAT_RGB48_161616_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb48_161616_bs; convert.argb64_from[RASTER_FORMAT_RGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_rgb48_custom; convert.argb64_from[RASTER_FORMAT_RGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_rgb48_custom_bs; convert.argb64_from[RASTER_FORMAT_ARGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_argb48_custom; convert.argb64_from[RASTER_FORMAT_ARGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_argb48_custom_bs; //convert.argb64_from[RASTER_FORMAT_ARGB64_16161616 ] = SKIP; convert.argb64_from[RASTER_FORMAT_ARGB64_16161616_BS ] = RasterOps_SSE2::Convert::argb64_from_argb64_16161616_bs; convert.argb64_from[RASTER_FORMAT_ARGB64_CUSTOM ] = RasterOps_SSE2::Convert::argb64_from_argb64_custom; convert.argb64_from[RASTER_FORMAT_ARGB64_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_from_argb64_custom_bs; //convert.argb64_from[RASTER_FORMAT_I8 ]; */ // TODO: Image conversion. /* convert.from_argb64[RASTER_FORMAT_RGB16_555 ] = RasterOps_SSE2::Convert::rgb16_555_from_argb64; convert.from_argb64[RASTER_FORMAT_RGB16_555_BS ] = RasterOps_SSE2::Convert::rgb16_555_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_RGB16_565 ] = RasterOps_SSE2::Convert::rgb16_565_from_argb64; convert.from_argb64[RASTER_FORMAT_RGB16_565_BS ] = RasterOps_SSE2::Convert::rgb16_565_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB16_4444 ] = RasterOps_SSE2::Convert::argb16_4444_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB16_4444_BS ] = RasterOps_SSE2::Convert::argb16_4444_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB16_CUSTOM ] = RasterOps_SSE2::Convert::argb16_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB16_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb16_custom_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_RGB24_888 ] = SKIP; convert.from_argb64[RASTER_FORMAT_RGB24_888_BS ] = RasterOps_SSE2::Convert::rgb24_888_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB24_CUSTOM ] = RasterOps_SSE2::Convert::argb24_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB24_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb24_custom_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_RGB32_888 ] = SKIP; convert.from_argb64[RASTER_FORMAT_RGB32_888_BS ] = RasterOps_SSE2::Convert::rgb32_888_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_ARGB32_8888 ] = SKIP; convert.from_argb64[RASTER_FORMAT_ARGB32_8888_BS ] = RasterOps_SSE2::Convert::argb32_8888_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB32_CUSTOM ] = RasterOps_SSE2::Convert::argb32_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB32_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb32_custom_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_RGB48_161616 ] = SKIP; convert.from_argb64[RASTER_FORMAT_RGB48_161616_BS ] = RasterOps_SSE2::Convert::rgb48_161616_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_RGB48_CUSTOM ] = RasterOps_SSE2::Convert::rgb48_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_RGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::rgb48_custom_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB48_CUSTOM ] = RasterOps_SSE2::Convert::argb48_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB48_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb48_custom_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_ARGB64_16161616 ] = SKIP; convert.from_argb64[RASTER_FORMAT_ARGB64_16161616_BS ] = RasterOps_SSE2::Convert::argb64_16161616_bs_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB64_CUSTOM ] = RasterOps_SSE2::Convert::argb64_custom_from_argb64; convert.from_argb64[RASTER_FORMAT_ARGB64_CUSTOM_BS ] = RasterOps_SSE2::Convert::argb64_custom_bs_from_argb64; //convert.from_argb64[RASTER_FORMAT_I8 ]; */ // -------------------------------------------------------------------------- // [RasterOps - Composite - Src - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_CORE_SRC]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); /* FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::Convert::copy_32); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_prgb64_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb48_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_a16_line); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_a8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_prgb64_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb48_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_a16_span); */ } // -------------------------------------------------------------------------- // [RasterOps - Composite - Src - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_CORE_SRC]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); /* FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::Convert::copy_32); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_prgb64_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb48_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_a16_line); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_a8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_prgb64_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::prgb32_vblit_rgb48_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::xrgb32_vblit_a16_span); */ } // -------------------------------------------------------------------------- // [RasterOps - Composite - Src - RGB24] // -------------------------------------------------------------------------- /* { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_RGB24][RASTER_COMPOSITE_CORE_SRC]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::rgb24_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::rgb24_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_xrgb32_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB24 ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_a8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_prgb64_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_rgb48_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_a16_line); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_xrgb32_span); //FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_a8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_prgb64_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_rgb48_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::rgb24_vblit_a16_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Src - A8] // -------------------------------------------------------------------------- { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_A8][RASTER_COMPOSITE_CORE_SRC]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::a8_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrc::a8_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::a8_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::Convert::fill_8); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::Convert::fill_8); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::a8_vblit_a8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::a8_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::a8_vblit_prgb64_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::Convert::fill_8); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::a8_vblit_a16_line); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrc::a8_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_XRGB32 ], RasterOps_SSE2::CompositeSrc::a8_vblit_white_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB24 ], RasterOps_SSE2::CompositeSrc::a8_vblit_white_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrc::a8_vblit_a8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrc::a8_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrc::a8_vblit_prgb64_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_RGB48 ], RasterOps_SSE2::CompositeSrc::a8_vblit_white_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrc::a8_vblit_a16_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOver - PRGB32] // -------------------------------------------------------------------------- */ { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_CORE_SRC_OVER]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB24 ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a8_line); /* FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb64_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB48 ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a16_line); */ FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB24 ]); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a8_span); /*//FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb64_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB48 ]); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a16_span); */ } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOver - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_CORE_SRC_OVER]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB24 ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a8_line); /* FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_i8_line); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb64_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB48 ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a16_line); */ FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB24 ]); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a8_span); /*//FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_i8_span); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_prgb64_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB48 ]); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::prgb32_vblit_a16_span); */ } /* // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOver - RGB24] // -------------------------------------------------------------------------- { RasterCompositeCoreFuncs& funcs = api.compositeCore[IMAGE_FORMAT_RGB24][RASTER_COMPOSITE_CORE_SRC_OVER]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::rgb24_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOver::rgb24_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB24 ]); //FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_a8_line); //FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_i8_line); //FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_prgb64_line); FOG_RASTER_SKIP(vblit_line[IMAGE_FORMAT_RGB48 ]); //FOG_RASTER_INIT(vblit_line[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_a16_line); FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB32 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_XRGB32 ]); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB24 ]); //FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A8 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_a8_span); //FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_I8 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_i8_span); //FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_PRGB64 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_prgb64_span); FOG_RASTER_SKIP(vblit_span[IMAGE_FORMAT_RGB48 ]); //FOG_RASTER_INIT(vblit_span[IMAGE_FORMAT_A16 ], RasterOps_SSE2::CompositeSrcOver::rgb24_vblit_a16_span); } */ // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOver - A8] // -------------------------------------------------------------------------- // TODO: Image compositing. /* // -------------------------------------------------------------------------- // [RasterOps - Composite - Clear - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_CLEAR]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], (RasterCBlitLineFunc)RasterOps_SSE2::CompositeClear::prgb32_xblit_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], (RasterCBlitSpanFunc)RasterOps_SSE2::CompositeClear::prgb32_cblit_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], (RasterVBlitLineFunc)RasterOps_SSE2::CompositeClear::prgb32_xblit_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], (RasterVBlitSpanFunc)RasterOps_SSE2::CompositeClear::prgb32_vblit_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Clear - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_CLEAR]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], (RasterCBlitLineFunc)RasterOps_SSE2::CompositeClear::xrgb32_xblit_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], (RasterCBlitSpanFunc)RasterOps_SSE2::CompositeClear::xrgb32_cblit_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], (RasterVBlitLineFunc)RasterOps_SSE2::CompositeClear::xrgb32_xblit_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], (RasterVBlitSpanFunc)RasterOps_SSE2::CompositeClear::xrgb32_vblit_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Clear - RGB24] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_RGB24][RASTER_COMPOSITE_EXT_CLEAR]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], (RasterCBlitLineFunc)RasterOps_SSE2::CompositeClear::rgb24_xblit_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], (RasterCBlitSpanFunc)RasterOps_SSE2::CompositeClear::rgb24_cblit_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_RGB24_AND_PRGB32 ], (RasterVBlitLineFunc)RasterOps_SSE2::CompositeClear::rgb24_xblit_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_RGB24_AND_XRGB32 ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_RGB24_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_RGB24_AND_PRGB32 ], (RasterVBlitSpanFunc)RasterOps_SSE2::CompositeClear::rgb24_vblit_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_RGB24_AND_XRGB32 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_RGB24_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Clear - A8] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_A8][RASTER_COMPOSITE_EXT_CLEAR]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], (RasterCBlitLineFunc)RasterOps_SSE2::CompositeClear::a8_xblit_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], (RasterCBlitSpanFunc)RasterOps_SSE2::CompositeClear::a8_cblit_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_A8_AND_PRGB32 ], (RasterVBlitLineFunc)RasterOps_SSE2::CompositeClear::a8_xblit_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_A8_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_A8_AND_PRGB32 ], (RasterVBlitSpanFunc)RasterOps_SSE2::CompositeClear::a8_vblit_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_A8_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcIn - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_SRC_IN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcIn::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSrcIn::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcIn::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSrcIn::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcIn::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcIn - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_SRC_IN]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOut - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_SRC_OUT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOut::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSrcOut::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcOut::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSrcOut::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcOut::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcOut - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_SRC_OUT]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcAtop - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_SRC_ATOP]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcAtop::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSrcAtop::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcAtop::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcAtop::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSrcAtop::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSrcAtop::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SrcAtop - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_SRC_ATOP]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstOver - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DST_OVER]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOver::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDstOver::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOver::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDstOver::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstOver - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DST_OVER]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstIn - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DST_IN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstIn::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstIn::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstIn::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstIn::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstIn::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstIn::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstIn - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DST_IN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstIn::xrgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstIn::xrgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstIn::xrgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstIn::xrgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstOut - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DST_OUT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOut::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOut::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstOut::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstOut::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstOut::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstOut::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstOut - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DST_OUT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOut::xrgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstOut::xrgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstOut::xrgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstOut::xrgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstAtop - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DST_ATOP]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstAtop::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDstAtop::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDstAtop::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - DstAtop - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DST_ATOP]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Xor - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_XOR]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeXor::prgb32_cblit_prgb32_line); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeXor::prgb32_cblit_prgb32_span); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeXor::prgb32_vblit_prgb32_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeXor::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeXor::prgb32_vblit_prgb32_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeXor::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Xor - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_XOR]; FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_line[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_PRGB ]); FOG_RASTER_SKIP(cblit_span[RASTER_CBLIT_XRGB ]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32]); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Plus - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_PLUS]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositePlus::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositePlus::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositePlus::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositePlus::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositePlus::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositePlus::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositePlus::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositePlus::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositePlus::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositePlus::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositePlus::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositePlus::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Plus - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_PLUS]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositePlus::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositePlus::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositePlus::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositePlus::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositePlus::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositePlus::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositePlus::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositePlus::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositePlus::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositePlus::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Minus - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_MINUS]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMinus::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMinus::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMinus::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMinus::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMinus::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMinus::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMinus::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeMinus::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMinus::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMinus::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMinus::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeMinus::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Minus - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_MINUS]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMinus::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMinus::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMinus::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMinus::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMinus::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Multiply - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_MULTIPLY]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMultiply::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMultiply::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMultiply::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMultiply::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeMultiply::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Multiply - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_MULTIPLY]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMultiply::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMultiply::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeMultiply::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeMultiply::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeMultiply::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Screen - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_SCREEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeScreen::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeScreen::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeScreen::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeScreen::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeScreen::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeScreen::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeScreen::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeScreen::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeScreen::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeScreen::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeScreen::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeScreen::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Screen - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_SCREEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeScreen::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeScreen::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeScreen::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeScreen::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeScreen::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Overlay - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_OVERLAY]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeOverlay::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeOverlay::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeOverlay::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeOverlay::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeOverlay::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Overlay - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_OVERLAY]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeOverlay::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeOverlay::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeOverlay::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeOverlay::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeOverlay::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Darken - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DARKEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDarken::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDarken::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDarken::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDarken::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDarken::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDarken::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDarken::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDarken::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDarken::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDarken::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDarken::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDarken::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Darken - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DARKEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDarken::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDarken::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDarken::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDarken::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDarken::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Lighten - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_LIGHTEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeLighten::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeLighten::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeLighten::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeLighten::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeLighten::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeLighten::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeLighten::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeLighten::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeLighten::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeLighten::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeLighten::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeLighten::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Lighten - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_LIGHTEN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeLighten::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeLighten::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeLighten::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeLighten::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeLighten::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - ColorDodge - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_COLOR_DODGE]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorDodge::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorDodge::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorDodge::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorDodge::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_rgb24_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorDodge::prgb32_vblit_rgb24_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - ColorDodge - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_COLOR_DODGE]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorDodge::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorDodge::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorDodge::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorDodge::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorDodge::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - ColorBurn - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_COLOR_BURN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorBurn::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorBurn::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorBurn::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorBurn::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_rgb24_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorBurn::prgb32_vblit_rgb24_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - ColorBurn - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_COLOR_BURN]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorBurn::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorBurn::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeColorBurn::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeColorBurn::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeColorBurn::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - HardLight - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_HARD_LIGHT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeHardLight::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeHardLight::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeHardLight::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeHardLight::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_rgb24_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeHardLight::prgb32_vblit_rgb24_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - HardLight - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_HARD_LIGHT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeHardLight::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeHardLight::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeHardLight::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeHardLight::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeHardLight::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SoftLight - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_SOFT_LIGHT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSoftLight::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSoftLight::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSoftLight::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSoftLight::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeSoftLight::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - SoftLight - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_SOFT_LIGHT]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSoftLight::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSoftLight::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeSoftLight::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeSoftLight::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeSoftLight::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Difference - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_DIFFERENCE]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDifference::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDifference::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDifference::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDifference::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDifference::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDifference::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDifference::prgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDifference::prgb32_vblit_a8_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDifference::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDifference::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDifference::prgb32_vblit_rgb24_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ], RasterOps_SSE2::CompositeDifference::prgb32_vblit_a8_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Difference - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_DIFFERENCE]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDifference::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDifference::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeDifference::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeDifference::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeDifference::xrgb32_vblit_rgb24_span); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Exclusion - PRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_PRGB32][RASTER_COMPOSITE_EXT_EXCLUSION]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeExclusion::prgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeExclusion::prgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeExclusion::prgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeExclusion::prgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_rgb24_line); FOG_RASTER_SKIP(vblit_line[RASTER_VBLIT_PRGB32_AND_A8 ]); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_PRGB32], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_XRGB32], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_PRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeExclusion::prgb32_vblit_rgb24_span); FOG_RASTER_SKIP(vblit_span[RASTER_VBLIT_PRGB32_AND_A8 ]); } // -------------------------------------------------------------------------- // [RasterOps - Composite - Exclusion - XRGB32] // -------------------------------------------------------------------------- { RasterCompositeExtFuncs& funcs = api.compositeExt[IMAGE_FORMAT_XRGB32][RASTER_COMPOSITE_EXT_EXCLUSION]; FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeExclusion::xrgb32_cblit_prgb32_line); FOG_RASTER_INIT(cblit_line[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeExclusion::xrgb32_cblit_xrgb32_line); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_PRGB ], RasterOps_SSE2::CompositeExclusion::xrgb32_cblit_prgb32_span); FOG_RASTER_INIT(cblit_span[RASTER_CBLIT_XRGB ], RasterOps_SSE2::CompositeExclusion::xrgb32_cblit_xrgb32_span); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_prgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_xrgb32_line); FOG_RASTER_INIT(vblit_line[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_rgb24_line); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_PRGB32], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_prgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_XRGB32], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_xrgb32_span); FOG_RASTER_INIT(vblit_span[RASTER_VBLIT_XRGB32_AND_RGB24 ], RasterOps_SSE2::CompositeExclusion::xrgb32_vblit_rgb24_span); } */ // -------------------------------------------------------------------------- // [RasterOps - Pattern - Solid] // -------------------------------------------------------------------------- /* { RasterSolidFuncs& solid = api.solid; solid.fetch[IMAGE_FORMAT_PRGB32] = RasterOps_SSE2::Helpers::p_solid_fetch_prgb32_xrgb32; solid.fetch[IMAGE_FORMAT_XRGB32] = RasterOps_SSE2::Helpers::p_solid_fetch_prgb32_xrgb32; solid.fetch[IMAGE_FORMAT_A8 ] = RasterOps_SSE2::Helpers::p_solid_fetch_a8; solid.fetch[IMAGE_FORMAT_PRGB64] = RasterOps_SSE2::Helpers::p_solid_fetch_prgb64; solid.fetch[IMAGE_FORMAT_RGB48 ] = RasterOps_SSE2::Helpers::p_solid_fetch_rgb48; solid.fetch[IMAGE_FORMAT_A16 ] = RasterOps_SSE2::Helpers::p_solid_fetch_a16; } */ // -------------------------------------------------------------------------- // [RasterOps - Pattern - Gradient - API] // -------------------------------------------------------------------------- RasterGradientFuncs& gradient = api.gradient; // -------------------------------------------------------------------------- // [RasterOps - Pattern - Gradient - Interpolate] // -------------------------------------------------------------------------- gradient.interpolate[IMAGE_FORMAT_PRGB32] = RasterOps_SSE2::PGradientBase::interpolate_prgb32; gradient.interpolate[IMAGE_FORMAT_XRGB32] = RasterOps_SSE2::PGradientBase::interpolate_prgb32; } } // Fog namespace
67.104381
136
0.723167
[ "solid" ]
01ca43de49f900db17e5af6aa4fdc812b72cd33d
494
cpp
C++
Cplus/SquaresofaSortedArray.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/SquaresofaSortedArray.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/SquaresofaSortedArray.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> using namespace std; class Solution { public: vector<int> sortedSquares(vector<int> &A) { int N = A.size(); vector<int> res(N); int i = lower_bound(A.begin(), A.end(), 0) - A.begin(), j = i - 1; //merge for (int k = 0; i < N || j >= 0; ++k) { if (i == N) res[k] = A[j] * A[j--]; else if (j == -1) res[k] = A[i] * A[i++]; else res[k] = (A[i] * A[i] > A[j] * A[j]) ? A[j] * A[j--] : A[i] * A[i++]; } return res; } };
19.76
73
0.47166
[ "vector" ]