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
e8cb15e39feaa838f92184222cc2e1ee28b3de1b
4,059
hpp
C++
include/aikido/control/Executor.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
null
null
null
include/aikido/control/Executor.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
null
null
null
include/aikido/control/Executor.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
null
null
null
#ifndef AIKIDO_CONTROL_EXECUTOR_HPP_ #define AIKIDO_CONTROL_EXECUTOR_HPP_ #include <chrono> #include <set> #include <vector> #include <dart/dart.hpp> #include "aikido/common/ExecutorThread.hpp" #include "aikido/common/pointers.hpp" namespace aikido { namespace control { AIKIDO_DECLARE_POINTERS(Executor) /// Type of executor /// Can be used to determine if 2 executors make conflicting /// demands of individual degrees of freedom (Dofs) /// Can also be used to gracefully dynamic_cast /// Roughly analogous to default ROS control types: /// https://wiki.ros.org/ros_control /// The following updates the state of the DoF directly: /// STATE /// The following do not necessarily update the DoF's state directly, /// but may require locking external resources: /// POSITION - commands position to dofs /// VELOCITY - commands velocity to dofs /// EFFORT - commands effort (i.e. torque) to dofs /// TRAJECTORY - commands a trajectory to dofs /// MODE - commands a hardware command mode (e.g. position/velocity/effort) /// The following doesn't update the DoF directly: /// READONLY enum class ExecutorType { STATE = 0, POSITION = 1, VELOCITY = 2, EFFORT = 3, TRAJECTORY = 4, MODE = 5, READONLY = 6 }; /// Default rate for ExecutorThread to call step() constexpr std::chrono::milliseconds defaultThreadRate{10}; /// Abstract class for executing commands on degrees of freedom class Executor { public: /// Constructor. /// \param[in] types Set of controller types /// \param[in] dofs Vector of degree-of-freedom names this Executor acts upon /// \param[in] threadRate (Optional) How often to call step() Executor( const std::set<ExecutorType>& types, const std::vector<dart::dynamics::DegreeOfFreedom*>& dofs, const std::chrono::milliseconds threadRate = defaultThreadRate); /// Constructor. /// \param[in] type Single type to be added to this class's set of types /// \param[in] dofs Vector of degree-of-freedom names this Executor acts upon /// \param[in] threadRate (Optional) How often to call step() Executor( const ExecutorType type, const std::vector<dart::dynamics::DegreeOfFreedom*>& dofs, std::chrono::milliseconds threadRate = defaultThreadRate); virtual ~Executor(); /// Get all of this Executor's ExecutorTypes std::set<ExecutorType> getTypes() const; /// Get list of dofs needed by this Executor std::vector<dart::dynamics::DegreeOfFreedom*> getDofs() const; /// Step to a point in time. /// \note \c timepoint can be a time in the future to enable faster than /// real-time execution. /// /// \param timepoint Time to simulate to virtual void step( const std::chrono::system_clock::time_point& /* timepoint */) { // Do nothing } /// Start the underlying ExecutorThread void start(); /// Stops the underlying ExecutorThread void stop(); /// Lock the resources required by the DoFs /// /// \return True if locked successfully, false otherwise. bool registerDofs(); /// Unlock any resources required by the DoFs void releaseDofs(); private: /// Call to spin first to pass current time to step /// Necessary for real-time execution via mThread. void spin() { if (mThread->isRunning()) { step(std::chrono::system_clock::now()); } } /// How often to run spin() on internal thread std::chrono::milliseconds mThreadRate; /// Whether this executor has a lock on its DoF resources bool mDofsRegistered{false}; /// Manager for locking resources for degrees of freedom static std:: unordered_map<ExecutorType, std::set<dart::dynamics::DegreeOfFreedom*>> mDofManager; /// Mutex to protects the DofManager static std::mutex mMutex; /// Executor thread calling step function std::unique_ptr<aikido::common::ExecutorThread> mThread; protected: /// Vector of executor types std::set<ExecutorType> mTypes; /// Vector of dof names std::vector<dart::dynamics::DegreeOfFreedom*> mDofs; }; } // namespace control } // namespace aikido #endif
28.1875
79
0.705346
[ "vector" ]
e8dac6d858b496c7ca0f96d94fc284905f8ecf03
260
cpp
C++
LeetCode/Array/88_merge_sorted_array.cpp
Shaownak/Data-Structures
5077333755f27effcc7e454a446192294bc84a59
[ "MIT" ]
null
null
null
LeetCode/Array/88_merge_sorted_array.cpp
Shaownak/Data-Structures
5077333755f27effcc7e454a446192294bc84a59
[ "MIT" ]
null
null
null
LeetCode/Array/88_merge_sorted_array.cpp
Shaownak/Data-Structures
5077333755f27effcc7e454a446192294bc84a59
[ "MIT" ]
null
null
null
class Solution { public: void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { int j = 0; for(int i=m; i<m+n; i++){ nums1[i] = nums2[j]; j++; } sort(nums1.begin(), nums1.end()); } };
21.666667
70
0.446154
[ "vector" ]
e8e01a15a26f39f2a728933333c19f7d985ed9cb
457
cpp
C++
leetcode/852.peak-index-in-a-mountain-array.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
177
2017-08-21T08:57:43.000Z
2020-06-22T03:44:22.000Z
leetcode/852.peak-index-in-a-mountain-array.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
2
2018-09-06T13:39:12.000Z
2019-06-03T02:54:45.000Z
leetcode/852.peak-index-in-a-mountain-array.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
23
2017-08-23T06:01:28.000Z
2020-04-20T03:17:36.000Z
class Solution { public: int peakIndexInMountainArray(vector<int>& A) { int start = 0; int end = A.size() - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] > A[mid + 1]) { end = mid; } else { start = mid; } } return A[start] > A[end] ? start : end; } };
19.869565
50
0.358862
[ "vector" ]
e8e752e629a86560ba7a24639cbaa5c1a676f008
4,788
cpp
C++
src_code/AdvancedQt/censusvisualizer/censusvisualizer.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/censusvisualizer/censusvisualizer.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/censusvisualizer/censusvisualizer.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is provided for educational purposes and 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. */ #include "censusvisualizer.hpp" #include "censusvisualizerheader.hpp" #include "censusvisualizerview.hpp" #include <QAbstractItemModel> #include <QLocale> #include <QPainter> #include <QScrollArea> #include <QScrollBar> #include <QVBoxLayout> CensusVisualizer::CensusVisualizer(QWidget *parent) : QWidget(parent), m_model(0), m_selectedRow(Invalid), m_selectedColumn(Invalid), m_maximumPopulation(Invalid) { QFontMetrics fm(font()); m_widthOfYearColumn = fm.width("W9999W"); m_widthOfTotalColumn = fm.width("W9,999,999W"); view = new CensusVisualizerView(this); header = new CensusVisualizerHeader(this); m_scrollArea = new QScrollArea; m_scrollArea->setBackgroundRole(QPalette::Light); m_scrollArea->setWidget(view); m_scrollArea->installEventFilter(view); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(header); layout->addWidget(m_scrollArea); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); setLayout(layout); connect(view, SIGNAL(clicked(const QModelIndex&)), this, SIGNAL(clicked(const QModelIndex&))); } void CensusVisualizer::setModel(QAbstractItemModel *model) { if (model) { QLocale locale; for (int row = 0; row < model->rowCount(); ++row) { int total = locale.toInt(model->data( model->index(row, Total)).toString()); if (total > m_maximumPopulation) m_maximumPopulation = total; } QString population = QString::number(m_maximumPopulation); population = QString("%1%2") .arg(population.left(1).toInt() + 1) .arg(QString(population.length() - 1, QChar('0'))); m_maximumPopulation = population.toInt(); QFontMetrics fm(font()); m_widthOfTotalColumn = fm.width(QString("W%1%2W") .arg(population) .arg(QString(population.length() / 3, ','))); } m_model = model; header->update(); view->update(); } int CensusVisualizer::widthOfMaleFemaleColumn() const { return width() - (m_widthOfYearColumn + m_widthOfTotalColumn + ExtraWidth + m_scrollArea->verticalScrollBar()->sizeHint().width()); } void CensusVisualizer::setSelectedRow(int row) { m_selectedRow = row; view->update(); } void CensusVisualizer::setSelectedColumn(int column) { m_selectedColumn = column; header->update(); } void CensusVisualizer::setCurrentIndex(const QModelIndex &index) { setSelectedRow(index.row()); setSelectedColumn(index.column()); int x = xOffsetForMiddleOfColumn(index.column()); int y = yOffsetForRow(index.row()); m_scrollArea->ensureVisible(x, y, 10, 20); } int CensusVisualizer::xOffsetForMiddleOfColumn(int column) const { switch (column) { case Year: return widthOfYearColumn() / 2; case Males: return widthOfYearColumn() + (widthOfMaleFemaleColumn() / 4); case Females: return widthOfYearColumn() + ((widthOfMaleFemaleColumn() * 4) / 3); default: return widthOfYearColumn() + widthOfMaleFemaleColumn() + (widthOfTotalColumn() / 2); } } int CensusVisualizer::yOffsetForRow(int row) const { return static_cast<int>((QFontMetricsF(font()).height() + ExtraHeight) * row); } void CensusVisualizer::paintItemBorder(QPainter *painter, const QPalette &palette, const QRect &rect) { painter->setPen(QPen(palette.button().color().darker(), 0.33)); painter->drawLine(rect.bottomLeft(), rect.bottomRight()); painter->drawLine(rect.bottomRight(), rect.topRight()); } int CensusVisualizer::maleFemaleHeaderTextWidth() const { return QFontMetrics(font()).width(maleFemaleHeaderText()); } QString CensusVisualizer::maleFemaleHeaderText() const { if (!m_model) return " - "; return QString("%1 - %2") .arg(m_model->headerData(Males, Qt::Horizontal).toString()) .arg(m_model->headerData(Females, Qt::Horizontal) .toString()); }
31.294118
72
0.654971
[ "model" ]
e8f5ae7e7359d023ffb994a4a21b0a5169af6cbb
2,632
cpp
C++
src/Application/Application.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
src/Application/Application.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
src/Application/Application.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
#include "Application.hpp" Application::Application() { } Application::~Application() { } void Application::run() { Config m_appConfig = ConfigLoader::loadConfigFile("../res/Config.json"); glfwInit(); ImageLoadingScheduler m_imageLoadingScheduler = ImageLoadingScheduler(m_appConfig); Window m_appWindow = Window(m_appConfig,std::make_shared<ImageLoadingScheduler>(m_imageLoadingScheduler)); /* GraphicsAPI m_graphicsAPI = APIUtil::getAPIByCascade(); if (m_graphicsAPI == GraphicsAPI::GRAPHICS_API_OPENGL) { glfwMakeContextCurrent(m_appWindow.getWindow()); ErrorHandler::handleOpenGLErrorCode(glewInit()); Version m_version = OpenGLUtil::getOpenGLVersion(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, m_version.getMajorVersion()); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, m_version.getMinorVersion()); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); static const std::vector<GLfloat> m_vertexBufferData = { 1.0f,1.0f,0.0f, 1.0f,-1.0f,0.0f, -1.0f,-1.0f,0.0f }; VAO m_buffer = VAO(std::make_tuple(m_vertexBufferData, 3)); std::chrono::high_resolution_clock::time_point t; do { t = std::chrono::high_resolution_clock::now(); glClear(GL_COLOR_BUFFER_BIT); //m_buffer.bind(); //glBindVertexArray(m_buffer.getVAOID()); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, m_buffer.getVAOID()); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_TRIANGLES, 0, 3); //glBindVertexArray(0); glDisableVertexAttribArray(0); glfwSwapBuffers(m_appWindow.getWindow()); glfwPollEvents(); double frametime = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t).count()); std::cout << "FPS: " << 1000 / frametime << std::endl; } while (!glfwWindowShouldClose(m_appWindow.getWindow())); m_buffer.unbind(); m_buffer.deleteVAO(); } else if (m_graphicsAPI == GraphicsAPI::GRAPHICS_API_VULKAN) { glfwWindowHint(GLFW_NO_API, GLFW_TRUE); Instance m_instance = Instance(m_appConfig); while (!glfwWindowShouldClose(m_appWindow.getWindow())) { glfwPollEvents(); } m_instance.destroy(); } */ /*GLuint m_vertexBuffer; glGenBuffers(1, &m_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(m_vertexBufferData), m_vertexBufferData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);*/ //m_buffer.bind(); glfwTerminate(); }
34.631579
152
0.74962
[ "vector" ]
e8fa83bbaf7b227a46f59f666cd50cabeefec95c
4,811
cpp
C++
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GKeyPair.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
2
2019-12-28T21:24:36.000Z
2020-04-18T03:52:05.000Z
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GKeyPair.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GKeyPair.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2006, Mike Gashler This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. see http://www.gnu.org/copyleft/lesser.html */ #include <stdio.h> #include "GKeyPair.h" #include "GBigInt.h" #include "GError.h" #include "GRand.h" #include "GDom.h" #include <time.h> namespace GClasses { GKeyPair::GKeyPair() { m_pPrivateKey = NULL; m_pPublicKey = NULL; m_pN = NULL; } GKeyPair::GKeyPair(GDomNode* pNode) { m_pN = new GBigInt(pNode->field("n")); m_pPublicKey = new GBigInt(pNode->field("public")); GDomNode* pPrivate = pNode->fieldIfExists("private"); if(pPrivate) m_pPrivateKey = new GBigInt(pPrivate); else m_pPrivateKey = NULL; } GKeyPair::~GKeyPair() { if(m_pPrivateKey) m_pPrivateKey->setToZero(); if(m_pPublicKey) m_pPublicKey->setToZero(); if(m_pN) m_pN->setToZero(); delete(m_pPrivateKey); delete(m_pPublicKey); delete(m_pN); } void GKeyPair::setPublicKey(GBigInt* pPublicKey) { delete(m_pPublicKey); m_pPublicKey = pPublicKey; } void GKeyPair::setPrivateKey(GBigInt* pPrivateKey) { delete(m_pPrivateKey); m_pPrivateKey = pPrivateKey; } void GKeyPair::setN(GBigInt* pN) { delete(m_pN); m_pN = pN; } void GKeyPair::copyPublicKey(GBigInt* pPublicKey) { delete(m_pPublicKey); m_pPublicKey = new GBigInt(); m_pPublicKey->copy(pPublicKey); } void GKeyPair::copyPrivateKey(GBigInt* pPrivateKey) { delete(m_pPrivateKey); m_pPrivateKey = new GBigInt(); m_pPrivateKey->copy(pPrivateKey); } void GKeyPair::copyN(GBigInt* pN) { delete(m_pN); m_pN = new GBigInt(); m_pN->copy(pN); } GBigInt* GKeyPair::publicKey() { return m_pPublicKey; } GBigInt* GKeyPair::privateKey() { return m_pPrivateKey; } GBigInt* GKeyPair::n() { return m_pN; } void GKeyPair::generateKeyPair(unsigned int uintCount, const unsigned int* pRawCryptographicBytes1, const unsigned int* pRawCryptographicBytes2, const unsigned int* pRawCryptographicBytes3) { // Make places to put the data GBigInt* pOutPublicKey = new GBigInt(); GBigInt* pOutPrivateKey = new GBigInt(); GBigInt* pOutN = new GBigInt(); // Find two primes GBigInt p; GBigInt q; int n; for(n = (int)uintCount - 1; n >= 0; n--) p.setUInt(n, pRawCryptographicBytes1[n]); for(n = uintCount - 1; n >= 0; n--) q.setUInt(n, pRawCryptographicBytes2[n]); p.setBit(0, true); q.setBit(0, true); int nTries = 0; while(!p.isPrime()) { p.increment(); p.increment(); nTries++; } nTries = 0; while(!q.isPrime()) { q.increment(); q.increment(); nTries++; } // Calculate N (the product of the two primes) pOutN->multiply(&p, &q); // Calculate prod ((p - 1) * (q - 1)) p.decrement(); q.decrement(); GBigInt prod; prod.multiply(&p, &q); // Calculate public and private keys pOutPublicKey->selectPublicKey(pRawCryptographicBytes3, uintCount, &prod); pOutPrivateKey->calculatePrivateKey(pOutPublicKey, &prod); // Fill in "this" GKeyPair object setPublicKey(pOutPublicKey); setPrivateKey(pOutPrivateKey); setN(pOutN); } GDomNode* GKeyPair::serialize(GDom* pDoc, bool bIncludePrivateKey) { GDomNode* pNode = pDoc->newObj(); if(!n() || !publicKey()) ThrowError("No key has been made yet"); if(bIncludePrivateKey && !privateKey()) ThrowError("This key-pair doesn't include the private key"); pNode->addField(pDoc, "n", n()->serialize(pDoc)); pNode->addField(pDoc, "public", publicKey()->serialize(pDoc)); if(bIncludePrivateKey) pNode->addField(pDoc, "private", privateKey()->serialize(pDoc)); return pNode; } int GKeyPair::maxBlockSize() { return (m_pN->getBitCount() - 1) / 8; } unsigned char* GKeyPair::powerMod(const unsigned char* pInput, int nInputSize, bool bPublicKey, int* pnOutputSize) { GBigInt input; input.fromByteBuffer(pInput, nInputSize); GBigInt results; results.powerMod(&input, bPublicKey ? publicKey() : privateKey(), n()); *pnOutputSize = results.getUIntCount() * sizeof(unsigned int); unsigned char* pOutput = (unsigned char*)results.toBufferGiveOwnership(); while(pOutput[(*pnOutputSize) - 1] == 0) (*pnOutputSize)--; return pOutput; } #ifndef NO_TEST_CODE /*static*/ void GKeyPair::test() { GRand prng(0); unsigned int buf[6]; for(int i = 0; i < 6; i++) buf[i] = (unsigned int)prng.next(); GKeyPair kp; kp.generateKeyPair(2, buf, buf + 2, buf + 4); // Make up a message GBigInt message; message.setUInt(0, 0x6a54); // Encrypt it GBigInt cypher; cypher.powerMod(&message, kp.privateKey(), kp.n()); // Decrypt it GBigInt final; final.powerMod(&cypher, kp.publicKey(), kp.n()); // Check the final value if(final.compareTo(&message) != 0) ThrowError("failed"); } #endif // !NO_TEST_CODE } // namespace GClasses
21.968037
189
0.704843
[ "object" ]
3306caf4f48df9308bb3e19d90492f595b998944
2,982
cpp
C++
effective-modern-cpp/src/1-template-type-deduction/deduct.cpp
ahxxm/cpp-exercise
abbe530770d49843ceaf706fb55b91ef100b1162
[ "WTFPL" ]
2
2016-12-06T00:49:35.000Z
2017-01-15T07:00:24.000Z
effective-modern-cpp/src/1-template-type-deduction/deduct.cpp
ahxxm/cpp-exercise
abbe530770d49843ceaf706fb55b91ef100b1162
[ "WTFPL" ]
5
2016-05-02T13:52:52.000Z
2016-09-28T07:57:09.000Z
effective-modern-cpp/src/1-template-type-deduction/deduct.cpp
ahxxm/cpp-exercise
abbe530770d49843ceaf706fb55b91ef100b1162
[ "WTFPL" ]
null
null
null
#include <array> #include <iostream> #include "gtest/gtest.h" // Case 1: pointer/reference ParamType // reasonable deduction template<typename T> void f1(T& param) { std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << &param << std::endl; }; template<typename T> void f11(const T &param) { std::cout << &param << std::endl; }; template<typename T> void f12(T *param) { std::cout << &param << std::endl; }; void case1() { int x = 27; const int cx = x; // const int const int &rx = x; // const ref to x const int *px = &x; // const pointer to non-const x // T param f1(x); // int , int& f1(cx); // const int, const int& f1(rx); // const int, const int& f11(x); // int, const int& f11(cx); // int, const int& f11(rx); // int, const int& f12(&x); // int *, int * f12(px); // const int, const int * }; // Case 2: universal ref && // - lvalue: T and paramType are &, collapse // - rvalue: normal rules template<typename T> void f2(T &&param) { // debug info, consistent with comments below std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << &param << std::endl; }; void case2() { int x = 27; const int cx = x; // const int const int &rx = x; // const ref to x // T paramType f2(x); // int &, int & f2(cx); // const int&, const int& f2(rx); // const int&, const int& f2(27); // int, int && }; // Case 3: neither pointer nor ref // pass by value, copy construct.. template<typename T> void f3(T param) { std::cout << &param << std::endl; } void case3() { int x = 27; const int cx = x; // const int const int &rx = x; // const ref to x // T paramType f3(x); // int, int f3(cx); // int, int f3(rx); // int, int }; void const_ptr_to_const() { const char* const ptr = "kk"; // here ptr copied into param, a pointer that points to const char, // but can be changed to point to other object f3(ptr); } // Decay // array decay into pointer // function also decay into function pointer void some_func(int, double) {}; void decay() { const char name[] = "J.P."; // const char *ptr = name; // name is char[], ptr is char*. // T is char* ... ! f3(name); // void (*)(int, double); f3(some_func); // T& prevents decay, this enables to get array size. // in this case T is char const[5](includes ending char) f1(name); // T: void (&)(int, double) // f1(some_func); // copy needs instantiation }; template<typename T, std::size_t N> constexpr std::size_t arraySize(T (&)[N]) noexcept { return N; }; TEST(TemplateDeductionTest, SomeTest) { case1(); case2(); case3(); const_ptr_to_const(); decay(); // modern cpp array int keyVals[] = {1, 2, 3, 4, 5, 6}; std::array<int, arraySize(keyVals)> vals; EXPECT_EQ(static_cast<int>(vals.size()), 6); } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
20.708333
69
0.589537
[ "object" ]
3307cefdbae031b9ea8dc976fd4bc49149bc209f
490
cpp
C++
examples/geography/geoplot/geoplot_2.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-02T14:02:26.000Z
2020-10-28T07:00:44.000Z
examples/geography/geoplot/geoplot_2.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
null
null
null
examples/geography/geoplot/geoplot_2.cpp
kurogane1031/matplotplusplus
44d21156edba8effe1e764a8642b0b70590d597b
[ "MIT" ]
2
2020-09-01T16:22:07.000Z
2020-09-02T14:02:27.000Z
#include <cmath> #include <matplot/matplot.h> int main() { using namespace matplot; double lat_seattle = 47.62; double lon_seattle = -122.33; double lat_anchorage = 61.20; double lon_anchorage = -149.9; geoplot(std::vector{lat_seattle,lat_anchorage}, std::vector{lon_seattle,lon_anchorage},"g-*"); geolimits({45,62}, {-155,-120}); text(lon_anchorage, lat_anchorage, "Anchorage"); text(lon_seattle, lat_seattle, "Seattle"); wait(); return 0; }
25.789474
98
0.667347
[ "vector" ]
330c5d397f7cdba1dad91a5a2a30d32f458c0eea
6,630
cpp
C++
hackerrank.com/fraud-prevention.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
hackerrank.com/fraud-prevention.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
hackerrank.com/fraud-prevention.cpp
bolatov/contests
39654ec36e1b7ff62052e324428141a9564fd576
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <map> #include <set> #include <vector> #include <iostream> #include <algorithm> #include <sstream> #include <cassert> using namespace std; string trim(string s) { string t = ""; int end = (int)s.size() - 1; for (; end >= 0; end--) { if (s[end] != ' ') break; } bool ok = 0; for (int i = 0; i <= end; i++) { if (s[i] != ' ') ok = 1; if (ok) t += s[i]; } return t; } string toLower(string s) { s = trim(s); string t = ""; for (char ch : s) { if ('A' <= ch && ch <= 'Z') { ch = (char)(ch - ('Z' - 'z')); } t.append(1, ch); } return t; } string getEmail(string s) { // printf("getEmail: %s\n", s.c_str()); s = toLower(s); int at = (int)s.find('@'); // printf("\t@ is at %d position\n", at); string pref = s.substr(0, at); // printf("\tprefix=%s\n", pref.c_str()); string buf = ""; for (char ch : pref) { if (ch == '.') continue; if (ch == '+') break; buf += ch; } string r = buf + s.substr(at); // printf("\treturn %s\n", r.c_str()); return r; } string getStreet(string s) { s = toLower(s); vector<pair<string, string>> vps = {{"street", "st."}, {"road", "rd."}}; for (auto p : vps) { size_t i = s.find(p.first); if (i != string::npos) { s.replace(i, p.first.size(), p.second); } } return s; } string getState(string s) { s = toLower(s); vector<pair<string, string>> vps = { {"illinois", "il"}, {"california", "ca"}, {"new york", "ny"}}; for (auto p : vps) { size_t i = s.find(p.first); if (i != string::npos) { s.replace(i, p.first.size(), p.second); } } return s; } string getZipCode(string s) { s = toLower(s); string buf = ""; for (char ch : s) { if (ch != '-') { buf += ch; } } return buf; } class Record { int orderId; int dealId; string email; string street; string city; string state; string zipCode; string creditCard; public: Record(vector<string>); void print(); string getKey1(); string getKey2(); int getOrderId(); string getCreditCard(); }; Record::Record(vector<string> vs) { // printf("Record::Record vs.size()=%lu\n", vs.size()); orderId = stoi(trim(vs[0])); dealId = stoi(trim(vs[1])); email = getEmail(vs[2]); street = getStreet(vs[3]); city = toLower(vs[4]); state = getState(vs[5]); zipCode = getZipCode(vs[6]); creditCard = trim(vs[7]); } void Record::print() { printf("oId: %d, dID: %d\n%s\n %s, %s\n %s %s\n %s \n", orderId, dealId, email.c_str(), street.c_str(), city.c_str(), state.c_str(), zipCode.c_str(), creditCard.c_str()); printf("============================\n"); } string Record::getKey1() { return email + to_string(dealId); } string Record::getKey2() { return street + ";" + city + ";" + state + ";" + zipCode + ";" + to_string(dealId); } int Record::getOrderId() { return orderId; } string Record::getCreditCard() { return creditCard; } vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); // turn the string into stream string tok; while (getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } vector<int> getFraudOrders(map<string, vector<Record>> m) { vector<int> v; for (map<string, vector<Record>>::iterator it = m.begin(); it != m.end(); ++it) { vector<Record> vi = it->second; bool ok = 0; for (Record r : vi) { if (r.getCreditCard() != vi[0].getCreditCard()) { ok = 1; } } if (ok) { for (Record r : vi) { v.push_back(r.getOrderId()); } } } return v; } vector<int> removeDuplicates(vector<int> v) { vector<int> r; for (int i = 0; i < (int)v.size(); ++i) { if (r.empty() || (v[i] != r[r.size() - 1])) { r.push_back(v[i]); } } return r; } void mainTest() { assert(getEmail("bugs@bunny.com") == getEmail("BuGS@BuNNy.COM")); assert(getStreet("123 Sesame St.") == getStreet("123 SeSAME st.")); assert(getEmail("bugs1@bunny.com") == getEmail("bugs.1@bunny.com")); assert(getEmail("bugs@bunny.com") == getEmail("bugs+10@bunny.com")); assert(getStreet("123 Sesame St.") == getStreet("123 Sesame Street")); assert(getState("IL") == getState("Illinois")); assert(getStreet("Road") == getStreet("Rd.")); assert(getState("California") == getState("CA")); assert(getState("New York") == getState("NY")); assert(getZipCode("12345689010") == getZipCode("123-45-689010")); } int main() { freopen("input.txt", "r", stdin); int n; cin >> n; string line; vector<Record> recs; getchar(); map<string, vector<Record>> m1, m2; for (int i = 0; i < n; ++i) { getline(cin, line); if (line.size() < 5) { i--; continue; } vector<string> vs = split(line, ','); // test // for (string s : vs) { // printf("\t%s\n", s.c_str()); // } // printf("=============================\n"); // end test Record r(vs); recs.push_back(r); // for_each(vs.begin(), vs.end(), // [](string s) { printf("'%s'; ", s.c_str()); }); // printf("\n"); // email + dealId string k1 = r.getKey1(); if (m1.find(k1) == m1.end()) { vector<Record> vi; m1[k1] = vi; } m1[k1].push_back(r); // Address/City/State/Zip + dealId string k2 = r.getKey2(); if (m2.find(k2) == m2.end()) { vector<Record> vi; m2[k2] = vi; } m2[k2].push_back(r); } // // for (Record r : recs) { // // r.print(); // // } vector<int> ans1 = getFraudOrders(m1); vector<int> ans2 = getFraudOrders(m2); vector<int> ans; ans.insert(ans.end(), ans1.begin(), ans1.end()); ans.insert(ans.end(), ans2.begin(), ans2.end()); sort(ans.begin(), ans.end()); ans = removeDuplicates(ans); for (int i = 0; i < (int)ans.size(); ++i) { printf("%d", ans[i]); if (i != (int)ans.size() - 1) { printf(","); } } printf("\n"); return 0; }
24.924812
77
0.486576
[ "vector" ]
330cae1434be59db366367ef4e351562499f7ab6
702
cpp
C++
sim_algorithm/binary_search.cpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
sim_algorithm/binary_search.cpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
sim_algorithm/binary_search.cpp
pachicobue/CacheObliviousAlgorithms
db6e5f19c708d83208206091ae44cd6d7c71c4e0
[ "Unlicense" ]
null
null
null
#include <algorithm> #include "binary_search.hpp" #include "simulator/simulator.hpp" binary_search::binary_search(std::vector<data_t> vs) { std::sort(vs.begin(), vs.end()); vs.push_back(Max + 1); for (const auto v : vs) { m_datas.push_back(disk_var<data_t>{v}); } } data_t binary_search::lower_bound(const data_t x) const { int inf = -1, sup = static_cast<int>(m_datas.size()); while (sup - inf > 1) { const std::size_t mid = static_cast<std::size_t>(inf + sup) / 2; const data_t v = sim::read<data_t>(m_datas[mid]); if (v == x) { return v; } (v < x ? inf : sup) = static_cast<int>(mid); } return sim::read<data_t>(m_datas[sup]); }
29.25
72
0.609687
[ "vector" ]
330ff7620f7c1194d1758a205897a17400d750f5
482
cpp
C++
Scripts/174_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
Scripts/174_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
Scripts/174_std.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int m = dungeon.size(), n = dungeon[0].size(); vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX)); dp[m][n - 1] = 1; dp[m - 1][n] = 1; for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]); } } return dp[0][0]; } };
34.428571
83
0.421162
[ "vector" ]
3310fbbfece2e1715fa04228f347315c89299bf4
7,102
cpp
C++
mpc/kmpc_casadi/casadi_windows/include/casadi/core/transpose.cpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
29
2020-05-11T16:59:10.000Z
2022-02-24T11:30:16.000Z
mpc/kmpc_casadi/casadi_windows/include/casadi/core/transpose.cpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
1
2021-02-04T04:20:55.000Z
2021-02-28T20:47:02.000Z
mpc/kmpc_casadi/casadi_windows/include/casadi/core/transpose.cpp
se-hwan/MIT_Driverless
7674b29887ba518c134cfba805432f9c98f92270
[ "MIT" ]
10
2020-06-22T22:41:32.000Z
2021-12-15T12:26:13.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * CasADi 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "transpose.hpp" #include "serializing_stream.hpp" using namespace std; namespace casadi { Transpose::Transpose(const MX& x) { set_dep(x); set_sparsity(x.sparsity().T()); } void Transpose::serialize_type(SerializingStream& s) const { MXNode::serialize_type(s); s.pack("Transpose::dense", false); } void DenseTranspose::serialize_type(SerializingStream& s) const { MXNode::serialize_type(s); // NOLINT s.pack("Transpose::dense", true); } MXNode* Transpose::deserialize(DeserializingStream& s) { bool t; s.unpack("Transpose::dense", t); if (t) { return new DenseTranspose(s); } else { return new Transpose(s); } } int Transpose::eval(const double** arg, double** res, casadi_int* iw, double* w) const { return eval_gen<double>(arg, res, iw, w); } int DenseTranspose::eval(const double** arg, double** res, casadi_int* iw, double* w) const { return eval_gen<double>(arg, res, iw, w); } int Transpose:: eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w) const { return eval_gen<SXElem>(arg, res, iw, w); } int DenseTranspose:: eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w) const { return eval_gen<SXElem>(arg, res, iw, w); } template<typename T> int Transpose::eval_gen(const T* const* arg, T* const* res, casadi_int* iw, T* w) const { // Get sparsity patterns //const vector<casadi_int>& x_colind = input[0]->colind(); const casadi_int* x_row = dep(0).row(); casadi_int x_sz = dep(0).nnz(); const casadi_int* xT_colind = sparsity().colind(); casadi_int xT_ncol = sparsity().size2(); const T* x = arg[0]; T* xT = res[0]; // Transpose copy(xT_colind, xT_colind+xT_ncol+1, iw); for (casadi_int el=0; el<x_sz; ++el) { xT[iw[x_row[el]]++] = x[el]; } return 0; } template<typename T> int DenseTranspose::eval_gen(const T* const* arg, T* const* res, casadi_int* iw, T* w) const { // Get sparsity patterns casadi_int x_nrow = dep().size1(); casadi_int x_ncol = dep().size2(); const T* x = arg[0]; T* xT = res[0]; for (casadi_int i=0; i<x_ncol; ++i) { for (casadi_int j=0; j<x_nrow; ++j) { xT[i+j*x_ncol] = x[j+i*x_nrow]; } } return 0; } int Transpose:: sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const { // Shortands const bvec_t *x = arg[0]; bvec_t *xT = res[0]; // Get sparsity casadi_int nz = nnz(); const casadi_int* x_row = dep().row(); const casadi_int* xT_colind = sparsity().colind(); casadi_int xT_ncol = sparsity().size2(); // Loop over the nonzeros of the argument copy(xT_colind, xT_colind+xT_ncol+1, iw); for (casadi_int el=0; el<nz; ++el) { xT[iw[*x_row++]++] = *x++; } return 0; } int Transpose:: sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const { // Shortands bvec_t *x = arg[0]; bvec_t *xT = res[0]; // Get sparsity casadi_int nz = nnz(); const casadi_int* x_row = dep().row(); const casadi_int* xT_colind = sparsity().colind(); casadi_int xT_ncol = sparsity().size2(); // Loop over the nonzeros of the argument copy(xT_colind, xT_colind+xT_ncol+1, iw); for (casadi_int el=0; el<nz; ++el) { casadi_int elT = iw[*x_row++]++; *x++ |= xT[elT]; xT[elT] = 0; } return 0; } int DenseTranspose:: sp_forward(const bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const { // Shorthands const bvec_t *x = arg[0]; bvec_t *xT = res[0]; casadi_int x_nrow = dep().size1(); casadi_int x_ncol = dep().size2(); // Loop over the elements for (casadi_int rr=0; rr<x_nrow; ++rr) { for (casadi_int cc=0; cc<x_ncol; ++cc) { *xT++ = x[rr+cc*x_nrow]; } } return 0; } int DenseTranspose:: sp_reverse(bvec_t** arg, bvec_t** res, casadi_int* iw, bvec_t* w) const { // Shorthands bvec_t *x = arg[0]; bvec_t *xT = res[0]; casadi_int x_nrow = dep().size1(); casadi_int x_ncol = dep().size2(); // Loop over the elements for (casadi_int rr=0; rr<x_nrow; ++rr) { for (casadi_int cc=0; cc<x_ncol; ++cc) { x[rr+cc*x_nrow] |= *xT; *xT++ = 0; } } return 0; } std::string Transpose::disp(const std::vector<std::string>& arg) const { return arg.at(0) + "'"; } void Transpose::eval_mx(const std::vector<MX>& arg, std::vector<MX>& res) const { res[0] = arg[0].T(); } void Transpose::ad_forward(const std::vector<std::vector<MX> >& fseed, std::vector<std::vector<MX> >& fsens) const { for (casadi_int d=0; d<fsens.size(); ++d) { fsens[d][0] = fseed[d][0].T(); } } void Transpose::ad_reverse(const std::vector<std::vector<MX> >& aseed, std::vector<std::vector<MX> >& asens) const { for (casadi_int d=0; d<aseed.size(); ++d) { asens[d][0] += aseed[d][0].T(); } } void Transpose::generate(CodeGenerator& g, const std::vector<casadi_int>& arg, const std::vector<casadi_int>& res) const { g << g.trans(g.work(arg[0], nnz()), dep().sparsity(), g.work(res[0], nnz()), sparsity(), "iw") << ";\n"; } void DenseTranspose::generate(CodeGenerator& g, const std::vector<casadi_int>& arg, const std::vector<casadi_int>& res) const { g.local("cs", "const casadi_real", "*"); g.local("rr", "casadi_real", "*"); g.local("i", "casadi_int"); g.local("j", "casadi_int"); g << "for (i=0, rr=" << g.work(res[0], nnz()) << ", " << "cs=" << g.work(arg[0], nnz()) << "; i<" << dep().size2() << "; ++i) " << "for (j=0; j<" << dep().size1() << "; ++j) " << "rr[i+j*" << dep().size2() << "] = *cs++;\n"; } } // namespace casadi
30.350427
95
0.579696
[ "vector" ]
331c2ace31fe6b85319350dd6eef435768c299dd
3,874
cpp
C++
src/App.cpp
tgcy210/cyclus
b9402710be94403d33aa5a9b9aa546cdcca1cb86
[ "Unlicense" ]
1
2018-07-29T16:10:02.000Z
2018-07-29T16:10:02.000Z
src/App.cpp
tgcy210/cyclus
b9402710be94403d33aa5a9b9aa546cdcca1cb86
[ "Unlicense" ]
null
null
null
src/App.cpp
tgcy210/cyclus
b9402710be94403d33aa5a9b9aa546cdcca1cb86
[ "Unlicense" ]
null
null
null
#include <iostream> #include <cstdlib> #include <cstring> #include <string> #include "boost/program_options.hpp" #include "boost/shared_ptr.hpp" #include "Model.h" #include "BookKeeper.h" #include "Timer.h" #include "InputXML.h" #include "CycException.h" #include "Env.h" #include "Logger.h" using namespace std; namespace po = boost::program_options; //----------------------------------------------------------------------- // Main entry point for the test application... //----------------------------------------------------------------------- int main(int argc, char* argv[]) { // verbosity help msg std::string vmessage = "output log verbosity. Can be text:\n\n"; vmessage += " LEV_ERROR (least verbose, default), LEV_WARN, \n LEV_INFO1 (through 5), and LEV_DEBUG1 (through 5).\n\n"; vmessage += "Or an integer:\n\n 0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv)\n"; // parse command line options po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("no-model", "only print log entries from cyclus core code") ("no-mem", "exclude memory log statement from logger output") ("verb,v", po::value<string>(), vmessage.c_str()) ("output-path,o", po::value<string>(), "output path") ("input-file", po::value<string>(), "input file") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); po::positional_options_description p; p.add("input-file", 1); //po::variables_map vm; po::store(po::command_line_parser(argc, argv). options(desc).positional(p).run(), vm); po::notify(vm); // announce yourself cout << endl; cout << "|--------------------------------------------|" << endl; cout << "| Cyclus |" << endl; cout << "| a nuclear fuel cycle simulator |" << endl; cout << "| from the University of Wisconsin-Madison |" << endl; cout << "|--------------------------------------------|" << endl; cout << endl; // respond to command line args if (vm.count("help")) { string err_msg = "Cyclus usage requires an input file.\n"; err_msg += "Usage: cyclus [path/to/input/filename]\n"; cout << err_msg << endl; cout << desc << "\n"; return 0; } if (vm.count("no-model")) { Logger::NoModel() = true; } if (vm.count("no-mem")) { Logger::NoMem() = true; } if (! vm.count("input-file")) { string err_msg = "Cyclus usage requires an input file.\n"; err_msg += "Usage: cyclus [path/to/input/filename]\n"; cout << err_msg << endl; cout << desc << "\n"; return 0; } if (vm.count("verb")) { std::string v_level = vm["verb"].as<string>(); if (v_level.length() < 3) { Logger::ReportLevel() = (LogLevel)strtol(v_level.c_str(), NULL, 10); } else { Logger::ReportLevel() = Logger::ToLogLevel(v_level); } } // tell ENV the path between the cwd and the cyclus executable string path = Env::pathBase(argv[0]); Env::setCyclusRelPath(path); // Create the output file try { if (vm.count("output-path")){ BI->createDB(vm["output-path"].as<string>()); } else { BI->createDB(); } } catch (CycException ge) { CLOG(LEV_ERROR) << ge.what(); } // read input file and setup simulation try { XMLinput->load_file(vm["input-file"].as<string>()); } catch (CycIOException ge) { CLOG(LEV_ERROR) << ge.what(); return 0; } catch (CycException e) { CLOG(LEV_ERROR) << e.what(); } // print the model list Model::printModelList(); // Run the simulation try { TI->runSim(); } catch (CycException err) { CLOG(LEV_ERROR) << err.what(); } // Close the output file try { BI->closeDB(); } catch (CycException ge) { CLOG(LEV_ERROR) << ge.what(); } return 0; }
28.072464
125
0.569437
[ "model" ]
33264675695a4afdc52210acafa9645bc4001c22
47,628
cpp
C++
sumo/src/netedit/GNELane.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netedit/GNELane.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netedit/GNELane.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file GNELane.cpp /// @author Jakob Erdmann /// @date Feb 2011 /// @version $Id$ /// // A class for visualizing Lane geometry (adapted from GNELaneWrapper) /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <string> #include <iostream> #include <utility> #include <foreign/polyfonts/polyfonts.h> #include <utils/foxtools/MFXUtils.h> #include <utils/geom/PositionVector.h> #include <utils/common/RandHelper.h> #include <utils/common/SUMOVehicleClass.h> #include <utils/common/ToString.h> #include <utils/geom/GeomHelper.h> #include <utils/geom/GeomConvHelper.h> #include <utils/gui/windows/GUISUMOAbstractView.h> #include <utils/gui/windows/GUIAppEnum.h> #include <utils/gui/images/GUIIconSubSys.h> #include <utils/gui/div/GUIParameterTableWindow.h> #include <utils/gui/globjects/GUIGLObjectPopupMenu.h> #include <utils/gui/div/GUIGlobalSelection.h> #include <utils/gui/div/GLHelper.h> #include <utils/gui/windows/GUIAppEnum.h> #include <utils/gui/images/GUITexturesHelper.h> #include <utils/gui/images/GUITextureSubSys.h> #include "GNELane.h" #include "GNEEdge.h" #include "GNEJunction.h" #include "GNETLSEditorFrame.h" #include "GNEInternalLane.h" #include "GNEUndoList.h" #include "GNENet.h" #include "GNEChange_Attribute.h" #include "GNEViewNet.h" #include "GNEViewParent.h" #include "GNEConnection.h" // =========================================================================== // FOX callback mapping // =========================================================================== // Object implementation FXIMPLEMENT(GNELane, FXDelegator, 0, 0) // =========================================================================== // method definitions // =========================================================================== GNELane::GNELane(GNEEdge& edge, const int index) : GNENetElement(edge.getNet(), edge.getNBEdge()->getLaneID(index), GLO_LANE, SUMO_TAG_LANE, ICON_LANE), myParentEdge(edge), myIndex(index), mySpecialColor(0), myTLSEditor(0) { } GNELane::GNELane() : GNENetElement(NULL, "dummyConstructorGNELane", GLO_LANE, SUMO_TAG_LANE, ICON_LOCATEEDGE), myParentEdge(*static_cast<GNEEdge*>(0)), myIndex(-1), mySpecialColor(0), myTLSEditor(0) { } GNELane::~GNELane() { } void GNELane::drawLinkNo(const GUIVisualizationSettings& s) const { const std::vector<NBEdge::Connection>& cons = myParentEdge.getNBEdge()->getConnectionsFromLane(myIndex); int noLinks = (int)cons.size(); if (noLinks == 0) { return; } // draw all links glPushMatrix(); glTranslated(0, 0, GLO_LANE + 0.1); double w = myParentEdge.getNBEdge()->getLaneWidth(myIndex) / (double) noLinks; double x1 = myParentEdge.getNBEdge()->getLaneWidth(myIndex) / 2; const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); for (int i = noLinks; --i >= 0;) { double x2 = x1 - (double)(w / 2.); const int linkIndex = myParentEdge.getNBEdge()->getToNode()->getConnectionIndex(myParentEdge.getNBEdge(), cons[lefthand ? noLinks - 1 - i : i]); GLHelper::drawTextAtEnd(toString(linkIndex), getShape(), x2, s.drawLinkJunctionIndex.size, s.drawLinkJunctionIndex.color); x1 -= w; } glPopMatrix(); } void GNELane::drawTLSLinkNo(const GUIVisualizationSettings& s) const { const std::vector<NBEdge::Connection>& cons = myParentEdge.getNBEdge()->getConnectionsFromLane(myIndex); int noLinks = (int)cons.size(); if (noLinks == 0) { return; } // draw all links glPushMatrix(); glTranslated(0, 0, GLO_LANE + 0.1); double w = myParentEdge.getNBEdge()->getLaneWidth(myIndex) / (double) noLinks; double x1 = myParentEdge.getNBEdge()->getLaneWidth(myIndex) / 2; const bool lefthand = OptionsCont::getOptions().getBool("lefthand"); for (int i = noLinks; --i >= 0;) { double x2 = x1 - (double)(w / 2.); int linkNo = cons[lefthand ? noLinks - 1 - i : i].tlLinkNo; GLHelper::drawTextAtEnd(toString(linkNo), getShape(), x2, s.drawLinkTLIndex.size, s.drawLinkTLIndex.color); x1 -= w; } glPopMatrix(); } void GNELane::drawLinkRules() const { } void GNELane::drawArrows() const { const Position& end = getShape().back(); const Position& f = getShape()[-2]; double rot = (double) atan2((end.x() - f.x()), (f.y() - end.y())) * (double) 180.0 / (double)M_PI; glPushMatrix(); glPushName(0); glTranslated(0, 0, GLO_JUNCTION + .1); // must draw on top of junction shape glColor3d(1, 1, 1); glTranslated(end.x(), end.y(), 0); glRotated(rot, 0, 0, 1); // draw all links const std::vector<NBEdge::Connection>& edgeCons = myParentEdge.getNBEdge()->myConnections; NBNode* dest = myParentEdge.getNBEdge()->myTo; for (std::vector<NBEdge::Connection>::const_iterator i = edgeCons.begin(); i != edgeCons.end(); ++i) { if ((*i).fromLane == myIndex) { LinkDirection dir = dest->getDirection(myParentEdge.getNBEdge(), i->toEdge, OptionsCont::getOptions().getBool("lefthand")); switch (dir) { case LINKDIR_STRAIGHT: GLHelper::drawBoxLine(Position(0, 4), 0, 2, .05); GLHelper::drawTriangleAtEnd(Position(0, 4), Position(0, 1), (double) 1, (double) .25); break; case LINKDIR_LEFT: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), 90, 1, .05); GLHelper::drawTriangleAtEnd(Position(0, 2.5), Position(1.5, 2.5), (double) 1, (double) .25); break; case LINKDIR_RIGHT: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), -90, 1, .05); GLHelper::drawTriangleAtEnd(Position(0, 2.5), Position(-1.5, 2.5), (double) 1, (double) .25); break; case LINKDIR_TURN: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), 90, .5, .05); GLHelper::drawBoxLine(Position(0.5, 2.5), 180, 1, .05); GLHelper::drawTriangleAtEnd(Position(0.5, 2.5), Position(0.5, 4), (double) 1, (double) .25); break; case LINKDIR_TURN_LEFTHAND: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), -90, 1, .05); GLHelper::drawBoxLine(Position(-0.5, 2.5), -180, 1, .05); GLHelper::drawTriangleAtEnd(Position(-0.5, 2.5), Position(-0.5, 4), (double) 1, (double) .25); break; case LINKDIR_PARTLEFT: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), 45, .7, .05); GLHelper::drawTriangleAtEnd(Position(0, 2.5), Position(1.2, 1.3), (double) 1, (double) .25); break; case LINKDIR_PARTRIGHT: GLHelper::drawBoxLine(Position(0, 4), 0, 1.5, .05); GLHelper::drawBoxLine(Position(0, 2.5), -45, .7, .05); GLHelper::drawTriangleAtEnd(Position(0, 2.5), Position(-1.2, 1.3), (double) 1, (double) .25); break; case LINKDIR_NODIR: GLHelper::drawBoxLine(Position(1, 5.8), 245, 2, .05); GLHelper::drawBoxLine(Position(-1, 5.8), 115, 2, .05); glTranslated(0, 5, 0); GLHelper::drawOutlineCircle(0.9, 0.8, 32); glTranslated(0, -5, 0); break; } } } glPopName(); glPopMatrix(); } void GNELane::drawLane2LaneConnections() const { glPushMatrix(); glPushName(0); glTranslated(0, 0, GLO_JUNCTION + .1); // must draw on top of junction shape std::vector<NBEdge::Connection> connections = myParentEdge.getNBEdge()->getConnectionsFromLane(myIndex); NBNode* node = myParentEdge.getNBEdge()->getToNode(); const Position& startPos = getShape()[-1]; for (std::vector<NBEdge::Connection>::iterator it = connections.begin(); it != connections.end(); it++) { const LinkState state = node->getLinkState( myParentEdge.getNBEdge(), it->toEdge, it->fromLane, it->toLane, it->mayDefinitelyPass, it->tlID); switch (state) { case LINKSTATE_TL_OFF_NOSIGNAL: glColor3d(1, 1, 0); break; case LINKSTATE_TL_OFF_BLINKING: glColor3d(0, 1, 1); break; case LINKSTATE_MAJOR: glColor3d(1, 1, 1); break; case LINKSTATE_MINOR: glColor3d(.4, .4, .4); break; case LINKSTATE_STOP: glColor3d(.7, .4, .4); break; case LINKSTATE_EQUAL: glColor3d(.7, .7, .7); break; case LINKSTATE_ALLWAY_STOP: glColor3d(.7, .7, 1); case LINKSTATE_ZIPPER: glColor3d(.75, .5, 0.25); break; default: throw ProcessError("Unexpected LinkState '" + toString(state) + "'"); } const Position& endPos = it->toEdge->getLaneShape(it->toLane)[0]; glBegin(GL_LINES); glVertex2d(startPos.x(), startPos.y()); glVertex2d(endPos.x(), endPos.y()); glEnd(); GLHelper::drawTriangleAtEnd(startPos, endPos, (double) 1.5, (double) .2); } glPopName(); glPopMatrix(); } void GNELane::drawGL(const GUIVisualizationSettings& s) const { // Push draw matrix 1 glPushMatrix(); // Push name glPushName(getGlID()); // Traslate to fromt glTranslated(0, 0, getType()); // Check if edge parent or this lane is selected const bool selectedEdge = gSelected.isSelected(myParentEdge.getType(), myParentEdge.getGlID()); const bool selected = gSelected.isSelected(getType(), getGlID()); // Set color if (mySpecialColor != 0) { // If special color is enabled, set it GLHelper::setColor(*mySpecialColor); } else if (selected && s.laneColorer.getActive() != 1) { // override with special colors (unless the color scheme is based on selection) GLHelper::setColor(GNENet::selectedLaneColor); } else if (selectedEdge && s.laneColorer.getActive() != 1) { // override with special colors (unless the color scheme is based on selection) GLHelper::setColor(GNENet::selectionColor); } else { // Get normal lane color const GUIColorer& c = s.laneColorer; if (!setFunctionalColor(c.getActive()) && !setMultiColor(c)) { GLHelper::setColor(c.getScheme().getColor(getColorValue(c.getActive()))); } } // start drawing lane checking whether it is not too small const double selectionScale = selected || selectedEdge ? s.selectionScale : 1; double exaggeration = selectionScale * s.laneWidthExaggeration; // * s.laneScaler.getScheme().getColor(getScaleValue(s.laneScaler.getActive())); // XXX apply usefull scale values //exaggeration *= s.laneScaler.getScheme().getColor(getScaleValue(s.laneScaler.getActive())); // recognize full transparency and simply don't draw GLfloat color[4]; glGetFloatv(GL_CURRENT_COLOR, color); if (color[3] == 0 || s.scale * exaggeration < s.laneMinSize) { // Pop draw matrix 1 glPopMatrix(); } else if (s.scale * exaggeration < 1.) { // draw as lines, depending of myShapeColors if (myShapeColors.size() > 0) { GLHelper::drawLine(getShape(), myShapeColors); } else { GLHelper::drawLine(getShape()); } // Pop draw matrix 1 glPopMatrix(); } else { if (drawAsRailway(s)) { // draw as railway const double halfRailWidth = 0.725 * exaggeration; // Draw box depending of myShapeColors if (myShapeColors.size() > 0) { GLHelper::drawBoxLines(getShape(), myShapeRotations, myShapeLengths, myShapeColors, halfRailWidth); } else { GLHelper::drawBoxLines(getShape(), myShapeRotations, myShapeLengths, halfRailWidth); } // Save current color RGBColor current = GLHelper::getColor(); // Set white color glColor3d(1, 1, 1); // Traslate matrix 1 glTranslated(0, 0, .1); // Draw Box GLHelper::drawBoxLines(getShape(), myShapeRotations, myShapeLengths, halfRailWidth - 0.2); // Set current color back GLHelper::setColor(current); // Draw crossties drawCrossties(0.3 * exaggeration, 1 * exaggeration, 1 * exaggeration); } else { // Draw as a normal lane, and reduce width to make sure that a selected edge can still be seen const double halfWidth = exaggeration * (myParentEdge.getNBEdge()->getLaneWidth(myIndex) / 2 - (selectedEdge ? .3 : 0)); if (myShapeColors.size() > 0) { GLHelper::drawBoxLines(getShape(), myShapeRotations, myShapeLengths, myShapeColors, halfWidth); } else { GLHelper::drawBoxLines(getShape(), myShapeRotations, myShapeLengths, halfWidth); } } // Pop draw matrix 1 glPopMatrix(); // only draw details depending of the scale if (s.scale >= 10) { // if exaggeration is 1, draw drawMarkings if (s.laneShowBorders && exaggeration == 1) { drawMarkings(selectedEdge, exaggeration); } // draw ROWs only if target junction has a valid logic) if (s.showLinkDecals && myParentEdge.getGNEJunctionDestiny()->isLogicValid() && s.scale > 3) { drawArrows(); } // Draw direction indicators if the correspondient option is enabled if (s.showLaneDirection) { drawDirectionIndicators(); } if (s.drawLinkJunctionIndex.show) { drawLinkNo(s); } if (s.drawLinkTLIndex.show) { drawTLSLinkNo(s); } } // If there are texture of restricted lanes to draw, and draw lane icons is enabled in options if ((OptionsCont::getOptions().getBool("disable-laneIcons") == false) && (myLaneRestrictedTexturePositions.size() > 0) && (s.scale >= 10)) { // Declare default width of icon (3) double iconWidth = 1; // Obtain width of icon, if width of lane is different if (myParentEdge.getNBEdge()->getLaneStruct(myIndex).width != -1) { iconWidth = myParentEdge.getNBEdge()->getLaneStruct(myIndex).width / 3; } // Draw list of icons for (int i = 0; i < (int)myLaneRestrictedTexturePositions.size(); i++) { // Push draw matrix 2 glPushMatrix(); // Set white color glColor3d(1, 1, 1); // Traslate matrix 2 glTranslated(myLaneRestrictedTexturePositions.at(i).x(), myLaneRestrictedTexturePositions.at(i).y(), getType() + 0.1); // Rotate matrix 2 glRotated(myLaneRestrictedTextureRotations.at(i), 0, 0, -1); glRotated(-90, 0, 0, 1); // draw texture box depending of type of restriction if (isRestricted(SVC_PEDESTRIAN)) { GUITexturesHelper::drawTexturedBox(GUITextureSubSys::getTexture(GNETEXTURE_LANEPEDESTRIAN), iconWidth); } else if (isRestricted(SVC_BICYCLE)) { GUITexturesHelper::drawTexturedBox(GUITextureSubSys::getTexture(GNETEXTURE_LANEBIKE), iconWidth); } else if (isRestricted(SVC_BUS)) { GUITexturesHelper::drawTexturedBox(GUITextureSubSys::getTexture(GNETEXTURE_LANEBUS), iconWidth); } // Pop draw matrix 2 glPopMatrix(); } } } // Pop Name glPopName(); } void GNELane::drawMarkings(const bool& selectedEdge, double scale) const { glPushMatrix(); glTranslated(0, 0, GLO_EDGE); const double halfWidth = myParentEdge.getNBEdge()->getLaneWidth(myIndex) * 0.5; // optionally draw inverse markings if (myIndex > 0 && (myParentEdge.getNBEdge()->getPermissions(myIndex - 1) & myParentEdge.getNBEdge()->getPermissions(myIndex)) != 0) { double mw = (halfWidth + SUMO_const_laneOffset + .01) * scale; int e = (int) getShape().size() - 1; for (int i = 0; i < e; ++i) { glPushMatrix(); glTranslated(getShape()[i].x(), getShape()[i].y(), 0.1); glRotated(myShapeRotations[i], 0, 0, 1); for (double t = 0; t < myShapeLengths[i]; t += 6) { const double length = MIN2((double)3, myShapeLengths[i] - t); glBegin(GL_QUADS); glVertex2d(-mw, -t); glVertex2d(-mw, -t - length); glVertex2d(halfWidth * 0.5 * scale, -t - length); glVertex2d(halfWidth * 0.5 * scale, -t); glEnd(); } glPopMatrix(); } } // draw white boundings (and white markings) depending on selection if (selectedEdge) { glTranslated(0, 0, 0.2); // draw selection on top of regular markings GLHelper::setColor(GNENet::selectionColor); } else { glColor3d(1, 1, 1); } GLHelper::drawBoxLines( getShape(), getShapeRotations(), getShapeLengths(), (halfWidth + SUMO_const_laneOffset) * scale); glPopMatrix(); } GUIGLObjectPopupMenu* GNELane::getPopUpMenu(GUIMainWindow& app, GUISUMOAbstractView& parent) { GUIGLObjectPopupMenu* ret = new GUIGLObjectPopupMenu(app, parent, *this); buildPopupHeader(ret, app); buildCenterPopupEntry(ret); new FXMenuCommand(ret, ("Copy " + toString(SUMO_TAG_EDGE) + " name to clipboard").c_str(), 0, ret, MID_COPY_EDGE_NAME); buildNameCopyPopupEntry(ret); buildSelectionPopupEntry(ret); buildPositionCopyEntry(ret, false); const int editMode = parent.getVisualisationSettings()->editMode; myTLSEditor = 0; if (editMode != GNE_MODE_CONNECT && editMode != GNE_MODE_TLS && editMode != GNE_MODE_CREATE_EDGE) { // Get icons FXIcon* pedestrianIcon = GUIIconSubSys::getIcon(ICON_LANEPEDESTRIAN); FXIcon* bikeIcon = GUIIconSubSys::getIcon(ICON_LANEBIKE); FXIcon* busIcon = GUIIconSubSys::getIcon(ICON_LANEBUS); // Create basic commands new FXMenuCommand(ret, ("Split " + toString(SUMO_TAG_EDGE) + " here").c_str(), 0, &parent, MID_GNE_EDGE_SPLIT); new FXMenuCommand(ret, ("Split " + toString(SUMO_TAG_EDGE) + "s in both direction here").c_str(), 0, &parent, MID_GNE_EDGE_SPLIT_BIDI); new FXMenuCommand(ret, ("Reverse " + toString(SUMO_TAG_EDGE)).c_str(), 0, &parent, MID_GNE_EDGE_REVERSE); new FXMenuCommand(ret, "Add reverse direction", 0, &parent, MID_GNE_EDGE_ADD_REVERSE); new FXMenuCommand(ret, "Set geometry endpoint here", 0, &parent, MID_GNE_EDGE_SET_ENDPOINT); new FXMenuCommand(ret, "Restore geometry endpoint", 0, &parent, MID_GNE_EDGE_RESET_ENDPOINT); if (gSelected.isSelected(GLO_LANE, getGlID())) { new FXMenuCommand(ret, ("Straighten selected " + toString(SUMO_TAG_EDGE) + "s").c_str(), 0, &parent, MID_GNE_EDGE_STRAIGHTEN); } else { new FXMenuCommand(ret, ("Straighten " + toString(SUMO_TAG_EDGE)).c_str(), 0, &parent, MID_GNE_EDGE_STRAIGHTEN); } if (gSelected.isSelected(GLO_LANE, getGlID())) { new FXMenuCommand(ret, ("Duplicate selected" + toString(SUMO_TAG_LANE) + "s").c_str(), 0, &parent, MID_GNE_LANE_DUPLICATE); // Create panel for lane operations FXMenuPane* addSpecialLanes = new FXMenuPane(ret); ret->insertMenuPaneChild(addSpecialLanes); FXMenuPane* removeSpecialLanes = new FXMenuPane(ret); ret->insertMenuPaneChild(removeSpecialLanes); FXMenuPane* transformSlanes = new FXMenuPane(ret); ret->insertMenuPaneChild(transformSlanes); // Create menu comands for all add special lanes new FXMenuCommand(addSpecialLanes, "Sidewalks", pedestrianIcon, &parent, MID_GNE_LANE_ADD_SIDEWALK); new FXMenuCommand(addSpecialLanes, "Bikelanes", bikeIcon, &parent, MID_GNE_LANE_ADD_BIKE); new FXMenuCommand(addSpecialLanes, "Buslanes", busIcon, &parent, MID_GNE_LANE_ADD_BUS); // Create menu comands for all remove special lanes and disable it new FXMenuCommand(removeSpecialLanes, "Sidewalks", pedestrianIcon, &parent, MID_GNE_LANE_REMOVE_SIDEWALK); new FXMenuCommand(removeSpecialLanes, "Bikelanes", bikeIcon, &parent, MID_GNE_LANE_REMOVE_BIKE); new FXMenuCommand(removeSpecialLanes, "Buslanes", busIcon, &parent, MID_GNE_LANE_REMOVE_BUS); // Create menu comands for all trasform special lanes and disable it new FXMenuCommand(transformSlanes, "Sidewalks", pedestrianIcon, &parent, MID_GNE_LANE_TRANSFORM_SIDEWALK); new FXMenuCommand(transformSlanes, "Bikelanes", bikeIcon, &parent, MID_GNE_LANE_TRANSFORM_BIKE); new FXMenuCommand(transformSlanes, "Buslanes", busIcon, &parent, MID_GNE_LANE_TRANSFORM_BUS); new FXMenuCommand(transformSlanes, "revert transformations", 0, &parent, MID_GNE_LANE_REVERT_TRANSFORMATION); // add menuCascade for lane operations new FXMenuCascade(ret, ("add special" + toString(SUMO_TAG_LANE) + "s").c_str(), 0, addSpecialLanes); new FXMenuCascade(ret, ("remove special" + toString(SUMO_TAG_LANE) + "s").c_str(), 0, removeSpecialLanes); new FXMenuCascade(ret, ("transform to special" + toString(SUMO_TAG_LANE) + "s").c_str(), 0, transformSlanes); } else { new FXMenuCommand(ret, ("Duplicate" + toString(SUMO_TAG_LANE)).c_str(), 0, &parent, MID_GNE_LANE_DUPLICATE); // Declare flags bool edgeHasSidewalk = myParentEdge.hasRestrictedLane(SVC_PEDESTRIAN); bool edgeHasBikelane = myParentEdge.hasRestrictedLane(SVC_BICYCLE); bool edgeHasBuslane = myParentEdge.hasRestrictedLane(SVC_BUS); // Create panel for lane operations and insert it in ret FXMenuPane* addSpecialLanes = new FXMenuPane(ret); ret->insertMenuPaneChild(addSpecialLanes); FXMenuPane* removeSpecialLanes = new FXMenuPane(ret); ret->insertMenuPaneChild(removeSpecialLanes); FXMenuPane* transformSlanes = new FXMenuPane(ret); ret->insertMenuPaneChild(transformSlanes); // Create menu comands for all add special lanes FXMenuCommand* addSidewalk = new FXMenuCommand(addSpecialLanes, "Sidewalk", pedestrianIcon, &parent, MID_GNE_LANE_ADD_SIDEWALK); FXMenuCommand* addBikelane = new FXMenuCommand(addSpecialLanes, "Bikelane", bikeIcon, &parent, MID_GNE_LANE_ADD_BIKE); FXMenuCommand* addBuslane = new FXMenuCommand(addSpecialLanes, "Buslane", busIcon, &parent, MID_GNE_LANE_ADD_BUS); // Create menu comands for all remove special lanes and disable it FXMenuCommand* removeSidewalk = new FXMenuCommand(removeSpecialLanes, "Sidewalk", pedestrianIcon, &parent, MID_GNE_LANE_REMOVE_SIDEWALK); removeSidewalk->disable(); FXMenuCommand* removeBikelane = new FXMenuCommand(removeSpecialLanes, "Bikelane", bikeIcon, &parent, MID_GNE_LANE_REMOVE_BIKE); removeBikelane->disable(); FXMenuCommand* removeBuslane = new FXMenuCommand(removeSpecialLanes, "Buslane", busIcon, &parent, MID_GNE_LANE_REMOVE_BUS); removeBuslane->disable(); // Create menu comands for all trasform special lanes and disable it FXMenuCommand* transformLaneToSidewalk = new FXMenuCommand(transformSlanes, "Sidewalk", pedestrianIcon, &parent, MID_GNE_LANE_TRANSFORM_SIDEWALK); FXMenuCommand* transformLaneToBikelane = new FXMenuCommand(transformSlanes, "Bikelane", bikeIcon, &parent, MID_GNE_LANE_TRANSFORM_BIKE); FXMenuCommand* transformLaneToBuslane = new FXMenuCommand(transformSlanes, "Buslane", busIcon, &parent, MID_GNE_LANE_TRANSFORM_BUS); FXMenuCommand* revertTransformation = new FXMenuCommand(transformSlanes, "revert transformation", 0, &parent, MID_GNE_LANE_REVERT_TRANSFORMATION); // add menuCascade for lane operations FXMenuCascade* cascadeAddSpecialLane = new FXMenuCascade(ret, ("add special" + toString(SUMO_TAG_LANE)).c_str(), 0, addSpecialLanes); FXMenuCascade* cascadeRemoveSpecialLane = new FXMenuCascade(ret, ("remove special" + toString(SUMO_TAG_LANE)).c_str(), 0, removeSpecialLanes); new FXMenuCascade(ret, ("transform to special" + toString(SUMO_TAG_LANE)).c_str(), 0, transformSlanes); // Enable and disable options depending of current transform of the lane if (edgeHasSidewalk) { transformLaneToSidewalk->disable(); addSidewalk->disable(); removeSidewalk->enable(); } if (edgeHasBikelane) { transformLaneToBikelane->disable(); addBikelane->disable(); removeBikelane->enable(); } if (edgeHasBuslane) { transformLaneToBuslane->disable(); addBuslane->disable(); removeBuslane->enable(); } // Check if cascade menus must be disabled if (edgeHasSidewalk && edgeHasBikelane && edgeHasBuslane) { cascadeAddSpecialLane->disable(); } if (!edgeHasSidewalk && !edgeHasBikelane && !edgeHasBuslane) { cascadeRemoveSpecialLane->disable(); } // Enable or disable revert transformation if (isRestricted(SVC_PEDESTRIAN) || isRestricted(SVC_BICYCLE) || isRestricted(SVC_BUS)) { revertTransformation->enable(); } else { revertTransformation->disable(); } } } else if (editMode == GNE_MODE_TLS) { myTLSEditor = static_cast<GNEViewNet&>(parent).getViewParent()->getTLSEditorFrame(); if (myTLSEditor->controlsEdge(myParentEdge)) { new FXMenuCommand(ret, "Select state for all links from this edge:", 0, 0, 0); const std::vector<std::string> names = GNEInternalLane::LinkStateNames.getStrings(); for (std::vector<std::string>::const_iterator it = names.begin(); it != names.end(); it++) { FXuint state = GNEInternalLane::LinkStateNames.get(*it); FXMenuRadio* mc = new FXMenuRadio(ret, (*it).c_str(), this, FXDataTarget::ID_OPTION + state); mc->setSelBackColor(MFXUtils::getFXColor(GNEInternalLane::colorForLinksState(state))); mc->setBackColor(MFXUtils::getFXColor(GNEInternalLane::colorForLinksState(state))); } } } else { FXMenuCommand* mc = new FXMenuCommand(ret, "Additional options available in 'Inspect Mode'", 0, 0, 0); mc->handle(&parent, FXSEL(SEL_COMMAND, FXWindow::ID_DISABLE), 0); } // buildShowParamsPopupEntry(ret, false); new FXMenuSeparator(ret); const double pos = getShape().nearest_offset_to_point2D(parent.getPositionInformation()); const double height = getShape().positionAtOffset2D(getShape().nearest_offset_to_point2D(parent.getPositionInformation())).z(); new FXMenuCommand(ret, ("Shape pos: " + toString(pos)).c_str(), 0, 0, 0); new FXMenuCommand(ret, ("Length pos: " + toString(pos * getLaneParametricLength() / getLaneShapeLength())).c_str(), 0, 0, 0); new FXMenuCommand(ret, ("Height: " + toString(height)).c_str(), 0, 0, 0); // new FXMenuSeparator(ret); // buildPositionCopyEntry(ret, false); // let the GNEViewNet store the popup position (dynamic_cast<GNEViewNet&>(parent)).markPopupPosition(); return ret; } GUIParameterTableWindow* GNELane::getParameterWindow(GUIMainWindow& app, GUISUMOAbstractView&) { GUIParameterTableWindow* ret = new GUIParameterTableWindow(app, *this, 2); // add items ret->mkItem("length [m]", false, myParentEdge.getNBEdge()->getLength()); // close building ret->closeBuilding(); return ret; } Boundary GNELane::getCenteringBoundary() const { Boundary b = getShape().getBoxBoundary(); b.grow(10); return b; } const PositionVector& GNELane::getShape() const { return myParentEdge.getNBEdge()->getLaneShape(myIndex); } const std::vector<double>& GNELane::getShapeRotations() const { return myShapeRotations; } const std::vector<double>& GNELane::getShapeLengths() const { return myShapeLengths; } Boundary GNELane::getBoundary() const { return myParentEdge.getNBEdge()->getLaneStruct(myIndex).shape.getBoxBoundary(); } void GNELane::updateGeometry() { // Clear containers myShapeRotations.clear(); myShapeLengths.clear(); myLaneRestrictedTexturePositions.clear(); myLaneRestrictedTextureRotations.clear(); //double length = myParentEdge.getLength(); // @todo see ticket #448 // may be different from length // Obtain lane and shape rotations int segments = (int) getShape().size() - 1; if (segments >= 0) { myShapeRotations.reserve(segments); myShapeLengths.reserve(segments); for (int i = 0; i < segments; ++i) { const Position& f = getShape()[i]; const Position& s = getShape()[i + 1]; myShapeLengths.push_back(f.distanceTo2D(s)); myShapeRotations.push_back((double) atan2((s.x() - f.x()), (f.y() - s.y())) * (double) 180.0 / (double)M_PI); } } // Update geometry of additionals vinculated with this lane for (AdditionalVector::iterator i = myAdditionals.begin(); i != myAdditionals.end(); i++) { (*i)->updateGeometry(); } // In Move mode, connections aren't updated if (myNet->getViewNet() && myNet->getViewNet()->getCurrentEditMode() != GNE_MODE_MOVE) { // Update incoming connections of this lane std::vector<GNEConnection*> incomingConnections = getGNEIncomingConnections(); for (std::vector<GNEConnection*>::iterator i = incomingConnections.begin(); i != incomingConnections.end(); i++) { (*i)->updateGeometry(); } // Update outgoings connections of this lane std::vector<GNEConnection*> outGoingConnections = getGNEOutcomingConnections(); for (std::vector<GNEConnection*>::iterator i = outGoingConnections.begin(); i != outGoingConnections.end(); i++) { (*i)->updateGeometry(); } } // If lane has enought length for show textures of restricted lanes if ((getLaneShapeLength() > 4)) { // if lane is restricted if (isRestricted(SVC_PEDESTRIAN) || isRestricted(SVC_BICYCLE) || isRestricted(SVC_BUS)) { // get values for position and rotation of icons for (int i = 2; i < getLaneShapeLength() - 1; i += 15) { myLaneRestrictedTexturePositions.push_back(getShape().positionAtOffset(i)); myLaneRestrictedTextureRotations.push_back(getShape().rotationDegreeAtOffset(i)); } } } } int GNELane::getIndex() const { return myIndex; } void GNELane::setIndex(int index) { myIndex = index; setMicrosimID(myParentEdge.getNBEdge()->getLaneID(index)); } double GNELane::getSpeed() const { return myParentEdge.getNBEdge()->getLaneSpeed(myIndex); } double GNELane::getLaneParametricLength() const { double laneParametricLenght = myParentEdge.getNBEdge()->getLoadedLength(); if (laneParametricLenght > 0) { return laneParametricLenght; } else { throw ProcessError("Lane Parametric Lenght cannot be never 0"); } } double GNELane::getLaneShapeLength() const { return getShape().length(); } void GNELane::addAdditionalChild(GNEAdditional* additional) { // Check if additional exist before remove if (std::find(myAdditionals.begin(), myAdditionals.end(), additional) == myAdditionals.end()) { myAdditionals.push_back(additional); } else { throw ProcessError(toString(getTag()) + " with ID='" + additional->getID() + "' was already inserted in lane with ID='" + getID() + "'"); } } void GNELane::removeAdditionalChild(GNEAdditional* additional) { AdditionalVector::iterator it = std::find(myAdditionals.begin(), myAdditionals.end(), additional); // Check if additional exist before remove if (it != myAdditionals.end()) { myAdditionals.erase(it); } else { throw ProcessError(toString(getTag()) + " with ID='" + additional->getID() + "' doesn't exist in lane with ID='" + getID() + "'"); } } const std::vector<GNEAdditional*>& GNELane::getAdditionalChilds() const { return myAdditionals; } bool GNELane::isRestricted(SUMOVehicleClass vclass) const { return myParentEdge.getNBEdge()->getPermissions(myIndex) == vclass; } std::string GNELane::getAttribute(SumoXMLAttr key) const { const NBEdge* edge = myParentEdge.getNBEdge(); switch (key) { case SUMO_ATTR_ID: return getMicrosimID(); case SUMO_ATTR_SPEED: return toString(edge->getLaneSpeed(myIndex)); case SUMO_ATTR_ALLOW: return getVehicleClassNames(edge->getPermissions(myIndex)); case SUMO_ATTR_DISALLOW: return getVehicleClassNames(invertPermissions(edge->getPermissions(myIndex))); case SUMO_ATTR_WIDTH: if (edge->getLaneStruct(myIndex).width == NBEdge::UNSPECIFIED_WIDTH) { return "default"; } else { return toString(edge->getLaneStruct(myIndex).width); } case SUMO_ATTR_ENDOFFSET: return toString(edge->getLaneStruct(myIndex).endOffset); case SUMO_ATTR_ACCELERATION: return toString(edge->getLaneStruct(myIndex).accelRamp); case SUMO_ATTR_CUSTOMSHAPE: return toString(edge->getLaneStruct(myIndex).customShape); case SUMO_ATTR_INDEX: return toString(myIndex); default: throw InvalidArgument(toString(getTag()) + " doesn't have an attribute of type '" + toString(key) + "'"); } } std::string GNELane::getAttributeForSelection(SumoXMLAttr key) const { std::string result = getAttribute(key); if ((key == SUMO_ATTR_ALLOW || key == SUMO_ATTR_DISALLOW) && result.find("all") != std::string::npos) { result += " " + getVehicleClassNames(SVCAll, true); } return result; } void GNELane::setAttribute(SumoXMLAttr key, const std::string& value, GNEUndoList* undoList) { switch (key) { case SUMO_ATTR_ID: throw InvalidArgument("Modifying attribute '" + toString(key) + "' of " + toString(getTag()) + " isn't allowed"); case SUMO_ATTR_SPEED: case SUMO_ATTR_ALLOW: case SUMO_ATTR_DISALLOW: case SUMO_ATTR_WIDTH: case SUMO_ATTR_ENDOFFSET: case SUMO_ATTR_ACCELERATION: case SUMO_ATTR_CUSTOMSHAPE: case SUMO_ATTR_INDEX: // no special handling undoList->p_add(new GNEChange_Attribute(this, key, value)); break; default: throw InvalidArgument(toString(getTag()) + " doesn't have an attribute of type '" + toString(key) + "'"); } } bool GNELane::isValid(SumoXMLAttr key, const std::string& value) { switch (key) { case SUMO_ATTR_ID: return false; case SUMO_ATTR_SPEED: return canParse<double>(value); case SUMO_ATTR_ALLOW: case SUMO_ATTR_DISALLOW: return canParseVehicleClasses(value); case SUMO_ATTR_WIDTH: if (value == "default") { return true; } else { return canParse<double>(value) && (isPositive<double>(value) || parse<double>(value) == NBEdge::UNSPECIFIED_WIDTH); } case SUMO_ATTR_ENDOFFSET: return canParse<double>(value); case SUMO_ATTR_ACCELERATION: return canParse<bool>(value); case SUMO_ATTR_CUSTOMSHAPE: { bool ok = true; PositionVector shape = GeomConvHelper::parseShapeReporting(value, "user-supplied position", 0, ok, true); return ok; } case SUMO_ATTR_INDEX: return canParse<int>(value) && (parse<int>(value) == myIndex); default: throw InvalidArgument(toString(getTag()) + " doesn't have an attribute of type '" + toString(key) + "'"); } } void GNELane::setSpecialColor(const RGBColor* color) { mySpecialColor = color; } // =========================================================================== // private // =========================================================================== void GNELane::setAttribute(SumoXMLAttr key, const std::string& value) { NBEdge* edge = myParentEdge.getNBEdge(); switch (key) { case SUMO_ATTR_ID: throw InvalidArgument("Modifying attribute '" + toString(key) + "' of " + toString(getTag()) + " isn't allowed"); case SUMO_ATTR_SPEED: edge->setSpeed(myIndex, parse<double>(value)); break; case SUMO_ATTR_ALLOW: edge->setPermissions(parseVehicleClasses(value), myIndex); updateGeometry(); myNet->getViewNet()->update(); break; case SUMO_ATTR_DISALLOW: edge->setPermissions(invertPermissions(parseVehicleClasses(value)), myIndex); updateGeometry(); myNet->getViewNet()->update(); break; case SUMO_ATTR_WIDTH: if (value == "default") { edge->setLaneWidth(myIndex, NBEdge::UNSPECIFIED_WIDTH); } else { edge->setLaneWidth(myIndex, parse<double>(value)); } updateGeometry(); myNet->getViewNet()->update(); break; case SUMO_ATTR_ENDOFFSET: edge->setEndOffset(myIndex, parse<double>(value)); break; case SUMO_ATTR_ACCELERATION: edge->setAcceleration(myIndex, parse<bool>(value)); break; case SUMO_ATTR_CUSTOMSHAPE: { bool ok; edge->setLaneShape(myIndex, GeomConvHelper::parseShapeReporting(value, "user-supplied position", 0, ok, true)); break; } default: throw InvalidArgument(toString(getTag()) + " doesn't have an attribute of type '" + toString(key) + "'"); } } bool GNELane::setFunctionalColor(int activeScheme) const { switch (activeScheme) { case 6: { double hue = GeomHelper::naviDegree(getShape().beginEndAngle()); // [0-360] GLHelper::setColor(RGBColor::fromHSV(hue, 1., 1.)); return true; } default: return false; } } bool GNELane::setMultiColor(const GUIColorer& c) const { const int activeScheme = c.getActive(); myShapeColors.clear(); switch (activeScheme) { case 9: // color by height at segment start for (PositionVector::const_iterator ii = getShape().begin(); ii != getShape().end() - 1; ++ii) { myShapeColors.push_back(c.getScheme().getColor(ii->z())); } return true; case 11: // color by inclination at segment start for (int ii = 1; ii < (int)getShape().size(); ++ii) { const double inc = (getShape()[ii].z() - getShape()[ii - 1].z()) / MAX2(POSITION_EPS, getShape()[ii].distanceTo2D(getShape()[ii - 1])); myShapeColors.push_back(c.getScheme().getColor(inc)); } return true; default: return false; } } double GNELane::getColorValue(int activeScheme) const { const SVCPermissions myPermissions = myParentEdge.getNBEdge()->getPermissions(myIndex); switch (activeScheme) { case 0: switch (myPermissions) { case SVC_PEDESTRIAN: return 1; case SVC_BICYCLE: return 2; case 0: return 3; case SVC_SHIP: return 4; default: break; } if ((myPermissions & SVC_PASSENGER) != 0 || isRailway(myPermissions)) { return 0; } else { return 5; } case 1: return gSelected.isSelected(getType(), getGlID()) || gSelected.isSelected(GLO_EDGE, dynamic_cast<GNEEdge*>(&myParentEdge)->getGlID()); case 2: return (double)myPermissions; case 3: return myParentEdge.getNBEdge()->getLaneSpeed(myIndex); case 4: return myParentEdge.getNBEdge()->getNumLanes(); case 5: { return myParentEdge.getNBEdge()->getLoadedLength() / myParentEdge.getNBEdge()->getLength(); } // case 6: by angle (functional) case 7: { return myParentEdge.getNBEdge()->getPriority(); } case 8: { // color by z of first shape point return getShape()[0].z(); } // case 9: by segment height case 10: { // color by incline return (getShape()[-1].z() - getShape()[0].z()) / myParentEdge.getNBEdge()->getLength(); } } return 0; } bool GNELane::drawAsRailway(const GUIVisualizationSettings& s) const { return isRailway(myParentEdge.getNBEdge()->getPermissions(myIndex)) && s.showRails; } bool GNELane::drawAsWaterway(const GUIVisualizationSettings& s) const { return isWaterway(myParentEdge.getNBEdge()->getPermissions(myIndex)) && s.showRails; // reusing the showRails setting } void GNELane::drawCrossties(double length, double spacing, double halfWidth) const { glPushMatrix(); // draw on top of of the white area between the rails glTranslated(0, 0, 0.1); int e = (int) getShape().size() - 1; for (int i = 0; i < e; ++i) { glPushMatrix(); glTranslated(getShape()[i].x(), getShape()[i].y(), 0.0); glRotated(myShapeRotations[i], 0, 0, 1); for (double t = 0; t < myShapeLengths[i]; t += spacing) { glBegin(GL_QUADS); glVertex2d(-halfWidth, -t); glVertex2d(-halfWidth, -t - length); glVertex2d(halfWidth, -t - length); glVertex2d(halfWidth, -t); glEnd(); } glPopMatrix(); } glPopMatrix(); } void GNELane::drawDirectionIndicators() const { const double width = myParentEdge.getNBEdge()->getLaneWidth(myIndex); glColor3d(0.3, 0.3, 0.3); glPushMatrix(); glTranslated(0, 0, GLO_JUNCTION + 0.1); int e = (int) getShape().size() - 1; for (int i = 0; i < e; ++i) { glPushMatrix(); glTranslated(getShape()[i].x(), getShape()[i].y(), 0.1); glRotated(myShapeRotations[i], 0, 0, 1); for (double t = 0; t < myShapeLengths[i]; t += width) { const double length = MIN2(width * 0.5, myShapeLengths[i] - t); glBegin(GL_TRIANGLES); glVertex2d(0, -t - length); glVertex2d(-width * 0.25, -t); glVertex2d(+width * 0.25, -t); glEnd(); } glPopMatrix(); } glPopMatrix(); } const std::string& GNELane::getParentName() const { return myParentEdge.getMicrosimID(); } long GNELane::onDefault(FXObject* obj, FXSelector sel, void* data) { if (myTLSEditor != 0) { myTLSEditor->handleMultiChange(this, obj, sel, data); } return 1; } GNEEdge& GNELane::getParentEdge() { return myParentEdge; } std::vector<GNEConnection*> GNELane::getGNEIncomingConnections() { // Declare a vector to save incoming connections std::vector<GNEConnection*> incomingConnections; // Obtain incoming edges if junction source was already created GNEJunction* junctionSource = myParentEdge.getGNEJunctionSource(); if (junctionSource) { // Iterate over incoming GNEEdges of junction for (std::vector<GNEEdge*>::const_iterator i = junctionSource->getGNEIncomingEdges().begin(); i != junctionSource->getGNEIncomingEdges().end(); i++) { // Iterate over connection of incoming edges for (std::vector<GNEConnection*>::const_iterator j = (*i)->getGNEConnections().begin(); j != (*i)->getGNEConnections().end(); j++) { if ((*j)->getNBEdgeConnection().fromLane == getIndex()) { incomingConnections.push_back(*j); } } } } return incomingConnections; } std::vector<GNEConnection*> GNELane::getGNEOutcomingConnections() { // Obtain GNEConnection of edge parent const std::vector<GNEConnection*>& edgeConnections = myParentEdge.getGNEConnections(); std::vector<GNEConnection*> outcomingConnections; // Obtain outgoing connections for (std::vector<GNEConnection*>::const_iterator i = edgeConnections.begin(); i != edgeConnections.end(); i++) { if ((*i)->getNBEdgeConnection().fromLane == getIndex()) { outcomingConnections.push_back(*i); } } return outcomingConnections; } void GNELane::updateConnectionIDs() { // update incoming connections of lane std::vector<GNEConnection*> incomingConnections = getGNEIncomingConnections(); for (std::vector<GNEConnection*>::iterator i = incomingConnections.begin(); i != incomingConnections.end(); i++) { (*i)->updateID(); } // update outocming connections of lane std::vector<GNEConnection*> outcomingConnections = getGNEOutcomingConnections(); for (std::vector<GNEConnection*>::iterator i = outcomingConnections.begin(); i != outcomingConnections.end(); i++) { (*i)->updateID(); } } /****************************************************************************/
41.742331
158
0.604098
[ "geometry", "object", "shape", "vector", "transform" ]
06bc743c1c61a9ae4f8d6ff3b96516ccf47324dd
3,694
cxx
C++
src/CalibXMLCnv/cnv/XmlAncQdcPedCnv.cxx
fermi-lat/CalibSvc
c262bbd5481a01af3f75a250fc1ba385bb5c775f
[ "BSD-3-Clause" ]
null
null
null
src/CalibXMLCnv/cnv/XmlAncQdcPedCnv.cxx
fermi-lat/CalibSvc
c262bbd5481a01af3f75a250fc1ba385bb5c775f
[ "BSD-3-Clause" ]
null
null
null
src/CalibXMLCnv/cnv/XmlAncQdcPedCnv.cxx
fermi-lat/CalibSvc
c262bbd5481a01af3f75a250fc1ba385bb5c775f
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/GlastRelease-scons/CalibSvc/src/CalibXMLCnv/cnv/XmlAncQdcPedCnv.cxx,v 1.1.618.1 2010/10/18 02:50:19 heather Exp $ #include <string> #include "GaudiKernel/CnvFactory.h" #include "GaudiKernel/IOpaqueAddress.h" #include "GaudiKernel/DataObject.h" #include "GaudiKernel/IAddressCreator.h" #include "GaudiKernel/IDataProviderSvc.h" #include "GaudiKernel/IConversionSvc.h" #include "GaudiKernel/MsgStream.h" #include "GaudiKernel/GenericAddress.h" #include "CalibSvc/ICalibXmlSvc.h" #include "CalibSvc/ICalibMetaCnvSvc.h" #include "CalibData/Anc/AncCalibQdcPed.h" #include "CalibData/CalibTime.h" #include "xmlBase/Dom.h" // Temporary. Hope to find a better way to do this #include "CalibData/CalibModel.h" /** @class XmlAncQdcPedCnv Converter from xml to TCDS ANC pedestals class @author J. Bogart */ #include "XmlAncBaseCnv.h" //class XmlAncQdcPedCnv; // template <class TYPE> class CnvFactory; //static CnvFactory<XmlAncQdcPedCnv> s_factory; //const ICnvFactory& XmlAncQdcPedCnvFactory = s_factory; //DECLARE_CONVERTER_FACTORY(XmlAncQdcPedCnv); class XmlAncQdcPedCnv : public XmlAncBaseCnv { /// Friend needed for instantiation friend class CnvFactory<XmlAncQdcPedCnv>; public: const CLID& objType() const; static const CLID& classID(); protected: XmlAncQdcPedCnv(ISvcLocator* svcs); virtual ~XmlAncQdcPedCnv() {} // most likely nothing to do virtual StatusCode i_createObj(const DOMElement* element, DataObject*& refpObject); }; DECLARE_CONVERTER_FACTORY(XmlAncQdcPedCnv); // XmlAncQdcPedCnv::XmlAncQdcPedCnv( ISvcLocator* svc) : XmlAncBaseCnv(svc, CLID_Calib_ANC_QdcPed) { } const CLID& XmlAncQdcPedCnv::objType() const { return CLID_Calib_ANC_QdcPed; } const CLID& XmlAncQdcPedCnv::classID() { return CLID_Calib_ANC_QdcPed; } namespace { /// Local utility which knows how to get the information out of a /// <qdcPed> element and make a CalibData::AncQdcPed with it CalibData::AncQdcPed* processChan(DOMElement* chanElt) { using xmlBase::Dom; // Element we're interested in is child of <chan> DOMElement* pedElt = xmlBase::Dom::getFirstChildElement(chanElt); // Could check here to make sure it really is an <ancPed> float val, rms; unsigned isBad; std::string dev; try { dev = xmlBase::Dom::getAttribute(chanElt, "device"); val = xmlBase::Dom::getDoubleAttribute(pedElt, "ped"); rms = xmlBase::Dom::getDoubleAttribute(pedElt, "pedRms"); isBad = xmlBase::Dom::getIntAttribute(pedElt, "isBad"); } catch (xmlBase::DomException ex) { std::cerr << "From CalibSvc::XmlAncQdcPedCnv::processChan" << std::endl; std::cerr << ex.getMsg() << std::endl; throw ex; } return new CalibData::AncQdcPed(val, rms, isBad, dev); } } // Create our specific object StatusCode XmlAncQdcPedCnv::i_createObj(const DOMElement* docElt, DataObject*& refpObject) { using xmlBase::Dom; using CalibData::AncQdcPed; unsigned nMod, nLay, nChan; // need dimensions to call the constructor StatusCode status = readAncDimension(docElt, nMod, nLay, nChan); if (status == StatusCode::FAILURE) return status; // refpObject CalibData::AncCalibQdcPed* pObj = new CalibData::AncCalibQdcPed(nMod, nChan); refpObject = pObj; if (!pObj) return StatusCode::FAILURE; setBaseInfo(pObj); DOMElement* chanElt = findFirstChan(docElt); while (chanElt != 0 ) { AncQdcPed* pPed = processChan(chanElt); pObj->putChan(m_iMod, m_iLay, m_iChan, pPed); chanElt = findNextChan(chanElt); } return StatusCode::SUCCESS; }
27.161765
154
0.710612
[ "object" ]
06c02245fcc8507c67dbb75ace5a14466a3a431b
3,148
hpp
C++
reflecxx/include/reflecxx/json_visitor.hpp
jimmyorourke/reflecxx
4be3ebb741ba540e447b5353c6abd057d2ee3d80
[ "MIT" ]
null
null
null
reflecxx/include/reflecxx/json_visitor.hpp
jimmyorourke/reflecxx
4be3ebb741ba540e447b5353c6abd057d2ee3d80
[ "MIT" ]
null
null
null
reflecxx/include/reflecxx/json_visitor.hpp
jimmyorourke/reflecxx
4be3ebb741ba540e447b5353c6abd057d2ee3d80
[ "MIT" ]
null
null
null
// Copyright (c) 2021-2022 Jimmy O'Rourke // Licensed under and subject to the terms of the LICENSE file accompanying this distribution. // Official repository: https://github.com/jimmyorourke/reflecxx #pragma once // The code below uses the generated visitor acceptors. To avoid problems if this header is included into headers that // get compiled by the generator, don't define it during generation. #ifndef REFLECXX_GENERATION #include <reflecxx/visit.hpp> // Note: This library does not link against/set include dirs for nlohmann json by default! #include <nlohmann/json.hpp> #include <string> // Automatically define to/from nlohmann JSON functions for any reflecxx visitable type. Wow! // Note that since this uses the adl_serializer, if specialization for any type is desired it must also be done by // specializing this adl_serializer struct rather than defining the to_json/from_json free functions (since ADL into the // argument namespace will no longer apply). namespace nlohmann { template <typename T> struct adl_serializer<T, std::enable_if_t<reflecxx::is_reflecxx_visitable_v<T>>> { static void to_json(json& j, const T& t) { reflecxx::ToJsonVisitor v{j}; reflecxx::visit(t, std::move(v)); } static void from_json(const json& j, T& t) { reflecxx::FromJsonVisitor v{j}; reflecxx::visit(t, std::move(v)); } }; } // namespace nlohmann namespace reflecxx { // Visitor functor for converting a named value (such as a class member) to JSON. // Requires that T is nlohmann::json serializable (possibly through the use of this visitor on T's fundamental type // members).. struct ToJsonVisitor { ToJsonVisitor(nlohmann::json& value) : jsonValue(value) {} template <typename T> void operator()(std::string_view name, const T& member) { // std::string required, https://github.com/nlohmann/json/issues/1529 jsonValue[std::string{name}] = member; } nlohmann::json& jsonValue; }; // Visitor functor for converting from JSON to a named object (such as a class member). struct FromJsonVisitor { FromJsonVisitor(const nlohmann::json& value) : jsonValue(value) {} template <typename T> void operator()(std::string_view name, T& member) const { // std::string required, https://github.com/nlohmann/json/issues/1529 fromJson(member, jsonValue.at(std::string{name})); } const nlohmann::json& jsonValue; private: template <typename T> void fromJson(T& value, const nlohmann::json& jsonObj) const { value = jsonObj.get<T>(); } // nlohmann::json.get() doesn't handle c-style arrays template <typename T, size_t N> void fromJson(T (&arr)[N], const nlohmann::json& jsonObj) const { if (jsonObj.size() != N) { throw std::runtime_error("JSON array size is different than expected"); } size_t index = 0; for (auto& item : jsonObj) { arr[index++] = item.get<T>(); } } }; } // namespace reflecxx #endif // REFLECXX_GENERATION
35.370787
121
0.671855
[ "object" ]
06c324d6ecb09dad26965308e028f2d9d5ea101d
1,196
cpp
C++
src/Cpp/10_Listy_dwie_listy/Zad3.cpp
djeada/Nauka-programowania
b1eb6840c15b830acf552f0a0fc5cc692759152f
[ "MIT" ]
3
2020-09-19T21:38:30.000Z
2022-03-30T11:02:26.000Z
src/Cpp/10_Listy_dwie_listy/Zad3.cpp
djeada/Nauka-programowania
b1eb6840c15b830acf552f0a0fc5cc692759152f
[ "MIT" ]
null
null
null
src/Cpp/10_Listy_dwie_listy/Zad3.cpp
djeada/Nauka-programowania
b1eb6840c15b830acf552f0a0fc5cc692759152f
[ "MIT" ]
1
2022-02-04T09:13:20.000Z
2022-02-04T09:13:20.000Z
#include <cassert> #include <vector> /* Dla otrzymanych dwoch list, zwroc liste, ktorej elementy sa suma odpowiadajacych sobie elementow otrzymanych list. Jesli listy nie sa rownej dlugosci, zaloz ze brakujace elementy krotszej listy sa rowne 0. */ std::vector<int> suma(std::vector<int> &listaA, std::vector<int> &listaB) { std::vector<int> wynik(listaA); unsigned int n = wynik.size() < listaB.size() ? wynik.size() : listaB.size(); for (unsigned int i = 0; i < n; i++) wynik[i] += listaB[i]; for (unsigned int i = n; i < listaB.size(); i++) wynik.push_back(listaB[i]); return wynik; } void test1() { std::vector<int> listaA{3, 1, 2, 5}; std::vector<int> listaB{2, 8, 6, 5}; std::vector<int> wynik{5, 9, 8, 10}; assert(suma(listaA, listaB) == wynik); } void test2() { std::vector<int> listaA{3, 1, 2, 5}; std::vector<int> listaB{2, 8}; std::vector<int> wynik{5, 9, 2, 5}; assert(suma(listaA, listaB) == wynik); } void test3() { std::vector<int> listaA{3, 1}; std::vector<int> listaB{2, 8, 6, 5}; std::vector<int> wynik{5, 9, 6, 4}; assert(suma(listaA, listaB) == wynik); } int main() { test1(); test2(); test3(); return 0; }
20.982456
81
0.622074
[ "vector" ]
06c863fc8e0a21b726f4a5a6b8208b2eae8a0253
467
cpp
C++
source/qml/Library/RendererQml/RenderedQmlAdaptiveCard.cpp
rohshar6/AdaptiveCards
13305e82f47ef24db4582599e01615e623f16d26
[ "MIT" ]
null
null
null
source/qml/Library/RendererQml/RenderedQmlAdaptiveCard.cpp
rohshar6/AdaptiveCards
13305e82f47ef24db4582599e01615e623f16d26
[ "MIT" ]
29
2021-02-16T15:51:01.000Z
2021-12-22T12:46:11.000Z
source/qml/Library/RendererQml/RenderedQmlAdaptiveCard.cpp
rohshar6/AdaptiveCards
13305e82f47ef24db4582599e01615e623f16d26
[ "MIT" ]
16
2021-02-10T07:46:07.000Z
2021-11-23T10:22:44.000Z
#include "pch.h" #include "RenderedQmlAdaptiveCard.h" namespace RendererQml { RenderedQmlAdaptiveCard::RenderedQmlAdaptiveCard(std::shared_ptr<QmlTag> qmlTag, std::shared_ptr<AdaptiveCards::AdaptiveCard> originatingCard, const std::vector<AdaptiveWarning>& warnings) : RenderedQmlAdaptiveCardBase(originatingCard, warnings), m_qml(qmlTag) { } std::shared_ptr<QmlTag> RenderedQmlAdaptiveCard::GetResult() { return m_qml; } }
27.470588
194
0.740899
[ "vector" ]
06cb980d4b4567aea8f6592107c575c764b2db83
4,797
cpp
C++
Graphics.DX12/DX12Renderer.cpp
MartijnTerpstra/CainEngine
da52dc065e619ba5761521a024055c6f03d04c8e
[ "MIT" ]
null
null
null
Graphics.DX12/DX12Renderer.cpp
MartijnTerpstra/CainEngine
da52dc065e619ba5761521a024055c6f03d04c8e
[ "MIT" ]
null
null
null
Graphics.DX12/DX12Renderer.cpp
MartijnTerpstra/CainEngine
da52dc065e619ba5761521a024055c6f03d04c8e
[ "MIT" ]
null
null
null
#include "Precomp.h" #include "Event.h" #include "DX12Renderer.h" using namespace ::CainEngine; using namespace ::CainEngine::Graphics; using namespace ::CainEngine::Graphics::DX12; DX12Renderer::DX12Renderer() { } DX12Renderer::~DX12Renderer() { } void DX12Renderer::Init(flag<RendererInitFlags> initFlags) { COMMON_CALLSTACK_CALL; UINT flags = 0; #if !defined(C) flags |= DXGI_CREATE_FACTORY_DEBUG; com_ptr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(MST_IID_PPV_ARGS(debugController)))) { debugController->EnableDebugLayer(); } #endif CHECK_HRESULT(CreateDXGIFactory2(DXGI_CREATE_FACTORY_DEBUG, MST_IID_PPV_ARGS(m_factory))); CHECK_HRESULT(m_factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, MST_IID_PPV_ARGS(m_adapter))); CHECK_HRESULT(D3D12CreateDevice(m_adapter.get(), D3D_FEATURE_LEVEL_11_0, MST_IID_PPV_ARGS(m_device))); D3D_FEATURE_LEVEL lvls[] { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_12_1, }; D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevelInfo; featureLevelInfo.pFeatureLevelsRequested = lvls; featureLevelInfo.NumFeatureLevels = (UINT)extentof(lvls); CHECK_HRESULT(m_device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevelInfo, sizeof(featureLevelInfo))); m_featureLvl = featureLevelInfo.MaxSupportedFeatureLevel; m_device.reset(); CHECK_HRESULT(D3D12CreateDevice(m_adapter.get(), m_featureLvl, MST_IID_PPV_ARGS(m_device))); D3D12_COMMAND_QUEUE_DESC desc = {}; desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; CHECK_HRESULT(m_device->CreateCommandQueue(&desc, MST_IID_PPV_ARGS(m_queue))); m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, MST_IID_PPV_ARGS(m_allocators[0])); m_device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, MST_IID_PPV_ARGS(m_allocators[1])); for (auto& evt : m_commandQueueCompletedEvents) { evt.Init(m_device.get()); } m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_allocators[0].get(), null, MST_IID_PPV_ARGS(m_commandLists[0])); m_device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, m_allocators[1].get(), null, MST_IID_PPV_ARGS(m_commandLists[1])); } void DX12Renderer::RenderFrame() { COMMON_CALLSTACK_CALL; if (m_swapChain == null) return; uint previousRenderIndex = (m_renderIndex + 1) & 1; uint currentBackBufferIndex = m_swapChain->GetCurrentBackBufferIndex(); m_commandQueueCompletedEvents[m_renderIndex].WaitTillCompletion(); CHECK_HRESULT(m_allocators[m_renderIndex]->Reset()); auto& renderQueue = m_commandLists[m_renderIndex]; CHECK_HRESULT(renderQueue->Reset(m_allocators[m_renderIndex].get(), null)); auto trans = CD3DX12_RESOURCE_BARRIER::Transition(m_backbuffers[currentBackBufferIndex].get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); renderQueue->ResourceBarrier(1, &trans); /* renderQueue->ClearDepthStencilView(); renderQueue->ClearRenderTargetView({ float4(0,0,0,0) }, 1, none); //renderQueue->SetResourceGroup(m_group); renderQueue->SetViewports({ Viewport((float)size.x, (float)size.y) }); //renderQueue->SetInputBuffers({ }, m_indexBuffer); //renderQueue->Draw(3); for (auto& mesh : m_meshes) { mesh->Render(renderQueue.get()); } */ trans = CD3DX12_RESOURCE_BARRIER::Transition(m_backbuffers[currentBackBufferIndex].get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); renderQueue->ResourceBarrier(1, &trans); renderQueue->Close(); ID3D12CommandList* ptr = renderQueue.get(); m_queue->ExecuteCommandLists(1, &ptr); m_commandQueueCompletedEvents->SignalFence(m_queue.get()); //m_gpuStream->Flush(); m_swapChain->Present(1, 0); m_renderIndex = (m_renderIndex + 1) & 1; } void DX12Renderer::Exit() { } void DX12Renderer::SetMainWindow(const Common::RefPtr<Platform::IWindow>& mainWindow) { COMMON_CALLSTACK_CALL; auto window = mainWindow->As<Platform::Win32::IWin32Window>(); auto hwnd = window->GetHwnd(); DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { }; swapChainDesc.BufferCount = 2; // double buffering swapChainDesc.Width = 0; swapChainDesc.Height = 0; swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; swapChainDesc.SampleDesc.Count = 1; com_ptr<IDXGISwapChain1> swapChain; CHECK_HRESULT(m_factory->CreateSwapChainForHwnd(m_device.get(), hwnd, &swapChainDesc, null, null, mst::initialize(swapChain))); m_swapChain = swapChain.as<IDXGISwapChain3>(); CHECK_HRESULT(m_swapChain->GetBuffer(0, MST_IID_PPV_ARGS(m_backbuffers[0]))); CHECK_HRESULT(m_swapChain->GetBuffer(1, MST_IID_PPV_ARGS(m_backbuffers[1]))); }
28.724551
162
0.791745
[ "mesh", "render" ]
06cc9ad31077182cd8494dd5fdec537dba575dae
3,739
cpp
C++
sgfx/src/ppm.cpp
keithoma/the_shape_of_data
143f94685f5b77e562463f158cc97544579f14ad
[ "MIT" ]
null
null
null
sgfx/src/ppm.cpp
keithoma/the_shape_of_data
143f94685f5b77e562463f158cc97544579f14ad
[ "MIT" ]
null
null
null
sgfx/src/ppm.cpp
keithoma/the_shape_of_data
143f94685f5b77e562463f158cc97544579f14ad
[ "MIT" ]
null
null
null
#include <iostream> #include <sgfx/ppm.hpp> #include <vector> #define let auto /* Pure provocation with respect to my dire love to F# & my hate to C++ auto keyword. */ namespace sgfx::ppm { using namespace std; canvas Parser::parseString(std::string const& data) { offset_ = 0; source_ = &data; consumeToken(); // initialize tokenizer parseMagic(); let dim = parseDimension(); /*let maximumColorValue = */ parseNumber(); let pixels = vector<color::rgb_color>{}; pixels.reserve(dim.width * dim.height); while (!eof()) pixels.emplace_back(parsePixel()); return canvas{dim, move(pixels)}; } void Parser::fatalSyntaxError(std::string const& diagnosticMessage) { throw FileFormatError{diagnosticMessage}; } char Parser::currentChar() const noexcept { return offset_ < source_->size() ? source_->at(offset_) : '\0'; } char Parser::peekChar() const noexcept { return offset_ + 1 < source_->size() ? source_->at(offset_ + 1) : '\0'; } char Parser::nextChar() noexcept { if (offset_ < source_->size()) ++offset_; return currentChar(); } Parser::TokenInfo Parser::consumeToken() { let const consumeOneToken = [this]() -> TokenInfo { // consume any leading spaces while (!eof() && isspace(currentChar())) nextChar(); if (eof()) return TokenInfo{Token::Eof, "EOF"}; if (currentChar() == '#') // parse comment { nextChar(); // skip '#' let text = string{}; while (!eof() && currentChar() != '\n') { text += currentChar(); nextChar(); } return TokenInfo{Token::Comment, text}; } if (currentChar() == 'P' && peekChar() == '3') { nextChar(); // skip P nextChar(); // skip 3 return TokenInfo{Token::Magic, "P3"}; } if (isdigit(currentChar())) { let literal = string{}; literal += currentChar(); while (isdigit(nextChar())) literal += currentChar(); return TokenInfo{Token::Number, literal}; } return TokenInfo{Token::Invalid, string(1, currentChar())}; }; do currentToken_ = consumeOneToken(); while (currentToken_.token == Token::Comment); return currentToken_; } string Parser::consumeToken(Token token) { if (currentToken().token != token) fatalSyntaxError("Unexpected token."); let literal = currentToken().literal; consumeToken(); return literal; } string Parser::parseMagic() { if (currentToken().token != Token::Magic) fatalSyntaxError("Expected Magic."); let id = currentToken().literal; consumeToken(); return id; } dimension Parser::parseDimension() { let width = stoi(consumeToken(Token::Number)); let height = stoi(consumeToken(Token::Number)); return dimension{width, height}; } color::rgb_color Parser::parsePixel() { let const parsePixel = [this]() -> uint8_t { int value = parseNumber(); if (value >= 0 && value <= 255) return static_cast<uint8_t>(value); fatalSyntaxError("Pixel value out of range."); return 0; // never reached }; let const red = parsePixel(); let const green = parsePixel(); let const blue = parsePixel(); let const color = color::rgb_color{red, green, blue}; return color; } int Parser::parseNumber() { if (currentToken().token != Token::Number) fatalSyntaxError("Expected a number."); let number = stoi(currentToken().literal); consumeToken(); return number; } } // namespace sgfx::ppm
23.664557
105
0.585183
[ "vector" ]
06ced825008b5ca9cf6b3a8ae9540aedc523ee20
89,583
cpp
C++
src/imaging/ossimEquationCombiner.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/imaging/ossimEquationCombiner.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/imaging/ossimEquationCombiner.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimEquationCombiner.cpp 23407 2015-07-06 15:59:23Z okramer $ #include <cstdlib> #include <sstream> using namespace std; #include <ossim/imaging/ossimEquationCombiner.h> #include <ossim/imaging/ossimCastTileSourceFilter.h> #include <ossim/imaging/ossimImageDataFactory.h> #include <ossim/imaging/ossimConvolutionSource.h> #include <ossim/imaging/ossimSubImageTileSource.h> #include <ossim/base/ossimStringProperty.h> #include <ossim/matrix/newmatio.h> #include <ossim/base/ossimScalarTypeLut.h> #include <ossim/base/ossimNotifyContext.h> RTTI_DEF1(ossimEquationCombiner, "ossimEquationCombiner", ossimImageCombiner); static const char* EQUATION_KW = "equation"; class ossimBinaryOpAdd : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 + v2; } }; class ossimBinaryOpAnd : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) & ((ossim_uint32)v2)); } }; class ossimBinaryOpOr : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) | ((ossim_uint32)v2)); } }; class ossimBinaryOpXor : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (double)(((ossim_uint32)v1) ^ ((ossim_uint32)v2)); } }; class ossimBinaryOpSub : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 - v2; } }; class ossimBinaryOpMax : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return std::max(v1, v2); } }; class ossimBinaryOpMin : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return std::min(v1, v2); } }; class ossimBinaryOpMul : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return v1 * v2; } }; class ossimBinaryOpDiv : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { if(fabs(v2)>FLT_EPSILON) return v1 / v2; return 1.0/FLT_EPSILON; } }; class ossimBinaryOpMod : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { if(fabs(v2)>FLT_EPSILON) return fmod(v1,v2); return 1.0/FLT_EPSILON; } }; class ossimBinaryOpPow : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return pow(v1, v2); } }; // boolean operators class ossimBinaryOpEqual : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1==v2)?1.0:0.0; } }; class ossimBinaryOpGreater : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1>v2)?1.0:0.0; } }; class ossimBinaryOpGreaterOrEqual : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1>=v2)?1.0:0.0; } }; class ossimBinaryOpLess : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1<v2)?1.0:0.0; } }; class ossimBinaryOpLessOrEqual : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1<=v2)?1.0:0.0; } }; class ossimBinaryOpDifferent : public ossimEquationCombiner::ossimBinaryOp { public: virtual double apply(double v1, double v2)const { return (v1!=v2)?1.0:0.0; } }; class ossimUnaryOpNot : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return 1-v; } }; class ossimUnaryOpAbs : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return fabs(v); } }; class ossimUnaryOpOnesComplement : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return (double)((ossim_uint8)~((ossim_uint8)v)); } }; class ossimUnaryOpLog : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return log(v); } }; class ossimUnaryOpLog10 : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return log10(v); } }; class ossimUnaryOpNeg : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return -v; } }; class ossimUnaryOpSqrt : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v >= 0) { return sqrt(v); } return -1; } }; class ossimUnaryOpExp : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return exp(v); } }; class ossimUnaryOpSin : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return sin(v); } }; class ossimUnaryOpSind : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return sin(v*M_PI/180.0); } }; class ossimUnaryOpASin : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return asin(v); } }; class ossimUnaryOpASind : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return (180/M_PI)*asin(v); } }; class ossimUnaryOpACos : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return acos(v); } }; class ossimUnaryOpACosd : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { if(v > 1) v = 1; if(v < -1) v = -1; return (180/M_PI)*acos(v); } }; class ossimUnaryOpCos : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return cos(v); } }; class ossimUnaryOpCosd : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return cos(v*M_PI/180.0); } }; class ossimUnaryOpTan : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return tan(v); } }; class ossimUnaryOpTand : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return tan(v*M_PI/180.0); } }; class ossimUnaryOpATan : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return atan(v); } }; class ossimUnaryOpATand : public ossimEquationCombiner::ossimUnaryOp { public: virtual double apply(double v)const { return (180/M_PI)*atan(v); } }; ossimEquationCombiner::ossimEquationCombiner() :ossimImageCombiner(), theOutputScalarType(OSSIM_FLOAT64), theEquation(""), theLexer(NULL), theTile(NULL), theCastFilter(NULL), theCastOutputFilter(NULL), theCurrentId(0), theCurrentResLevel(0) { theLexer = new ossimEquTokenizer; theCastFilter = new ossimCastTileSourceFilter; theCastFilter->setOutputScalarType(OSSIM_FLOAT64); } ossimEquationCombiner::ossimEquationCombiner(ossimConnectableObject::ConnectableObjectList& inputs) :ossimImageCombiner(inputs), theOutputScalarType(OSSIM_FLOAT64), theEquation(""), theLexer(NULL), theTile(NULL), theCastFilter(NULL), theCastOutputFilter(NULL), theCurrentId(0), theCurrentResLevel(0) { theLexer = new ossimEquTokenizer; theCastFilter = new ossimCastTileSourceFilter; theCastFilter->setOutputScalarType(OSSIM_FLOAT64); } ossimEquationCombiner::~ossimEquationCombiner() { if(theLexer) { delete theLexer; theLexer = NULL; } if(theCastFilter.valid()) { theCastFilter->disconnect(); theCastFilter = 0; } if(theCastOutputFilter.valid()) { theCastOutputFilter->disconnect(); theCastOutputFilter = 0; } // make sure they are cleared clearStacks(); } double ossimEquationCombiner::getNullPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getNullPixelValue(band); } } } return ossim::defaultNull(getOutputScalarType()); } double ossimEquationCombiner::getMinPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getMinPixelValue(band); } } } return ossim::defaultMin(getOutputScalarType()); } double ossimEquationCombiner::getMaxPixelValue(ossim_uint32 band)const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getMaxPixelValue(band); } } } return ossim::defaultMax(getOutputScalarType()); } ossimScalarType ossimEquationCombiner::getOutputScalarType() const { if(theEquation == "") { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getOutputScalarType(); } } } return theOutputScalarType; } ossimRefPtr<ossimImageData> ossimEquationCombiner::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if(!theTile) { initialize(); } long w = tileRect.width(); long h = tileRect.height(); long tw = theTile->getWidth(); long th = theTile->getHeight(); if(theEquation != "") { theTile->setImageRectangle(tileRect); if(w*h != tw*th) { theTile->initialize(); } else { theTile->makeBlank(); } theCurrentResLevel = resLevel; ossimRefPtr<ossimImageData> outputTile = parseEquation(); if(theCastOutputFilter.valid()) { outputTile = theCastOutputFilter->applyCast(outputTile); } return outputTile; } else { if(getInput()) { ossimImageSource* inter = PTR_CAST(ossimImageSource, getInput()); if(inter) { return inter->getTile(tileRect, resLevel); } } } return ossimRefPtr<ossimImageData>(); } void ossimEquationCombiner::setOutputScalarType(ossimScalarType scalarType) { if(theOutputScalarType != scalarType) { theOutputScalarType = scalarType; if(theOutputScalarType == OSSIM_SCALAR_UNKNOWN) { theOutputScalarType = OSSIM_FLOAT64; } if(theCastOutputFilter.valid()) { theCastOutputFilter = 0; } if(theOutputScalarType != OSSIM_FLOAT64) { theCastOutputFilter = new ossimCastTileSourceFilter; theCastOutputFilter->setOutputScalarType(theOutputScalarType); theCastOutputFilter->connectMyInputTo(0, this); theCastOutputFilter->initialize(); } } } void ossimEquationCombiner::setProperty(ossimRefPtr<ossimProperty> property) { if(!property) return; if(property->getName() == "Equation") { theEquation = property->valueToString(); } else if(property->getName() == "Output scalar type") { setOutputScalarType(ossimScalarTypeLut::instance()-> getScalarTypeFromString(property->valueToString())); } else { ossimImageCombiner::setProperty(property); } } ossimRefPtr<ossimProperty> ossimEquationCombiner::getProperty(const ossimString& name)const { if(name == "Equation") { ossimStringProperty* stringProp = new ossimStringProperty("Equation", theEquation, false); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } else if(name == "Output scalar type") { ossimScalarTypeLut* sl = ossimScalarTypeLut::instance(); std::vector<ossimString> scalarNames; ossim_int32 tableSize = (ossim_int32)sl->getTableSize(); ossim_int32 idx; for(idx = 0; idx < tableSize; ++idx) { scalarNames.push_back(sl->getEntryString(idx)); } ossimStringProperty* stringProp = new ossimStringProperty("Output scalar type", sl->getEntryString((ossim_int32)theOutputScalarType), false, scalarNames); stringProp->clearChangeType(); stringProp->setReadOnlyFlag(false); stringProp->setCacheRefreshBit(); return stringProp; } return ossimImageCombiner::getProperty(name); } void ossimEquationCombiner::getPropertyNames(std::vector<ossimString>& propertyNames)const { ossimImageCombiner::getPropertyNames(propertyNames); propertyNames.push_back("Equation"); propertyNames.push_back("Output scalar type"); } void ossimEquationCombiner::initialize() { ossimImageCombiner::initialize(); theTile = ossimImageDataFactory::instance()->create(this, OSSIM_FLOAT64, getNumberOfOutputBands(), getTileWidth(), getTileHeight()); theTile->initialize(); if(theCastOutputFilter.valid()) { theCastOutputFilter->initialize(); } } void ossimEquationCombiner::assignValue() { if(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_IMAGE_DATA_TYPE) { ossimImageData* topData = theValueStack.top().d.imageDataValue; ossim_uint32 minBands = std::min(theTile->getNumberOfBands(), topData->getNumberOfBands()); ossim_uint32 maxBands = theTile->getNumberOfBands(); ossim_uint32 band = 0; ossim_uint32 offset = 0; ossim_uint32 size = theTile->getWidth()*theTile->getHeight(); if(topData->getDataObjectStatus() == OSSIM_PARTIAL) { for(band = 0; band < minBands; ++band) { double* inBuf = (double*)topData->getBuf(band); double* outBuf = (double*)theTile->getBuf(band); double np = topData->getNullPix(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { if(*inBuf != np) { *outBuf = *inBuf; } ++outBuf; ++inBuf; } } } for(;band < maxBands; ++band) { double* inBuf = (double*)topData->getBuf(minBands-1); double* outBuf = (double*)theTile->getBuf(band); double np = topData->getNullPix(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { if(*inBuf != np) { *outBuf = *inBuf; } ++outBuf; ++inBuf; } } } } else if(topData->getDataObjectStatus() == OSSIM_FULL) { for(band = 0; band < minBands; ++band) { double* inBuf = (double*)theValueStack.top().d.imageDataValue->getBuf(band); double* outBuf = (double*)theTile->getBuf(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { *outBuf = *inBuf; ++outBuf; ++inBuf; } } } for(;band < maxBands; ++band) { double* inBuf = (double*)theValueStack.top().d.imageDataValue->getBuf(minBands-1); double* outBuf = (double*)theTile->getBuf(band); if(outBuf && inBuf) { for(offset = 0; offset < size; ++offset) { *outBuf = *inBuf; ++outBuf; ++inBuf; } } } } // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = theValueStack.top().d.imageDataValue; id = NULL; } else { double* buf = static_cast<double*>(theTile->getBuf()); ossim_uint32 size = theTile->getSize(); double value = (double)theValueStack.top().d.doubleValue; for(ossim_uint32 offset = 0; offset < size; ++offset) { *buf = value; ++buf; } } theValueStack.pop(); } } void ossimEquationCombiner::clearStacks() { while(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_IMAGE_DATA_TYPE) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = theValueStack.top().d.imageDataValue; id = NULL; } theValueStack.pop(); } } void ossimEquationCombiner::clearArgList(vector<ossimEquValue>& argList) { for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(argList[i].d.imageDataValue) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = argList[i].d.imageDataValue; id = NULL; argList[i].d.imageDataValue = (ossimImageData*)NULL; } } } argList.clear(); } void ossimEquationCombiner::deleteArgList(vector<ossimEquValue>& args) { int i = 0; for(i = 0; i < (int)args.size(); ++i) { if(args[i].type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(args[i].d.imageDataValue) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = args[i].d.imageDataValue; id = NULL; args[i].d.imageDataValue = NULL; } } } args.clear(); } bool ossimEquationCombiner::parseArgList(vector<ossimEquValue>& args, bool popValueStack) { bool result = true; if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); do { if(parseExpression()) { if(!theValueStack.empty()) { args.push_back(theValueStack.top()); if(popValueStack) { theValueStack.pop(); } } else { ossimNotify(ossimNotifyLevel_WARN) << "The expression at arg " << (args.size()+1) << " is empty" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) <<"Unable to parse expression" << endl; result = false; } if(theCurrentId == OSSIM_EQU_TOKEN_COMMA) { theCurrentId = theLexer->yylex(); } else if(theCurrentId != OSSIM_EQU_TOKEN_RIGHT_PAREN) { ossimNotify(ossimNotifyLevel_WARN) <<"Missing comma in argument list" << endl; result = false; } }while(result&&(theCurrentId != OSSIM_EQU_TOKEN_RIGHT_PAREN)); } else { ossimNotify(ossimNotifyLevel_WARN) << "Starting left parenthesis missing from arg list" << endl; result = false; } if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { theCurrentId = theLexer->yylex(); // skip past right parenthesis } else { ossimNotify(ossimNotifyLevel_WARN) <<"No matching right parenthesis for arg list" << endl; result = false; } if(!result && popValueStack) { clearArgList(args); } return result; } bool ossimEquationCombiner::parseAssignBand() { bool result = true; vector<ossimEquValue> argList; if(parseArgList(argList)) { if((argList.size() == 3) || (argList.size() == 4)) { ossimEquValue v3 = argList[2]; ossimEquValue v2 = argList[1]; ossimEquValue v1 = argList[0]; if(argList.size() == 3) { if((v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) && (v2.type == OSSIM_EQU_DOUBLE_TYPE)) { ossimImageData *data = (ossimImageData*)v1.d.imageDataValue->dup(); ossimEquValue v; if(v3.type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(data->getBuf()&& v3.d.imageDataValue->getBuf()) { if((ossim_uint32)(v2.d.doubleValue) < data->getNumberOfBands()) { data->assignBand(v3.d.imageDataValue, 0, (ossim_uint32)v2.d.doubleValue); } } } else { if(data->getBuf()&& (ossim_uint32)v2.d.doubleValue < data->getNumberOfBands()) { ossim_uint32 upper = data->getWidth()*data->getHeight(); double* buf = (double*)data->getBuf((ossim_uint32)v2.d.doubleValue); double value = v3.d.doubleValue; if(buf) { for(ossim_uint32 i = 0; i < upper; ++i) { *buf = value; ++buf; } } else { result = false; } } } if(result) { data->validate(); v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; theValueStack.push(v); } } else { result = false; } } else { ossimEquValue v4 = argList[3]; if((v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) && (v2.type == OSSIM_EQU_DOUBLE_TYPE)&& (v3.type == OSSIM_EQU_IMAGE_DATA_TYPE)&& (v4.type == OSSIM_EQU_DOUBLE_TYPE)) { ossimImageData *data = (ossimImageData*)v1.d.imageDataValue->dup(); ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; if(data->getBuf()&&v3.d.imageDataValue->getBuf()) { ossim_uint32 index1 = (ossim_uint32)v4.d.doubleValue; ossim_uint32 index2 = (ossim_uint32)v2.d.doubleValue; if((index1 > data->getNumberOfBands()) || (index1 > v3.d.imageDataValue->getNumberOfBands())) { result = false; } else { data->assignBand(v3.d.imageDataValue, index1, index2); data->validate(); } } theValueStack.push(v); } } } else { ossimNotify(ossimNotifyLevel_WARN) << "Invalid number of arguments to assign_band" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "unable to parse arguments for assign band" << endl; result = false; } clearArgList(argList); return result; } bool ossimEquationCombiner::parseStdFuncs() { bool result = true; switch(theCurrentId) { case OSSIM_EQU_TOKEN_ASSIGN_BAND: { theCurrentId = theLexer->yylex(); if(!parseAssignBand()) { result = false; } break; } case OSSIM_EQU_TOKEN_CONV: { theCurrentId = theLexer->yylex(); vector<ossimEquValue> args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyConvolution(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "function conv error: resulting image is NULL" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to apply convolution" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_CLAMP: { theCurrentId = theLexer->yylex(); vector<ossimEquValue> args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyClamp(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "function clamp error: resulting image is NULL" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to apply clamp" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BAND: { // need to parse the following rule for blurr function // // band(image data, number) theCurrentId = theLexer->yylex(); vector<ossimEquValue> argList; if(parseArgList(argList)) { if(argList.size() == 2) { ossimEquValue v1 = argList[0]; ossimEquValue v2 = argList[1]; ossimImageData* tempData = NULL; ossim_uint32 bandNumber = 0; if(v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) { tempData = v1.d.imageDataValue; } else { result = false; } if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { bandNumber = (ossim_uint32)(v2.d.doubleValue); } else { result = false; } if(bandNumber > tempData->getNumberOfBands()) { result = false; } if(result) { ossimImageData* data = new ossimImageData(this, OSSIM_FLOAT64, 1); data->setWidthHeight(tempData->getWidth(), tempData->getHeight()); data->setOrigin(tempData->getOrigin()); data->setNullPix(tempData->getNullPix(bandNumber), 0); data->setMinPix(tempData->getMinPix(bandNumber), 0); data->setMaxPix(tempData->getMaxPix(bandNumber), 0); data->initialize(); if((tempData->getBuf())&& (bandNumber < tempData->getNumberOfBands())) { data->assignBand(tempData, bandNumber, 0); data->validate(); } ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data; theValueStack.push(v); } if(tempData) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = tempData; tempData = NULL; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Invalid number of args in function band" << endl; result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLURR: { theCurrentId = theLexer->yylex(); vector<ossimEquValue> args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyBlurr(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { result = false; } } else { result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SHIFT: { theCurrentId = theLexer->yylex(); vector<ossimEquValue> args; if(parseArgList(args)) { ossimImageData* resultImage = (ossimImageData*)NULL; if(applyShift(resultImage, args)) { if(resultImage) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = resultImage; theValueStack.push(v); } else { result = false; } } else { result = false; } } else { result = false; } break; } case OSSIM_EQU_TOKEN_MAX: case OSSIM_EQU_TOKEN_MIN: { ossimBinaryOp* op = NULL; if(theCurrentId == OSSIM_EQU_TOKEN_MIN) op = new ossimBinaryOpMin; else op = new ossimBinaryOpMax; int argCount = 0; theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); bool done = false; while(!done) { if(parseExpression()) { ++argCount; if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { theCurrentId = theLexer->yylex(); done = true; } else if(theCurrentId == OSSIM_EQU_TOKEN_COMMA) { theCurrentId = theLexer->yylex(); } else { result = false; done = true; } } else { done = true; result = false; } } if((argCount > 1)&&result) { result = true; ossimEquValue v; ossimEquValue v1; ossimEquValue v2; v2 = theValueStack.top(); theValueStack.pop(); v1 = theValueStack.top(); theValueStack.pop(); argCount -=2; do { if(applyOp(*op, v, v1, v2)) { theValueStack.push(v); } else { result = false; argCount = 0; } --argCount; if((argCount>0)&&result) { v2 = theValueStack.top(); theValueStack.pop(); v1 = theValueStack.top(); theValueStack.pop(); } }while((argCount > 0)&&(result)); } else { result = false; } } else { result = false; } if(op) { delete op; op = NULL; } break; } case OSSIM_EQU_TOKEN_ABS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpAbs(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SIN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSin(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SIND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSind(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ASIN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpASin(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ASIND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpASind(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_COS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpCos(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_COSD: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpCosd(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ACOS: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpACos(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ACOSD: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpACosd(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_TAN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpTan(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_TAND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpTand(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ATAN: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpATan(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_ATAND: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpATand(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_LOG: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpLog(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_LOG10: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpLog10(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_SQRT: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpSqrt(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } case OSSIM_EQU_TOKEN_EXP: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_PAREN) { theCurrentId = theLexer->yylex(); result = parseExpression(); if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { if(theValueStack.size() > 0) { theCurrentId = theLexer->yylex(); ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpExp(), v, v1); theValueStack.push(v); } else { result = false; } } } else { result = false; } break; } default: { result = false; } } return result; } bool ossimEquationCombiner::parseUnaryFactor() { bool result = false; if(theCurrentId == OSSIM_EQU_TOKEN_MINUS) { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 0) { ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpNeg(), v, v1); theValueStack.push(v); } else { result = false; } result = true; } else { result = false; } } else if(theCurrentId == OSSIM_EQU_TOKEN_TILDE) { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 0) { ossimEquValue v; ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimUnaryOpOnesComplement(), v, v1); theValueStack.push(v); } else { result = false; } result = true; } else { result = false; } } return result; } bool ossimEquationCombiner::parseFactor() { bool result = false; switch(theCurrentId) { case OSSIM_EQU_TOKEN_CONSTANT: { ossimEquValue v; v.type = OSSIM_EQU_DOUBLE_TYPE; v.d.doubleValue = atof(theLexer->YYText()); theValueStack.push(v); theCurrentId = theLexer->yylex(); result = true; break; } case OSSIM_EQU_TOKEN_PI: { ossimEquValue v; v.type = OSSIM_EQU_DOUBLE_TYPE; v.d.doubleValue = M_PI; theValueStack.push(v); theCurrentId = theLexer->yylex(); result = true; break; } case OSSIM_EQU_TOKEN_IMAGE_VARIABLE: { theCurrentId = theLexer->yylex(); if(theCurrentId == OSSIM_EQU_TOKEN_LEFT_ARRAY_BRACKET) { theCurrentId = theLexer->yylex(); if(parseExpression()) { if(!theValueStack.empty()) { if(theValueStack.top().type == OSSIM_EQU_DOUBLE_TYPE) { if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_ARRAY_BRACKET) { theCurrentId = theLexer->yylex(); ossim_uint32 index = (ossim_uint32)theValueStack.top().d.doubleValue; theValueStack.pop(); ossimRefPtr<ossimImageData> data = getNewImageData(index); result = true; if(data.valid()) { ossimEquValue v; v.type = OSSIM_EQU_IMAGE_DATA_TYPE; v.d.imageDataValue = data.release(); theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) <<"Data is NULL for array operation" << endl; } result = true; } else { ossimNotify(ossimNotifyLevel_WARN) << "Mismatched Right array bracket" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Expression between array brackets is not a number" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "no expression within array brackets" << endl; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unabel to parse expression"<<endl; } } else { ossimNotify(ossimNotifyLevel_WARN) <<"Need left array brackets to access an input source"<<endl; } break; } case OSSIM_EQU_TOKEN_LEFT_PAREN: { theCurrentId = theLexer->yylex(); if(parseExpression()) { if(theCurrentId == OSSIM_EQU_TOKEN_RIGHT_PAREN) { result = true; theCurrentId = theLexer->yylex(); } else { ossimNotify(ossimNotifyLevel_WARN) << "Right parenthesis missing" << endl; result = false; } } else { ossimNotify(ossimNotifyLevel_WARN) << "Unable to parse expression within parenthesis" << endl; result = false; } break; } } if(!result) result = parseUnaryFactor(); if(!result) result = parseStdFuncs(); return result; } bool ossimEquationCombiner::parseRestOfTerm() { //--- // Parse the following rule: // RestOfTerm: * Factor RestOfTerm | / Factor RestOfTerm | // ^ Factor RestOfTerm //--- bool result = true; switch(theCurrentId) { case OSSIM_EQU_TOKEN_MULT: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpMul(), v, v1, v2); theValueStack.push(v); } else { ossimNotify(ossimNotifyLevel_WARN) << "Multiplication requires two arguments" << endl; result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_DIV: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpDiv(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_XOR: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpXor(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_AMPERSAND: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpAnd(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_OR_BAR: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpOr(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_MOD: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpMod(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_POWER: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpPow(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BEQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BGREATER: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpGreater(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BGREATEROREQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpGreaterOrEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLESS: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpLess(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BLESSOREQUAL: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpLessOrEqual(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } case OSSIM_EQU_TOKEN_BDIFFERENT: { theCurrentId = theLexer->yylex(); if(parseFactor()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpDifferent(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfTerm(); } } else { result = false; } break; } } return result; } bool ossimEquationCombiner::parseTerm() { // parse the following rule: // // Term : Factor RestOfTerm bool result = false; result = parseFactor(); if(result) { result = parseRestOfTerm(); } return result; } bool ossimEquationCombiner::parseRestOfExp() { // parse the following rule: // RestOfExpression : + Term RestOfExpression | - Term RestOfExpression | epsilon // bool result = true; if(theCurrentId == OSSIM_EQU_TOKEN_PLUS) { theCurrentId = theLexer->yylex(); if(parseTerm()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpAdd(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfExp(); } } else { result = false; } } else if(theCurrentId == OSSIM_EQU_TOKEN_MINUS) { theCurrentId = theLexer->yylex(); if(parseTerm()) { if(theValueStack.size() > 1) { ossimEquValue v; ossimEquValue v2 = theValueStack.top(); theValueStack.pop(); ossimEquValue v1 = theValueStack.top(); theValueStack.pop(); applyOp(ossimBinaryOpSub(), v, v1, v2); theValueStack.push(v); } else { result = false; } if(result) { result = parseRestOfExp(); } } else { result = false; } } return result; } ossimRefPtr<ossimImageData> ossimEquationCombiner::getImageData(ossim_uint32 index) { ossimRefPtr<ossimImageData> result; ossimConnectableObject* obj = getInput(index); if(obj) { theCastFilter->connectMyInputTo(0, obj); result= (theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel)); if(result.valid()) { result->setMinPix(theTile->getMinPix(), theTile->getNumberOfBands()); result->setMaxPix(theTile->getMaxPix(), theTile->getNumberOfBands()); } } return result; } ossimRefPtr<ossimImageData> ossimEquationCombiner::getNewImageData( ossim_uint32 index) { ossimRefPtr<ossimImageData> result = getImageData(index); if(result.valid()) { if(result->getBuf()) { result = (ossimImageData*)result->dup(); } } return result; } bool ossimEquationCombiner::parseExpression() { // parse the following rule: // expression : Term ResOfExpression // bool result = false; if(parseTerm()) { result = parseRestOfExp(); } return result; } ossimRefPtr<ossimImageData> ossimEquationCombiner::parseEquation() { ostringstream s; s << theEquation; istringstream inS(s.str()); theLexer->switch_streams(&inS, &ossimNotify(ossimNotifyLevel_WARN)); theCurrentId = theLexer->yylex(); while(theCurrentId) { if(!parseExpression()) { break; } } if(!theValueStack.empty()) { assignValue(); theTile->validate(); clearStacks(); } return theTile; } bool ossimEquationCombiner::applyClamp(ossimImageData* &result, const vector<ossimEquValue>& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() <3) { return false; } if(argList[0].type == OSSIM_EQU_DOUBLE_TYPE) { return false; } else if( (argList[1].type == OSSIM_EQU_DOUBLE_TYPE)&& (argList[2].type == OSSIM_EQU_DOUBLE_TYPE)) { result = argList[0].d.imageDataValue; if(argList[0].d.imageDataValue) { ossimDataObjectStatus status = result->getDataObjectStatus(); if((status != OSSIM_NULL) && (status != OSSIM_EMPTY)) { double minValue = argList[1].d.doubleValue; double maxValue = argList[2].d.doubleValue; if(minValue > maxValue) { std::swap(minValue, maxValue); } int band = 0; int offset = 0; int upperBoundBand = result->getNumberOfBands(); int offsetUpperBound = result->getWidth()*result->getHeight(); if(status == OSSIM_PARTIAL) { for(band = 0; band < upperBoundBand; ++band) { double np = static_cast<double>(result->getNullPix(band)); double *buf = static_cast<double*>(result->getBuf(band)); for(offset = 0; offset < offsetUpperBound; ++ offset) { if( *buf != np ) { if( (*buf) < minValue) *buf = minValue; else if( (*buf) >maxValue) *buf = maxValue; } ++buf; } } } else { for(band = 0; band < upperBoundBand; ++band) { double *buf = static_cast<double*>(result->getBuf(band)); for(offset = 0; offset < offsetUpperBound; ++ offset) { if( (*buf) < minValue) *buf = minValue; else if( (*buf) >maxValue) *buf = maxValue; ++buf; } } } } } return true; } return false; } bool ossimEquationCombiner::applyConvolution(ossimImageData* &result, const vector<ossimEquValue>& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() <4) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int rows = (int)argList[1].d.doubleValue; int cols = (int)argList[2].d.doubleValue; if((rows*cols) != (int)(argList.size()-3)) { return false; } NEWMAT::Matrix m(rows,cols); int count = 3; for(int r = 0; r< rows;++r) { for(int c=0;c<cols;++c) { m[r][c] = argList[count].d.doubleValue; ++count; } } ossimConnectableObject* obj = getInput(index); if(obj) { ossimRefPtr<ossimConvolutionSource> conv = new ossimConvolutionSource(NULL, m); conv->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, conv.get()); ossimRefPtr<ossimImageData> tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } else { result = (ossimImageData*)theTile->dup(); } conv->disconnect(); conv = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyBlurr(ossimImageData* &result, const vector<ossimEquValue>& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() !=3) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int rows = (int)argList[1].d.doubleValue; int cols = (int)argList[2].d.doubleValue; NEWMAT::Matrix m(rows, cols); m = 1.0/(rows*cols); ossimConnectableObject* obj = getInput(index); if(obj) { ossimRefPtr<ossimConvolutionSource> conv = new ossimConvolutionSource(NULL, m); conv->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, conv.get()); theCastFilter->initialize(); ossimRefPtr<ossimImageData> tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } conv->disconnect(); conv = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyShift(ossimImageData* &result, const vector<ossimEquValue>& argList) { if(result) { // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = result; id = NULL; result = (ossimImageData*) NULL; } if(argList.size() !=3) return false; for(ossim_uint32 i = 0; i < argList.size(); ++i) { if(argList[i].type != OSSIM_EQU_DOUBLE_TYPE) { return false; } } ossim_uint32 index = (ossim_uint32)argList[0].d.doubleValue; int x = (int)argList[1].d.doubleValue; int y = (int)argList[2].d.doubleValue; ossimConnectableObject* obj = getInput(index); if(obj) { ossimRefPtr<ossimSubImageTileSource> shiftSource = new ossimSubImageTileSource(NULL, ossimIpt(x, y)); shiftSource->connectMyInputTo(0, obj); theCastFilter->connectMyInputTo(0, shiftSource.get()); ossimRefPtr<ossimImageData> tempData = theCastFilter->getTile(theTile->getImageRectangle(), theCurrentResLevel); if(tempData.valid()) { result = (ossimImageData*)tempData->dup(); } shiftSource->disconnect(); shiftSource = 0; } if(result) { return true; } return false; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimEquValue& result, ossimEquValue& v1, ossimEquValue& v2) { bool returnValue = true; if(v1.type == OSSIM_EQU_DOUBLE_TYPE) { if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { result.type = OSSIM_EQU_DOUBLE_TYPE; result.d.doubleValue = op.apply(v1.d.doubleValue, v2.d.doubleValue); } else if(v2.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v1.d.doubleValue, v2.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v2.d.imageDataValue; } else { returnValue = false; } } else if(v1.type == OSSIM_EQU_IMAGE_DATA_TYPE) { if(v2.type == OSSIM_EQU_DOUBLE_TYPE) { returnValue = applyOp(op, v1.d.imageDataValue, v2.d.doubleValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v1.d.imageDataValue; returnValue = true; } else if(v2.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v1.d.imageDataValue, v2.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v1.d.imageDataValue; // Delete the object indirectly through an ossimRefPtr. ossimRefPtr<ossimImageData> id = v2.d.imageDataValue; id = NULL; v2.d.imageDataValue = (ossimImageData*)NULL; returnValue = true; } else { returnValue = false; } } else { returnValue = false; } return returnValue; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimImageData* v1, double v2) { double* buf = static_cast<double*>(v1->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v1->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v1->getSize(); double value = (static_cast<double>(v2)); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(*buf, value); ++buf; } } else { ossim_uint32 sizePerBand = v1->getSizePerBand(); ossim_uint32 numberOfBands = v1->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast<double*>(v1->getBuf(band)); if(buf) { double np = static_cast<double>(v1->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand;++offset) { if(*buf != np) { *buf = (double)op.apply(*buf, v2); } ++buf; } } } } } return true; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, double v1, ossimImageData* v2) { double* buf = static_cast<double*>(v2->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v2->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v2->getSize(); double value = (static_cast<double>(v1)); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(value, *buf); ++buf; } } else { ossim_uint32 sizePerBand = v2->getSizePerBand(); ossim_uint32 numberOfBands = v2->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast<double*>(v2->getBuf(band)); if(buf) { double np = static_cast<double>(v2->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand; ++offset) { if(*buf != np) { *buf = (double)op.apply((double)v1, *buf); } ++buf; } } } } } return true; } bool ossimEquationCombiner::applyOp(const ossimBinaryOp& op, ossimImageData* v1, ossimImageData* v2) { ossim_uint32 minNumberOfBands = std::min(v1->getNumberOfBands(), v2->getNumberOfBands()); ossim_uint32 maxNumberOfBands = std::max(v1->getNumberOfBands(), v2->getNumberOfBands()); ossim_uint32 size = v1->getWidth()*v1->getHeight(); ossimDataObjectStatus status1 = v1->getDataObjectStatus(); ossimDataObjectStatus status2 = v2->getDataObjectStatus(); double** bandV1 = new double*[maxNumberOfBands]; double** bandV2 = new double*[maxNumberOfBands]; double* bandV1Np = new double[maxNumberOfBands]; double* bandV2Np = new double[maxNumberOfBands]; ossim_uint32 band = 0; for(band = 0; band < minNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(band); bandV2[band] = (double*)v2->getBuf(band); bandV1Np[band] = (double)v1->getNullPix(band); bandV2Np[band] = (double)v2->getNullPix(band); } if(v1->getNumberOfBands() < v2->getNumberOfBands()) { for(band = 0; band < maxNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(minNumberOfBands-1); bandV2[band] = (double*)v2->getBuf(band); bandV1Np[band] = (double)v1->getNullPix(minNumberOfBands-1); bandV2Np[band] = (double)v2->getNullPix(band); } } else if(v2->getNumberOfBands() < v1->getNumberOfBands()) { for(band = 0; band < maxNumberOfBands; ++band) { bandV1[band] = (double*)v1->getBuf(band); bandV2[band] = (double*)v2->getBuf(minNumberOfBands-1); bandV1Np[band] = (double)v1->getNullPix(band); bandV2Np[band] = (double)v2->getNullPix(minNumberOfBands-1); } } if(status1 == OSSIM_EMPTY) { if(status2 == OSSIM_FULL) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; for(ossim_uint32 i = 0; i < size; ++i) { *buf1 = *buf2; ++buf1; ++buf2; } } } else if(status2 == OSSIM_PARTIAL) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf2 != nullPix2) { *buf1 = *buf2; } ++buf1; ++buf2; } } } v1->setDataObjectStatus(status2); } else if((status1 == OSSIM_FULL)&& (status2 == OSSIM_FULL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; for(ossim_uint32 i = 0; i < size; ++i) { *buf1 = op.apply(*buf1, *buf2); ++buf1; ++buf2; } } } else if((status1 == OSSIM_FULL)&& (status2 == OSSIM_PARTIAL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf2 != nullPix2) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } else if((status1 == OSSIM_PARTIAL)&& (status2 == OSSIM_FULL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix1 = bandV1Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if(*buf1 != nullPix1) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } else if((status1 == OSSIM_PARTIAL)&& (status2 == OSSIM_PARTIAL)) { for(band = 0; band < maxNumberOfBands; ++band) { double* buf1 = bandV1[band]; double* buf2 = bandV2[band]; double nullPix1 = bandV1Np[band]; double nullPix2 = bandV2Np[band]; for(ossim_uint32 i = 0; i < size; ++i) { if((*buf1 != nullPix1)&& (*buf2 != nullPix2)) { *buf1 = op.apply(*buf1, *buf2); } ++buf1; ++buf2; } } } delete [] bandV1; delete [] bandV2; delete [] bandV1Np; delete [] bandV2Np; return true; } bool ossimEquationCombiner::applyOp(const ossimUnaryOp& op, ossimEquValue& result, ossimEquValue& v) { bool returnValue = true; if(v.type == OSSIM_EQU_DOUBLE_TYPE) { result.type = OSSIM_EQU_DOUBLE_TYPE; result.d.doubleValue = op.apply(v.d.doubleValue); } else if(v.type == OSSIM_EQU_IMAGE_DATA_TYPE) { returnValue = applyOp(op, v.d.imageDataValue); result.type = OSSIM_EQU_IMAGE_DATA_TYPE; result.d.imageDataValue = v.d.imageDataValue; returnValue = true; } else { returnValue = false; } return returnValue; } bool ossimEquationCombiner::applyOp(const ossimUnaryOp& op, ossimImageData* v) { double* buf = static_cast<double*>(v->getBuf()); if(!buf) return true; ossimDataObjectStatus status = v->getDataObjectStatus(); if(status == OSSIM_EMPTY || status == OSSIM_NULL) { return true; } if(status == OSSIM_FULL ) { ossim_uint32 size = v->getSize(); for(ossim_uint32 i = 0; i < size; ++i) { *buf = (double)op.apply(*buf); ++buf; } } else { ossim_uint32 sizePerBand = v->getSizePerBand(); ossim_uint32 numberOfBands = v->getNumberOfBands(); if(numberOfBands) { for(ossim_uint32 band = 0; band < numberOfBands; ++band) { double* buf = static_cast<double*>(v->getBuf(band)); if(buf) { double np = static_cast<double>(v->getNullPix()[band]); for(ossim_uint32 offset = 0; offset < sizePerBand;++offset) { if(*buf != np) { *buf = (double)op.apply(*buf); } ++buf; } } } } } return true; } bool ossimEquationCombiner::saveState(ossimKeywordlist& kwl, const char* prefix)const { ossimString outputScalarType = ossimScalarTypeLut::instance()->getEntryString(theOutputScalarType); kwl.add(prefix, EQUATION_KW, theEquation.c_str(), true); kwl.add(prefix, "output_scalar_type", outputScalarType.c_str(), true); return ossimImageCombiner::saveState(kwl, prefix); } bool ossimEquationCombiner::loadState(const ossimKeywordlist& kwl, const char* prefix) { const char* equ = kwl.find(prefix, EQUATION_KW); const char* scalar = kwl.find(prefix, "output_scalar_type"); bool result = ossimImageCombiner::loadState(kwl, prefix); if(equ) { theEquation = equ; } if(scalar) { setOutputScalarType(ossimScalarTypeLut::instance()-> getScalarTypeFromString(scalar)); } return result; }
25.044171
135
0.474688
[ "object", "vector" ]
06d457b24f3d9966012745f9b1c6d7a762cd80b9
3,964
hpp
C++
composite/graph/compute_loss.hpp
kingang1986/purine2
e53447da173e83fb62bae8cf50bde17f75723203
[ "BSD-2-Clause" ]
312
2015-03-16T15:29:38.000Z
2021-09-16T22:48:41.000Z
composite/graph/compute_loss.hpp
zuiwufenghua/purine2
e53447da173e83fb62bae8cf50bde17f75723203
[ "BSD-2-Clause" ]
19
2015-03-17T16:20:19.000Z
2015-10-03T03:34:09.000Z
composite/graph/compute_loss.hpp
zuiwufenghua/purine2
e53447da173e83fb62bae8cf50bde17f75723203
[ "BSD-2-Clause" ]
108
2015-03-16T07:07:30.000Z
2021-08-22T07:32:13.000Z
// Copyright Lin Min 2015 #ifndef PURINE_COMPUTE_LOSS #define PURINE_COMPUTE_LOSS #include <iomanip> #include <fstream> #include <set> #include "composite/composite.hpp" using namespace std; namespace purine { template <typename Net> class ComputeLoss : public Runnable { protected: Net* net_; vector<Blob*> data_; vector<Blob*> labels_; vector<Blob*> loss_; vector<Blob*> weights_; public: explicit ComputeLoss(int rank, int device); virtual ~ComputeLoss() override {} void load(const string& filename); void print_loss(); void feed(const vector<Blob*>& data, const vector<Blob*>& labels); }; template <typename Net> ComputeLoss<Net>::ComputeLoss(int rank, int device) : Runnable() { net_ = createGraph<Net>("net", rank, device); // prune const vector<Blob*>& data_diff = net_->data_diff(); const vector<Blob*>& weight_diff = net_->weight_diff(); // add to prune vector<Node*> to_prune; transform(data_diff.begin(), data_diff.end(), std::back_inserter(to_prune), [](Blob* b)->Node* { return dynamic_cast<Node*>(b); }); transform(weight_diff.begin(), weight_diff.end(), std::back_inserter(to_prune), [](Blob* b)->Node* { return dynamic_cast<Node*>(b); }); net_->prune(to_prune); // get the data and labels data_ = net_->data(); labels_ = net_->label(); weights_ = net_->weight_data(); const vector<Blob*>& loss = net_->loss(); auto copier = createAny<Vectorize<Copy> >("copy_loss", vector<Copy::param_tuple>(loss.size(), Copy::param_tuple(0, -1))); vector<vector<Blob*> >{ loss } >> *copier; loss_ = copier->top()[0]; } template <typename Net> void ComputeLoss<Net>::feed(const vector<Blob*>& data, const vector<Blob*>& labels) { CHECK_EQ(data.size(), data_.size()); CHECK_EQ(labels.size(), labels_.size()); for (int i = 0; i < data.size(); ++i) { if (current_rank() == data_[i]->rank()) { data_[i]->tensor()->swap_memory(data[i]->tensor()); } } for (int i = 0; i < labels.size(); ++i) { if (current_rank() == labels_[i]->rank()) { labels_[i]->tensor()->swap_memory(labels[i]->tensor()); } } } template <typename Net> void ComputeLoss<Net>::print_loss() { if (current_rank() == 0) { vector<DTYPE> ret(loss_.size()); transform(loss_.begin(), loss_.end(), ret.begin(), [](Blob* b)->DTYPE { return b->tensor()->cpu_data()[0]; }); stringstream ss; for (int i = 0; i < ret.size(); ++i) { ss << "[" << std::scientific << ret[i] << "] "; } LOG(INFO) << "loss: " << ss.str(); } } template <typename Net> void ComputeLoss<Net>::load(const string& filename) { Runnable loader(0, -1); weights_ = net_->weight_data(); int num_param = weights_.size(); vector<Blob*> tmp(num_param); vector<Blob*> weights(num_param); for (int i = 0; i < num_param; ++i) { tmp[i] = loader.create("tmp", weights_[i]->tensor()->size()); } for (int i = 0; i < num_param; ++i) { weights[i] = loader.create("weight", weights_[i]->shared_tensor()); } vector<vector<Blob*> >{ tmp } >> *loader.createAny<Vectorize<Copy> >("copy", vector<Copy::param_tuple>(num_param, Copy::param_tuple())) >> vector<vector<Blob*> >{ weights }; if (current_rank() == 0) { LOG(INFO) << "Loading snapshot " << filename; ifstream in(filename, ios::binary); stringstream ss; ss << in.rdbuf(); const string& raw = ss.str(); int total_len = 0; for (Blob* b : tmp) { total_len += b->tensor()->size().count() * sizeof(DTYPE); } CHECK_EQ(raw.length(), total_len) << "Snapshot size incompatible with network weight"; int offset = 0; for (Blob* b : tmp) { int len = b->tensor()->size().count() * sizeof(DTYPE); memcpy(b->tensor()->mutable_cpu_data(), raw.c_str() + offset, len); offset += len; } } loader.run(); MPI_LOG( << "Snapshot loaded" ); } } #endif
29.147059
78
0.606458
[ "vector", "transform" ]
06d743df20a1807a753aa73e2c1d4a3f23a2b8d6
11,675
cc
C++
media/gpu/ipc/service/picture_buffer_manager.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
media/gpu/ipc/service/picture_buffer_manager.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
media/gpu/ipc/service/picture_buffer_manager.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/gpu/ipc/service/picture_buffer_manager.h" #include <map> #include <set> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/synchronization/lock.h" #include "gpu/command_buffer/common/mailbox_holder.h" namespace media { namespace { // Generates nonnegative picture buffer IDs, which are assumed to be unique. int32_t NextID(int32_t* counter) { int32_t value = *counter; *counter = (*counter + 1) & 0x3FFFFFFF; return value; } class PictureBufferManagerImpl : public PictureBufferManager { public: explicit PictureBufferManagerImpl( ReusePictureBufferCB reuse_picture_buffer_cb) : reuse_picture_buffer_cb_(std::move(reuse_picture_buffer_cb)) { DVLOG(1) << __func__; } void Initialize( scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, scoped_refptr<CommandBufferHelper> command_buffer_helper) override { DVLOG(1) << __func__; DCHECK(!gpu_task_runner_); gpu_task_runner_ = std::move(gpu_task_runner); command_buffer_helper_ = std::move(command_buffer_helper); } bool CanReadWithoutStalling() override { DVLOG(3) << __func__; base::AutoLock lock(picture_buffers_lock_); // If there are no assigned picture buffers, predict that the VDA will // request some. if (picture_buffers_.empty()) return true; // Predict that the VDA can output a picture if at least one picture buffer // is not in use as an output. for (const auto& it : picture_buffers_) { if (it.second.state != PictureBufferState::OUTPUT) return true; } return false; } std::vector<PictureBuffer> CreatePictureBuffers( uint32_t count, VideoPixelFormat pixel_format, uint32_t planes, gfx::Size texture_size, uint32_t texture_target) override { DVLOG(2) << __func__; DCHECK(gpu_task_runner_); DCHECK(gpu_task_runner_->BelongsToCurrentThread()); DCHECK(count); DCHECK(planes); DCHECK_LE(planes, static_cast<uint32_t>(VideoFrame::kMaxPlanes)); // TODO(sandersd): Consider requiring that CreatePictureBuffers() is called // with the context current. if (!command_buffer_helper_->MakeContextCurrent()) { DVLOG(1) << "Failed to make context current"; return std::vector<PictureBuffer>(); } std::vector<PictureBuffer> picture_buffers; for (uint32_t i = 0; i < count; i++) { PictureBuffer::TextureIds service_ids; PictureBufferData picture_data = {PictureBufferState::AVAILABLE, pixel_format, texture_size}; for (uint32_t j = 0; j < planes; j++) { // Create a texture for this plane. GLuint service_id = command_buffer_helper_->CreateTexture( texture_target, GL_RGBA, texture_size.width(), texture_size.height(), GL_RGBA, GL_UNSIGNED_BYTE); DCHECK(service_id); service_ids.push_back(service_id); // The texture is not cleared yet, but it will be before the VDA outputs // it. Rather than requiring output to happen on the GPU thread, mark // the texture as cleared immediately. command_buffer_helper_->SetCleared(service_id); // Generate a mailbox while we are still on the GPU thread. picture_data.mailbox_holders[j] = gpu::MailboxHolder( command_buffer_helper_->CreateMailbox(service_id), gpu::SyncToken(), texture_target); } // Generate a picture buffer ID and record the picture buffer. int32_t picture_buffer_id = NextID(&picture_buffer_id_); { base::AutoLock lock(picture_buffers_lock_); DCHECK(!picture_buffers_.count(picture_buffer_id)); picture_buffers_[picture_buffer_id] = picture_data; } // Since our textures have no client IDs, we reuse the service IDs as // convenient unique identifiers. // // TODO(sandersd): Refactor the bind image callback to use service IDs so // that we can get rid of the client IDs altogether. picture_buffers.emplace_back(picture_buffer_id, texture_size, service_ids, service_ids, texture_target, pixel_format); // Record the textures used by the picture buffer. picture_buffer_textures_[picture_buffer_id] = std::move(service_ids); } return picture_buffers; } bool DismissPictureBuffer(int32_t picture_buffer_id) override { DVLOG(2) << __func__ << "(" << picture_buffer_id << ")"; DCHECK(gpu_task_runner_); DCHECK(gpu_task_runner_->BelongsToCurrentThread()); base::AutoLock lock(picture_buffers_lock_); // Check the state of the picture buffer. const auto& it = picture_buffers_.find(picture_buffer_id); if (it == picture_buffers_.end()) { DVLOG(1) << "Unknown picture buffer " << picture_buffer_id; return false; } bool is_available = it->second.state == PictureBufferState::AVAILABLE; // Destroy the picture buffer data. picture_buffers_.erase(it); // If the picture was available, we can destroy its textures immediately. if (is_available) { gpu_task_runner_->PostTask( FROM_HERE, base::BindOnce( &PictureBufferManagerImpl::DestroyPictureBufferTextures, this, picture_buffer_id)); } return true; } scoped_refptr<VideoFrame> CreateVideoFrame(Picture picture, base::TimeDelta timestamp, gfx::Rect visible_rect, gfx::Size natural_size) override { DVLOG(2) << __func__ << "(" << picture.picture_buffer_id() << ")"; DCHECK(!picture.size_changed()); DCHECK(!picture.texture_owner()); DCHECK(!picture.wants_promotion_hint()); base::AutoLock lock(picture_buffers_lock_); int32_t picture_buffer_id = picture.picture_buffer_id(); // Verify that the picture buffer is available. const auto& it = picture_buffers_.find(picture_buffer_id); if (it == picture_buffers_.end()) { DVLOG(1) << "Unknown picture buffer " << picture_buffer_id; return nullptr; } PictureBufferData& picture_buffer_data = it->second; if (picture_buffer_data.state != PictureBufferState::AVAILABLE) { DLOG(ERROR) << "Picture buffer " << picture_buffer_id << " is not available"; return nullptr; } // Verify that the picture buffer is large enough. if (!gfx::Rect(picture_buffer_data.texture_size).Contains(visible_rect)) { DLOG(ERROR) << "visible_rect " << visible_rect.ToString() << " exceeds coded_size " << picture_buffer_data.texture_size.ToString(); return nullptr; } // Mark the picture as an output. picture_buffer_data.state = PictureBufferState::OUTPUT; // Create and return a VideoFrame for the picture buffer. scoped_refptr<VideoFrame> frame = VideoFrame::WrapNativeTextures( picture_buffer_data.pixel_format, picture_buffer_data.mailbox_holders, base::BindRepeating(&PictureBufferManagerImpl::OnVideoFrameDestroyed, this, picture_buffer_id), picture_buffer_data.texture_size, visible_rect, natural_size, timestamp); frame->set_color_space(picture.color_space()); if (picture.allow_overlay()) frame->metadata()->SetBoolean(VideoFrameMetadata::ALLOW_OVERLAY, true); // TODO(sandersd): Provide an API for VDAs to control this. frame->metadata()->SetBoolean(VideoFrameMetadata::POWER_EFFICIENT, true); return frame; } private: ~PictureBufferManagerImpl() override { DVLOG(1) << __func__; } void OnVideoFrameDestroyed(int32_t picture_buffer_id, const gpu::SyncToken& sync_token) { DVLOG(3) << __func__ << "(" << picture_buffer_id << ")"; base::AutoLock lock(picture_buffers_lock_); // If the picture buffer is still assigned, mark it as unreleased. const auto& it = picture_buffers_.find(picture_buffer_id); if (it != picture_buffers_.end()) { DCHECK_EQ(it->second.state, PictureBufferState::OUTPUT); it->second.state = PictureBufferState::WAITING_FOR_SYNCTOKEN; } // Wait for the SyncToken release. gpu_task_runner_->PostTask( FROM_HERE, base::BindOnce( &CommandBufferHelper::WaitForSyncToken, command_buffer_helper_, sync_token, base::BindOnce(&PictureBufferManagerImpl::OnSyncTokenReleased, this, picture_buffer_id))); } void OnSyncTokenReleased(int32_t picture_buffer_id) { DVLOG(3) << __func__ << "(" << picture_buffer_id << ")"; DCHECK(gpu_task_runner_); DCHECK(gpu_task_runner_->BelongsToCurrentThread()); // If the picture buffer is still assigned, mark it as available. bool is_assigned = false; { base::AutoLock lock(picture_buffers_lock_); const auto& it = picture_buffers_.find(picture_buffer_id); if (it != picture_buffers_.end()) { DCHECK_EQ(it->second.state, PictureBufferState::WAITING_FOR_SYNCTOKEN); it->second.state = PictureBufferState::AVAILABLE; is_assigned = true; } } // If the picture buffer is still assigned, it is ready to be reused. // Otherwise it has been dismissed and we can now delete its textures. // Neither of these operations should be done while holding the lock. if (is_assigned) { reuse_picture_buffer_cb_.Run(picture_buffer_id); } else { DestroyPictureBufferTextures(picture_buffer_id); } } void DestroyPictureBufferTextures(int32_t picture_buffer_id) { DVLOG(3) << __func__ << "(" << picture_buffer_id << ")"; DCHECK(gpu_task_runner_); DCHECK(gpu_task_runner_->BelongsToCurrentThread()); if (!command_buffer_helper_->MakeContextCurrent()) return; const auto& it = picture_buffer_textures_.find(picture_buffer_id); DCHECK(it != picture_buffer_textures_.end()); for (GLuint service_id : it->second) command_buffer_helper_->DestroyTexture(service_id); picture_buffer_textures_.erase(it); } ReusePictureBufferCB reuse_picture_buffer_cb_; scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_; scoped_refptr<CommandBufferHelper> command_buffer_helper_; int32_t picture_buffer_id_ = 0; // Includes picture puffers that have been dismissed if their textures have // not been deleted yet. std::map<int32_t, std::vector<GLuint>> picture_buffer_textures_; base::Lock picture_buffers_lock_; enum class PictureBufferState { // Available for use by the VDA. AVAILABLE, // Output by the VDA, still bound to a VideoFrame. OUTPUT, // Waiting on a SyncToken before being reused. WAITING_FOR_SYNCTOKEN, }; struct PictureBufferData { PictureBufferState state; VideoPixelFormat pixel_format; gfx::Size texture_size; gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes]; }; // Pictures buffers that are assigned to the VDA. std::map<int32_t, PictureBufferData> picture_buffers_; DISALLOW_COPY_AND_ASSIGN(PictureBufferManagerImpl); }; } // namespace // static scoped_refptr<PictureBufferManager> PictureBufferManager::Create( ReusePictureBufferCB reuse_picture_buffer_cb) { return base::MakeRefCounted<PictureBufferManagerImpl>( std::move(reuse_picture_buffer_cb)); } } // namespace media
35.378788
80
0.685824
[ "vector" ]
06db1950339410af32731a681c028012767ce9dd
3,609
cpp
C++
ds/security/ssr/te/ssrcore.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/ssr/te/ssrcore.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/ssr/te/ssrcore.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// SsrCore.cpp : Implementation of CSsrCore #include "stdafx.h" #include "SSRTE.h" #include "ActionData.h" #include "SSRTEngine.h" #include "SsrCore.h" #include "SSRLog.h" #include "global.h" #include "util.h" //------------------------------------------------------------------------------- // ISsrCore implementation //------------------------------------------------------------------------------- /* Routine Description: Name: CSsrCore::CSsrCore Functionality: constructor Virtual: no. Arguments: none. Return Value: none. Notes: */ CSsrCore::CSsrCore() : m_pEngine(NULL) { if (SUCCEEDED(CComObject<CSsrEngine>::CreateInstance(&m_pEngine))) { m_pEngine->AddRef(); } } /* Routine Description: Name: CSsrCore::~CSsrCore Functionality: destructor Virtual: yes. Arguments: none. Return Value: none. Notes: */ CSsrCore::~CSsrCore() { if (m_pEngine != NULL) { m_pEngine->Release(); } } /* Routine Description: Name: CSsrCore::get_ActionData Functionality: It returns the engine's action data object (the property bag) which holds all runtime and static data needed to carry out the action. Virtual: Yes. Arguments: pVal - out parameter receives the ISsrActionData object of the engine. Return Value: Success: S_OK Failure: various error codes. Notes: */ STDMETHODIMP CSsrCore::get_ActionData ( OUT VARIANT * pVal // [out, retval] ) { HRESULT hr = E_NOTIMPL; if (pVal == NULL) { hr = E_INVALIDARG; } ::VariantInit(pVal); if (m_pEngine != NULL) { pVal->vt = VT_DISPATCH; hr = m_pEngine->GetActionData((ISsrActionData **)&(pVal->pdispVal)); if (hr != S_OK) { pVal->vt = VT_EMPTY; } } else { hr = E_SSR_ENGINE_NOT_AVAILABLE; } return hr; } /* Routine Description: Name: CSsrCore::get_Engine Functionality: It returns the engine itself. Virtual: Yes. Arguments: pVal - out parameter receives the ISsrEngine object. Return Value: Success: S_OK Failure: various error codes. Notes: */ STDMETHODIMP CSsrCore::get_Engine ( OUT VARIANT * pVal // [out, retval] ) { HRESULT hr = S_OK; if (pVal == NULL) { hr = E_INVALIDARG; } ::VariantInit(pVal); if (m_pEngine != NULL) { pVal->vt = VT_DISPATCH; hr = m_pEngine->QueryInterface(IID_ISsrEngine, (LPVOID*)&(pVal->pdispVal)); if (hr != S_OK) { pVal->vt = VT_EMPTY; hr = E_SSR_ENGINE_NOT_SUPPORT_INTERFACE; } } else { hr = E_SSR_ENGINE_NOT_AVAILABLE; } return hr; } /* Routine Description: Name: CSsrCore::get_SsrLog Functionality: It returns the engine's logging object. Virtual: Yes. Arguments: pVal - out parameter receives the ISsrPreProcessor object. Return Value: Success: S_OK Failure: various error codes. Notes: */ STDMETHODIMP CSsrCore::get_SsrLog ( OUT VARIANT * pVal // [out, retval] ) { return g_fblog.GetLogObject(pVal); }
13.366667
84
0.511222
[ "object" ]
06f2dd80349f298755d7adb03f5c2a85415c40ba
1,387
cpp
C++
0617-Maximum Average Subarray/0617-Maximum Average Subarray.cpp
lightwindy/LintCode-1
316fa395c9a6de9bfac1d9c9cf58acb5ffb384a6
[ "MIT" ]
77
2017-12-30T13:33:37.000Z
2022-01-16T23:47:08.000Z
0601-0700/0617-Maximum Average Subarray/0617-Maximum Average Subarray.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
1
2018-05-14T14:15:40.000Z
2018-05-14T14:15:40.000Z
0601-0700/0617-Maximum Average Subarray/0617-Maximum Average Subarray.cpp
jxhangithub/LintCode-1
a8aecc65c47a944e9debad1971a7bc6b8776e48b
[ "MIT" ]
39
2017-12-07T14:36:25.000Z
2022-03-10T23:05:37.000Z
class Solution { public: /** * @param nums an array with positive and negative numbers * @param k an integer * @return the maximum average */ double maxAverage(vector<int>& nums, int k) { // Write your code here int minNum = INT_MAX, maxNum = INT_MIN; for (int num : nums) { minNum = min(minNum, num); maxNum = max(maxNum, num); } double start = minNum, end = maxNum; while (end - start > 1e-5) { double mid = (start + end) / 2; if (available(nums, mid, k)) { start = mid; } else { end = mid; } } return start; } private: bool available(vector<int>& nums, double candidate, int k) { int n = nums.size(); double sum = 0; for (int i = 0; i < k; ++i) { sum += nums[i] - candidate; } if (sum >= 0) { return true; } double presum = 0; double premin = 0; for (int i = k; i < nums.size(); ++i) { sum += nums[i] - candidate; presum += nums[i - k] - candidate; premin = min(premin, presum); if (sum - premin >= 0) { return true; } } return false; } };
25.685185
64
0.427541
[ "vector" ]
06f44b3747d5fec719968f8d7c7997e5b0b4f8f4
42,004
cpp
C++
Code/C++_OpenCV_Projeto_TCII/main.cpp
aabling2/projeto_tcc_2017
d276ddb40c49eb75271977953502d3a08e4f4fe5
[ "MIT" ]
null
null
null
Code/C++_OpenCV_Projeto_TCII/main.cpp
aabling2/projeto_tcc_2017
d276ddb40c49eb75271977953502d3a08e4f4fe5
[ "MIT" ]
null
null
null
Code/C++_OpenCV_Projeto_TCII/main.cpp
aabling2/projeto_tcc_2017
d276ddb40c49eb75271977953502d3a08e4f4fe5
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Term Paper - Electrical Engineering - UNISC //Start date: 27/09/2016 //By: Augusto Abling //Description: This program was designed for a computer vision system that inspects some parts (Dolce Gusto capsules specifically) // on the first camera, identifies some features to compare with a standard database, and if they are okay or not, keep tracking // the parts on the second camera. // Features to compare: Size and color. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///LIBRARIES #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include <opencv2/objdetect.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/features2d.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <iostream> #include <stdlib.h> #include <conio.h> #include <time.h> #include <dirent.h> #include <sstream> #include <windows.h> ///DEFINITIONS #define pi 3.14159 #define screen1 "Imagem Webcam 1" #define screen2 "Imagem Processada 1" #define screen3 "Imagem Webcam 2" #define screen4 "Imagem Processada 2" #define screen5 "Limiar RGB" #define num_max_parts 10 //Maximum number of parts to register in image #define num_max_default 5 //Maximum number of standard parts #define num_inspections 1 //Times to do the inspections #define size_part 53 //Real diameter of the part(millimeters) #define mask_angle 73.5 //Angle to make the lines in camera2 to align the conveyor #define offset_line 26 //Offset from the side of the image (pixels) #define width_conveyor 297 //Width of the conveyor to use on reading at second camera (millimeters) #define length_conveyor 510 //Length of the conveyor to use on reading at second camera (millimeters) #define dist_ref 420 //Distance between camera2 and end of length conveyor (millimeters) #define dist_h 360 //Height distance between camera2 and conveyor (millimeters) #define f_correct 1.0 //Correction factor to apply at the distance between camera2 and object #define h_correct 35 //Height of the object to correct distance using namespace cv; using namespace std; ///FUNCTIONS void LoadDataTxt(); void SaveDataTxt(); void SnapDefault(Mat imgPart, int num_obj); void LoadDefault(); void CleanDefault(); Scalar ImgAvgColor(Mat imgPart); Scalar CheckColors(Mat imgPart); ///VARIABLES int key; int thresh1, thresh2, thresh3; int Bmin, Gmin, Rmin, Bmax, Gmax, Rmax; Mat img1, img1Gray, img1Proc, imgLoad, img1Capture, img1Backg, img1Foreg, img2, img2Gray, img2Proc, img2Mask, img2Capture, img2Backg, img2Foreg, img2Segm; double cont_time_fps, avg_fps; int cont_frames, press_times; char screen_fps[10], screen_obj[15],label_part_def[num_max_default][15]; string label_part; int cont_parts1, cont_parts2, cont_good_parts, cont_bad_parts, cont_nodef_parts, acumul_parts2; int num_part[num_max_parts], num_part2[num_max_parts]; int init_part, limit_part, init_part2, limit_part2; Scalar color_def[num_max_default], color_part, color_result, color_size; float ratio_part; //Ratio between image and part radius bool first_check = 0; bool key_pause = false; ///CLASS class Parts{ public: int num_inspec[num_max_parts]; Scalar color[num_max_parts]; Point last_center[num_max_parts][50]; Point last_center2[num_max_parts][50]; float Size[num_max_parts]; string screen_defect[num_max_parts]; string screen_label[num_max_parts]; Point coord2[num_max_parts]; }; ///MAIN PROGRAM int main(){ while(key != 27){ system("cls"); cout <<"Image processing started."<< endl <<endl; //Start class Parts Parts parts; mkdir("photo_parts"); press_times = 0; ratio_part = 0; cont_parts1 = 0; cont_parts2 = 0; cont_nodef_parts = 0; cont_bad_parts = 0; cont_good_parts = 0; acumul_parts2 = 0; //Fill the vectors for(int k=0; k<num_max_parts; k++){ num_part[k] = k; num_part2[k] = k; parts.num_inspec[k] = NULL; } ///Capture from web camera //VideoCapture cap1(0); //Camera 1 //VideoCapture cap2(2); //Camera 2 VideoCapture cap1("Cam1_video.avi"); //Capture image from video recorded VideoCapture cap2("Cam2_video.avi"); //Capture image from video recorded if(!cap1.isOpened() || !cap2.isOpened()){ cout<<"Camera is not connected!" <<endl; break; } cap1 >> img1; cout<<"Image Size: " <<img1.cols <<"x" <<img1.rows <<endl; //Create windows namedWindow(screen2, WINDOW_AUTOSIZE); namedWindow(screen4, WINDOW_AUTOSIZE); namedWindow(screen1, WINDOW_AUTOSIZE); namedWindow(screen3, WINDOW_AUTOSIZE); //namedWindow(screen5, WINDOW_FREERATIO); //Load images of part default and get the average color LoadDefault(); //Read data and create TrackBar to RGB features LoadDataTxt(); //Variables of limit lines for camera 2 Point ang_line_tl, ang_line_bl, ang_line_tr, ang_line_br, limit_line_tl, limit_line_tr, limit_line_bl, limit_line_br; ang_line_tl.x = (img1.rows/tan(mask_angle*pi/180)) + offset_line; ang_line_tl.y = 0; ang_line_bl.x= offset_line; ang_line_bl.y = img1.rows; ang_line_tr.x = img1.cols - (img1.rows/tan(mask_angle*pi/180)) - offset_line; ang_line_tr.y = 0; ang_line_br.x = img1.cols - offset_line; ang_line_br.y = img1.rows; limit_line_tl.x = (img1.rows/tan(mask_angle*pi/180)) + offset_line; limit_line_tl.y = 20; limit_line_tr.x = img1.cols - (img1.rows/tan(mask_angle*pi/180)) - offset_line; limit_line_tr.y = 20; limit_line_bl.x = offset_line; limit_line_bl.y = img1.rows; limit_line_br.x = img1.cols - offset_line; limit_line_br.y = img1.rows; ///Create and apply mask (limit angle) at image 2 img2Mask = Mat::zeros(img1.size(), CV_8U); for(int i=limit_line_tl.y; i<limit_line_bl.y; i++){ float x1, x2; x1 = (img2Mask.rows - i)/tan(mask_angle*pi/180); x2 = img2Mask.cols - x1; line(img2Mask, Point2f(x1+offset_line, i), Point2f(x2-offset_line, i), Scalar(255,0,0), 1, 8, 0); } for (;;){ //- CAMERA 1 -//////////////////////////////////////////////////////////////////////////////////////////////////////////// //Get time to FPS double time_fps = (double)getTickCount(); ///IMAGE ACQUISITION if(key_pause == false){ //Image from camera to Mat cap1 >> img1; img1.copyTo(img1Capture); } else{ img1Capture.copyTo(img1); } //Frame empty at the end of the video if (img1.empty()){ SaveDataTxt(); cap1.release(); cap2.release(); destroyAllWindows(); cout <<endl <<"End of image processing."<< endl; return 0; } /* //Resize image for better frame resize(img1, img1, Size(640,480), 0, 0, INTER_CUBIC); */ //Get first image to the background image if(first_check!=1){ //cap1 >> img1Backg; img1Backg = imread("photo_parts/Img1Background.jpg"); } ///PRE-PROCESSING //Do a simple background subtraction absdiff(img1, img1Backg, img1Foreg); ///Convert image type // cvtColor(img1, img1Gray, COLOR_RGB2GRAY, 1); ///Low-pass filters //blur(img1Gray, img1Proc, Size(7,7)); //medianBlur(img1Gray, img1Proc, 9); GaussianBlur(img1Foreg, img1Proc, Size(7,7), 0, 0, BORDER_DEFAULT); //bilateralFilter(img1Gray, img1Proc, 9, 20, 20); ///SEGMENTATION //THRESHOLD //Apply threshold Mat img1Segm; // threshold(img1Proc, img1Segm, thresh1, 255, CV_THRESH_BINARY_INV); //THRESHOLD BY COLOR inRange(img1Proc, Scalar(0, 45, 0), Scalar(255, 255, 255), img1Segm); inRange(img1Proc, Scalar(54, 0, 0), Scalar(177, 26, 86), img1Proc); //inRange(img1Proc, Scalar(Bmin, Gmin, Rmin), Scalar(Bmax, Gmax, Rmax), img1Proc); //imshow(screen2, img1Proc); add(img1Segm, img1Proc, img1Segm); //DILATION AND EROSION //Apply opening that is erosion followed by dilation to to remove noise morphologyEx(img1Segm, img1Segm, MORPH_OPEN, Mat(), Point(-1,-1), 1, BORDER_DEFAULT); //Apply closing that is dilation followed by erosion to fill the holes morphologyEx(img1Segm, img1Segm, MORPH_CLOSE, Mat(), Point(-1,-1), 7, BORDER_DEFAULT); //dilate(img1Segm, img1Segm, Mat(), Point(-1,-1), 2, BORDER_DEFAULT); erode(img1Segm, img1Segm, Mat(), Point(-1,-1), 3, BORDER_DEFAULT); imshow(screen2, img1Segm); ///RECOGNITION AND INTERPRETATION //POLYGONAL APPROXIMATION vector<Rect> boundRect( num_max_parts ); vector<vector<Point> > contours; vector<Vec4i> hierarchy; vector<vector<Point> > contours_poly( num_max_parts ); vector<Point2f> center( num_max_parts ); vector<float> radius( num_max_parts ); //Find contours findContours(img1Segm, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); if(first_check != 0){ for(int i=0; i<contours.size(); i++ ){ //Approximate contours to polygons + get bounding rects + center approxPolyDP( Mat(contours[i]), contours_poly[num_part[i]], 3, true ); boundRect[num_part[i]] = boundingRect( Mat(contours_poly[num_part[i]]) ); minEnclosingCircle( (Mat)contours_poly[num_part[i]], center[num_part[i]], radius[num_part[i]] ); //Get the right number of the parts if(contours.size()<limit_part){ //Save which is the first position init_part = num_part[0]; //Move positions and your data for(int k=0; k<(num_max_parts-1); k++){ num_part[k] = num_part[k+1]; parts.color[num_part[k]] = parts.color[num_part[k+1]]; parts.Size[num_part[k]] = parts.Size[num_part[k+1]]; parts.num_inspec[num_part[k]] = parts.num_inspec[num_part[k+1]]; parts.screen_defect[num_part[k]] = parts.screen_defect[num_part[k+1]]; parts.screen_label[num_part[k]] = parts.screen_label[num_part[k+1]]; for(int h=19; h>=0; h--){ parts.last_center[num_part[k]][h] = parts.last_center[num_part[k+1]][h]; } } //Define the first position to the last and clean data of vectors num_part[num_max_parts-1] = init_part; parts.color[num_part[contours.size()]] = NULL; parts.Size[num_part[contours.size()]] = NULL; parts.num_inspec[num_part[contours.size()]] = NULL; parts.screen_defect[num_part[contours.size()]] = '\0'; parts.screen_label[num_part[contours.size()]] = '\0'; for(int h=19; h>=0; h--){ parts.last_center[num_part[contours.size()]][h] = Point(0,0); } } limit_part = contours.size(); //Inspection of the parts if(boundRect[num_part[i]].tl().y > 10 && boundRect[num_part[i]].br().y < (img1.rows - 10) && parts.num_inspec[num_part[i]] < num_inspections){ //Verify the scale if is ok if((radius[num_part[i]]<(size_part/ratio_part)-3) || (radius[num_part[i]]>(size_part/ratio_part)+3)){ color_size = Scalar(0,0,255); } else{ color_size = Scalar(0,255,0); } //Verify the color //Pick a rect from the part Mat imgRect(img1, Rect(boundRect[num_part[i]].tl(), boundRect[num_part[i]].br())); //Get the average color of the part color_part = ImgAvgColor(imgRect); //Compare color of the part with the default color_result = CheckColors(imgRect); //Compare results if(color_size == Scalar(0,255,0) && color_result == Scalar(0,255,0)){ parts.screen_defect[num_part[i]] = "OK"; parts.screen_label[num_part[i]] = label_part; parts.Size[num_part[i]] = radius[num_part[i]]*ratio_part; parts.color[num_part[i]] = Scalar(0,255,0); cont_good_parts++; cont_parts1++; } else if(color_size == Scalar(0,0,255) && color_result == Scalar(0,255,0)) { parts.screen_defect[num_part[i]] = "Size"; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,255); cont_bad_parts++; cont_parts1++; } else if(color_size == Scalar(0,255,0) && color_result == Scalar(0,0,255)) { parts.screen_defect[num_part[i]] = "Color"; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,255); cont_bad_parts++; cont_parts1++; } else if(color_size == Scalar(0,0,255) && color_result == Scalar(0,0,255)) { parts.screen_defect[num_part[i]] = "Size/Color"; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,255); cont_bad_parts++; cont_parts1++; } else if(color_size == Scalar(0,0,255) && color_result == Scalar(0,0,0)) { parts.screen_defect[num_part[i]] = "Size/No ref."; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,255); cont_bad_parts++; cont_parts1++; } else if(color_size == Scalar(0,255,0) && color_result == Scalar(0,0,0)) { parts.screen_defect[num_part[i]] = "No ref."; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,0); cont_nodef_parts++; cont_parts1++; } parts.num_inspec[num_part[i]]++; //Save scale of the part parts.Size[num_part[i]] = radius[num_part[i]]*ratio_part; } else if(parts.num_inspec[num_part[i]] == 0 && boundRect[num_part[i]].br().y > (img1.rows - 10)){ parts.screen_defect[num_part[i]] = "No def."; parts.screen_label[num_part[i]] = "?"; parts.color[num_part[i]] = Scalar(0,0,0); cont_nodef_parts++; parts.num_inspec[num_part[i]]++; cont_parts1++; } else if(parts.num_inspec[num_part[i]] == num_inspections){ parts.num_inspec[num_part[i]]++; } //Take picture from the part if(key == ' ' && boundRect[num_part[i]].tl().y > 10 && center[num_part[i]].y < (img1.rows-10)){ Mat imgRect(img1, Rect(boundRect[num_part[i]].tl(), boundRect[num_part[i]].br())); SnapDefault(imgRect, contours.size()); } //Save last center of objects to get trajectory if(boundRect[num_part[i]].tl().y > 10){ for(int j=19; j>=0; j--){ //Draw trajectory //drawMarker(img1, parts.last_center[num_part[i]][j], parts.color[num_part[i]], MARKER_CROSS, 5, 1, 8); if(j!=0) parts.last_center[num_part[i]][j] = parts.last_center[num_part[i]][j-1]; else parts.last_center[num_part[i]][j] = center[num_part[i]]; } } //Define boundRect with the size of the inspection if(parts.Size[num_part[i]] != NULL && parts.Size[num_part[i]] > (size_part - 20)){ boundRect[num_part[i]].y = center[num_part[i]].y - (parts.Size[num_part[i]]/ratio_part); boundRect[num_part[i]].x = center[num_part[i]].x - (parts.Size[num_part[i]]/ratio_part); boundRect[num_part[i]].height = 2 * parts.Size[num_part[i]]/ratio_part; boundRect[num_part[i]].width = 2 * parts.Size[num_part[i]]/ratio_part; } ///PARTS RESULTS if(boundRect[num_part[i]].tl().y > 10 && center[num_part[i]].y < (img1.rows-10)){ //Draw rectangles and center points rectangle(img1, boundRect[num_part[i]].tl(), boundRect[num_part[i]].br(), parts.color[num_part[i]], 1, 8, 0 ); drawMarker(img1, center[num_part[i]], parts.color[num_part[i]], MARKER_CROSS, radius[num_part[i]]/2, 1, 8); //Draw object number if(cont_parts1>0){ sprintf(screen_obj, "%d", num_part[i]+1); putText(img1, screen_obj, center[num_part[i]], FONT_HERSHEY_PLAIN, 2, parts.color[num_part[i]], 2, 8); } //Draw Result putText(img1, parts.screen_defect[num_part[i]], Point(boundRect[num_part[i]].tl().x, boundRect[num_part[i]].br().y) , FONT_HERSHEY_PLAIN, 1, parts.color[num_part[i]], 1, 8); putText(img1, parts.screen_label[num_part[i]], Point(boundRect[num_part[i]].tl().x, boundRect[num_part[i]].tl().y+12) , FONT_HERSHEY_PLAIN, 1, 0, 1, 8); //Draw Size at the part if(parts.Size[num_part[i]] != NULL){ sprintf(screen_obj, "Size: %.fmm", (parts.Size[num_part[i]])); //sprintf(screen_obj, "Size: %.fmm", (radius[num_part[i]]*ratio_part)); } else{ sprintf(screen_obj, "Size: %.fmm", (radius[num_part[i]]*ratio_part)); } putText(img1, screen_obj, Point2f(boundRect[num_part[i]].tl().x, boundRect[num_part[i]].tl().y - 2) , FONT_HERSHEY_PLAIN, 0.7, Scalar(0,0,0), 1, 8); //Draw Coordinates at the part sprintf(screen_obj, "X:%.f Y:%.f", (center[num_part[i]].x*ratio_part/2), (center[num_part[i]].y*ratio_part/2)); putText(img1, screen_obj, Point2f(boundRect[num_part[i]].tl().x, boundRect[num_part[i]].tl().y + (radius[num_part[i]]*2) + 8) , FONT_HERSHEY_PLAIN, 0.7, Scalar(0,0,0), 1, 8); } } } //- CAMERA 2 -//////////////////////////////////////////////////////////////////////////////////////////////////////////// ///IMAGE ACQUISITION if(key_pause == false){ //Image from camera to Mat cap2 >> img2; img2.copyTo(img2Capture); } else{ img2Capture.copyTo(img2); } //Frame empty at the end of the video if (img2.empty()){ SaveDataTxt(); cap1.release(); cap2.release(); destroyAllWindows(); cout <<endl <<"End of image processing."<< endl; return 0; } //Get first image to the background image if(first_check!=1){ cap2 >> img2Backg; //img2Backg = imread("photo_parts/img2Background.jpg"); } ///PRE-PROCESSING //Do a simple background subtraction absdiff(img2, img2Backg, img2Foreg); //Add the mask of limits img2Foreg.copyTo(img2Proc, img2Mask); //Low-pass filter GaussianBlur(img2Proc, img2Proc, Size(5,5), 0, 0, BORDER_DEFAULT); ///SEGMENTATION //THRESHOLD BY COLOR inRange(img2Proc, Scalar(0, 83, 0), Scalar(255, 150, 95), img2Segm); //inRange(img2Proc, Scalar(Bmin, Gmin, Rmin), Scalar(Bmax, Gmax, Rmax), img2Segm); inRange(img2Proc, Scalar(83, 0, 0), Scalar(255, 46, 75), img2Proc); //inRange(img2Proc, Scalar(Bmin, Gmin, Rmin), Scalar(Bmax, Gmax, Rmax), img2Proc); //Add first image thresholded to second add(img2Segm, img2Proc, img2Segm); imshow(screen4, img2Segm); //DILATION AND EROSION //Apply opening that is erosion followed by dilation to to remove noise morphologyEx(img2Segm, img2Segm, MORPH_OPEN, Mat(), Point(-1,-1), 2, BORDER_DEFAULT); //Apply closing that is dilation followed by erosion to fill the holes morphologyEx(img2Segm, img2Segm, MORPH_CLOSE, Mat(), Point(-1,-1), 7, BORDER_DEFAULT); dilate(img2Segm, img2Segm, Mat(), Point(-1,-1), 2, BORDER_DEFAULT); ///RECOGNITION AND INTERPRETATION //Find contours vector<vector<Point> > contours2; vector<Vec4i> hierarchy2; vector<vector<Point> > contours_poly2( num_max_parts ); vector<Rect> boundRect2( num_max_parts ); vector<Point2f>center2( num_max_parts ); vector<float>radius2( num_max_parts ); findContours(img2Segm, contours2, hierarchy2, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); //Fill the vectors in order of the parts at the conveyor if(first_check == 0){ for(int k=0; k<num_max_parts; k++){ if(contours2.size() < num_max_parts) num_part[k] = contours2.size()+ k; else num_part[k] = (contours2.size() + k) - (num_max_parts-1); } first_check = 1; } for(int i=0; i<contours2.size(); i++ ){ //Approximate contours to polygons + get bounding rects + center approxPolyDP( Mat(contours2[i]), contours_poly2[num_part2[i]], 3, true ); boundRect2[num_part2[i]] = boundingRect( Mat(contours_poly2[num_part2[i]]) ); minEnclosingCircle( (Mat)contours_poly2[num_part2[i]], center2[num_part2[i]], radius2[num_part2[i]] ); //Get the right number of the parts if(contours2.size()<limit_part2){ //Save which is the first position init_part2 = num_part2[0]; if(parts.last_center2[num_part2[i]][0].y > (img2.rows)){ //Move positions and your data for(int k=0; k<(num_max_parts-1); k++){ num_part2[k] = num_part2[k+1]; parts.color[num_part2[k]] = parts.color[num_part2[k+1]]; for(int h=19; h>=0; h--){ parts.last_center2[num_part2[k]][h] = parts.last_center2[num_part2[k+1]][h]; } } //Define the first position to the last and clean data of vectors num_part2[num_max_parts-1] = init_part2; for(int h=19; h>=0; h--){ parts.last_center2[num_part2[num_max_parts-1]][h] = Point(0,0); } } } limit_part2 = contours2.size(); if(boundRect2[num_part2[i]].tl().y > limit_line_tl.y && center2[num_part2[i]].y < limit_line_bl.y){ if(num_part2[contours2.size()-1] == num_max_parts) acumul_parts2 = num_max_parts; cont_parts2 = acumul_parts2 + num_part2[i]+1; } //Save last center of objects to get trajectory if(boundRect2[num_part2[i]].tl().y > limit_line_tl.y){ for(int j=19; j>=0; j--){ //Draw trajectory //drawMarker(img2, parts.last_center2[num_part2[i]][j], parts.color[num_part2[i]], MARKER_CROSS, 5, 1, 8); if(j!=0) parts.last_center2[num_part2[i]][j] = parts.last_center2[num_part2[i]][j-1]; else parts.last_center2[num_part2[i]][j] = center2[num_part2[i]]; } } //Calculate the real coordinate of the parts in millimeters float x1, x2; x1 = (img2.rows - center2[num_part2[i]].y)/tan(mask_angle*pi/180); x2 = img2.cols - x1; parts.coord2[num_part2[i]].x = ((center2[num_part2[i]].x - (x1 + offset_line)) * width_conveyor) / ((x2-offset_line) - (x1+offset_line)); int pix_h_correct = (h_correct - (h_correct * center2[num_part2[i]].y / img2.rows)) * (((x2-offset_line) - (x1+offset_line)) / width_conveyor); x1 = (img2.rows - ((center2[num_part2[i]].y) + pix_h_correct)) /tan(mask_angle*pi/180); x2 = img2.cols - x1; int dist_a = sqrt(pow(dist_ref, 2) - pow(dist_h, 2)); int dist_focal = (((img2.cols-offset_line)- offset_line) * dist_ref) / width_conveyor; //F = ( P x D ) / W int dist_obj = ((width_conveyor * dist_focal) / ((x2-offset_line) - (x1+offset_line))) / f_correct; //D' = ( W x F ) / P' int dist_b = sqrt(pow(dist_obj, 2) - pow(dist_h, 2)) - dist_a; parts.coord2[num_part2[i]].y = length_conveyor - dist_b + h_correct; //Calculate the scale to use on ellipses float ratio_widht2 = 0.06; float ratio_height2 = 0.04; float ell_width, ell_height; if(parts.Size[num_part2[i]] != NULL){ ell_width = parts.Size[num_part2[i]]/1.9 + (ratio_widht2*center2[num_part2[i]].y); ell_height = parts.Size[num_part2[i]]/4.6 + (ratio_height2*center2[num_part2[i]].y); } else{ ell_width = size_part/1.9 + (ratio_widht2*center2[num_part2[i]].y); ell_height = size_part/4.6 + (ratio_height2*center2[num_part2[i]].y); } ///PARTS RESULTS if(boundRect2[num_part2[i]].tl().y > limit_line_tl.y && center2[num_part2[i]].y < limit_line_bl.y){ //Draw ellipses, rectangles and center points at the part drawMarker(img2, Point(center2[num_part2[i]].x, center2[num_part2[i]].y) , parts.color[num_part2[i]], MARKER_CROSS, radius2[num_part2[i]]/3, 1, 8); //ellipse(img2, center2[num_part2[i]], Size(ell_width, ell_height), 0, 0, 360, parts.color[num_part2[i]], 1, 8); rectangle(img2, boundRect2[num_part2[i]].tl(), boundRect2[num_part2[i]].br(), parts.color[num_part2[i]], 1, 8, 0 ); drawMarker(img2, Point(center2[num_part2[i]].x, center2[num_part2[i]].y + pix_h_correct) , Scalar(255,0,0), MARKER_TRIANGLE_DOWN, radius2[num_part2[i]]/3, 1, 8); //Draw object number if(cont_parts1>0){ sprintf(screen_obj, "%d", num_part2[i]+1); putText(img2, screen_obj, center2[num_part2[i]], FONT_HERSHEY_PLAIN, 1.2, parts.color[num_part2[i]], 2, 8); } //Draw Coordinates of the part sprintf(screen_obj, "P.%d - X:%.f Y:%.f", num_part2[i]+1, (float) parts.coord2[num_part2[i]].x, (float) parts.coord2[num_part2[i]].y); putText(img2, screen_obj, Point2f(10,460 - ((i+1)*15)), FONT_HERSHEY_PLAIN, .7, parts.color[num_part2[i]], 1, 8); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///GENERAL RESULTS ///-Camera 1 //Calculate time to FPS time_fps = ((double)getTickCount() - time_fps) /getTickFrequency();//Elapsed time in ms in a frame cont_time_fps = cont_time_fps + time_fps;//Counter of total elapsed time cont_frames++; if(cont_frames == 20){ avg_fps = cont_frames/cont_time_fps;//n frames/second cont_frames = 0; cont_time_fps = 0; } //Draw FPS sprintf(screen_fps, "FPS: %.lf", avg_fps); putText(img1, screen_fps, Point2f(560,25), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); /* //Draw limits line(img1, Point(10, 10), Point(img1.cols - 10, 10), Scalar(100,100,100), 2, LINE_4, 0); line(img1, Point(10, img1.rows - 10), Point(img1.cols - 10, img1.rows - 10), Scalar(100,100,100), 2, LINE_4, 0); /* //Draw info for shortcuts putText(img1,"Esc - quit", Point2f(10,25), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); putText(img1,"space - snap parts", Point2f(10,40), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); putText(img1,"r - restart", Point2f(10,55), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); putText(img1,"c - clean data", Point2f(10,70), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); putText(img1,"p - pause video", Point2f(10,85), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); putText(img1,"o - continue video", Point2f(10,100), FONT_HERSHEY_PLAIN, .8, Scalar(0,0,0), 1, 8); */ //Draw number of objects sprintf(screen_obj, "Bad: %d", cont_bad_parts); putText(img1, screen_obj, Point2f(10,400), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); sprintf(screen_obj, "Good: %d", cont_good_parts); putText(img1, screen_obj, Point2f(10,420), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); sprintf(screen_obj, "No def.: %d", cont_nodef_parts); putText(img1, screen_obj, Point2f(10,440), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); sprintf(screen_obj, "Objects: %d", cont_parts1); putText(img1, screen_obj, Point2f(10,460), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); //Show the results at the screen imshow(screen1, img1); ///-Camera 2 //Draw limits //line(img2, ang_line_tl, ang_line_bl, Scalar(255,0,0), 2, LINE_4, 0); //line(img2, ang_line_tr, ang_line_br, Scalar(255,0,0), 2, LINE_4, 0); //line(img2, limit_line_tl, limit_line_tr, Scalar(0,0,255), 2, LINE_4, 0); //line(img2, limit_line_bl, limit_line_br, Scalar(0,0,255), 10, LINE_4, 0); //Draw number of objects sprintf(screen_obj, "Objects: %d", cont_parts2); putText(img2, screen_obj, Point2f(10,460), FONT_HERSHEY_PLAIN, 1, Scalar(0,0,0), 1, 8); //Show the results at the screen imshow(screen3, img2); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Update screens and get key if pressed key = waitKey(10); //Key to exit ou reset if(key == 27 || key == 'r') break; //27 - ESC //Key to clean database of part default if(key == 'c') CleanDefault(); //Key to pause video if(key == 'p') key_pause = true; //Pause video //Key to continue video video if(key == 'o') key_pause = false; //Continue video if(key == 'f'){ imwrite("Img1.jpg", img1); imwrite("Img2.jpg", img2); } } SaveDataTxt(); cap1.release(); cap2.release(); destroyAllWindows(); cout <<endl <<"End of image processing."<< endl; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LoadDataTxt(){ FILE *load_data; //Read info load_data = fopen("Database.txt", "r"); fscanf(load_data, "Threshold cam 1 = %d;\n", &thresh1); fscanf(load_data, "Threshold cam 2 = %d;\n", &thresh2); fscanf(load_data, "Threshold cam 3 = %d;\n", &thresh3); fscanf(load_data, "Bmin = %d;\n", &Bmin); fscanf(load_data, "Gmin = %d;\n", &Gmin); fscanf(load_data, "Rmin = %d;\n", &Rmin); fscanf(load_data, "Bmax = %d;\n", &Bmax); fscanf(load_data, "Gmax = %d;\n", &Gmax); fscanf(load_data, "Rmax = %d;\n", &Rmax); //Track bar for image createTrackbar("Thresh1", screen1, &thresh1, 255); //createTrackbar("Thresh2", screen3, &thresh2, 255); //createTrackbar("Thresh3", screen3, &thresh3, 255); createTrackbar("Bmin", screen5, &Bmin, 255); createTrackbar("Gmin", screen5, &Gmin, 255); createTrackbar("Rmin", screen5, &Rmin, 255); createTrackbar("Bmax", screen5, &Bmax, 255); createTrackbar("Gmax", screen5, &Gmax, 255); createTrackbar("Rmax", screen5, &Rmax, 255); if(ratio_part == 0.0) fscanf(load_data, "Ratio_part = %f; \n", &ratio_part); load_data = fopen("photo_parts/Data_parts.txt", "r"); for(int j=0; j<num_max_default; j++){ const char *c_label; string read_part_label = "Part "; stringstream read_num_part; read_num_part << j+1; read_part_label = read_part_label + read_num_part.str() + " : %s \n"; c_label = read_part_label.c_str(); fscanf(load_data, c_label, &label_part_def[j]); } fclose(load_data); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SaveDataTxt(){ FILE *save_data; save_data = fopen("Database.txt", "w"); fprintf(save_data, "Threshold cam 1 = %d; \n", thresh1); fprintf(save_data, "Threshold cam 2 = %d; \n", thresh2); fprintf(save_data, "Threshold cam 3 = %d; \n", thresh3); fprintf(save_data, "Bmin = %d; \n", Bmin); fprintf(save_data, "Gmin = %d; \n", Gmin); fprintf(save_data, "Rmin = %d; \n", Rmin); fprintf(save_data, "Bmax = %d; \n", Bmax); fprintf(save_data, "Gmax = %d; \n", Gmax); fprintf(save_data, "Rmax = %d; \n", Rmax); fprintf(save_data, "Ratio_part = %.6f; \n", ratio_part); fclose(save_data); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Scalar ImgAvgColor(Mat imgPart){ Scalar color_result, color_pix1, color_pix2; int color_sum[3]; int calib = 4; int lin = imgPart.rows + calib; int col = imgPart.cols; int a, b, n_sum; memset(color_sum,(int)0,sizeof(int)*3); n_sum = 0; Point p; p.y = lin-5; p.x = col/2; color_pix1 = imgPart.at<Vec3b>(p.y, p.x); //Get pixel reference color_sum[0] = color_pix1.val[0]; color_sum[1] = color_pix1.val[1]; color_sum[2] = color_pix1.val[2]; //Get median color of pixels doing a rhombus for(int i=calib; i<=(lin-(calib*2)); i++){ if(i == calib){ a = col/2; b = a; } if(i>0 && i<(lin/2)){ a--; b++; } if(i>=(lin/2)){ a++; b--; } n_sum++; color_pix1 = imgPart.at<Vec3b>(i, a); color_pix2 = imgPart.at<Vec3b>(i, b); color_sum[0] = color_sum[0] + color_pix1.val[0]; color_sum[1] = color_sum[1] + color_pix1.val[1]; color_sum[2] = color_sum[2] + color_pix1.val[2]; /* //Draw rhombus Point losang1, losang2; losang1.y = i; losang1.x = a; losang2.y = i; losang2.x = b; drawMarker(imgPart, losang1, Scalar(0,255,0), MARKER_CROSS, 1, 1, 8); drawMarker(imgPart, losang2, Scalar(0,255,0), MARKER_CROSS, 1, 1, 8); */ } n_sum = n_sum + 1; color_result.val[0] = color_sum[0]/n_sum; color_result.val[1] = color_sum[1]/n_sum; color_result.val[2] = color_sum[2]/n_sum; return color_result; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Scalar CheckColors(Mat imgPart){ //Compare color part with color default int limit_erro = 80; int color_diff[4]; int color_test = 500; Scalar color_result; for(int i=0; i<=(num_max_default-1); i++){ if(color_def[i] != Scalar(0,0,0)){ color_diff[0] = color_def[i].val[0] - color_part.val[0]; color_diff[1] = color_def[i].val[1] - color_part.val[1]; color_diff[2] = color_def[i].val[2] - color_part.val[2]; if(color_diff[0]<0) color_diff[0] = color_diff[0] * (-1); if(color_diff[1]<0) color_diff[1] = color_diff[1] * (-1); if(color_diff[2]<0) color_diff[2] = color_diff[2] * (-1); color_diff[3] = color_diff[0] + color_diff[1] + color_diff[2]; if(color_diff[3] < limit_erro && color_diff[3] < color_test){ cout <<"*Part " <<cont_parts1+1 <<" / default " <<i+1 <<" : OK "; color_test = color_diff[3]; label_part = '\0'; label_part = label_part_def[i]; color_result = Scalar(0,255,0); } else{ cout <<"*Part " <<cont_parts1+1 <<" / default " <<i+1 <<" : ERROR "; } //cout<<color_diff[3]<<endl; } } if(color_result != Scalar(0,255,0)) color_result = Scalar(0,0,255); cout <<endl; return color_result; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SnapDefault(Mat imgPart, int num_obj){ if(press_times == 0){ CleanDefault(); } press_times++; string file_name_number = "photo_parts/photo_part"; stringstream num_picture; num_picture << press_times; file_name_number = file_name_number + num_picture.str() + ".jpg"; cout <<"Picture saved - "<< file_name_number<< endl; imwrite(file_name_number, imgPart); if(press_times == num_obj){ FILE *save_data; save_data = fopen("photo_parts/Data_parts.txt", "w"); cout <<endl; for(int j=0; j<num_obj; j++){ string name_part; cout <<"Digit the name of the part " <<j+1 <<": "; getline(cin, name_part); fprintf(save_data, "Part %d : %s\n", j+1, name_part.c_str()); } cout <<"Name of the parts saved!" <<endl; fclose(save_data); press_times=0; } cout <<flush; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void LoadDefault(){ float avg_size_def = 0.0; int num_obj = 0; cout <<"Size default: " <<size_part <<"mm" <<endl; for(int i=0; i<num_max_default; i++){ string file_name_number = "photo_parts/photo_part"; stringstream num_picture; num_picture << i+1; file_name_number = file_name_number + num_picture.str() + ".jpg"; const char *file_name_test = file_name_number.c_str(); FILE *file_test; file_test = fopen(file_name_test, "r"); if(!file_test){ color_def[i] = NULL; cout <<"Part default "<< i+1<< " not found!"<< endl; fclose(file_test); } else{ imgLoad = imread(file_name_number); color_def[i] = ImgAvgColor(imgLoad); avg_size_def = (2.*size_part/((imgLoad.rows+imgLoad.cols)/2.)); ratio_part = ratio_part+avg_size_def; num_obj++; cout <<"Part default " <<i+1 <<" : avg color " <<color_def[i] << endl; fclose(file_test); } } if(num_obj != 0) ratio_part = ratio_part/num_obj; cout <<endl; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CleanDefault(){ for(int i=0; i<num_max_default; i++){ string file_name_number = "photo_parts/photo_part"; stringstream num_picture; num_picture << i+1; file_name_number = file_name_number + num_picture.str() + ".jpg"; const char *file_name_test = file_name_number.c_str(); FILE *file_test; file_test = fopen(file_name_test, "w"); if(!file_test){ fclose(file_test); } else{ fclose(file_test); DeleteFile(file_name_test); color_def[i] = NULL; cout <<"Part default " <<i+1 <<" removed " << color_def[i] <<endl; } } cout <<"Clean database default sucessfully!" <<endl <<endl; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
44.876068
150
0.52795
[ "object", "vector" ]
06f71dcff04d8a2184c14e1c076c1e33b214f1e8
1,208
cpp
C++
week 2/queue.cpp
mtereshkin/coursera-white-belt-cpp
54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7
[ "MIT" ]
null
null
null
week 2/queue.cpp
mtereshkin/coursera-white-belt-cpp
54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7
[ "MIT" ]
null
null
null
week 2/queue.cpp
mtereshkin/coursera-white-belt-cpp
54c57315bdc8733ebfdbd83b72d767f1c6e9a2d7
[ "MIT" ]
null
null
null
#include <iostream> #include<vector> #include<string> using namespace std; int main() { int n; cin >> n; vector<int> people; vector<int> count_vector; string command; int number; for (int i = 0; i < n; i++) { cin >> command; if (command == "COME") { cin >> number; if (number > 0) { for (int t = 0; t < number; t++) { people.push_back(0); } } else { for (int t = 0; t < -number; t++) { people.pop_back(); } } } else if (command == "QUIET") { cin >> number; people[number] = 0; } else if (command == "WORRY") { cin >> number; people[number] = 1; } else if (command == "WORRY_COUNT") { int count = 0; for (int r = 0; r < people.size(); r++) { if (people[r] == 1) { count++; } } count_vector.push_back(count); } } for (auto i:count_vector) { cout <<i <<endl; } return 0; }
23.230769
53
0.379967
[ "vector" ]
06f7f570035d4d9d318558232b216c2f5879f984
737
cpp
C++
cpp/1001-10000/1631-1640/Check Array Formation Through Concatenation.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/1001-10000/1631-1640/Check Array Formation Through Concatenation.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/1001-10000/1631-1640/Check Array Formation Through Concatenation.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { public: bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) { map<int, int> mymap; for (int i = 0; i < arr.size(); i++) { mymap[arr[i]] = i; } for (const vector<int>& piece : pieces) { for (int i = 0; i < piece.size(); i++) { if (mymap.count(piece[i]) == 0) { return false; } } } for (const vector<int>& piece : pieces) { for (int i = 1; i < piece.size(); i++) { if (mymap[piece[i-1]] > mymap[piece[i]]) { return false; } } } return true; } };
26.321429
70
0.378562
[ "vector" ]
66001a65b6381905e8ffaaf4a8449f3852963a87
22,942
cpp
C++
projects/pbr_viewer/pbr_viewer.cpp
crocdialer/vierkant_projects
0f84ff6c809f303b19babe8093544d967e60207e
[ "MIT" ]
null
null
null
projects/pbr_viewer/pbr_viewer.cpp
crocdialer/vierkant_projects
0f84ff6c809f303b19babe8093544d967e60207e
[ "MIT" ]
null
null
null
projects/pbr_viewer/pbr_viewer.cpp
crocdialer/vierkant_projects
0f84ff6c809f303b19babe8093544d967e60207e
[ "MIT" ]
null
null
null
#include <fstream> #include <crocore/filesystem.hpp> #include <crocore/http.hpp> #include <crocore/Image.hpp> #include <crocore/json.hpp> #include <vierkant/imgui/imgui_util.h> #include <vierkant/Visitor.hpp> #include <vierkant/PBRDeferred.hpp> #include <vierkant/cubemap_utils.hpp> #include <vierkant/assimp.hpp> #include <vierkant/gltf.hpp> #include "pbr_viewer.hpp" ////////////////////////////// VALIDATION LAYER /////////////////////////////////////////////////// #ifdef NDEBUG const bool g_enable_validation_layers = false; #else const bool g_enable_validation_layers = true; #endif using double_second = std::chrono::duration<double>; void PBRViewer::setup() { // try to read settings m_settings = load_settings(); crocore::g_logger.set_severity(m_settings.log_severity); create_context_and_window(); // create ui and inputs create_ui(); create_texture_image(); create_graphics_pipeline(); // load stuff load_model(m_settings.model_path); load_environment(m_settings.environment_path); } void PBRViewer::teardown() { LOG_INFO << "ciao " << name(); background_queue().join_all(); vkDeviceWaitIdle(m_device->handle()); } void PBRViewer::poll_events() { glfwPollEvents(); } void PBRViewer::create_context_and_window() { m_instance = vk::Instance(g_enable_validation_layers, vk::Window::required_extensions()); // attach logger for debug-output m_instance.set_debug_fn([](const char *msg){ LOG_WARNING << msg; }); m_settings.window_info.title = name(); m_settings.window_info.instance = m_instance.handle(); m_window = vk::Window::create(m_settings.window_info); // create device vk::Device::create_info_t device_info = {}; device_info.instance = m_instance.handle(); device_info.physical_device = m_instance.physical_devices().front(); device_info.use_validation = m_instance.use_validation_layers(); device_info.surface = m_window->surface(); // add the raytracing-extensions device_info.extensions = vierkant::RayTracer::required_extensions(); m_device = vk::Device::create(device_info); m_window->create_swapchain(m_device, std::min(m_device->max_usable_samples(), m_settings.window_info.sample_count), m_settings.window_info.vsync); // create a WindowDelegate vierkant::window_delegate_t window_delegate = {}; window_delegate.draw_fn = [this](const vierkant::WindowPtr &w){ return draw(w); }; window_delegate.resize_fn = [this](uint32_t w, uint32_t h) { create_graphics_pipeline(); m_camera->set_aspect(m_window->aspect_ratio()); m_arcball.screen_size = {w, h}; }; window_delegate.close_fn = [this](){ set_running(false); }; m_window->window_delegates[name()] = window_delegate; // create a draw context m_draw_context = vierkant::DrawContext(m_device); m_font = vk::Font::create(m_device, g_font_path, 64); m_pipeline_cache = vk::PipelineCache::create(m_device); // set some separate queues for background stuff m_queue_loading = m_device->queues(vierkant::Device::Queue::GRAPHICS)[1]; m_queue_path_tracer = m_device->queues(vierkant::Device::Queue::GRAPHICS)[2]; } void PBRViewer::create_ui() { // create a KeyDelegate vierkant::key_delegate_t key_delegate = {}; key_delegate.key_press = [this](const vierkant::KeyEvent &e) { if(!(m_gui_context.capture_flags() & vk::gui::Context::WantCaptureKeyboard)) { switch(e.code()) { case vk::Key::_ESCAPE: set_running(false); break; case vk::Key::_G: m_pbr_renderer->settings.draw_grid = !m_pbr_renderer->settings.draw_grid; break; case vk::Key::_P: if(m_scene_renderer == m_pbr_renderer){ m_scene_renderer = m_path_tracer; } else{ m_scene_renderer = m_pbr_renderer; } break; case vk::Key::_B: m_settings.draw_aabbs = !m_settings.draw_aabbs; break; case vk::Key::_S: save_settings(m_settings); break; default: break; } } }; m_window->key_delegates[name()] = key_delegate; // create a gui and add a draw-delegate vk::gui::Context::create_info_t gui_create_info = {}; gui_create_info.ui_scale = 2.f; gui_create_info.font_path = g_font_path; gui_create_info.font_size = 23.f; m_gui_context = vk::gui::Context(m_device, gui_create_info); m_gui_context.delegates["application"] = [this] { vk::gui::draw_application_ui(std::static_pointer_cast<Application>(shared_from_this()), m_window); }; // renderer window m_gui_context.delegates["renderer"] = [this] { bool is_path_tracer = m_scene_renderer == m_path_tracer; ImGui::Begin("renderer"); if(ImGui::RadioButton("pbr-deferred", !is_path_tracer)){ m_scene_renderer = m_pbr_renderer; } ImGui::SameLine(); if(ImGui::RadioButton("pathtracer", is_path_tracer)){ m_scene_renderer = m_path_tracer; } ImGui::Separator(); vk::gui::draw_scene_renderer_ui(m_scene_renderer, m_camera); ImGui::End(); }; // scenegraph window m_gui_context.delegates["scenegraph"] = [this]{ vk::gui::draw_scene_ui(m_scene, m_camera, &m_selected_objects); }; // imgui demo window m_gui_context.delegates["demo"] = []{ if(DEMO_GUI){ ImGui::ShowDemoWindow(&DEMO_GUI); }}; // attach gui input-delegates to window m_window->key_delegates["gui"] = m_gui_context.key_delegate(); m_window->mouse_delegates["gui"] = m_gui_context.mouse_delegate(); // camera m_camera = vk::PerspectiveCamera::create(m_window->aspect_ratio(), 45.f, .1f, 100.f); // init arcball m_arcball.screen_size = m_window->size(); m_arcball.enabled = true; // restore settings m_arcball.rotation = m_settings.view_rotation; m_arcball.look_at = m_settings.view_look_at; m_arcball.distance = m_settings.view_distance; // attach arcball mouse delegate auto arcball_delegeate = m_arcball.mouse_delegate(); arcball_delegeate.enabled = [this]() { return !(m_gui_context.capture_flags() & vk::gui::Context::WantCaptureMouse); // return true; }; m_window->mouse_delegates["arcball"] = std::move(arcball_delegeate); // attach arcball mouse delegate auto arcball_key_delegeate = m_arcball.key_delegate(); arcball_key_delegeate.enabled = [this]() { return !(m_gui_context.capture_flags() & vk::gui::Context::WantCaptureKeyboard); }; m_window->key_delegates["arcball"] = std::move(arcball_key_delegeate); // update camera with arcball m_arcball.transform_cb = [this](const glm::mat4 &transform) { m_camera->set_global_transform(transform); if(m_path_tracer){ m_path_tracer->reset_accumulator(); } }; m_camera->set_global_transform(m_arcball.transform()); vierkant::mouse_delegate_t simple_mouse = {}; simple_mouse.mouse_press = [this](const vierkant::MouseEvent &e) { if(!(m_gui_context.capture_flags() & vk::gui::Context::WantCaptureMouse)) { if(e.is_right()){ m_selected_objects.clear(); } else if(e.is_left()) { auto picked_object = m_scene->pick(m_camera->calculate_ray(e.position(), m_window->size())); if(picked_object) { if(e.is_control_down()){ m_selected_objects.insert(picked_object); } else{ m_selected_objects = {picked_object}; } } } } }; m_window->mouse_delegates["simple_mouse"] = simple_mouse; // attach drag/drop mouse-delegate vierkant::mouse_delegate_t file_drop_delegate = {}; file_drop_delegate.file_drop = [this](const vierkant::MouseEvent &e, const std::vector<std::string> &files) { auto &f = files.back(); switch(crocore::filesystem::get_file_type(f)) { case crocore::filesystem::FileType::IMAGE: load_environment(f); break; case crocore::filesystem::FileType::MODEL: load_model(f); break; default: break; } }; m_window->mouse_delegates["filedrop"] = file_drop_delegate; } void PBRViewer::create_graphics_pipeline() { m_pipeline_cache->clear(); bool use_raytracer = m_scene_renderer == m_path_tracer; const auto &framebuffers = m_window->swapchain().framebuffers(); auto fb_extent = framebuffers.front().extent(); vierkant::Renderer::create_info_t create_info = {}; create_info.num_frames_in_flight = framebuffers.size(); create_info.sample_count = m_window->swapchain().sample_count(); create_info.viewport.width = fb_extent.width; create_info.viewport.height = fb_extent.height; create_info.viewport.maxDepth = fb_extent.depth; create_info.pipeline_cache = m_pipeline_cache; m_renderer = vk::Renderer(m_device, create_info); m_renderer_gui = vk::Renderer(m_device, create_info); vierkant::PBRDeferred::create_info_t pbr_render_info = {}; pbr_render_info.num_frames_in_flight = framebuffers.size(); pbr_render_info.size = fb_extent; pbr_render_info.pipeline_cache = m_pipeline_cache; pbr_render_info.settings = m_settings.pbr_settings; if(m_pbr_renderer) { pbr_render_info.conv_lambert = m_pbr_renderer->environment_lambert(); pbr_render_info.conv_ggx = m_pbr_renderer->environment_ggx(); pbr_render_info.settings = m_pbr_renderer->settings; } m_pbr_renderer = vierkant::PBRDeferred::create(m_device, pbr_render_info); vierkant::PBRPathTracer::create_info_t path_tracer_info = {}; path_tracer_info.num_frames_in_flight = framebuffers.size(); path_tracer_info.pipeline_cache = m_pipeline_cache; path_tracer_info.settings = m_path_tracer ? m_path_tracer->settings : m_settings.path_tracer_settings; path_tracer_info.queue = m_queue_path_tracer; m_path_tracer = vierkant::PBRPathTracer::create(m_device, path_tracer_info); if(use_raytracer){ m_scene_renderer = m_path_tracer; } else{ m_scene_renderer = m_pbr_renderer; } } void PBRViewer::create_texture_image() { // try to fetch cool image auto http_response = crocore::net::http::get(g_texture_url); crocore::ImagePtr img; vk::Image::Format fmt; // create from downloaded data if(!http_response.data.empty()){ img = crocore::create_image_from_data(http_response.data, 4); } else { // create 2x2 black/white checkerboard image uint32_t v[4] = {0xFFFFFFFF, 0xFF000000, 0xFF000000, 0xFFFFFFFF}; img = crocore::Image_<uint8_t>::create(reinterpret_cast<uint8_t *>(v), 2, 2, 4); fmt.mag_filter = VK_FILTER_NEAREST; fmt.format = VK_FORMAT_R8G8B8A8_UNORM; } fmt.extent = {img->width(), img->height(), 1}; fmt.use_mipmap = true; m_textures["test"] = vk::Image::create(m_device, img->data(), fmt); if(m_font) { // draw_gui some text into a texture m_textures["font"] = m_font->create_texture(m_device, "Pooop!\nKleines kaka,\ngrosses KAKA ..."); } } void PBRViewer::load_model(const std::string &path) { vierkant::MeshPtr mesh; // additionally required buffer-flags for raytracing VkBufferUsageFlags buffer_flags = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; if(!path.empty()) { m_settings.model_path = path; auto load_task = [this, path, buffer_flags]() { m_num_loading++; auto start_time = std::chrono::steady_clock::now(); // tinygltf auto mesh_assets = vierkant::model::gltf(path); // assimp //auto old_mesh_assets = vierkant::model::load_model(model_path, background_pool); if(mesh_assets.entry_create_infos.empty()) { LOG_WARNING << "could not load file: " << path; return; } auto mesh = load_mesh(m_device, mesh_assets, m_queue_loading, buffer_flags); if(!mesh) { LOG_WARNING << crocore::format("loading '%s' failed ...", path.c_str()); m_num_loading--; return; } auto done_cb = [this, mesh, start_time, path]() { m_selected_objects.clear(); m_scene->clear(); auto mesh_node = vierkant::MeshNode::create(mesh); // scale float scale = 5.f / glm::length(mesh_node->aabb().half_extents()); mesh_node->set_scale(scale); // center aabb auto aabb = mesh_node->aabb().transform(mesh_node->transform()); mesh_node->set_position(-aabb.center() + glm::vec3(0.f, aabb.height() / 2.f, 0.f)); m_scene->add_object(mesh_node); if(m_path_tracer){ m_path_tracer->reset_accumulator(); } auto dur = double_second( std::chrono::steady_clock::now() - start_time); LOG_DEBUG << crocore::format("loaded '%s' -- (%.2fs)", path.c_str(), dur.count()); m_num_loading--; }; main_queue().post(done_cb); }; background_queue().post(load_task); } else { vierkant::Mesh::create_info_t mesh_create_info = {}; mesh_create_info.buffer_usage_flags = buffer_flags; mesh = vk::Mesh::create_from_geometry(m_device, vk::Geometry::Box(glm::vec3(.5f)), mesh_create_info); auto mat = vk::Material::create(); auto it = m_textures.find("test"); if(it != m_textures.end()){ mat->textures[vierkant::Material::Color] = it->second; } mesh->materials = {mat}; auto mesh_node = vierkant::MeshNode::create(mesh); m_selected_objects.clear(); m_scene->clear(); m_scene->add_object(mesh_node); } } void PBRViewer::load_environment(const std::string &path) { auto load_task = [&, path]() { m_num_loading++; auto start_time = std::chrono::steady_clock::now(); auto img = crocore::create_image_from_file(path, 4); vierkant::ImagePtr panorama, skybox, conv_lambert, conv_ggx; if(img) { bool use_float = (img->num_bytes() / (img->width() * img->height() * img->num_components())) > 1; // command pool for background transfer auto command_pool = vierkant::create_command_pool(m_device, vierkant::Device::Queue::GRAPHICS, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT); { auto cmd_buf = vierkant::CommandBuffer(m_device, command_pool.get()); cmd_buf.begin(); vk::Image::Format fmt = {}; fmt.extent = {img->width(), img->height(), 1}; fmt.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; fmt.format = use_float ? VK_FORMAT_R32G32B32A32_SFLOAT : VK_FORMAT_R8G8B8A8_UNORM; fmt.initial_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; fmt.initial_cmd_buffer = cmd_buf.handle(); panorama = vk::Image::create(m_device, nullptr, fmt); auto buf = vierkant::Buffer::create(m_device, img->data(), img->num_bytes(), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VMA_MEMORY_USAGE_CPU_ONLY); // copy and layout transition panorama->copy_from(buf, cmd_buf.handle()); panorama->transition_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, cmd_buf.handle()); // submit and sync cmd_buf.submit(m_queue_loading, true); // derive sane resolution for cube from panorama-width float res = crocore::next_pow_2(std::max(img->width(), img->height()) / 4); skybox = vierkant::cubemap_from_panorama(panorama, {res, res}, m_queue_loading, true); } if(skybox) { constexpr uint32_t lambert_size = 128; conv_lambert = vierkant::create_convolution_lambert(m_device, skybox, lambert_size, m_queue_loading); conv_ggx = vierkant::create_convolution_ggx(m_device, skybox, skybox->width(), m_queue_loading); auto cmd_buf = vierkant::CommandBuffer(m_device, command_pool.get()); cmd_buf.begin(); // skybox->transition_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, cmd_buf.handle()); conv_lambert->transition_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, cmd_buf.handle()); conv_ggx->transition_layout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, cmd_buf.handle()); // submit and sync cmd_buf.submit(m_queue_loading, true); } } main_queue().post([this, path, skybox, conv_lambert, conv_ggx, start_time]() { m_scene->set_environment(skybox); m_pbr_renderer->set_environment(conv_lambert, conv_ggx); m_path_tracer->reset_accumulator(); m_settings.environment_path = path; auto dur = double_second(std::chrono::steady_clock::now() - start_time); LOG_DEBUG << crocore::format("loaded '%s' -- (%.2fs)", path.c_str(), dur.count()); m_num_loading--; }); }; background_queue().post(load_task); } void PBRViewer::update(double time_delta) { m_arcball.update(time_delta); // update animated objects in the scene m_scene->update(time_delta); // issue top-level draw-command m_window->draw(); } vierkant::window_delegate_t::draw_result_t PBRViewer::draw(const vierkant::WindowPtr &w) { auto image_index = w->swapchain().image_index(); const auto &framebuffer = m_window->swapchain().framebuffers()[image_index]; std::vector<vierkant::semaphore_submit_info_t> semaphore_infos; auto render_scene = [this, &framebuffer, &semaphore_infos]() -> VkCommandBuffer { auto render_result = m_scene_renderer->render_scene(m_renderer, m_scene, m_camera, {}); semaphore_infos = render_result.semaphore_infos; if(m_settings.draw_aabbs) { for(auto &obj : m_selected_objects) { m_draw_context.draw_boundingbox(m_renderer, obj->aabb(), m_camera->view_matrix() * obj->transform(), m_camera->projection_matrix()); auto mesh_node = std::dynamic_pointer_cast<vierkant::MeshNode>(obj); if(mesh_node) { for(const auto &entry : mesh_node->mesh->entries) { m_draw_context.draw_boundingbox(m_renderer, entry.boundingbox, m_camera->view_matrix() * mesh_node->transform() * entry.transform, m_camera->projection_matrix()); } } } } return m_renderer.render(framebuffer); }; auto render_gui = [this, &framebuffer]() -> VkCommandBuffer { m_gui_context.draw_gui(m_renderer_gui); if(m_num_loading) { m_draw_context.draw_text(m_renderer_gui, "loading ...", m_font, {m_window->size().x - 375, 50.f}); } return m_renderer_gui.render(framebuffer); }; vierkant::window_delegate_t::draw_result_t ret; // submit and wait for all command-creation tasks to complete std::vector<std::future<VkCommandBuffer>> cmd_futures; cmd_futures.push_back(background_queue().post(render_scene)); cmd_futures.push_back(background_queue().post(render_gui)); crocore::wait_all(cmd_futures); // get values from completed futures for(auto &f : cmd_futures){ ret.command_buffers.push_back(f.get()); } // ret.command_buffers = {render_scene(), render_gui()}; // get semaphore infos ret.semaphore_infos = std::move(semaphore_infos); return ret; } void PBRViewer::save_settings(PBRViewer::settings_t settings, const std::filesystem::path &path) const { vierkant::Window::create_info_t window_info = {}; window_info.size = m_window->size(); window_info.position = m_window->position(); window_info.fullscreen = m_window->fullscreen(); window_info.sample_count = m_window->swapchain().sample_count(); window_info.title = m_window->title(); window_info.vsync = m_window->swapchain().v_sync(); settings.log_severity = crocore::g_logger.severity(); settings.window_info = window_info; settings.view_rotation = m_arcball.rotation; settings.view_look_at = m_arcball.look_at; settings.view_distance = m_arcball.distance; settings.pbr_settings = m_pbr_renderer->settings; settings.path_tracer_settings = m_path_tracer->settings; settings.path_tracing = m_scene_renderer == m_path_tracer; // create and open a character archive for output std::ofstream ofs(path.string()); // save data to archive try { cereal::JSONOutputArchive archive(ofs); // write class instance to archive archive(settings); } catch(std::exception &e){ LOG_ERROR << e.what(); } LOG_DEBUG << "save settings: " << path; } PBRViewer::settings_t PBRViewer::load_settings(const std::filesystem::path &path) { PBRViewer::settings_t settings = {}; // create and open a character archive for input std::ifstream file_stream(path.string()); // load data from archive if(file_stream.is_open()) { try { cereal::JSONInputArchive archive(file_stream); // read class instance from archive archive(settings); } catch(std::exception &e){ LOG_ERROR << e.what(); } LOG_DEBUG << "loading settings: " << path; } return settings; }
35.241167
119
0.618821
[ "mesh", "geometry", "render", "vector", "model", "transform" ]
660148d2fae59c10c2e0e76ab6bc630533f93fc3
2,175
cpp
C++
data/dailyCodingProblem34.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem509.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem509.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). For example, given the string "race", you should return "ecarace", since we can add three letters to it (which is the smallest amount to make a palindrome). There are seven other palindromes that can be made from "race" by adding three letters, but "ecarace" comes first alphabetically. As another example, given the string "google", you should return "elgoogle". */ string shortestCommonSuper(string s, string rev, vector<vector<int>>& dp){ int n = s.length(); for(int i=0; i<=n; i++){ for(int j=0; j<=n; j++){ if(i == 0) dp[i][j] = j; else if(j == 0) dp[i][j] = i; else if(s[i-1] == rev[j-1]) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j]); } } int index = dp[n][n]; int i = n, j = n; string str; while(i > 0 && j > 0){ if(s[i-1] == rev[j-1]){ str.push_back(s[i-1]); i--; j--; } else if(dp[i-1][j] > dp[i][j-1]){ str.push_back(rev[j-1]); j--; } else{ str.push_back(s[i-1]); i--; } index--; } while(i > 0){ str.push_back(s[i-1]); i--; index--; } while(j > 0){ str.push_back(rev[j-1]); j--; index--; } return str; } string minInsertPalindrome(string s){ string rev = s; reverse(rev.begin(), rev.end()); int n = s.length(); vector<vector<int>> dp(n+1, vector<int>(n+1)); auto ans1 = shortestCommonSuper(s, rev, dp); auto ans2 = shortestCommonSuper(rev, s, dp); return (ans1 < ans2)? ans1 : ans2; } // main function int main(){ cout << minInsertPalindrome("google") << "\n"; cout << minInsertPalindrome("race") << "\n"; cout << minInsertPalindrome("lol") << "\n"; cout << minInsertPalindrome("olo") << "\n"; cout << minInsertPalindrome("aacc") << "\n"; cout << minInsertPalindrome("ccaa") << "\n"; cout << minInsertPalindrome("ac") << "\n"; cout << minInsertPalindrome("ca") << "\n"; return 0; }
22.193878
74
0.611954
[ "vector" ]
66033ebeb987632531d26a0e1d7f920859ea64e5
8,623
cpp
C++
languages/cxx/chain_proxy/12-mutex.cpp
amerlyq/aeternum-langs
8424dd2ff1680cb82ea78a44a798a15fc87de103
[ "MIT" ]
4
2018-05-18T20:29:53.000Z
2021-12-06T04:57:44.000Z
languages/cxx/chain_proxy/12-mutex.cpp
amerlyq/aeternum-langs
8424dd2ff1680cb82ea78a44a798a15fc87de103
[ "MIT" ]
null
null
null
languages/cxx/chain_proxy/12-mutex.cpp
amerlyq/aeternum-langs
8424dd2ff1680cb82ea78a44a798a15fc87de103
[ "MIT" ]
null
null
null
//bin/mkdir -p "/tmp${d:=$(realpath -s "${0%/*}")}/${n:=${0##*/}}" && exec \ //usr/bin/make -C "$_" -sf/dev/null --eval="!:${n%.*};./$<" VPATH="$d" CXXFLAGS=-g LDFLAGS=-lpthread "$@" #include <atomic> #include <cassert> #include <chrono> #include <functional> #include <iostream> #include <map> #include <memory> #include <mutex> #include <thread> #include <vector> struct IDB { virtual void exec() const = 0; virtual void interrupt() const = 0; }; struct MyDB : IDB { MyDB(char id) : m_id(id) {} void interrupt() const override final { std::cout << "---Interrupt---" << std::endl; // ALT: sqlite3_interrupt(); m_ongoing.clear(); } void exec() const override final { if (m_ongoing.test_and_set()) { throw std::logic_error("BUG: already being executed"); } std::cout << "MyDB(" << m_id << ") beg..."; for (int i = 0; i < 20; ++i) { if (!m_ongoing.test_and_set()) { m_ongoing.clear(); std::cout << std::endl; throw std::runtime_error("interrupted"); } std::cout << m_id << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::cout << " END(" << m_id << ")" << std::endl; } char m_id; mutable std::atomic_flag m_ongoing; }; struct Lockable; struct Accessor { virtual ~Accessor() = default; virtual void interrupt() const = 0; virtual Lockable operator->() const = 0; virtual explicit operator IDB const * () const { throw std::domain_error("not implemented"); } virtual bool try_lock() const { throw std::domain_error("not implemented"); } }; // ATT: can't be replaced by std::unique_ptr<db, custom_deleter> // <= otherwise to call ptr->exec() you must reimplement whole IDB for all accessors struct Lockable { using lock_t = std::unique_lock<std::mutex>; Lockable(Accessor const * const a, lock_t lock = lock_t()) : m_a(a), m_lock(std::move(lock)) { assert(a); std::cout << "*lock*" << std::endl; } ~Lockable() { std::cout << "*unlock*" << std::endl; } explicit Lockable(Lockable const&) = delete; Lockable& operator=(Lockable const&) = delete; Lockable(Lockable&&) = default; Lockable& operator=(Lockable&&) = default; IDB const * operator->() { std::cout << "Lockable->" << std::endl; assert(m_a); return static_cast<IDB const *>(*m_a); } lock_t m_lock; Accessor const * const m_a; }; struct Unsafe : Accessor { Unsafe(std::unique_ptr<IDB> db) : m_db(std::move(db)) {} virtual ~Unsafe() = default; Lockable operator->() const override final { std::cout << "Unsafe->" << std::endl; return Lockable(this); } void interrupt() const override final { m_db->interrupt(); } explicit operator IDB const * () const override final { return m_db.get(); } std::unique_ptr<IDB> const m_db; }; struct Exclusive : Accessor { Exclusive(std::unique_ptr<Accessor> a) : m_a(std::move(a)) {} virtual ~Exclusive() = default; bool try_lock() const override final { if (m_Lock) { throw std::logic_error("BUG: already pre-locked"); } // ATT: raises std::system_error() if already owned by this THREAD m_Lock = Lockable::lock_t(m_Mutex, std::try_to_lock); return m_Lock.owns_lock(); } void interrupt() const override final { m_a->interrupt(); } Lockable operator->() const override final { std::cout << "Exclusive->" << std::endl; if (!m_Lock && !try_lock()) { throw std::logic_error("BUG: simultaneous access is forbidden"); } return Lockable(m_a.get(), std::move(m_Lock)); } std::unique_ptr<Accessor> const m_a; mutable std::mutex m_Mutex; mutable Lockable::lock_t m_Lock; }; struct Pool : Accessor { using make_new_t = std::function<std::unique_ptr<Accessor>(void)>; Pool(make_new_t f) : m_f(std::move(f)) {} virtual ~Pool() { clear(); } void interrupt() const override final { std::lock_guard<std::mutex> guard(m_Mutex); for (auto const& a : m_as) { a->interrupt(); } } Lockable operator->() const override final { // FAIL: won't save us, if we are blocked after somebody called dtor() std::lock_guard<std::mutex> guard(m_Mutex); std::cout << "Pool->" << std::endl; for (auto const& a : m_as) { if (a->try_lock()) { return a->operator->(); } } std::cout << "=MakeNew=" << std::endl; m_as.push_back(m_f()); return m_as.back()->operator->(); } void clear() { std::lock_guard<std::mutex> guard(m_Mutex); std::cout << "---DeadPool---" << std::endl; for (auto const& a : m_as) { // FAIL: can't send interrupt when exec() is ongoing (due to Exclusive) a->interrupt(); // WTF: try_lock_for() not available by default ? // FAIL:(gcc4.8): uses MONOTONIC instead of STEADY clock in // ALT: for/sleep 25 times by 200ms and try to lock each time // auto locked = Lockable::lock_t(m_Mutexes[i], std::chrono::seconds(5)); std::this_thread::sleep_for(std::chrono::milliseconds(200)); // HACK: hold locks on all connections until .clear()->destroy()->release() if (!a->try_lock()) { throw std::logic_error("interrupt takes too long"); } } m_as.clear(); } make_new_t const m_f; mutable std::vector<std::unique_ptr<Accessor>> m_as; mutable std::mutex m_Mutex; }; struct Proxy : Accessor { using lock_t = std::lock_guard<std::mutex>; Proxy() = default; virtual ~Proxy() = default; void interrupt() const override final { m_a->interrupt(); } void use(std::unique_ptr<Accessor> a) { lock_t guard(m_Mutex); std::cout << "---Switch---" << std::endl; // NOTE: interrupt and destroy whole pool of connections // BUG? m_a = std::move(a); } Lockable operator->() const override final { // BET:(<C++14): use RW/S boost::shared_lock + boost::unique_lock lock_t guard(m_Mutex); std::cout << "Proxy->" << std::endl; if (!m_a) { throw std::logic_error("BUG: accessing empty proxy"); } return m_a->operator->(); } std::unique_ptr<Accessor> m_a; mutable std::mutex m_Mutex; }; // NOTE: used as persistent member of all objects which use db // => required for shared->exec() syntax instead of unnatural (*proxysharedptr)->exec(); struct Shared : Accessor { Shared(std::shared_ptr<Accessor> a) : m_a(std::move(a)) {} virtual ~Shared() = default; void interrupt() const override final { m_a->interrupt(); } Lockable operator->() const override final { std::cout << "Shared->" << std::endl; return m_a->operator->(); } std::shared_ptr<Accessor> const m_a; }; struct Manager { Manager() { for (auto const i : std::array<int,2>{1, 2}) { m_ps.emplace(i, std::make_shared<Proxy>()); } } ~Manager() { for (auto const it : m_ps) { it.second->use(std::unique_ptr<Pool>()); } } Shared get(int i) const { return Shared(m_ps.at(i)); } void activate(char id) const { auto fmakenew = [id]() { auto db = std::unique_ptr<IDB>(new MyDB(id)); auto unsafe = std::unique_ptr<Accessor>(new Unsafe(std::move(db))); auto excl = std::unique_ptr<Accessor>(new Exclusive(std::move(unsafe))); return excl; }; for (auto const it : m_ps) { it.second->use(std::unique_ptr<Pool>(new Pool(fmakenew))); } } std::map<int, std::shared_ptr<Proxy>> m_ps; }; struct User { User(Shared&& db) : m_db(std::move(db)) {} void f() { try { m_db->exec(); } catch (std::runtime_error const& exc) { std::cout << ":: " << exc.what() << std::endl; } } Shared m_db; }; int main() { Manager mgr; mgr.activate('A'); std::thread service([&](){ User user1(mgr.get(1)); user1.f(); // runs A until interrupted user1.f(); // continues with B }); std::this_thread::sleep_for(std::chrono::milliseconds(500)); mgr.activate('B'); service.join(); return 0; }
32.175373
105
0.560362
[ "vector" ]
66046218635f5f61c726f4f7ec3b45b13e0dbc8a
1,225
cpp
C++
cpp/331-340/Nested List Weight Sum.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/331-340/Nested List Weight Sum.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/331-340/Nested List Weight Sum.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ class Solution { int DFS(vector<NestedInteger>& nestedList, int depth){ int sum(0); for (int i = 0;i < nestedList.size();i++){ if(nestedList[i].isInteger()) sum += nestedList[i].getInteger()*depth; else sum += DFS(nestedList[i].getList(),depth+1); } return sum; } public: int depthSum(vector<NestedInteger>& nestedList) { return DFS(nestedList, 1); } };
34.027778
95
0.626122
[ "vector" ]
6609f7ad8b77eb229645771296b0cf4f748c6b14
1,784
cpp
C++
uva/599 - The Forrest for the Trees.cpp
terror/Solutions
1ad33daec95b565a38ac4730261593bcf249ac86
[ "CC0-1.0" ]
2
2021-04-05T14:26:37.000Z
2021-06-10T04:22:01.000Z
uva/599 - The Forrest for the Trees.cpp
terror/Solutions
1ad33daec95b565a38ac4730261593bcf249ac86
[ "CC0-1.0" ]
null
null
null
uva/599 - The Forrest for the Trees.cpp
terror/Solutions
1ad33daec95b565a38ac4730261593bcf249ac86
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef unsigned int uint; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<vi> vvi; typedef vector<vl> vvl; typedef pair<int, int> ii; typedef map<int, int> MPII; typedef set<int> SETI; const int mxN = 2e5; const ld pi = 4.0 * atanl(1.0); const int iinf = 1e9 + 10; const int inf = 1e18 + iinf + 10; const int mod = 1000000007; const ld prec = .000001; #define F first #define S second #define pb push_back #define mp make_pair #define all(c) c.begin(), c.end() #define rall(c) c.end(), c.begin() const int MXN = 2e5; int n, m, t, a[mxN]; vi v; void fast() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); } void dfs(int v, vi adj[], bool vis[]) { vis[v] = 1; for (auto u : adj[v]) { if (!vis[u]) { vis[u] = 1; dfs(u, adj, vis); } } } int cc(int v, vi ed, vi adj[], bool vis[]) { int ans = 0; for (int i = 0; i < ed.size(); ++i) vis[i] = 0; for (int i = 0; i < ed.size(); ++i) { if (!vis[ed[i]]) { ++ans; dfs(ed[i], adj, vis); } } return ans; } // tle :( int main() { int T; cin >> T; while (T--) { string s; vi adj[MXN], ed; bool vis[MXN]; while (cin >> s and s.find("*") == string::npos) { int u = s[1], v = s[3]; adj[u].pb(v); adj[v].pb(u); ed.pb(v); ed.pb(u); } cin >> s; int ac = 0; for (int i = 0; i < s.size(); i += 2) if (find(ed.begin(), ed.end(), s[i]) == ed.end()) ++ac; int ans = 0; if (ed.size() != 0) ans = cc(ed[0], ed, adj, vis); cout << "There are " << ans << " tree(s) and " << ac << " acorn(s)." << "\n"; fill(vis, vis + MXN, 0); } }
20.044944
72
0.5213
[ "vector" ]
660ee7ad18a7b1d9ef72035bd1cb3c6cec61c255
38,744
cpp
C++
libarea/kbool/src/line.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
libarea/kbool/src/line.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
libarea/kbool/src/line.cpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
/*! \file kbool/src/line.cpp \brief Mainly used for calculating crossings \author Klaas Holwerda Copyright: 2001-2004 (C) Klaas Holwerda Licence: see kboollicense.txt RCS-ID: $Id: line.cpp,v 1.10 2005/06/17 22:48:46 kbluck Exp $ */ #ifdef __GNUG__ #pragma implementation #endif // Standard include files #include <assert.h> #include <math.h> #include "kbool/include/booleng.h" // Include files for forward declarations #include "kbool/include/link.h" #include "kbool/include/node.h" // header #include "kbool/include/line.h" #include "kbool/include/graph.h" #include "kbool/include/graphlst.h" // // The default constructor // KBoolLine::KBoolLine(Bool_Engine* GC) { m_GC=GC; m_AA = 0.0; m_BB = 0.0; m_CC = 0.0; m_link = 0; linecrosslist = NULL; m_valid_parameters = false; } KBoolLine::~KBoolLine() { if (linecrosslist) delete linecrosslist; } // // constructor with a link // KBoolLine::KBoolLine(KBoolLink *a_link,Bool_Engine* GC) { m_GC=GC; // a_link must exist assert(a_link); // points may not be equal // must be an if statement because if an assert is used there will // be a macro expansion error //if (a_link->GetBeginNode()->Equal(a_link->GetEndNode(), 1)) // assert(!a_link); linecrosslist = NULL; m_link = a_link; m_valid_parameters = false; } // ActionOnTable1 // This function decide which action must be taken, after PointInLine // has given the results of two points in relation to a line. See table 1 in the report // // input Result_beginnode: // Result_endnode : // The results can be LEFT_SIDE, RIGHT_SIDE, ON_AREA, IN_AREA // // return -1: Illegal combination // 0: No action, no crosspoints // 1: Investigate results points in relation to the other line // 2: endnode is a crosspoint, no further investigation // 3: beginnode is a crosspoint, no further investigation // 4: beginnode and endnode are crosspoints, no further investigation // 5: beginnode is a crosspoint, need further investigation // 6: endnode is a crosspoint, need further investigation int KBoolLine::ActionOnTable1(PointStatus Result_beginnode, PointStatus Result_endnode) { // Action 1.5 beginnode and endnode are crosspoints, no further investigation needed if ( (Result_beginnode == IN_AREA) && (Result_endnode == IN_AREA) ) return 4; // Action 1.1, there are no crosspoints, no action if ( ( (Result_beginnode == LEFT_SIDE) && (Result_endnode == LEFT_SIDE) ) || ( (Result_beginnode == RIGHT_SIDE) && (Result_endnode == RIGHT_SIDE) ) ) return 0; // Action 1.2, maybe there is a crosspoint, further investigation needed if ( ( (Result_beginnode == LEFT_SIDE) && ( (Result_endnode == RIGHT_SIDE) || (Result_endnode == ON_AREA) ) ) || ( (Result_beginnode == RIGHT_SIDE) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == ON_AREA) ) ) || ( (Result_beginnode == ON_AREA) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == RIGHT_SIDE) || (Result_endnode == ON_AREA) ) ) ) return 1; // Action 1.3, there is a crosspoint, no further investigation if ( ( (Result_beginnode == LEFT_SIDE) || (Result_beginnode == RIGHT_SIDE) ) && (Result_endnode == IN_AREA) ) return 2; // Action 1.4 there is a crosspoint, no further investigation if ( (Result_beginnode == IN_AREA) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == RIGHT_SIDE) ) ) return 3; // Action 1.6 beginnode is a crosspoint, further investigation needed if ( (Result_beginnode == IN_AREA) && (Result_endnode == ON_AREA) ) return 5; // Action 1.7 endnode is a crosspoint, further investigation needed if ( (Result_beginnode == ON_AREA) && (Result_endnode == IN_AREA) ) return 6; // All other combinations are illegal return -1; } // ActionOnTable2 // This function decide which action must be taken, after PointInLine // has given the results of two points in relation to a line. It can only give a // correct decision if first the relation of the points from the line // are investigated in relation to the line wich can be constucted from the points. // // input Result_beginnode: // Result_endnode : // The results can be LEFT_SIDE, RIGHT_SIDE, ON_AREA, IN_AREA // // return -1: Illegal combination // 0: No action, no crosspoints // 1: Calculate crosspoint // 2: endnode is a crosspoint // 3: beginnode is a crosspoint // 4: beginnode and endnode are crosspoints int KBoolLine::ActionOnTable2(PointStatus Result_beginnode, PointStatus Result_endnode) { // Action 2.5, beginnode and eindpoint are crosspoints if ( (Result_beginnode == IN_AREA) && (Result_endnode == IN_AREA) ) return 4; // Action 2.1, there are no crosspoints if ( ( (Result_beginnode == LEFT_SIDE) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == ON_AREA) ) ) || ( (Result_beginnode == RIGHT_SIDE) && ( (Result_endnode == RIGHT_SIDE) || (Result_endnode == ON_AREA) ) ) || ( (Result_beginnode == ON_AREA) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == RIGHT_SIDE) || (Result_endnode == ON_AREA) ) ) ) return 0; // Action 2.2, there is a real intersect ion, which must be calculated if ( ( (Result_beginnode == LEFT_SIDE) && (Result_endnode == RIGHT_SIDE) ) || ( (Result_beginnode == RIGHT_SIDE) && (Result_endnode == LEFT_SIDE) ) ) return 1; // Action 2.3, endnode is a crosspoint if ( ( (Result_beginnode == LEFT_SIDE) || (Result_beginnode == RIGHT_SIDE) || (Result_beginnode == ON_AREA) ) && (Result_endnode == IN_AREA) ) return 2; // Action 2.4, beginnode is a crosspoint if ( (Result_beginnode == IN_AREA) && ( (Result_endnode == LEFT_SIDE) || (Result_endnode == RIGHT_SIDE) || (Result_endnode == ON_AREA) ) ) return 3; // All other combinations are illegal return -1; } // // This fucntion will ad a crossing to this line and the other line // the crossing will be put in the link, because the line will be destructed // after use of the variable // void KBoolLine::AddLineCrossing(B_INT X, B_INT Y, KBoolLine *other_line) { // the other line must exist assert(other_line); // the links of the lines must exist assert(other_line->m_link && m_link); other_line->AddCrossing(AddCrossing(X,Y)); } // Calculate the Y when the X is given // B_INT KBoolLine::Calculate_Y(B_INT X) { // link must exist to get info about the nodes assert(m_link); CalculateLineParameters(); if (m_AA != 0) return (B_INT)(-(m_AA * X + m_CC) / m_BB); else // horizontal line return m_link->GetBeginNode()->GetY(); } B_INT KBoolLine::Calculate_Y_from_X(B_INT X) { // link must exist to get info about the nodes assert(m_link); assert(m_valid_parameters); if (m_AA != 0) return (B_INT) ((-(m_AA * X + m_CC) / m_BB)+0.5); else // horizontal line return m_link->GetBeginNode()->GetY(); } void KBoolLine::Virtual_Point(LPoint *a_point,double distance) { // link must exist to get info about the nodes assert(m_link); assert(m_valid_parameters); //calculate the distance using the slope of the line //and rotate 90 degrees a_point->SetY((B_INT)(a_point->GetY() + (distance * -(m_BB)))); a_point->SetX((B_INT)(a_point->GetX() - (distance * m_AA ))); } // // Calculate the lineparameters for the line if nessecary // void KBoolLine::CalculateLineParameters() { // linkmust exist to get beginnode AND endnode assert(m_link); // if not valid_parameters calculate the parameters if (!m_valid_parameters) { Node *bp, *ep; double length; // get the begin and endnode via the link bp = m_link->GetBeginNode(); ep = m_link->GetEndNode(); // bp AND ep may not be the same if (bp == ep) assert (bp != ep); m_AA = (double) (ep->GetY() - bp->GetY()); // A = (Y2-Y1) m_BB = (double) (bp->GetX() - ep->GetX()); // B = (X1-X2) // the parameters A end B can now be normalized length = sqrt(m_AA*m_AA + m_BB*m_BB); if(length ==0) m_GC->error("length = 0","CalculateLineParameters"); m_AA = (m_AA / length); m_BB = (m_BB / length); m_CC = -((m_AA * bp->GetX()) + (bp->GetY() * m_BB)); m_valid_parameters = true; } } // Checks if a line intersect with another line // inout Line : another line // Marge: optional, standard on MARGE (declared in MISC.CPP) // // return true : lines are crossing // false: lines are not crossing // int KBoolLine::CheckIntersect (KBoolLine * lijn, double Marge) { double distance=0; // link must exist assert(m_link); // lijn must exist assert(lijn); // points may not be equal // must be an if statement because if an assert is used there will // be a macro expansion error if (m_link->GetBeginNode() == m_link->GetEndNode()) assert(!m_link); int Take_Action1, Take_Action2, Total_Result; Node *bp, *ep; PointStatus Result_beginnode,Result_endnode; bp = lijn->m_link->GetBeginNode(); ep = lijn->m_link->GetEndNode(); Result_beginnode = PointInLine(bp,distance,Marge); Result_endnode = PointInLine(ep,distance,Marge); Take_Action1 = ActionOnTable1(Result_beginnode,Result_endnode); switch (Take_Action1) { case 0: Total_Result = false ; break; case 1: { bp = m_link->GetBeginNode(); ep = m_link->GetEndNode(); Result_beginnode = lijn->PointInLine(bp,distance,Marge); Result_endnode = lijn->PointInLine(ep,distance,Marge); Take_Action2 = ActionOnTable2(Result_beginnode,Result_endnode); switch (Take_Action2) { case 0: Total_Result = false; break; case 1: case 2: case 3: case 4: Total_Result = true; break; default: Total_Result = false; assert( Total_Result ); } }; break; // This break belongs to the switch(Take_Action1) case 2: case 3: case 4: case 5: case 6: Total_Result = true; break; default: Total_Result = false; assert( Total_Result ); } return Total_Result; //This is the final decision } // // Get the beginnode from the line // usage: Node *anode = a_line.GetBeginNode() // Node *KBoolLine::GetBeginNode() { // link must exist assert(m_link); return m_link->GetBeginNode(); } // // Get the endnode from the line // usage: Node *anode = a_line.GetEndNode() // Node *KBoolLine::GetEndNode() { // link must exist assert(m_link); return m_link->GetEndNode(); } // Intersects two lines // input Line : another line // Marge: optional, standard on MARGE // // return 0: If there are no crossings // 1: If there is one crossing // 2: If there are two crossings int KBoolLine::Intersect(KBoolLine * lijn, double Marge) { double distance=0; // lijn must exist assert(lijn); // points may not be equal // must be an if statement because if an assert is used there will // be a macro expansion error if (m_link->GetBeginNode() == m_link->GetEndNode()) assert(!m_link); Node *bp, *ep; PointStatus Result_beginnode,Result_endnode; int Take_Action1, Take_Action2, Number_of_Crossings = 0; // Get the nodes from lijn via the link bp = lijn->m_link->GetBeginNode(); ep = lijn->m_link->GetEndNode(); Result_beginnode = PointInLine(bp,distance,Marge); Result_endnode = PointInLine(ep,distance,Marge); Take_Action1 = ActionOnTable1(Result_beginnode,Result_endnode); // The first switch will insert a crosspoint immediatly switch (Take_Action1) { // for the cases see the returnvalue of ActionTable1 case 2: case 6: AddCrossing(ep); Number_of_Crossings = 1; break; case 3: case 5: AddCrossing(bp); Number_of_Crossings = 1; break; case 4: AddCrossing(bp); AddCrossing(ep); Number_of_Crossings = 2; break; } // This switch wil investigate the points of this line in relation to lijn switch (Take_Action1) { // for the cases see the returnvalue of ActionTable1 case 1: case 5: case 6: { // Get the nodes from this line via the link bp = m_link->GetBeginNode(); ep = m_link->GetEndNode(); Result_beginnode = lijn->PointInLine(bp,distance,Marge); Result_endnode = lijn->PointInLine(ep,distance,Marge); Take_Action2 = ActionOnTable2(Result_beginnode,Result_endnode); switch (Take_Action2) { // for the cases see the returnvalue of ActionTable2 case 1: { // begin of scope to calculate the intersection double X, Y, Denominator; CalculateLineParameters(); Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB); // Denominator may not be 0 assert(Denominator != 0.0); // Calculate intersection of both linesegments X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator; Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator; //make a decent rounding to B_INT AddLineCrossing((B_INT)X,(B_INT)Y,lijn); } // end of scope to calculate the intersection Number_of_Crossings++; break; case 2: lijn->AddCrossing(ep); Number_of_Crossings++; break; case 3: lijn->AddCrossing(bp); Number_of_Crossings++; break; case 4: lijn->AddCrossing(bp); lijn->AddCrossing(ep); Number_of_Crossings = 2; break; } }; break; // This break belongs to the outer switch } return Number_of_Crossings; //This is de final number of crossings } // Intersects two lines there must be a crossing int KBoolLine::Intersect_simple(KBoolLine * lijn) { // lijn must exist assert(lijn); double X, Y, Denominator; Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB); // Denominator may not be 0 if (Denominator == 0.0) m_GC->error("colliniar lines","line"); // Calculate intersection of both linesegments X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator; Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator; AddLineCrossing((B_INT)X,(B_INT)Y,lijn); return(0); } // Intersects two lines there must be a crossing bool KBoolLine::Intersect2(Node* crossing,KBoolLine * lijn) { // lijn must exist assert(lijn); double X, Y, Denominator; Denominator = (m_AA * lijn->m_BB) - (lijn->m_AA * m_BB); // Denominator may not be 0 if (Denominator == 0.0) return false; // Calculate intersection of both linesegments X = ((m_BB * lijn->m_CC) - (lijn->m_BB * m_CC)) / Denominator; Y = ((lijn->m_AA * m_CC) - (m_AA * lijn->m_CC)) / Denominator; crossing->SetX((B_INT)X); crossing->SetY((B_INT)Y); return true; } // // test if a point lies in the linesegment. If the point isn't on the line // the function returns a value that indicates on which side of the // line the point is (in linedirection from first point to second point // // returns LEFT_SIDE, when point lies on the left side of the line // RIGHT_SIDE, when point lies on the right side of the line // ON_AREA, when point lies on the infinite line within a range // IN_AREA, when point lies in the area of the linesegment // the returnvalues are declared in (LINE.H) PointStatus KBoolLine::PointInLine(Node *a_node, double& Distance, double Marge) { Distance=0; //Punt must exist assert(a_node); // link must exist to get beginnode and endnode via link assert(m_link); // get the nodes form the line via the link Node *bp, *ep; bp = m_link->GetBeginNode(); ep = m_link->GetEndNode(); // both node must exist assert(bp && ep); // node may not be the same assert(bp != ep); //quick test if point is begin or endpoint if (a_node == bp || a_node == ep) return IN_AREA; int Result_of_BBox=false; PointStatus Result_of_Online; // Checking if point is in bounding-box with marge B_INT xmin=bmin(bp->GetX(),ep->GetX()); B_INT xmax=bmax(bp->GetX(),ep->GetX()); B_INT ymin=bmin(bp->GetY(),ep->GetY()); B_INT ymax=bmax(bp->GetY(),ep->GetY()); if ( a_node->GetX() >= (xmin - Marge) && a_node->GetX() <= (xmax + Marge) && a_node->GetY() >= (ymin - Marge) && a_node->GetY() <= (ymax + Marge) ) Result_of_BBox=true; // Checking if point is on the infinite line Result_of_Online = PointOnLine(a_node, Distance, Marge); // point in boundingbox of the line and is on the line then the point is IN_AREA if ((Result_of_BBox) && (Result_of_Online == ON_AREA)) return IN_AREA; else return Result_of_Online; } // // test if a point lies on the line. If the point isn't on the line // the function returns a value that indicates on which side of the // line the point is (in linedirection from first point to second point // // returns LEFT_SIDE, when point lies on the left side of the line // ON_AREA, when point lies on the infinite line within a range // RIGHT_SIDE, when point lies on the right side of the line // LEFT_SIDE , RIGHT_SIDE , ON_AREA PointStatus KBoolLine::PointOnLine(Node *a_node, double& Distance, double Marge) { Distance=0; // a_node must exist assert(a_node); // link must exist to get beginnode and endnode assert(m_link); // get the nodes from the line via the link Node *bp, *ep; bp = m_link->GetBeginNode(); ep = m_link->GetEndNode(); // both node must exist assert(bp && ep); // node may not be queal assert(bp!=ep); //quick test if point is begin or endpoint if (a_node == bp || a_node == ep) return ON_AREA; CalculateLineParameters(); // calculate the distance of a_node in relation to the line Distance = (m_AA * a_node->GetX())+(m_BB * a_node->GetY()) + m_CC; if (Distance < -Marge) return LEFT_SIDE; else { if (Distance > Marge) return RIGHT_SIDE; else return ON_AREA; } } // // Sets lines parameters // usage: a_line.Set(a_pointer_to_a_link); // void KBoolLine::Set(KBoolLink *a_link) { // points must exist assert(a_link); // points may not be equal // must be an if statement because if an assert is used there will // be a macro expansion error // if (a_link->GetBeginNode()->Equal(a_link->GetEndNode(),MARGE)) assert(!a_link); linecrosslist = NULL; m_link = a_link; m_valid_parameters = false; } KBoolLink* KBoolLine::GetLink() { return m_link; } // // makes a line same as these // usage : line1 = line2; // KBoolLine& KBoolLine::operator=(const KBoolLine& a_line) { m_AA = a_line.m_AA; m_BB = a_line.m_BB; m_CC = a_line.m_CC; m_link = a_line.m_link; linecrosslist = NULL; m_valid_parameters = a_line.m_valid_parameters; return *this; } Node* KBoolLine::OffsetContour(KBoolLine* const nextline,Node* _last_ins, double factor,Graph *shape) { KBoolLink* offs_currentlink; KBoolLine offs_currentline(m_GC); KBoolLink* offs_nextlink; KBoolLine offs_nextline(m_GC); Node* offs_end; Node* offs_bgn_next; Node* offs_end_next; // make a node from this point offs_end = new Node(GetEndNode(), m_GC); Virtual_Point(offs_end,factor); offs_currentlink=new KBoolLink(0, m_link->m_user_data, _last_ins,offs_end, m_GC); offs_currentline.Set(offs_currentlink); offs_bgn_next = new Node(nextline->m_link->GetBeginNode(), m_GC); nextline->Virtual_Point(offs_bgn_next,factor); offs_end_next = new Node(nextline->m_link->GetEndNode(), m_GC); nextline->Virtual_Point(offs_end_next,factor); offs_nextlink=new KBoolLink(0, m_link->m_user_data, offs_bgn_next, offs_end_next, m_GC); offs_nextline.Set(offs_nextlink); offs_currentline.CalculateLineParameters(); offs_nextline.CalculateLineParameters(); offs_currentline.Intersect2(offs_end,&offs_nextline); // make a link between the current and the previous and add this to graph shape->AddLink(offs_currentlink); delete offs_nextlink; return(offs_end); } Node* KBoolLine::OffsetContour_rounded(KBoolLine* const nextline,Node* _last_ins, double factor,Graph *shape) { KBoolLink* offs_currentlink; KBoolLine offs_currentline(m_GC); KBoolLink* offs_nextlink; KBoolLine offs_nextline(m_GC); Node* offs_end; Node* medial_axes_point= new Node(m_GC); Node* bu_last_ins = new Node(_last_ins, m_GC); Node* offs_bgn_next; Node* offs_end_next; // make a node from this point offs_end = new Node(GetEndNode(), m_GC); *_last_ins = *GetBeginNode(); Virtual_Point(_last_ins,factor); Virtual_Point(offs_end,factor); offs_currentlink=new KBoolLink(0, m_link->m_user_data, _last_ins,offs_end, m_GC); offs_currentline.Set(offs_currentlink); offs_bgn_next = new Node(nextline->m_link->GetBeginNode(), m_GC); nextline->Virtual_Point(offs_bgn_next,factor); offs_end_next = new Node(nextline->m_link->GetEndNode(), m_GC); nextline->Virtual_Point(offs_end_next,factor); offs_nextlink=new KBoolLink(0, m_link->m_user_data, offs_bgn_next, offs_end_next, m_GC); offs_nextline.Set(offs_nextlink); offs_currentline.CalculateLineParameters(); offs_nextline.CalculateLineParameters(); offs_currentline.Intersect2(medial_axes_point,&offs_nextline); double result_offs=sqrt( pow((double)GetEndNode()->GetY()-medial_axes_point->GetY(),2) + pow((double)GetEndNode()->GetX()-medial_axes_point->GetX(),2) ); if ( result_offs < fabs(m_GC->GetRoundfactor()*factor)) { *_last_ins=*bu_last_ins; *offs_end=*medial_axes_point; delete medial_axes_point; delete bu_last_ins; // make a link between the current and the previous and add this to graph delete offs_nextlink; shape->AddLink(offs_currentlink); return(offs_end); } else { //let us create a circle *_last_ins=*bu_last_ins; delete medial_axes_point; delete bu_last_ins; Node* endarc= new Node(offs_bgn_next, m_GC); shape->AddLink(offs_currentlink); delete offs_nextlink; shape->CreateArc(GetEndNode(), &offs_currentline, endarc,fabs(factor),m_GC->GetInternalCorrectionAber(), m_link->m_user_data); return(endarc); } } bool KBoolLine::OkeForContour(KBoolLine* const nextline,double factor,Node* LastLeft,Node* LastRight, LinkStatus& _outproduct) { assert(m_link); assert(m_valid_parameters); assert(nextline->m_link); assert(nextline->m_valid_parameters); factor = fabs(factor); // PointStatus status=ON_AREA; double distance=0; Node offs_end_next(nextline->m_link->GetEndNode(), m_GC); _outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur()); switch (_outproduct) { // current line lies on leftside of prev line case IS_RIGHT : { nextline->Virtual_Point(&offs_end_next,-factor); // status= nextline->PointOnLine(LastRight, distance, m_GC->GetAccur()); if (distance > factor) { PointOnLine(&offs_end_next, distance, m_GC->GetAccur()); if (distance > factor) return(true); } } break; // current line lies on rightside of prev line case IS_LEFT : { nextline->Virtual_Point(&offs_end_next,factor); // status= nextline->PointOnLine(LastLeft, distance, m_GC->GetAccur()); if (distance < -factor) { PointOnLine(&offs_end_next, distance, m_GC->GetAccur()); if (distance <-factor) return(true); } } break; // current line lies on prev line case IS_ON : { return(true); } }//end switch return(false); } bool KBoolLine::Create_Ring_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape) { Node* _current; LinkStatus _outproduct=IS_ON; if (OkeForContour(nextline,factor,*_last_ins_left,*_last_ins_right,_outproduct)) { switch (_outproduct) { // Line 2 lies on leftside of this line case IS_RIGHT : { *_last_ins_left =OffsetContour_rounded(nextline,*_last_ins_left,factor,shape); *_last_ins_right =OffsetContour(nextline,*_last_ins_right,-factor,shape); } break; case IS_LEFT : { *_last_ins_left =OffsetContour(nextline,*_last_ins_left,factor,shape); *_last_ins_right =OffsetContour_rounded(nextline,*_last_ins_right,-factor,shape); } break; // Line 2 lies on this line case IS_ON : { // make a node from this point _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,factor); // make a link between the current and the previous and add this to graph shape->AddLink(*_last_ins_left, _current, m_link->m_user_data); *_last_ins_left=_current; _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,-factor); shape->AddLink(*_last_ins_right, _current, m_link->m_user_data); *_last_ins_right=_current; } break; }//end switch return(true); } /* else { switch (_outproduct) { // Line 2 lies on leftside of this line case IS_RIGHT : { *_last_ins_left =OffsetContour_rounded(nextline,*_last_ins_left,factor,Ishape); *_last_ins_right =OffsetContour(nextline,*_last_ins_right,-factor,Ishape); } break; case IS_LEFT : { *_last_ins_left =OffsetContour(nextline,*_last_ins_left,factor,Ishape); *_last_ins_right =OffsetContour_rounded(nextline,*_last_ins_right,-factor,Ishape); } break; // Line 2 lies on this line case IS_ON : { // make a node from this point _current = new Node(m_link->GetEndNode()); Virtual_Point(_current,factor); // make a link between the current and the previous and add this to graph Ishape->AddLink(*_last_ins_left, _current); *_last_ins_left=_current; _current = new Node(m_link->GetEndNode()); Virtual_Point(_current,-factor); Ishape->AddLink(*_last_ins_right, _current); *_last_ins_right=_current; } break; }//end switch return(true); } */ return(false); } void KBoolLine::Create_Begin_Shape(KBoolLine* nextline,Node** _last_ins_left,Node** _last_ins_right,double factor,Graph *shape) { factor = fabs(factor); LinkStatus _outproduct; _outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur()); switch (_outproduct) { case IS_RIGHT : { *_last_ins_left = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(*_last_ins_left,factor); *_last_ins_right = new Node(nextline->m_link->GetBeginNode(), m_GC); nextline->Virtual_Point(*_last_ins_right,-factor); shape->AddLink(*_last_ins_left, *_last_ins_right, m_link->m_user_data); *_last_ins_left=OffsetContour_rounded(nextline,*_last_ins_left,factor,shape); } break; case IS_LEFT : { *_last_ins_left = new Node(nextline->m_link->GetBeginNode(), m_GC); nextline->Virtual_Point(*_last_ins_left,factor); *_last_ins_right = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(*_last_ins_right,-factor); shape->AddLink(*_last_ins_left, *_last_ins_right, m_link->m_user_data); *_last_ins_right=OffsetContour_rounded(nextline,*_last_ins_right,-factor,shape); } break; // Line 2 lies on this line case IS_ON : { *_last_ins_left = new Node(nextline->m_link->GetBeginNode(), m_GC); Virtual_Point(*_last_ins_left,factor); *_last_ins_right = new Node(nextline->m_link->GetBeginNode(), m_GC); Virtual_Point(*_last_ins_right,-factor); shape->AddLink(*_last_ins_left, *_last_ins_right, m_link->m_user_data); } break; }//end switch } void KBoolLine::Create_End_Shape(KBoolLine* nextline,Node* _last_ins_left,Node* _last_ins_right,double factor,Graph *shape) { Node* _current; factor = fabs(factor); LinkStatus _outproduct; _outproduct= m_link->OutProduct(nextline->m_link,m_GC->GetAccur()); switch (_outproduct) { case IS_RIGHT : { _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,-factor); shape->AddLink(_last_ins_right, _current, m_link->m_user_data); _last_ins_right=_current; _last_ins_left=OffsetContour_rounded(nextline,_last_ins_left,factor,shape); shape->AddLink(_last_ins_left,_last_ins_right, m_link->m_user_data); } break; case IS_LEFT : { _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,factor); shape->AddLink(_last_ins_left, _current, m_link->m_user_data); _last_ins_left=_current; _last_ins_right=OffsetContour_rounded(nextline,_last_ins_right,-factor,shape); shape->AddLink(_last_ins_right, _last_ins_left, m_link->m_user_data); } break; // Line 2 lies on this line case IS_ON : { _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,factor); shape->AddLink(_last_ins_left, _current, m_link->m_user_data); _last_ins_left=_current; _current = new Node(m_link->GetEndNode(), m_GC); Virtual_Point(_current,-factor); shape->AddLink(_last_ins_right, _current, m_link->m_user_data); _last_ins_right=_current; shape->AddLink(_last_ins_left, _last_ins_right, m_link->m_user_data); } break; }//end switch } // // Generate from the found crossings a part of the graph // bool KBoolLine::ProcessCrossings(TDLI<KBoolLink>* _LI) { Node *last; KBoolLink *dummy; // assert (beginnode && endnode); if (!linecrosslist) return false; if (linecrosslist->empty()) return false; if (linecrosslist->count()>1) SortLineCrossings(); m_link->GetEndNode()->RemoveLink(m_link); last=m_link->GetEndNode(); // Make new links : while (!linecrosslist->empty()) { dummy=new KBoolLink(m_link->GetGraphNum(), m_link->m_user_data, (Node*) linecrosslist->tailitem(),last, m_GC); dummy->SetBeenHere(); dummy->SetGroup(m_link->Group()); _LI->insbegin(dummy); last=(Node*)linecrosslist->tailitem(); linecrosslist->removetail(); } // Recycle this link : last->AddLink(m_link); m_link->SetEndNode(last); delete linecrosslist; linecrosslist=NULL; return true; } /* // Sorts the links on the X values int NodeXYsorter(Node* a, Node* b) { if ( a->GetX() < b->GetX()) return(1); if ( a->GetX() > b->GetX()) return(-1); //they are eqaul in x if ( a->GetY() < b->GetY()) return(-1); if ( a->GetY() > b->GetY()) return(1); //they are eqaul in y return(0); } // // Generate from the found crossings a part of the graph // this routine is used in combination with the scanbeam class // the this link most stay at the same place in the sorted graph // The link is split into peaces wich are inserted sorted into the graph // on beginnode. // The mostleft link most become the new link for the beam record // therefore the mostleft new/old link is returned to become the beam record link // also the part returned needs to have the bin flag set to the original value it had in the beam KBoolLink* KBoolLine::ProcessCrossingsSmart(TDLI<KBoolLink>* _LI) { Node *lastinserted; KBoolLink *new_link; KBoolLink *returnlink; assert (beginnode && endnode); if (!linecrosslist) return this; if (linecrosslist->empty()) return this; if (linecrosslist->count()>1) { SortLineCrossings(); } int inbeam; //most left at the beginnode or endnode if (NodeXYsorter(beginnode,endnode)==1) { //re_use this link endnode->RemoveLink(this); linecrosslist->insend(endnode); //the last link to create is towards this node endnode=(Node*) linecrosslist->headitem(); endnode->AddLink(this); inbeam=NodeXYsorter(_LI->item()->beginnode,beginnode); switch (inbeam) { case -1: case 0: bin=true; break; case 1: bin=false; break; } returnlink=this; lastinserted=endnode; linecrosslist->removehead(); // Make new links starting at endnode while (!linecrosslist->empty()) { new_link=new KBoolLink(graphnum,lastinserted,(Node*) linecrosslist->headitem()); new_link->group=group; int inbeam=NodeXYsorter(_LI->item()->beginnode,lastinserted); switch (inbeam) { case -1: { double x,y,xl,yl; char buf[80]; x=((Node*)(linecrosslist->headitem()))->GetX(); y=((Node*)(linecrosslist->headitem()))->GetY(); xl=_LI->item()->beginnode->GetX(); yl=_LI->item()->beginnode->GetY(); sprintf(buf," x=%f , y=%f inserted before %f,%f",x,y,xl,yl); _messagehandler->info(buf,"scanbeam"); new_link->bin=true; } break; case 0: new_link->bin=true; returnlink=new_link; break; case 1: new_link->bin=false; break; } //insert a link into the graph that is already sorted on beginnodes of the links. //starting at a given position // if empty then just insert if (_LI->empty()) _LI->insend(new_link); else { // put new item left of the one that is bigger are equal int i=0; int insert=0; while(!_LI->hitroot()) { if ((insert=linkXYsorter(new_link,_LI->item()))!=-1) break; (*_LI)++; i++; } _LI->insbefore_unsave(new_link); if (insert==0 && _LI->item()->beginnode!=new_link->beginnode) //the begin nodes are equal but not the same merge them into one node { Node* todelete=_LI->item()->beginnode; new_link->beginnode->Merge(todelete); delete todelete; } //set back iter (*_LI) << (i+1); } lastinserted=(Node*)linecrosslist->headitem(); linecrosslist->removehead(); } } else { //re_use this link endnode->RemoveLink(this); linecrosslist->insend(endnode); //the last link to create is towards this node endnode=(Node*) linecrosslist->headitem(); endnode->AddLink(this); inbeam=NodeXYsorter(_LI->item()->beginnode,endnode); switch (inbeam) { case -1: case 0: bin=true; break; case 1: bin=false; break; } returnlink=this; lastinserted=endnode; linecrosslist->removehead(); // Make new links starting at endnode while (!linecrosslist->empty()) { new_link=new KBoolLink(graphnum,lastinserted,(Node*) linecrosslist->headitem()); new_link->group=group; inbeam=NodeXYsorter(_LI->item()->beginnode,(Node*) linecrosslist->headitem()); switch (inbeam) { case -1: case 0: new_link->bin=true; break; case 1: new_link->bin=false; break; } inbeam=NodeXYsorter(_LI->item()->beginnode,lastinserted); switch (inbeam) { case -1: { double x,y,xl,yl; char buf[80]; x=lastinserted->GetX(); y=lastinserted->GetY(); xl=_LI->item()->beginnode->GetX(); yl=_LI->item()->beginnode->GetY(); sprintf(buf," x=%f , y=%f inserted before %f,%f",x,y,xl,yl); _messagehandler->info(buf,"scanbeam"); } break; case 0: break; case 1: returnlink=new_link; break; } //insert a link into the graph that is already sorted on beginnodes of the links. //starting at a given position // if empty then just insert if (_LI->empty()) _LI->insend(new_link); else { // put new item left of the one that is bigger are equal int i=0; int insert=0; while(!_LI->hitroot()) { if ((insert=linkXYsorter(new_link,_LI->item()))!=-1) break; (*_LI)++; i++; } _LI->insbefore_unsave(new_link); if (insert==0 && _LI->item()->beginnode!=new_link->beginnode) //the begin nodes are equal but not the same merge them into one node { Node* todelete=_LI->item()->beginnode; new_link->beginnode->Merge(todelete); delete todelete; } //set back iter (*_LI) << (i+1); } lastinserted=(Node*)linecrosslist->headitem(); linecrosslist->removehead(); } } delete linecrosslist; linecrosslist=NULL; return returnlink; } */ static int NODE_X_ASCENDING_L (Node* a, Node* b) { if(b->GetX() > a->GetX()) return(1); else if(b->GetX() == a->GetX()) return(0); return(-1); } static int NODE_X_DESCENDING_L(Node* a, Node* b) { if(a->GetX() > b->GetX()) return(1); else if(a->GetX() == b->GetX()) return(0); return(-1); } static int NODE_Y_ASCENDING_L (Node* a, Node* b) { if(b->GetY() > a->GetY()) return(1); else if(b->GetY() == a->GetY()) return(0); return(-1); } static int NODE_Y_DESCENDING_L(Node* a, Node* b) { if(a->GetY() > b->GetY()) return(1); else if(a->GetY() == b->GetY()) return(0); return(-1); } // // This function finds out which sortfunction to use with sorting // the crossings. // void KBoolLine::SortLineCrossings() { TDLI<Node> I(linecrosslist); B_INT dx, dy; dx=babs(m_link->GetEndNode()->GetX() - m_link->GetBeginNode()->GetX()); dy=babs(m_link->GetEndNode()->GetY() - m_link->GetBeginNode()->GetY()); if (dx > dy) { // thislink is more horizontal then vertical if (m_link->GetEndNode()->GetX() > m_link->GetBeginNode()->GetX()) I.mergesort(NODE_X_ASCENDING_L); else I.mergesort(NODE_X_DESCENDING_L); } else { // this link is more vertical then horizontal if (m_link->GetEndNode()->GetY() > m_link->GetBeginNode()->GetY()) I.mergesort(NODE_Y_ASCENDING_L); else I.mergesort(NODE_Y_DESCENDING_L); } } // // Adds a cross Node to this. a_node may not be deleted before processing the crossings // void KBoolLine::AddCrossing(Node *a_node) { if (a_node==m_link->GetBeginNode() || a_node==m_link->GetEndNode()) return; if (!linecrosslist) { linecrosslist=new DL_List<void*>(); linecrosslist->insend(a_node); } else { TDLI<Node> I(linecrosslist); if (!I.has(a_node)) I.insend(a_node); } } // // see above // Node* KBoolLine::AddCrossing(B_INT X, B_INT Y) { Node* result=new Node(X,Y, m_GC); AddCrossing(result); return result; } DL_List<void*>* KBoolLine::GetCrossList() { if (linecrosslist) return linecrosslist; return NULL; } bool KBoolLine::CrossListEmpty() { if (linecrosslist) return linecrosslist->empty(); return true; } /* bool KBoolLine::HasInCrossList(Node *n) { if(linecrosslist!=NULL) { TDLI<Node> I(linecrosslist); return I.has(n); } return false; } */
26.23155
128
0.655121
[ "shape" ]
660faf4f1df801815c69735670ec34d864cc374e
3,014
cpp
C++
src/swagger/v1/model/PacketProtocolMpls.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/swagger/v1/model/PacketProtocolMpls.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/swagger/v1/model/PacketProtocolMpls.cpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
/** * OpenPerf API * REST API interface for OpenPerf * * OpenAPI spec version: 1 * Contact: support@spirent.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "PacketProtocolMpls.h" namespace swagger { namespace v1 { namespace model { PacketProtocolMpls::PacketProtocolMpls() { m_Bottom_of_stack = false; m_Bottom_of_stackIsSet = false; m_Label = 0; m_LabelIsSet = false; m_Traffic_class = 0; m_Traffic_classIsSet = false; m_Ttl = 0; m_TtlIsSet = false; } PacketProtocolMpls::~PacketProtocolMpls() { } void PacketProtocolMpls::validate() { // TODO: implement validation } nlohmann::json PacketProtocolMpls::toJson() const { nlohmann::json val = nlohmann::json::object(); if(m_Bottom_of_stackIsSet) { val["bottom_of_stack"] = m_Bottom_of_stack; } if(m_LabelIsSet) { val["label"] = m_Label; } if(m_Traffic_classIsSet) { val["traffic_class"] = m_Traffic_class; } if(m_TtlIsSet) { val["ttl"] = m_Ttl; } return val; } void PacketProtocolMpls::fromJson(nlohmann::json& val) { if(val.find("bottom_of_stack") != val.end()) { setBottomOfStack(val.at("bottom_of_stack")); } if(val.find("label") != val.end()) { setLabel(val.at("label")); } if(val.find("traffic_class") != val.end()) { setTrafficClass(val.at("traffic_class")); } if(val.find("ttl") != val.end()) { setTtl(val.at("ttl")); } } bool PacketProtocolMpls::isBottomOfStack() const { return m_Bottom_of_stack; } void PacketProtocolMpls::setBottomOfStack(bool value) { m_Bottom_of_stack = value; m_Bottom_of_stackIsSet = true; } bool PacketProtocolMpls::bottomOfStackIsSet() const { return m_Bottom_of_stackIsSet; } void PacketProtocolMpls::unsetBottom_of_stack() { m_Bottom_of_stackIsSet = false; } int32_t PacketProtocolMpls::getLabel() const { return m_Label; } void PacketProtocolMpls::setLabel(int32_t value) { m_Label = value; m_LabelIsSet = true; } bool PacketProtocolMpls::labelIsSet() const { return m_LabelIsSet; } void PacketProtocolMpls::unsetLabel() { m_LabelIsSet = false; } int32_t PacketProtocolMpls::getTrafficClass() const { return m_Traffic_class; } void PacketProtocolMpls::setTrafficClass(int32_t value) { m_Traffic_class = value; m_Traffic_classIsSet = true; } bool PacketProtocolMpls::trafficClassIsSet() const { return m_Traffic_classIsSet; } void PacketProtocolMpls::unsetTraffic_class() { m_Traffic_classIsSet = false; } int32_t PacketProtocolMpls::getTtl() const { return m_Ttl; } void PacketProtocolMpls::setTtl(int32_t value) { m_Ttl = value; m_TtlIsSet = true; } bool PacketProtocolMpls::ttlIsSet() const { return m_TtlIsSet; } void PacketProtocolMpls::unsetTtl() { m_TtlIsSet = false; } } } }
18.604938
75
0.680823
[ "object", "model" ]
6616c0aca7080bcf3940f2731e2bf33744b4bcd9
11,560
cpp
C++
framework_c++/jugimap/jmVectorShapesUtilities.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
8
2020-11-23T23:34:39.000Z
2022-02-23T12:14:02.000Z
framework_c++/jugimap/jmVectorShapesUtilities.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
null
null
null
framework_c++/jugimap/jmVectorShapesUtilities.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
3
2019-12-19T13:44:43.000Z
2020-05-15T01:02:10.000Z
#include <assert.h> #include "jmDrawing.h" #include "jmVectorShapesUtilities.h" namespace jugimap{ bool IsPolygonConvex(std::vector<Vec2f> &vertices, bool &cw) { bool negative = false; bool positive = false; int nVertices = vertices.size(); for (int i = 0; i < nVertices; i++){ int iNext = (i + 1) % nVertices; int iNextNext = (iNext + 1) % nVertices; Vec2f v1 = vertices[iNext] - vertices[i]; Vec2f v2 = vertices[iNextNext] - vertices[iNext]; float cross_product = v1.x*v2.y - v1.y*v2.x; if(cross_product < 0){ negative = true; cw = true; }else if (cross_product > 0){ positive = true; cw = false; } if (negative && positive) return false; } return true; } bool SameGeometricShapes(std::vector<VectorShape *> &shapes1, std::vector<VectorShape *> &shapes2) { if(shapes1.size()!=shapes2.size()){ return false; }else if(shapes1.size()==1 && shapes2.size()==1){ return GeometricShapesEqual(shapes1[0]->GetGeometricShape(), shapes2[0]->GetGeometricShape()); }else{ for(VectorShape * vs1 : shapes1){ bool foundSameShape = false; for(VectorShape * vs2 : shapes2){ if(GeometricShapesEqual(vs1->GetGeometricShape(), vs2->GetGeometricShape())){ foundSameShape = true; break; }; } if(foundSameShape==false){ return false; } } } return true; } bool GeometricShapesEqual(GeometricShape * gs1, GeometricShape *gs2) { if(gs1->GetKind() != gs2->GetKind()) return false; if(gs1->GetKind()==ShapeKind::POLYLINE){ PolyLineShape *poly1 = static_cast<PolyLineShape *>(gs1); PolyLineShape *poly2 = static_cast<PolyLineShape *>(gs2); if(poly1->vertices.size() != poly2->vertices.size()){ return false; } if(poly1->IsClosed() != poly2->IsClosed()){ return false; } for(int i=0; i<poly1->vertices.size(); i++){ if(poly1->vertices[i].Equals(poly2->vertices[i])==false){ return false; } } }else if(gs1->GetKind()==ShapeKind::BEZIER_POLYCURVE){ BezierShape *bezpoly1 = static_cast<BezierShape *>(gs1); BezierShape *bezpoly2 = static_cast<BezierShape *>(gs2); if(bezpoly1->vertices.size() != bezpoly2->vertices.size()){ return false; } if(bezpoly1->IsClosed() != bezpoly2->IsClosed()){ return false; } for(int i=0; i<bezpoly1->vertices.size(); i++){ if(bezpoly1->vertices[i].P.Equals(bezpoly2->vertices[i].P)==false){ return false; } if(bezpoly1->vertices[i].CPprevious.Equals(bezpoly2->vertices[i].CPprevious)==false){ return false; } if(bezpoly1->vertices[i].CPnext.Equals(bezpoly2->vertices[i].CPnext)==false){ return false; } } }else if(gs1->GetKind()==ShapeKind::ELLIPSE){ EllipseShape *ellipse1 = static_cast<EllipseShape *>(gs1); EllipseShape *ellipse2 = static_cast<EllipseShape *>(gs2); if(ellipse1->center.Equals(ellipse2->center)==false){ return false; } if(AreEqual(ellipse1->a, ellipse2->a)==false || AreEqual(ellipse1->b, ellipse2->b)==false){ return false; } }else if(gs1->GetKind()==ShapeKind::SINGLE_POINT){ SinglePointShape *sp1 = static_cast<SinglePointShape *>(gs1); SinglePointShape *sp2 = static_cast<SinglePointShape *>(gs2); if(sp1->point.Equals(sp2->point)==false){ return false; } } return true; } /* void _AddVertexToPolyline(std::vector<Vec2f>&Vertices, Vec2f v, float pointsDistanceMin) { if(Vertices.empty()){ Vertices.push_back(v); }else{ float dist = v.Distance(Vertices.back()); if(dist>=pointsDistanceMin){ Vertices.push_back(v); } } } void BezierPolycurveToPolyline(std::vector<BezierVertex>&bezierVertices, std::vector<Vec2f>&vertices) { float pointsDistanceMin = 2.0; vertices.clear(); if(bezierVertices.empty()) return; for(int i=0; i<bezierVertices.size()-1; i++){ Vec2f BP1 = bezierVertices[i].P; Vec2f BP2 = bezierVertices[i].CPnext; Vec2f BP3 = bezierVertices[i+1].CPprevious; Vec2f BP4 = bezierVertices[i+1].P; float length14 = BP1.Distance(BP4); if(length14 <= 2){ _AddVertexToPolyline(vertices, BP1, pointsDistanceMin); continue; } // straight line between BP1 and BP4 //if( AreSameVec2f(BP1,BP2) && AreSameVec2f(BP3,BP4)){ if( BP1.Equals(BP2) && BP3.Equals(BP4)){ _AddVertexToPolyline(vertices, BP1, pointsDistanceMin); _AddVertexToPolyline(vertices, BP4, pointsDistanceMin); continue; } float t = 0.0; float length = BP1.Distance(BP2) + BP2.Distance(BP3) + BP3.Distance(BP4); float f = length14/length; float dStep = 0.05 * f; // this looks ok _AddVertexToPolyline(vertices, BP1, pointsDistanceMin); while(t <= 1.00-dStep){ float t2 = 1.0-t; float xB = BP1.x * t2*t2*t2 + 3*BP2.x * t*t2*t2 + 3*BP3.x * t2*t*t + BP4.x * t*t*t; float yB = BP1.y * t2*t2*t2 + 3*BP2.y * t*t2*t2 + 3*BP3.y * t2*t*t + BP4.y * t*t*t; _AddVertexToPolyline(vertices, Vec2f(xB,yB), pointsDistanceMin); t += dStep; } //last point _AddVertexToPolyline(vertices, BP4, pointsDistanceMin); } } */ void MoveGeometricShape(GeometricShape * gs, Vec2f dPos) { if(gs->GetKind()==ShapeKind::POLYLINE){ PolyLineShape *poly = static_cast<PolyLineShape *>(gs); for(int i=0; i<poly->vertices.size(); i++){ poly->vertices[i] = poly->vertices[i] + dPos; } }else if(gs->GetKind()==ShapeKind::BEZIER_POLYCURVE){ BezierShape *bezpoly = static_cast<BezierShape *>(gs); for(int i=0; i<bezpoly->vertices.size(); i++){ bezpoly->vertices[i].P = bezpoly->vertices[i].P + dPos; bezpoly->vertices[i].CPprevious = bezpoly->vertices[i].CPprevious + dPos; bezpoly->vertices[i].CPnext = bezpoly->vertices[i].CPnext + dPos; } //for(int i=0; i<bezpoly->polylineVertices.size(); i++){ // bezpoly->polylineVertices[i] = bezpoly->polylineVertices[i] + dPos; //} }else if(gs->GetKind()==ShapeKind::ELLIPSE){ EllipseShape *ellipse = static_cast<EllipseShape *>(gs); ellipse->center = ellipse->center + dPos; }else if(gs->GetKind()==ShapeKind::SINGLE_POINT){ SinglePointShape *sp = static_cast<SinglePointShape *>(gs); sp->point = sp->point + dPos; } //---- path for(int i=0; i<gs->GetPath().size(); i++){ //gs->GetPathPoints()[i] = gs->GetPathPoints()[i] + dPos; // NO becouse it clear distance and smooth corner parameters! gs->GetPath()[i].x += dPos.x; gs->GetPath()[i].y += dPos.y; } } void DrawTransformedGeometricShape(Drawer *drawer, GeometricShape *vs, AffineMat3f m, float scale) { Vec2f v, v1, v2; if(vs->GetKind()==ShapeKind::POLYLINE){ PolyLineShape *poly = static_cast<PolyLineShape*>(vs); for(int i=0; i<int(poly->vertices.size())-1; i++){ v1 = poly->vertices[i]; v2 = poly->vertices[i+1]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } if(poly->IsClosed()){ v1 = poly->vertices[poly->vertices.size()-1]; v2 = poly->vertices[0]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } }else if(vs->GetKind()==ShapeKind::BEZIER_POLYCURVE){ /* BezierShape *bezpoly = static_cast<BezierShape*>(vs); for(int i=0; i<bezpoly->polylineVertices.size()-1; i++){ v1 = bezpoly->polylineVertices[i]; v2 = bezpoly->polylineVertices[i+1]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } if(bezpoly->IsClosed()){ v1 = bezpoly->polylineVertices[bezpoly->polylineVertices.size()-1]; v2 = bezpoly->polylineVertices[0]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } */ //BezierShape *bezpoly = static_cast<BezierShape*>(vs); for(int i=0; i<int(vs->GetPath().size())-1; i++){ v1 = vs->GetPath()[i]; v2 = vs->GetPath()[i+1]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } /* if(bezpoly->IsClosed()){ v1 = bezpoly->polylineVertices[bezpoly->polylineVertices.size()-1]; v2 = bezpoly->polylineVertices[0]; v1 = m.Transform(v1); v2 = m.Transform(v2); drawer->Line(v1,v2); } */ }else if(vs->GetKind()==ShapeKind::ELLIPSE){ EllipseShape *e = static_cast<EllipseShape*>(vs); v = e->center; v = m.Transform(v); drawer->EllipseOutline(v, Vec2f(scale*e->a, scale*e->b)); }else if(vs->GetKind()==ShapeKind::SINGLE_POINT){ SinglePointShape *p = static_cast<SinglePointShape*>(vs); v = p->point; v = m.Transform(v); drawer->Dot(v); } } void DrawGeometricShape(Drawer* drawer, GeometricShape *vs, jugimap::Vec2f offset) { Vec2f v, v1, v2; if(vs->GetKind()==ShapeKind::POLYLINE){ PolyLineShape *poly = static_cast<PolyLineShape*>(vs); for(int i=0; i<int(poly->vertices.size())-1; i++){ v1 = poly->vertices[i] + offset; v2 = poly->vertices[i+1] + offset; drawer->Line(v1,v2); } if(poly->IsClosed()){ v1 = poly->vertices[poly->vertices.size()-1] + offset; v2 = poly->vertices[0] + offset; drawer->Line(v1,v2); } }else if(vs->GetKind()==ShapeKind::BEZIER_POLYCURVE){ for(int i=0; i<int(vs->GetPath().size())-1; i++){ v1 = vs->GetPath()[i] + offset; v2 = vs->GetPath()[i+1] + offset; drawer->Line(v1,v2); } /* BezierShape *bezpoly = static_cast<BezierShape*>(vs); for(int i=0; i<bezpoly->polylineVertices.size()-1; i++){ v1 = bezpoly->polylineVertices[i] + offset;; v2 = bezpoly->polylineVertices[i+1] + offset;; drawer->Line(v1,v2); } if(bezpoly->IsClosed()){ v1 = bezpoly->polylineVertices[bezpoly->polylineVertices.size()-1] + offset;; v2 = bezpoly->polylineVertices[0] + offset;; drawer->Line(v1,v2); } */ }else if(vs->GetKind()==ShapeKind::ELLIPSE){ EllipseShape *e = static_cast<EllipseShape*>(vs); v = e->center + offset;; drawer->EllipseOutline(v, Vec2f(e->a,e->b)); }else if(vs->GetKind()==ShapeKind::SINGLE_POINT){ SinglePointShape *p = static_cast<SinglePointShape*>(vs); v = p->point + offset; drawer->Dot(v); } } }
26.821346
137
0.548183
[ "vector", "transform" ]
6617d99771719e3cbd48b934285a2ad3cc3df382
4,234
cpp
C++
tests/majority_element_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
tests/majority_element_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
tests/majority_element_tester.cpp
pawel-kieliszczyk/algorithms
0703ec99ce9fb215709b56fb0eefbdd576c71ed2
[ "MIT" ]
null
null
null
#include <vector> #include <gtest/gtest.h> #include "majority_element.hpp" namespace gt = testing; namespace pk { namespace testing { struct majority_element_tester : public gt::Test { std::vector<int> numbers; }; TEST_F(majority_element_tester, tests_existing_majority_element_in_one_element_sequence) { // given numbers.push_back(42); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_NE(numbers.end(), elem); EXPECT_EQ(42, *elem); } TEST_F(majority_element_tester, tests_nonexisting_majority_element_in_two_element_sequence) { // given numbers.push_back(11); numbers.push_back(22); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_EQ(numbers.end(), elem); } TEST_F(majority_element_tester, tests_existing_majority_element_in_two_element_sequence) { // given numbers.push_back(11); numbers.push_back(11); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_NE(numbers.end(), elem); ASSERT_EQ(11, *elem); } TEST_F(majority_element_tester, tests_nonexisting_majority_element_in_three_element_sequence) { // given numbers.push_back(11); numbers.push_back(22); numbers.push_back(33); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_EQ(numbers.end(), elem); } TEST_F(majority_element_tester, tests_existing_majority_element_in_three_element_sequence) { // given numbers.push_back(11); numbers.push_back(22); numbers.push_back(22); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_NE(numbers.end(), elem); ASSERT_EQ(22, *elem); } TEST_F(majority_element_tester, tests_nonexisting_majority_element_in_four_element_sequence) { // given numbers.push_back(11); numbers.push_back(11); numbers.push_back(22); numbers.push_back(22); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_EQ(numbers.end(), elem); } TEST_F(majority_element_tester, tests_existing_majority_element_in_four_element_sequence) { // given numbers.push_back(42); numbers.push_back(42); numbers.push_back(42); numbers.push_back(42); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_NE(numbers.end(), elem); ASSERT_EQ(42, *elem); } TEST_F(majority_element_tester, tests_nonexisting_majority_element_in_five_element_sequence) { // given numbers.push_back(11); numbers.push_back(11); numbers.push_back(22); numbers.push_back(22); numbers.push_back(33); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_EQ(numbers.end(), elem); } TEST_F(majority_element_tester, tests_existing_majority_element_in_five_element_sequence) { // given numbers.push_back(11); numbers.push_back(11); numbers.push_back(22); numbers.push_back(22); numbers.push_back(11); // when std::vector<int>::iterator elem = majority_element(numbers.begin(), numbers.end()); // then ASSERT_NE(numbers.end(), elem); ASSERT_EQ(11, *elem); } TEST_F(majority_element_tester, tests_nonexisting_majority_element_in_two_noninteger_element_sequence) { // given std::vector<double> seq; seq.push_back(12.3); seq.push_back(-45.6); // when std::vector<double>::iterator elem = majority_element(seq.begin(), seq.end()); // then ASSERT_EQ(seq.end(), elem); } TEST_F(majority_element_tester, tests_existing_majority_element_in_two_noninteger_element_sequence) { // given std::vector<double> seq; seq.push_back(12.3); seq.push_back(12.3); // when std::vector<double>::iterator elem = majority_element(seq.begin(), seq.end()); // then ASSERT_NE(seq.end(), elem); ASSERT_EQ(12.3, *elem); } } // namespace testing } // namespace pk
21.383838
102
0.691308
[ "vector" ]
6627db63de52924ae81724447003264209f32798
13,872
cpp
C++
src/main/cpp/subsystems/Shooter.cpp
crephoto/Wilson2021
542f13b613e5ffe135123d6c1e1850f7b9f80712
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Shooter.cpp
crephoto/Wilson2021
542f13b613e5ffe135123d6c1e1850f7b9f80712
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Shooter.cpp
crephoto/Wilson2021
542f13b613e5ffe135123d6c1e1850f7b9f80712
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "subsystems/Shooter.h" #include <frc/shuffleboard/BuiltInWidgets.h> #include <frc/smartdashboard/SmartDashboard.h> #include <wpi/StringMap.h> // for wpi::StringMap #include <utility> // for std::pair Shooter::Shooter() { #ifdef ENABLE_SHOOTER m_timer = frc::Timer(); m_timer.Reset(); m_timer.Start(); // Invert shooter motors correctly m_topMotor.SetInverted(false); m_bottomMotor.SetInverted(true); m_kickerMotor.SetInverted(true); // m_jumblerMotor.SetInverted(true); // Set velocity of shaft relative to velocity of wheel m_topEncoder.SetVelocityConversionFactor(ConShooter::Top::VELOCITY_FACTOR); m_bottomEncoder.SetVelocityConversionFactor(ConShooter::Bottom::VELOCITY_FACTOR); // Set controller gains from constants // See this for tuning help (Robot Characterization Tool) // https://docs.wpilib.org/en/latest/docs/software/wpilib-overview/new-for-2020.html m_topVelocityPID.SetP(ConShooter::Top::P); m_topVelocityPID.SetI(ConShooter::Top::I); m_topVelocityPID.SetD(ConShooter::Top::D); m_topVelocityPID.SetFF(ConShooter::Top::FF); m_topVelocityPID.SetOutputRange(0.0, 1.0); m_bottomVelocityPID.SetP(ConShooter::Bottom::P); m_bottomVelocityPID.SetI(ConShooter::Bottom::I); m_bottomVelocityPID.SetD(ConShooter::Bottom::D); m_bottomVelocityPID.SetFF(ConShooter::Bottom::FF); m_bottomVelocityPID.SetOutputRange(0.0, 1.0); m_topMotor.BurnFlash(); m_bottomMotor.BurnFlash(); // First choose kicker sensor m_kickerMotor.ConfigSelectedFeedbackSensor(ctre::phoenix::motorcontrol::FeedbackDevice::CTRE_MagEncoder_Absolute, 0, 30); // Set the current limit m_kickerMotor.EnableCurrentLimit(true); m_kickerMotor.ConfigContinuousCurrentLimit(ConShooter::Kicker::CONT_CURRENT_LIMIT); m_kickerMotor.ConfigPeakCurrentLimit(ConShooter::Kicker::PEAK_CURRENT_LIMIT); m_kickerMotor.ConfigPeakCurrentDuration(ConShooter::Kicker::PEAK_CURRENT_DURATION); // Set the peak and nominal outputs m_kickerMotor.ConfigNominalOutputForward(0, 30); m_kickerMotor.ConfigNominalOutputReverse(0, 30); m_kickerMotor.ConfigPeakOutputForward(1, 30); m_kickerMotor.ConfigPeakOutputReverse(-1, 30); // Kicker motor PID code m_kickerMotor.SelectProfileSlot(0,0); m_kickerMotor.Config_kP(0, ConShooter::Kicker::P, 30); // "Slot", Value, timeout (ms) m_kickerMotor.Config_kI(0, ConShooter::Kicker::I, 30); m_kickerMotor.Config_kD(0, ConShooter::Kicker::D, 30); m_kickerMotor.Config_kF(0, ConShooter::Kicker::F, 30); m_kickerMotor.SetNeutralMode(ctre::phoenix::motorcontrol::NeutralMode::Coast); m_jumblerMotor.SetNeutralMode(ctre::phoenix::motorcontrol::NeutralMode::Brake); m_hopperFlapper.SetNeutralMode(ctre::phoenix::motorcontrol::NeutralMode::Coast); #endif // ENABLE_SHOOTER // Create and get reference to SB tab m_sbt_Shooter = &frc::Shuffleboard::GetTab(ConShuffleboard::ShooterTab); m_nte_TopMotorInputRPM = m_sbt_Shooter-> AddPersistent("Top Motor Input RPM", ConShooter::Top::OPTIMAL_RPM) .WithSize(2, 1) .WithPosition(0, 0) .GetEntry(); m_nte_BottomMotorInputRPM = m_sbt_Shooter-> AddPersistent("Bottom Motor Input RPM", ConShooter::Bottom::OPTIMAL_RPM) .WithSize(2, 1) .WithPosition(0, 1) .GetEntry(); m_nte_TopMotorOutputRPM = m_sbt_Shooter-> AddPersistent("Top Motor Output RPM", 0.0) .WithWidget(frc::BuiltInWidgets::kGraph) .WithSize(6, 2) .WithPosition(2, 0) .GetEntry(); m_nte_BottomMotorOutputRPM = m_sbt_Shooter-> AddPersistent("Bottom Motor Output RPM", 0.0) .WithWidget(frc::BuiltInWidgets::kGraph) .WithSize(6, 2) .WithPosition(2, 2) .GetEntry(); m_nte_EnableMotorGraphs = m_sbt_Shooter-> AddPersistent("Enable Motor Graphs", true) .WithWidget(frc::BuiltInWidgets::kToggleButton) .WithSize(1, 1) .WithPosition(8, 0) .GetEntry(); m_nte_JumblerMotorSpeed = m_sbt_Shooter-> AddPersistent("Jumbler Motor Speed", ConShooter::Jumbler::MOTOR_SPEED) .WithSize(2, 1) .WithPosition(0, 3) .GetEntry(); m_nte_KickerInputRPM = m_sbt_Shooter-> AddPersistent("Kicker RPM", ConShooter::Kicker::OPTIMAL_RPM) .WithSize(1, 1) .WithPosition(0, 2) .GetEntry(); m_nte_KickerMotorError = m_sbt_Shooter-> AddPersistent("Kicker Error", 0.0) .WithSize(2,1) .WithPosition(6,1) .GetEntry(); /* Is there a way to get the current speed of a TalonSRX Motor? */ m_nte_KickerMotorVoltage = m_sbt_Shooter-> AddPersistent("Kicker Motor Voltage", 0.0) .WithSize(2, 1) .WithPosition(6, 2) .GetEntry(); m_nte_IndexSensorOutput = m_sbt_Shooter-> AddPersistent("Index Sensor Output", 0.0) .WithSize(2,1) .WithPosition(8, 1) .GetEntry(); m_nte_LoadSensorOutput = m_sbt_Shooter-> AddPersistent("Load Sensor Output", 0.0) .WithSize(1, 1) .WithPosition(8, 2) .GetEntry(); m_nte_LoadSensorDistance = m_sbt_Shooter-> AddPersistent("Load Sensor Distance", 0.0) .WithSize(1,1) .WithPosition(9,2) .GetEntry(); m_nte_IntakeDelay = m_sbt_Shooter-> AddPersistent("Intake delay", 0.5) .WithSize(1,1) .WithPosition(3,4) .GetEntry(); m_nte_DesiredIntakeSpeed = m_sbt_Shooter-> AddPersistent("Desired Intake Speed", 0.0) .WithSize(1,1) .WithPosition(0,4) .GetEntry(); m_nte_ActualIntakeSpeed = m_sbt_Shooter-> AddPersistent("Actual Intake Speed", 0.0) .WithSize(1,1) .WithPosition(1,4) .GetEntry(); m_nte_ShooterDelay = m_sbt_Shooter-> AddPersistent("Shooter Delay", 0.0) .WithSize(1,1) .WithPosition(8,5) .GetEntry(); /* m_nte_JumblerStatus = m_sbt_Shooter-> AddPersistent("Jumbler Status", false) .WithWidget(frc::BuiltInWidgets::kToggleButton) .WithSize(2, 1) .WithPosition(3, 2) .GetEntry(); */ } #ifdef ENABLE_SHOOTER // This method will be called once per scheduler run void Shooter::Periodic() { // Update Network Table/Shuffleboard Values m_nte_TopMotorOutputRPM.SetDouble(GetTopMotorSpeed()); m_nte_BottomMotorOutputRPM.SetDouble(GetBottomMotorSpeed()); m_nte_KickerMotorVoltage.SetDouble(GetKickerMotorVoltage()); m_nte_KickerMotorError.SetDouble(GetKickerError()); m_nte_IndexSensorOutput.SetDouble(m_IndexSensor.GetRange()); m_nte_LoadSensorOutput.SetDouble(m_LoadSensor.GetAverageVoltage()); m_nte_LoadSensorDistance.SetDouble((m_LoadSensor.GetAverageVoltage() / ConShooter::Loader::VOLTAGE_TO_IN) + 1.7); m_nte_ActualIntakeSpeed.SetDouble(0.0); //FIXME:: Make this return the Load Motor's speed #if 0 // Test code for the sensors // Check TimeofFLight sensor to see if a powerCell is ... stuck? loaded? ?? frc::SmartDashboard::PutNumber("Range: ", m_IndexSensor.GetRange()); // Greater than 30 b/c if no object is sensed it returns between 0-1, right in front of the sensor returns ~40 if (m_IndexSensor.GetRange() < 300.0 && m_IndexSensor.GetRange() > 30.0) { // FIXME: range in mm frc::SmartDashboard::PutBoolean("PowerCell", true); m_indexMotor.Set(TalonSRXControlMode::PercentOutput, ConShooter::Indexer::MOTOR_SPEED); } else { frc::SmartDashboard::PutBoolean("PowerCell", false); m_indexMotor.Set(TalonSRXControlMode::PercentOutput, 0.0); } if (m_LoadSensor.GetAverageVoltage() < 2.0) { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, ConShooter::Loader::MOTOR_SPEED); } else { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, 0); } #endif } // Used internally only void Shooter::SetBottomMotorSpeed(double velocity) { double vlimit = (velocity > ConShooter::Bottom::MAX_RPM) ? ConShooter::Bottom::MAX_RPM : velocity; m_bottomVelocityPID.SetReference(vlimit, rev::ControlType::kVelocity); } // Used internally only void Shooter::SetTopMotorSpeed(double velocity) { double vlimit = (velocity > ConShooter::Top::MAX_RPM) ? ConShooter::Top::MAX_RPM : velocity; m_topVelocityPID.SetReference(vlimit, rev::ControlType::kVelocity); } // Used internally only for dashboard double Shooter::GetBottomMotorSpeed() { return m_bottomEncoder.GetVelocity(); } // Used internally only for dashboard double Shooter::GetTopMotorSpeed() { return m_topEncoder.GetVelocity(); } // Used internally only for dashboard double Shooter::GetKickerMotorVoltage() { // Showing current draw might be more useful? // return m_kickerMotor.GetOutputCurrent(); return m_kickerMotor.GetMotorOutputVoltage(); } // Used internally only for dashboard double Shooter::GetKickerError() { return m_kickerMotor.GetClosedLoopError(); } // Used by SpinUpShooter void Shooter::SpinUp() { double bottomMotorTarget = m_nte_BottomMotorInputRPM.GetDouble(ConShooter::Bottom::OPTIMAL_RPM); #if 0 // Implement Fine-Tuning of bottom shooter motor if (m_codriver_control != nullptr) { bottomMotorTarget += ConShooter::Bottom::RPM_FINE_TUNE * m_codriver_control->GetRawAxis(ConLaunchPad::Dial::RIGHT); } #endif SetTopMotorSpeed(m_nte_TopMotorInputRPM.GetDouble(ConShooter::Top::OPTIMAL_RPM)); SetBottomMotorSpeed(bottomMotorTarget); SetKickerSpeed(m_nte_KickerMotorSpeed.GetDouble(ConShooter::Kicker::OPTIMAL_RPM)); } // Used by SpinUpShooter void Shooter::StopSpinUp(){ //SetTopMotorSpeed(0.0); //SetBottomMotorSpeed(0.0); m_topVelocityPID.SetReference(0.0, rev::ControlType::kVoltage); m_bottomVelocityPID.SetReference(0.0, rev::ControlType::kVoltage); SetKickerSpeed(0.0); } // Used by JumbleShooter void Shooter::Jumble(int direction) { double speed = m_nte_JumblerMotorSpeed.GetDouble(ConShooter::Jumbler::MOTOR_SPEED); if (IsIndexSensorClear()) { if (direction != 1) { speed = -speed; } m_jumblerMotor.Set(TalonSRXControlMode::PercentOutput, speed); m_hopperFlapper.Set(TalonSRXControlMode::PercentOutput, ConShooter::HopperFlapper::MOTOR_SPEED); } else { m_jumblerMotor.Set(TalonSRXControlMode::PercentOutput, 0); } } void Shooter::ForceJumble(int direction) { double speed = m_nte_JumblerMotorSpeed.GetDouble(ConShooter::Jumbler::MOTOR_SPEED); if (direction != 1) { speed = -speed; } m_jumblerMotor.Set(TalonSRXControlMode::PercentOutput, speed); m_hopperFlapper.Set(TalonSRXControlMode::PercentOutput, ConShooter::HopperFlapper::MOTOR_SPEED); } // Used by JumbleShooter void Shooter::Dejumble() { m_jumblerMotor.Set(TalonSRXControlMode::PercentOutput, 0.0); m_hopperFlapper.Set(TalonSRXControlMode::PercentOutput, 0.0); } // "Choo choo" motor used by FlapHopper() for manual control void Shooter::FlapHopper() { m_hopperFlapper.Set(TalonSRXControlMode::PercentOutput, ConShooter::HopperFlapper::MOTOR_SPEED); } // "Choo choo" motor used by FlapHopper() for manual control void Shooter::StopFlapper() { m_hopperFlapper.Set(TalonSRXControlMode::PercentOutput, 0.0); } // Used internally only void Shooter::SetKickerSpeed(double speed) { // Power Mode... // m_kickerMotor.Set(TalonSRXControlMode::PercentOutput, speed); /// Velocity Mode for use with hex shaft encoder m_kickerMotor.Set(TalonSRXControlMode::Velocity, speed); } // Used by RobotContainer to bring controller object into subsystem // Periodic will check for reset of encoder void Shooter::SetCodriverControl(frc::XboxController *codriver_control) { m_codriver_control = codriver_control; } void Shooter::Index(int direction) { #if 0 // Turned off to test TOF sensor as the index sensor if (m_IndexSensor.GetRange() < 300.0 && m_IndexSensor.GetRange() > 30.0) { m_loadMotor.Set(TalonSRXControlMode::Velocity, 0); m_nte_DesiredIntakeSpeed.SetDouble(0.0); m_lastIntake = (m_timer.Get() - m_nte_IntakeDelay.GetDouble(0.0)); } else if (m_LoadSensor.GetAverageVoltage() < 2.0) { //FIXME: Change m_loadMotor.Set(TalonSRXControlMode::Velocity, (ConShooter::Loader::MOTOR_SPEED * direction)); m_lastIntake = m_timer.Get(); m_nte_DesiredIntakeSpeed.SetDouble(800.0); } else if (m_lastIntake + m_nte_IntakeDelay.GetDouble(0.0) < m_timer.Get()) { m_loadMotor.Set(TalonSRXControlMode::Velocity, 0); m_nte_DesiredIntakeSpeed.SetDouble(0.0); } #endif #if 0 if (m_IndexSensor.GetRange() < 100.0 ) { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, (m_nte_DesiredIntakeSpeed.GetDouble(0.1))); m_lastIntake = m_timer.Get(); } else if ((m_lastIntake + m_nte_IntakeDelay.GetDouble(0.0) < m_timer.Get())) { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, 0); } #endif #if 0 if (m_IndexSensor.GetRange() < 100.0) { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, m_nte_DesiredIntakeSpeed.GetDouble(0.1)); } else { m_loadMotor.Set(TalonSRXControlMode::PercentOutput, 0); } #endif } void Shooter::Undex() { m_loadMotor.Set(TalonSRXControlMode::Velocity, 0); //m_nte_DesiredIntakeSpeed.SetDouble(0.0); } void Shooter::ForceIndex(int direction) { m_loadMotor.Set(TalonSRXControlMode::Velocity, 800 * direction); m_nte_DesiredIntakeSpeed.SetDouble(800.0 * direction); } bool Shooter::IsIndexSensorClear() { return (m_IndexSensor.GetRange() > 300.0 || m_IndexSensor.GetRange() < 30.0); } double Shooter::ShooterDelay() { return m_nte_ShooterDelay.GetDouble(0.0); } #endif // ENABLE_SHOOTER
35.478261
129
0.712731
[ "object" ]
663255f80c11a8f6194f9b9c7b8f2b997e63cdce
6,483
cc
C++
src/HostManager.cc
ARCCN/Host-Manager
f574471839f4bc404229f92f566b54d68bfcdc72
[ "Apache-2.0" ]
null
null
null
src/HostManager.cc
ARCCN/Host-Manager
f574471839f4bc404229f92f566b54d68bfcdc72
[ "Apache-2.0" ]
null
null
null
src/HostManager.cc
ARCCN/Host-Manager
f574471839f4bc404229f92f566b54d68bfcdc72
[ "Apache-2.0" ]
1
2019-10-24T17:11:07.000Z
2019-10-24T17:11:07.000Z
/* * Copyright 2015 Applied Research Center for Computer Networks * * 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 "HostManager.hpp" #include "Controller.hpp" #include "PacketParser.hpp" #include "oxm/openflow_basic.hh" #include <boost/lexical_cast.hpp> #include <fluid/util/ipaddr.hh> namespace runos { REGISTER_APPLICATION(HostManager, {"switch-manager", ""}) struct HostImpl { uint64_t id; std::string mac; ipv4addr ip; uint64_t switchID; uint32_t switchPort; }; struct HostManagerImpl { // mac address -> Host std::unordered_map<std::string, Host*> hosts; }; Host::Host(std::string mac, ipv4addr ip) { m = new HostImpl; m->mac = mac; m->ip = ip; m->id = rand()%1000 + 1000; } Host::~Host() { delete m; } uint64_t Host::id() const { return m->id; } std::string Host::mac() const { return m->mac; } std::string Host::ip() const { return boost::lexical_cast<std::string>(m->ip); } uint64_t Host::switchID() const { return m->switchID; } uint32_t Host::switchPort() const { return m->switchPort; } json11::Json Host::to_json() const { return json11::Json::object { {"ID", boost::lexical_cast<std::string>(id())}, {"mac", mac()}, {"switch_id", boost::lexical_cast<std::string>(switchID())}, {"switch_port", (int)switchPort()} }; } void Host::switchID(uint64_t id) { m->switchID = id; } void Host::switchPort(uint32_t port) { m->switchPort = port; } void Host::ip(std::string ip) { m->ip = convert(ip).first; } void Host::ip(ipv4addr ip) { m->ip = ipv4addr(ip); } HostManager::HostManager() { m = new HostManagerImpl; } HostManager::~HostManager() { delete m; } void HostManager::init(Loader *loader, const Config &config) { m_switch_manager = SwitchManager::get(loader); const auto ofb_in_port = oxm::in_port(); const auto ofb_eth_type = oxm::eth_type(); const auto ofb_eth_src = oxm::eth_src(); const auto ofb_arp_spa = oxm::arp_spa(); const auto ofb_ipv4_src = oxm::ipv4_src(); handler = Controller::get(loader)->register_handler( [=](of13::PacketIn& pi, OFConnectionPtr connection) { PacketParser pp(pi); Packet& pkt(pp); ethaddr eth_src = pkt.load(ofb_eth_src); std::string host_mac = boost::lexical_cast<std::string>(eth_src); ipv4addr host_ip(convert("0.0.0.0").first); if (pkt.test(ofb_eth_type == 0x0800)) { host_ip = ipv4addr(pkt.load(ofb_ipv4_src)); } else if (pkt.test(ofb_eth_type == 0x0806)) { host_ip = ipv4addr(pkt.load(ofb_arp_spa)); } if (isSwitch(host_mac)) return false; uint32_t in_port = pkt.load(ofb_in_port); if (in_port > of13::OFPP_MAX) return false; if (not findMac(host_mac)) { auto sw = m_switch_manager->switch_(connection->dpid()); addHost(sw, host_ip, host_mac, in_port); LOG(INFO) << "Host discovered. MAC: " << host_mac << ", IP: " << host_ip << ", Switch ID: " << sw->dpid() << ", port: " << in_port; } else { Host* h = getHost(host_mac); if (host_ip != convert("0.0.0.0").first) { h->ip(host_ip); } } return false; }, -40 ); QObject::connect(m_switch_manager, &SwitchManager::switchUp, this, &HostManager::onSwitchDiscovered); QObject::connect(m_switch_manager, &SwitchManager::switchDown, this, &HostManager::onSwitchDown); } void HostManager::onSwitchDiscovered(SwitchPtr dp) { QObject::connect(dp.get(), &Switch::portAdded, this, &HostManager::newPort); } void HostManager::onSwitchDown(SwitchPtr dp) { delHostForSwitch(dp); for (auto port : dp->ports()) { auto pos = std::find(switch_macs.begin(), switch_macs.end(), boost::lexical_cast<std::string>(port->hw_addr())); if (pos != switch_macs.end()) switch_macs.erase(pos); } } void HostManager::addHost(SwitchPtr sw, ipv4addr ip, std::string mac, uint32_t port) { std::lock_guard<std::mutex> lk(mutex); Host* dev = createHost(mac, ip); attachHost(mac, sw->dpid(), port); emit hostDiscovered(dev); } Host* HostManager::createHost(std::string mac, ipv4addr ip) { Host* dev = new Host(mac, ip); m->hosts[mac] = dev; return dev; } bool HostManager::findMac(std::string mac) { if (m->hosts.count(mac) > 0) return true; return false; } bool HostManager::isSwitch(std::string mac) { for (auto sw_mac : switch_macs) { if (sw_mac == mac) return true; } return false; } void HostManager::attachHost(std::string mac, uint64_t id, uint32_t port) { m->hosts[mac]->switchID(id); m->hosts[mac]->switchPort(port); } void HostManager::delHostForSwitch(SwitchPtr dp) { auto itr = m->hosts.begin(); while (itr != m->hosts.end()) { if (itr->second->switchID() == dp->dpid()) { m->hosts.erase(itr++); } else ++itr; } } Host* HostManager::getHost(std::string mac) { if (m->hosts.count(mac) > 0) return m->hosts[mac]; else return nullptr; } Host* HostManager::getHost(ipv4addr ip) { auto string_ip = boost::lexical_cast<std::string>(ip); for (auto it : m->hosts) { if (it.second->ip() == string_ip) return it.second; } return nullptr; } void HostManager::newPort(PortPtr port) { switch_macs.push_back(boost::lexical_cast<std::string>(port->hw_addr())); } std::unordered_map<std::string, Host*> HostManager::hosts() { return m->hosts; } } // namespace runos
25.72619
120
0.594786
[ "object" ]
6641244609956b2e3b022a252b70c40c7f58a7e3
22,732
cc
C++
client/client.cc
rescrv/Consus
bb05df2f314b1dc7510a3fb73604491227ebc516
[ "BSD-3-Clause" ]
239
2016-12-13T16:27:52.000Z
2021-09-19T20:46:38.000Z
client/client.cc
ngaut/Consus
bb05df2f314b1dc7510a3fb73604491227ebc516
[ "BSD-3-Clause" ]
6
2016-12-19T02:11:28.000Z
2017-09-07T02:44:47.000Z
client/client.cc
ngaut/Consus
bb05df2f314b1dc7510a3fb73604491227ebc516
[ "BSD-3-Clause" ]
16
2016-12-18T09:48:28.000Z
2019-01-27T08:51:34.000Z
// Copyright (c) 2015-2017, Robert Escriva, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Consus 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. // po6 #include <po6/time.h> // treadstone #include <treadstone.h> // consus #include "common/client_configuration.h" #include "common/consus.h" #include "common/coordinator_returncode.h" #include "common/kvs_configuration.h" #include "common/macros.h" #include "common/paxos_group.h" #include "common/txman_configuration.h" #include "client/client.h" #include "client/pending.h" #include "client/pending_begin_transaction.h" #include "client/pending_string.h" using consus::client; #define ERROR(CODE) \ *status = CONSUS_ ## CODE; \ m_last_error.set_loc(__FILE__, __LINE__); \ m_last_error.set_msg() #define _BUSYBEE_ERROR(BBRC) \ case BUSYBEE_ ## BBRC: \ ERROR(INTERNAL) << "internal error: BusyBee unexpectedly returned " XSTR(BBRC) << ": please file a bug" #define BUSYBEE_ERROR_CASE(BBRC) \ _BUSYBEE_ERROR(BBRC); \ return -1; #define BUSYBEE_ERROR_CASE_FALSE(BBRC) \ _BUSYBEE_ERROR(BBRC); \ return false; client :: client(const char* host, uint16_t port) : m_coord(replicant_client_create(host, port)) , m_config() , m_config_id(-1) , m_config_status(REPLICANT_SUCCESS) , m_config_state(0) , m_config_data(NULL) , m_config_data_sz(0) , m_busybee_controller(&m_config) , m_busybee(busybee_client::create(&m_busybee_controller)) , m_next_client_id(1) , m_next_server_nonce(1) , m_pending() , m_returnable() , m_returned() , m_flagfd() , m_last_error() { if (!m_coord) { throw std::bad_alloc(); } busybee_returncode rc = m_busybee->set_external_fd(replicant_client_poll_fd(m_coord)); assert(rc == BUSYBEE_SUCCESS); } client :: client(const char* conn_str) : m_coord(replicant_client_create_conn_str(conn_str)) , m_config() , m_config_id(-1) , m_config_status(REPLICANT_SUCCESS) , m_config_state(0) , m_config_data(NULL) , m_config_data_sz(0) , m_busybee_controller(&m_config) , m_busybee(busybee_client::create(&m_busybee_controller)) , m_next_client_id(1) , m_next_server_nonce(1) , m_pending() , m_returnable() , m_returned() , m_flagfd() , m_last_error() { if (!m_coord) { throw std::bad_alloc(); } busybee_returncode rc = m_busybee->set_external_fd(replicant_client_poll_fd(m_coord)); assert(rc == BUSYBEE_SUCCESS); } client :: ~client() throw () { replicant_client_destroy(m_coord); } int64_t client :: loop(int timeout, consus_returncode* status) { *status = CONSUS_SUCCESS; m_last_error = e::error(); while (!m_returnable.empty() || !m_pending.empty()) { if (!m_returnable.empty()) { m_returned = m_returnable.front(); m_returnable.pop_front(); m_last_error = m_returned->error(); return m_returned->client_id(); } if (inner_loop(timeout, status) < 0) { return -1; } } return post_loop(status); } int64_t client :: wait(int64_t id, int timeout, consus_returncode* status) { *status = CONSUS_SUCCESS; m_last_error = e::error(); while (true) { for (std::list<e::intrusive_ptr<pending> >::iterator it = m_returnable.begin(); it != m_returnable.end(); ++it) { pending* p = it->get(); if (p->client_id() == id) { m_returned = *it; m_returnable.erase(it); m_last_error = m_returned->error(); return m_returned->client_id(); } } if (inner_loop(timeout, status) < 0) { return -1; } } return post_loop(status); } int64_t client :: begin_transaction(consus_returncode* status, consus_transaction** xact) { if (!maintain_coord_connection(status)) { return -1; } int64_t client_id = generate_new_client_id(); pending* p = new pending_begin_transaction(client_id, status, xact); p->kickstart_state_machine(this); return client_id; } int client :: create_data_center(const char* name, consus_returncode* status) { std::string tmp; e::packer(&tmp) << e::slice(name); replicant_returncode rc; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_call(m_coord, "consus", "data_center_create", tmp.data(), tmp.size(), REPLICANT_CALL_ROBUST, &rc, &data, &data_sz); if (!replicant_finish(id, &rc, status)) { return -1; } // XXX if (data) free(data); #if 0 coordinator_returncode crc; e::unpacker up(data, data_sz); up = up >> e::unpack_uint16(crc); if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: invalid return value"; return -1; } switch (crc) { case COORDINATOR_SUCCESS: *status = REPLICANT_SUCCESS; return 0; } abort(); #endif return 0; } int client :: set_default_data_center(const char* name, consus_returncode* status) { std::string tmp; e::packer(&tmp) << e::slice(name); replicant_returncode rc; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_call(m_coord, "consus", "data_center_default", tmp.data(), tmp.size(), REPLICANT_CALL_ROBUST, &rc, &data, &data_sz); if (!replicant_finish(id, &rc, status)) { return -1; } // XXX if (data) free(data); #if 0 coordinator_returncode crc; e::unpacker up(data, data_sz); up = up >> e::unpack_uint16(crc); if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: invalid return value"; return -1; } switch (crc) { case COORDINATOR_SUCCESS: *status = REPLICANT_SUCCESS; return 0; } abort(); #endif return 0; } int client :: availability_check(consus_availability_requirements* reqs, int timeout, consus_returncode* status) { if (!maintain_coord_connection(status)) { return -1; } const uint64_t start = po6::monotonic_time(); uint64_t now = 0; uint64_t version = 0; while (timeout < 0 || start + PO6_SECONDS * timeout >= (now = po6::monotonic_time())) { replicant_returncode rc = REPLICANT_GARBAGE; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_cond_wait(m_coord, "consus", "txmanconf", version, &rc, &data, &data_sz); int to = -1; if (timeout >= 0) { to = (start + PO6_SECONDS * timeout - now) / PO6_MILLIS + 1; to = std::min(to, int(100)); } if (!replicant_finish(id, to, &rc, status)) { replicant_client_kill(m_coord, id); if (rc == REPLICANT_TIMEOUT) { continue; } else { return -1; } } assert(data || data_sz == 0); e::unpacker up(data, data_sz); cluster_id cid; version_id vid; uint64_t flags; std::vector<data_center> dcs; std::vector<txman_state> txmans; std::vector<paxos_group> txman_groups; std::vector<kvs> kvss; up = txman_configuration(up, &cid, &vid, &flags, &dcs, &txmans, &txman_groups, &kvss); if (data) { free(data); } if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: bad client configuration"; return -1; } version = vid.get() + 1; unsigned txmans_avail = 0; for (size_t i = 0; i < txmans.size(); ++i) { if (txmans[i].state == txman_state::ONLINE) { ++txmans_avail; } } if (txmans_avail < reqs->txmans || txman_groups.size() < reqs->txman_groups || kvss.size() < reqs->kvss) { continue; } if (!reqs->stable) { *status = CONSUS_SUCCESS; return 0; } rc = REPLICANT_GARBAGE; data = NULL; data_sz = 0; id = replicant_client_call(m_coord, "consus", "is_stable", NULL, 0, REPLICANT_CALL_IDEMPOTENT, &rc, &data, &data_sz); if (!replicant_finish(id, -1, &rc, status)) { replicant_client_kill(m_coord, id); return -1; } assert(data || data_sz == 0); up = e::unpacker(data, data_sz); coordinator_returncode ccr; up = up >> ccr; if (data) { free(data); } if (!up.error() && ccr == COORD_SUCCESS) { *status = CONSUS_SUCCESS; return 0; } } ERROR(TIMEOUT) << "operation timed out"; return -1; } bool client :: replicant_finish(int64_t id, replicant_returncode* rc, consus_returncode* status) { return replicant_finish(id, -1, rc, status); } bool client :: replicant_finish(int64_t id, int timeout, replicant_returncode* rc, consus_returncode* status) { if (id < 0) { ERROR(COORD_FAIL) << "coordinator failure: " << replicant_client_error_message(m_coord); return false; } replicant_returncode lrc; int64_t lid = replicant_client_wait(m_coord, id, timeout, &lrc); if (lid < 0) { *rc = lrc; ERROR(COORD_FAIL) << "coordinator failure: " << replicant_client_error_message(m_coord); return false; } assert(id == lid); if (*rc != REPLICANT_SUCCESS) { ERROR(COORD_FAIL) << "coordinator failure: " << replicant_client_error_message(m_coord); return false; } return true; } int client :: debug_client_configuration(consus_returncode* status, const char** str) { if (!maintain_coord_connection(status)) { return -1; } replicant_returncode rc = REPLICANT_GARBAGE; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_cond_wait(m_coord, "consus", "clientconf", 0, &rc, &data, &data_sz); if (!replicant_finish(id, &rc, status) || (!data && data_sz != 0)) { return -1; } e::unpacker up(data, data_sz); cluster_id cid; version_id vid; uint64_t flags; std::vector<txman> txmans; up = client_configuration(up, &cid, &vid, &flags, &txmans); free(data); if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: bad client configuration"; return -1; } std::ostringstream ostr; ostr << cid << "\n" << vid << "\n"; if (txmans.empty()) { ostr << "no transaction managers"; } else if (txmans.size() == 1) { ostr << "1 transaction manager:\n"; } else { ostr << txmans.size() << " transaction managers:\n"; } for (unsigned i = 0; i < txmans.size(); ++i) { ostr << txmans[i] << "\n"; } e::intrusive_ptr<pending_string> p = new pending_string(ostr.str()); *str = p->string(); m_returned = p.get(); *status = CONSUS_SUCCESS; m_last_error = e::error(); return 0; } int client :: debug_txman_configuration(consus_returncode* status, const char** str) { if (!maintain_coord_connection(status)) { return -1; } replicant_returncode rc = REPLICANT_GARBAGE; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_cond_wait(m_coord, "consus", "txmanconf", 0, &rc, &data, &data_sz); if (!replicant_finish(id, &rc, status) || (!data && data_sz != 0)) { return -1; } e::unpacker up(data, data_sz); cluster_id cid; version_id vid; uint64_t flags; std::vector<data_center> dcs; std::vector<txman_state> txmans; std::vector<paxos_group> txman_groups; std::vector<kvs> kvss; up = txman_configuration(up, &cid, &vid, &flags, &dcs, &txmans, &txman_groups, &kvss); free(data); if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: bad client configuration"; return -1; } std::string s = txman_configuration(cid, vid, flags, dcs, txmans, txman_groups, kvss); e::intrusive_ptr<pending_string> p = new pending_string(s); *str = p->string(); m_returned = p.get(); *status = CONSUS_SUCCESS; m_last_error = e::error(); return 0; } int client :: debug_kvs_configuration(consus_returncode* status, const char** str) { if (!maintain_coord_connection(status)) { return -1; } replicant_returncode rc = REPLICANT_GARBAGE; char* data = NULL; size_t data_sz = 0; int64_t id = replicant_client_cond_wait(m_coord, "consus", "kvsconf", 0, &rc, &data, &data_sz); if (!replicant_finish(id, &rc, status) || (!data && data_sz != 0)) { return -1; } e::unpacker up(data, data_sz); cluster_id cid; version_id vid; uint64_t flags; std::vector<kvs_state> kvss; std::vector<ring> rings; up = kvs_configuration(up, &cid, &vid, &flags, &kvss, &rings); free(data); if (up.error()) { ERROR(COORD_FAIL) << "coordinator failure: bad client configuration"; return -1; } std::string s = kvs_configuration(cid, vid, flags, kvss, rings); e::intrusive_ptr<pending_string> p = new pending_string(s); *str = p->string(); m_returned = p.get(); *status = CONSUS_SUCCESS; m_last_error = e::error(); return 0; } const char* client :: error_message() { return m_last_error.msg(); } const char* client :: error_location() { return m_last_error.loc(); } void client :: set_error_message(const char* msg) { m_last_error = e::error(); m_last_error.set_loc(__FILE__, __LINE__); m_last_error.set_msg() << msg; } uint64_t client :: generate_new_nonce() { return m_next_server_nonce++; } int64_t client :: generate_new_client_id() { return m_next_client_id++; } void client :: initialize(server_selector* ss) { m_config.initialize(ss); } void client :: add_to_returnable(pending* p) { m_returnable.push_back(p); } bool client :: send(uint64_t nonce, comm_id id, std::auto_ptr<e::buffer> msg, pending* p) { busybee_returncode rc = m_busybee->send(id.get(), msg); if (rc == BUSYBEE_DISRUPTED) { handle_disruption(id); } if (rc == BUSYBEE_SUCCESS) { m_pending[std::make_pair(id, nonce)] = p; } return rc == BUSYBEE_SUCCESS; } void client :: handle_disruption(const comm_id& id) { for (std::map<std::pair<comm_id, uint64_t>, e::intrusive_ptr<pending> >::iterator it = m_pending.begin(); it != m_pending.end(); ) { if (it->first.first == id) { e::intrusive_ptr<pending> p = it->second; m_pending.erase(it); p->handle_server_disruption(this, id); it = m_pending.begin(); } else { ++it; } } } int64_t client :: inner_loop(int timeout, consus_returncode* status) { uint64_t cid_num; std::auto_ptr<e::buffer> msg; busybee_returncode rc = m_busybee->recv(timeout, &cid_num, &msg); comm_id id(cid_num); switch (rc) { case BUSYBEE_SUCCESS: break; case BUSYBEE_INTERRUPTED: ERROR(INTERRUPTED) << "signal received"; return -1; case BUSYBEE_TIMEOUT: return 0; case BUSYBEE_DISRUPTED: handle_disruption(id); return 0; case BUSYBEE_EXTERNAL: if (!maintain_coord_connection(status)) { return -1; } return 0; case BUSYBEE_SEE_ERRNO: ERROR(SEE_ERRNO) << po6::strerror(errno); return -1; BUSYBEE_ERROR_CASE(SHUTDOWN); default: ERROR(INTERNAL) << "internal error: BusyBee unexpectedly returned " << (unsigned) rc << ": please file a bug"; return -1; } network_msgtype msg_type; uint64_t nonce; e::unpacker up = msg->unpack_from(BUSYBEE_HEADER_SIZE); up = up >> msg_type; if (up.error()) { ERROR(SERVER_ERROR) << "communication error: server " << cid_num << " sent message=" << msg->as_slice().hex() << " with invalid header"; return -1; } if (msg_type == TXMAN_FINISHED) { transaction_group tg; uint64_t outcome; up = up >> tg >> outcome; if (up.error()) { ERROR(SERVER_ERROR) << "communication error: server " << cid_num << " sent invalid message=" << msg->as_slice().hex() << " about a finished transaction"; return -1; } std::map<std::pair<comm_id, uint64_t>, e::intrusive_ptr<pending> >::iterator it; for (it = m_pending.begin(); it != m_pending.end(); ) { e::intrusive_ptr<pending> p(it->second); if (p->transaction_finished(this, tg, outcome)) { m_pending.erase(it); it = m_pending.begin(); } else { ++it; } } return 0; } else if (msg_type != CLIENT_RESPONSE) { ERROR(SERVER_ERROR) << "communication error: server " << cid_num << " sent message=" << msg->as_slice().hex() << " which is not a client response"; return -1; } up = up >> nonce; if (up.error()) { ERROR(SERVER_ERROR) << "communication error: server " << cid_num << " sent message=" << msg->as_slice().hex() << " without nonce"; return -1; } std::map<std::pair<comm_id, uint64_t>, e::intrusive_ptr<pending> >::iterator it; it = m_pending.find(std::make_pair(id, nonce)); if (it != m_pending.end()) { e::intrusive_ptr<pending> p(it->second); m_pending.erase(it); p->handle_busybee_op(this, nonce, msg, up); return p->client_id(); } return 0; } int64_t client :: post_loop(consus_returncode* status) { uint64_t cid_num; busybee_returncode rc = m_busybee->recv_no_msg(0, &cid_num); switch (rc) { case BUSYBEE_TIMEOUT: break; case BUSYBEE_INTERRUPTED: ERROR(INTERRUPTED) << "signal received"; return -1; case BUSYBEE_DISRUPTED: handle_disruption(comm_id(cid_num)); break; case BUSYBEE_EXTERNAL: if (!maintain_coord_connection(status)) { return -1; } break; case BUSYBEE_SEE_ERRNO: ERROR(SEE_ERRNO) << po6::strerror(errno); return -1; BUSYBEE_ERROR_CASE(SHUTDOWN); case BUSYBEE_SUCCESS: default: ERROR(INTERNAL) << "internal error: BusyBee unexpectedly returned " << (unsigned) rc << ": please file a bug"; return -1; } ERROR(NONE_PENDING) << "no outstanding operations to process"; return -1; } bool client :: maintain_coord_connection(consus_returncode* status) { if (m_config_status != REPLICANT_SUCCESS) { replicant_client_kill(m_coord, m_config_id); m_config_id = -1; } if (m_config_id < 0) { m_config_id = replicant_client_cond_follow(m_coord, "consus", "clientconf", &m_config_status, &m_config_state, &m_config_data, &m_config_data_sz); replicant_returncode rc; if (replicant_client_wait(m_coord, m_config_id, -1, &rc) < 0) { ERROR(COORD_FAIL) << "coordinator failure: " << replicant_client_error_message(m_coord); return false; } } replicant_returncode rc; if (replicant_client_loop(m_coord, 0, &rc) < 0) { if (rc == REPLICANT_TIMEOUT || rc == REPLICANT_INTERRUPTED || rc == REPLICANT_NONE_PENDING) { } else { ERROR(COORD_FAIL) << "coordinator failure: " << replicant_client_error_message(m_coord); return false; } } if (m_config.version().get() < m_config_state) { configuration new_config; e::unpacker up(m_config_data, m_config_data_sz); up = up >> new_config; if (!up.error()) { m_config = new_config; } } return true; }
25.949772
111
0.571705
[ "vector" ]
664af8d4238d924fc7efebcb47dc19ea0d6068c4
833
cpp
C++
HackerRank/C++/VariableSizedArray.cpp
Iltwats/Competitive-Programming-
5e3af928e10d06a11dd5daab1b572184029ac3a4
[ "MIT" ]
1
2020-09-29T11:21:22.000Z
2020-09-29T11:21:22.000Z
HackerRank/C++/VariableSizedArray.cpp
Iltwats/Competitive-Programming-
5e3af928e10d06a11dd5daab1b572184029ac3a4
[ "MIT" ]
null
null
null
HackerRank/C++/VariableSizedArray.cpp
Iltwats/Competitive-Programming-
5e3af928e10d06a11dd5daab1b572184029ac3a4
[ "MIT" ]
null
null
null
// For problem and its details: https://www.hackerrank.com/challenges/variable-sized-arrays/problem #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n; int q; cin >> n >> q; vector<int> a[n]; for(int i = 0; i < n; i++){ int m; cin >> m; int o; for(int j = 0; j < m; j++){ cin >> o; a[i].push_back(o); // for every i, m elements array is inserted into the array i.e a[2]={1,2,3,4} till n here i =2 } } int r, s; for(int k = 1; k <= q; k++){ cin >> r >> s; cout << a[r][s] << endl; // then just printing the specific position from array like if r=2, and s=2 from above O/P will be 3. } return 0; }
22.513514
109
0.510204
[ "vector" ]
664b8cb55b0076ecbadbe1788971340d34899571
791
cpp
C++
1st/plus_one.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/plus_one.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
1st/plus_one.cpp
buptlxb/leetcode
b641419de040801c4f54618d7ee26edcf10ee53c
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int> &digits) { int carry, tmp; for (vector<int>::reverse_iterator iter = digits.rbegin(); iter != digits.rend(); iter++) { tmp = *iter + 1; carry = tmp / 10; *iter = tmp % 10; if (!carry) break; } if (carry) digits.insert(digits.begin(), 1); return digits; } }; int main(void) { vector<int> vec(5, 8); vector<int> ret = Solution().plusOne(vec); for (vector<int>::iterator iter = ret.begin(); iter != ret.end(); iter++) { cout << *iter; } cout << endl; return 0; }
23.969697
103
0.472819
[ "vector" ]
664d1daf4fdcaf7aea12fcc9f85ad1e1d8b6adab
5,085
hpp
C++
src/SivComponent/Collision/Colliders.hpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
1
2021-01-24T08:55:59.000Z
2021-01-24T08:55:59.000Z
src/SivComponent/Collision/Colliders.hpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
2
2021-01-24T06:12:12.000Z
2021-01-24T14:37:10.000Z
src/SivComponent/Collision/Colliders.hpp
mak1a/SivComponent
1043cde67a5dc14f2d4e0128aecfee7f54ed7002
[ "MIT" ]
null
null
null
#pragma once #define NO_S3D_USING #include <Siv3D.hpp> #include "ICollider.hpp" // #include <list> #include "../../ComponentEngine/AttachableComponent.hpp" // #include "../ComponentEngine/GameObject.hpp" // #include "../ComponentEngine/IComponent.hpp" #include "CollisionSystem.hpp" namespace ComponentEngine::Collision { template <class Shape> class Collider : public ICollider, public AttachableComponent { Shape shape; public: Shape GetShape() const { return shape; } void SetShape(const Shape& _shape) { shape = _shape; } Shape& row_shape() { return shape; } virtual bool intersects(const s3d::Circle& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::Rect& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::RectF& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::Line& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::Triangle& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::Quad& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::RoundRect& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::Polygon& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } virtual bool intersects(const s3d::LineString& other) const override { return other.intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } // virtual bool intersects(const ICollider& other) const override virtual bool intersects(ICollider* other) const override { return other->intersects(Collision::transformed(shape, GetGameObject().lock()->transform().GetMatrix())); } private: virtual void Start() override final { GetGameObject().lock()->template GetComponent<CollisionObject>()->Register(this); } virtual void OnDestroy() override final { GetGameObject().lock()->template GetComponent<CollisionObject>()->Dispose(this); } }; using CircleCollider = Collider<s3d::Circle>; // using RectCollider = Collider<s3d::Rect>; // using RectFCollider = Collider<s3d::RectF>; using RectCollider = Collider<s3d::RectF>; using LineCollider = Collider<s3d::Line>; // using TriangleCollider = Collider<s3d::Triangle>; using QuadCollider = Collider<s3d::Quad>; // using RoundRectCollider = Collider<s3d::RoundRect>; // using PolygonCollider = Collider<s3d::Polygon>; // using LineStringCollider = Collider<s3d::LineString>; // template <class Shape> // class Collider : public AttachableComponent, public ColliderBase // { // virtual void Start() override final // { // GetGameObject().lock()->template GetComponent<CollisionSystem>()->Register(this); // } // virtual void OnDestory() override final // { // GetGameObject().lock()->template GetComponent<CollisionSystem>()->Dispose(this); // } // public: // void SetShape(const Shape& _shape) // { // shape = _shape; // } // void GetShape() const // { // return shape; // } // bool intersects(const Collider& other) const // { // return intersects(other.shape); // } // }; // using CircleCollider = Collider<s3d::Circle>; // using RectCollider = Collider<s3d::Rect>; // using RectFCollider = Collider<s3d::RectF>; // using LineCollider = Collider<s3d::Line>; // using TriangleCollider = Collider<s3d::Triangle>; // using QuadCollider = Collider<s3d::Quad>; // using RoundRectCollider = Collider<s3d::RoundRect>; // using PolygonCollider = Collider<s3d::Polygon>; // using LineStringCollider = Collider<s3d::LineString>; } // namespace ComponentEngine::Collision
33.453947
117
0.616912
[ "shape", "transform" ]
5949743e38c474f5ff0620d764aa20f751b43978
1,082
cpp
C++
src/camlsnark_c/libsnark-caml/depends/libfqfft/tutorials/polynomial_multiplication_on_fft_example.cpp
Pratyush/snarky
4776e98ba72d4c8706c689fd747462ef87db8799
[ "MIT" ]
71
2016-07-21T02:49:57.000Z
2022-03-23T12:46:13.000Z
src/camlsnark_c/libsnark-caml/depends/libfqfft/tutorials/polynomial_multiplication_on_fft_example.cpp
Pratyush/snarky
4776e98ba72d4c8706c689fd747462ef87db8799
[ "MIT" ]
11
2017-05-09T03:47:55.000Z
2021-03-26T01:53:39.000Z
src/camlsnark_c/libsnark-caml/depends/libfqfft/tutorials/polynomial_multiplication_on_fft_example.cpp
Pratyush/snarky
4776e98ba72d4c8706c689fd747462ef87db8799
[ "MIT" ]
41
2016-07-22T05:54:38.000Z
2022-03-28T12:11:55.000Z
#include <cstdio> #include <vector> #include <libff/common/double.hpp> #include <libfqfft/polynomial_arithmetic/basic_operations.hpp> using namespace libfqfft; /* Polynomial Multiplication via FFT */ template <typename FieldT> void polynomial_multiplication_on_FFT_example () { /* Polynomial a = 1 + 2x + 3x^2 + x^3 */ std::vector<FieldT> a = { 1, 2, 3, 1 }; /* Polynomial b = 1 + 2x + x^2 + x^3 */ std::vector<FieldT> b = { 1, 2, 1, 1 }; /* * c = a * b * = (1 + 2x + 3x^2 + x^3) * (1 + 2x + x^2 + x^3) * = 1 + 4x + 8x^2 + 10x^3 + 7x^4 + 4x^5 + x^6 */ std::vector<FieldT> c(1, FieldT::zero()); _polynomial_multiplication(c, a, b); /* Print out the polynomial in human-readable form */ for (size_t i = 0; i < c.size(); i++) { unsigned long coefficient = c[i].as_ulong(); if (i == 0) std::cout << coefficient << " + "; else if (i < 6) std::cout << coefficient << "x^" << i << " + "; else std::cout << coefficient << "x^" << i << std::endl; } } int main() { polynomial_multiplication_on_FFT_example<libff::Double> (); }
25.162791
67
0.577634
[ "vector" ]
5950778a887cb6711d509e8bd3406d2f0321de70
2,107
cpp
C++
src/graphicsnodescene.cpp
rochus/qt5-node-editor
9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a
[ "MIT" ]
168
2015-07-02T09:41:31.000Z
2020-12-29T11:33:09.000Z
src/graphicsnodescene.cpp
Guyiguang/qt5-node-editor
9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a
[ "MIT" ]
11
2015-06-19T07:39:40.000Z
2018-09-04T13:49:23.000Z
src/graphicsnodescene.cpp
rochus/qt5-node-editor
9c9bc9b713aa6fe4c59e6d70ce0115a2800d461a
[ "MIT" ]
52
2015-04-02T03:59:26.000Z
2020-12-29T11:33:10.000Z
/* See LICENSE file for copyright and license details. */ #include "graphicsnodescene.hpp" #include <cmath> #include <QPainter> #include <QGraphicsTextItem> #include <algorithm> #include <iostream> // TODO: move to graphicsnodeview. use graphicsnodescene for management GraphicsNodeScene::GraphicsNodeScene(QObject *parent) : QGraphicsScene(parent) , _color_background(QColor("#393939")) , _color_light(QColor("#2F2F2F")) , _color_dark(QColor("#292929")) , _pen_light(QPen(_color_light)) , _pen_dark(QPen(_color_dark)) , _brush_background(_color_background) { // initialize default pen settings for (auto p : {&_pen_light, &_pen_dark}) { p->setWidth(0); } // initialize the background setBackgroundBrush(_brush_background); } /* * TODO: move the visualization into the graphicsview, and move all the GUI * logic into the graphicsnodescene */ void GraphicsNodeScene:: drawBackground(QPainter *painter, const QRectF &rect) { // call parent method QGraphicsScene::drawBackground(painter, rect); // augment the painted with grid const int gridsize = 20; auto left = static_cast<int>(std::floor(rect.left())); auto right = static_cast<int>(std::ceil(rect.right())); auto top = static_cast<int>(std::floor(rect.top())); auto bottom = static_cast<int>(std::ceil(rect.bottom())); // compute indices of lines to draw const auto first_left = left - (left % gridsize); const auto first_top = top - (top % gridsize); // compute lines to draw and std::vector<QLine> lines_light; std::vector<QLine> lines_dark; for (auto x = first_left; x <= right; x += gridsize) { if (x % 100 != 0) lines_light.push_back(QLine(x, top, x, bottom)); else lines_dark.push_back(QLine(x, top, x, bottom)); } for (auto y = first_top; y <= bottom; y += gridsize) { if (y % 100 != 0) lines_light.push_back(QLine(left, y, right, y)); else lines_dark.push_back(QLine(left, y, right, y)); } // draw calls painter->setPen(_pen_light); painter->drawLines(lines_light.data(), lines_light.size()); painter->setPen(_pen_dark); painter->drawLines(lines_dark.data(), lines_dark.size()); }
27.723684
75
0.713811
[ "vector" ]
5960dca9f40b38f0c1acdea47da49d5bd00231b2
3,603
cpp
C++
modules/task_2/zarubin_m_bubble_sort_even_odd_algorithm/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_2/zarubin_m_bubble_sort_even_odd_algorithm/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/zarubin_m_bubble_sort_even_odd_algorithm/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Zarubin Mikhail #include <gtest/gtest.h> #include <vector> #include "./bubble_sort_even_odd_algorithm.h" #include <gtest-mpi-listener.hpp> TEST(GENERATE_VECTOR, can_generate_random_vector) { std::vector<int> vector(5); ASSERT_NO_THROW(generateRandomVector(&vector, 5)); } TEST(SEQUENTIAL_OPERATIONS, can_run_sequential_operations) { std::vector<int> vector(5); generateRandomVector(&vector, 5); ASSERT_NO_THROW(getSequentialOperations(vector.begin(), vector.end())); } TEST(SEQUENTIAL_OPERATIONS, correct_work_on_vector_even_size) { std::vector<int> vector{ 3, 2, 5, 0, 4, 2 }; std::vector<int> expected_result{ 0, 2, 2, 3, 4, 5 }; getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, expected_result); } TEST(SEQUENTIAL_OPERATIONS, correct_work_on_vector_odd_size) { std::vector<int> vector{ 3, 2, 5, 0, 4 }; std::vector<int> expected_result{ 0, 2, 3, 4, 5 }; getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, expected_result); } TEST(PARALLEL_OPERATIONS, can_run_parallel_operations) { std::vector<int> vector{ 3, 2, 5, 4, 0 }; ASSERT_NO_THROW(getParallelOperations(vector, 5)); } TEST(PARALLEL_OPERATIONS, correct_work_on_vector_even_size_v1) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int>::size_type size = 400; std::vector<int> vector(size, 0); if (rank == 0) { generateRandomVector(&vector, size); } std::vector<int> result = getParallelOperations(vector, size); if (rank == 0) { getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, result); } } TEST(PARALLEL_OPERATIONS, correct_work_on_vector_even_size_v2) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int>::size_type size = 34; std::vector<int> vector(size, 0); if (rank == 0) { generateRandomVector(&vector, size); } std::vector<int> result = getParallelOperations(vector, size); if (rank == 0) { getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, result); } } TEST(PARALLEL_OPERATIONS, correct_work_on_vector_odd_size_v1) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int>::size_type size = 41; std::vector<int> vector(size, 0); if (rank == 0) { generateRandomVector(&vector, size); } std::vector<int> result = getParallelOperations(vector, size); if (rank == 0) { getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, result); } } TEST(PARALLEL_OPERATIONS, correct_work_on_vector_odd_size_v2) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int>::size_type size = 33; std::vector<int> vector(size, 0); if (rank == 0) { generateRandomVector(&vector, size); } std::vector<int> result = getParallelOperations(vector, size); if (rank == 0) { getSequentialOperations(vector.begin(), vector.end()); ASSERT_EQ(vector, result); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
29.056452
78
0.679989
[ "vector" ]
596d4f022f78fecab3a1d89c20dfdb46f172bc9d
4,351
cpp
C++
test-chargingcurrent-range.cpp
clean-code-craft-tcq-2/tdd-buckets-Vedashree-Dayananda
a8c08f403e5a421e66d6d85834f139f2a3c1349b
[ "MIT" ]
null
null
null
test-chargingcurrent-range.cpp
clean-code-craft-tcq-2/tdd-buckets-Vedashree-Dayananda
a8c08f403e5a421e66d6d85834f139f2a3c1349b
[ "MIT" ]
null
null
null
test-chargingcurrent-range.cpp
clean-code-craft-tcq-2/tdd-buckets-Vedashree-Dayananda
a8c08f403e5a421e66d6d85834f139f2a3c1349b
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "test/catch.hpp" #include "chargingcurrent-range.h" TEST_CASE("detect the ranges in the given input list with 2 elements") { std::vector<Range> listofRanges1 = {}; std::vector<double> inputList1 = { 4, 5 }; listofRanges1 = computeCurrentRanges(inputList1); REQUIRE(listofRanges1.size() == 1); REQUIRE(listofRanges1[0].lowerLimit == 4); REQUIRE(listofRanges1[0].upperLimit == 5); REQUIRE(listofRanges1[0].numOfReadingsInRange == 2); } TEST_CASE("detect the ranges in the unsorted input list ") { std::vector<Range> listofRanges2 = {}; std::vector<double> inputList2 = { 3, 3, 5, 4, 10, 11, 12 }; listofRanges2 = computeCurrentRanges(inputList2); REQUIRE(listofRanges2.size() == 2); REQUIRE(listofRanges2[0].lowerLimit == 3); REQUIRE(listofRanges2[0].upperLimit == 5); REQUIRE(listofRanges2[0].numOfReadingsInRange == 4); REQUIRE(listofRanges2[1].lowerLimit == 10); REQUIRE(listofRanges2[1].upperLimit == 12); REQUIRE(listofRanges2[1].numOfReadingsInRange == 3); } TEST_CASE("return empty list of the ranges when no readings are provided") { std::vector<Range> listofRanges3 = {}; std::vector<double> inputList3 = {}; listofRanges3 = computeCurrentRanges(inputList3); REQUIRE(listofRanges3.empty() == true); } TEST_CASE("verify format of data printed") { std::vector<Range> listofRanges4 = { { 1, 7, 3 }, { 18, 25, 8 } }; std::string expectedOutputText = "Range, Reading \n"; for (int i = 0; (size_t)i < listofRanges4.size(); i++) expectedOutputText += std::to_string(listofRanges4[i].lowerLimit) + "-" + std::to_string(listofRanges4[i].upperLimit) + "," + std::to_string(listofRanges4[i].numOfReadingsInRange) + "\n"; std::string actualOutputText = formatOutputToCsv(listofRanges4); REQUIRE(expectedOutputText.compare(actualOutputText) == 0); } TEST_CASE("detect the ranges in the given input list with 12 bit ADC elements") { std::vector<Range> listofRanges5 = {}; std::vector<double> inputList5 = { 1146, 1806 , 3065,3450,3650}; listofRanges5 = computeCurrentRangesFromADCReading(inputList5, 12); REQUIRE(listofRanges5.size() == 2); REQUIRE(listofRanges5[0].lowerLimit == 3); REQUIRE(listofRanges5[0].upperLimit == 4); REQUIRE(listofRanges5[0].numOfReadingsInRange == 2); REQUIRE(listofRanges5[1].lowerLimit == 7); REQUIRE(listofRanges5[1].upperLimit == 9); REQUIRE(listofRanges5[1].numOfReadingsInRange == 3); } TEST_CASE("return empty list of the ranges when negative readings are provided for 12 bit ADC") { std::vector<Range> listofRanges6 = {}; std::vector<double> inputList6 = { 1146, 1806, 3065, 3450, 3650 , -1146 }; listofRanges6 = computeCurrentRangesFromADCReading(inputList6, 12); REQUIRE(listofRanges6.empty() == true); } TEST_CASE("return empty list of the ranges when out of range readings are provided for 12 bit ADC") { std::vector<Range> listofRanges7 = {}; std::vector<double> inputList7 = { 1146, 1806, 3065, 3450, 3650, 4095}; listofRanges7 = computeCurrentRangesFromADCReading(inputList7, 12); REQUIRE(listofRanges7.empty() == true); } TEST_CASE("detect the ranges in the given input list with 10 bit ADC elements") { std::vector<Range> listofRanges8 = {}; std::vector<double> inputList8 = { 0, 1022, 1000, 100 , 900 }; listofRanges8 = computeCurrentRangesFromADCReading(inputList8, 10); REQUIRE(listofRanges8.size() == 2); REQUIRE(listofRanges8[0].lowerLimit == 11); REQUIRE(listofRanges8[0].upperLimit == 12); REQUIRE(listofRanges8[0].numOfReadingsInRange == 2); REQUIRE(listofRanges8[1].lowerLimit == 14); REQUIRE(listofRanges8[1].upperLimit == 15); REQUIRE(listofRanges8[1].numOfReadingsInRange == 3); } TEST_CASE("return empty list of the ranges when negative readings are provided for 10 bit ADC") { std::vector<Range> listofRanges9 = {}; std::vector<double> inputList9 = { 0, -1022, 1000, 100, 900 }; listofRanges9 = computeCurrentRangesFromADCReading(inputList9, 10); REQUIRE(listofRanges9.empty() == true); } TEST_CASE("return empty list of the ranges when out of range readings are provided for 10 bit ADC") { std::vector<Range> listofRanges10 = {}; std::vector<double> inputList10 = { 0, 1024, 1000, 100, 900 }; listofRanges10 = computeCurrentRangesFromADCReading(inputList10, 10); REQUIRE(listofRanges10.empty() == true); }
43.51
189
0.730177
[ "vector" ]
596f63286c443297a93663ea932d5931a79deb63
2,072
cc
C++
src/type.cc
neeilan/neeilang
1c7776bfd7d895f3f203adde5c2606096f12cc46
[ "MIT" ]
50
2019-10-15T23:14:06.000Z
2022-02-03T20:59:50.000Z
src/type.cc
neeilan/neeilang
1c7776bfd7d895f3f203adde5c2606096f12cc46
[ "MIT" ]
null
null
null
src/type.cc
neeilan/neeilang
1c7776bfd7d895f3f203adde5c2606096f12cc46
[ "MIT" ]
4
2020-01-22T20:14:00.000Z
2020-03-25T08:36:14.000Z
#include "type.h" struct FuncType; bool Type::has_field(const std::string &name) { if (supertype && supertype->has_field(name)) { return true; } for (auto field : fields) { if (field.name == name) { return true; } } return false; } Field Type::get_field(const std::string &name) { if (supertype && supertype->has_field(name)) { return supertype->get_field(name); } assert(has_field(name)); for (auto field : fields) { if (field.name == name) { return field; } } // Unreachable return Field(); } int Type::num_fields() { int offset = supertype ? supertype->num_fields() : 0; return offset + fields.size(); } int Type::field_idx(const std::string &name) { assert(has_field(name)); if (supertype && supertype->has_field(name)) { return supertype->field_idx(name); } int offset = supertype ? supertype->num_fields() : 0; for (int i = 0; i < fields.size(); i++) { if (fields[i].name == name) { return offset + i; } } return -1; // Unreachable } bool Type::has_method(const std::string &name) { for (auto method : methods) { if (method->name == name) return true; } return false; } std::shared_ptr<FuncType> Type::get_method(const std::string &name) { assert(has_method(name)); for (auto method : methods) { if (method->name == name) return method; } return std::make_shared<FuncType>(); // Unreachable } std::vector<std::shared_ptr<FuncType>> Type::get_methods() { if (!supertype) { return methods; } std::vector<std::shared_ptr<FuncType>> all_methods; auto super_methods = supertype->get_methods(); for (auto sm : super_methods) { all_methods.push_back(sm); } for (std::shared_ptr<FuncType> m : methods) { bool overridden = false; for (int i = 0; i < all_methods.size(); i++) { if (m->name == all_methods[i]->name) { overridden = true; all_methods[i] = m; break; } } if (!overridden) { all_methods.push_back(m); } } return all_methods; }
20.116505
69
0.609073
[ "vector" ]
5977c67625b314bb91516e34bd92f49af3fabe65
5,346
hpp
C++
include/blmc_controllers/impedance_controller.hpp
jviereck/blmc_controllers
f7f6f83874151c6e8cc33cb7c30bec5893a2e9d0
[ "BSD-3-Clause" ]
1
2020-12-17T17:51:52.000Z
2020-12-17T17:51:52.000Z
include/blmc_controllers/impedance_controller.hpp
jviereck/blmc_controllers
f7f6f83874151c6e8cc33cb7c30bec5893a2e9d0
[ "BSD-3-Clause" ]
1
2020-12-17T11:08:11.000Z
2021-01-11T16:47:45.000Z
include/blmc_controllers/impedance_controller.hpp
jviereck/blmc_controllers
f7f6f83874151c6e8cc33cb7c30bec5893a2e9d0
[ "BSD-3-Clause" ]
1
2020-12-17T11:04:40.000Z
2020-12-17T11:04:40.000Z
/** * @file * @license BSD 3-clause * @copyright Copyright (c) 2020, New York University and Max Planck * Gesellschaft * * @brief This is the implementation for impedance controller between any two * frames of the robot. * */ #pragma once #include "pinocchio/multibody/data.hpp" #include "pinocchio/multibody/model.hpp" namespace blmc_controllers { /** * @brief Impedance controller between any two frames of the robot. */ class ImpedanceController { public: typedef Eigen::Array<double, 6, 1> Array6d; typedef Eigen::Matrix<double, 6, 1> Vector6d; /** * @brief Construct a new ImpedanceController object. */ ImpedanceController(); /** * @brief Initialize the internal data. None real-time safe method. * * @param pinocchio_model rigid body model of the robot * @param root_frame_name root frame name where the spring starts(Ex. Hip) * @param end_frame_name frame name where the spring ends(Ex. end effector) */ void initialize(const pinocchio::Model& pinocchio_model, const std::string& root_frame_name, const std::string& end_frame_name); /** * @brief Computes the desired joint torques * * \f$ * \tau = J^T (k_p (x^{des} - x) + * k_d (\dot{x}^{des} - \dot{x}) -k_f f) * \f$ * * with: * - \f$ \tau \f$ the joint torques, * - \f$ J \f$ the Jacobian of the sub-kinematic-tree between the root and * the end frame, * - \f$ k_p \f$ the gain proportional to the frame placement error, * - \f$ x_{des} \f$ desired end frame placement with respect to the * desired root frame. * - \f$ x \f$ measured end frame placement with respect to the * measured root frame. * - \f$ k_d \f$ is the derivative gain applied to the time derivative of * the error. * - \f$ \dot{x}^{des} \f$ desired end frame velocity with respect to the * desired root frame. * - \f$ \dot{x} \f$ measured end frame velocity with respect to the * measured root frame. * - \f$ k_f \f$ the gain over the feed forward force, * - \f$ f \f$ the feed forward force, * * @param robot_configuration robot generalized coordinates configuration. * @param robot_velocity robot generalized coordinates velocity. * @param gain_proportional 6d vector for the proportionnal gains on {x, y, * z, roll, pitch, yaw}. * @param gain_derivative 6d vector for the proportionnal gains on {x, y, z, * roll, pitch, yaw}. * @param gain_feed_forward_force gain multiplying the feed forward force. * @param desired_end_frame_placement desired end fram placement relative to * the desired root joint. * @param desired_end_frame_velocity desired end frame velocity relative to * the desired root joint. * @param feed_forward_force feed forward force applied to the foot by the * environement. */ void run(Eigen::Ref<const Eigen::VectorXd> robot_configuration, Eigen::Ref<const Eigen::VectorXd> robot_velocity, Eigen::Ref<const Array6d> gain_proportional, Eigen::Ref<const Array6d> gain_derivative, const double& gain_feed_forward_force, const pinocchio::SE3& desired_end_frame_placement, const pinocchio::Motion& desired_end_frame_velocity, const pinocchio::Force& feed_forward_force); /** * @brief Get the computed torques from the impedance controller. * * @return Eigen::VectorXd& */ Eigen::VectorXd& get_torques(); /** * @brief Get the impedance force \f$ f_i \f$ with \f$ \tau = J^T f_i \f$. * * @return Eigen::VectorXd& */ Vector6d& get_impedance_force(); private: // attributes /** @brief Rigid body dynamics model. */ pinocchio::Model pinocchio_model_; /** @brief Cache of the rigid body dynamics algorithms. */ pinocchio::Data pinocchio_data_; /** @brief (urdf) name of the root frame. The impedance controller is * computed with respect to this frame. */ std::string root_frame_name_; /** @brief Index of the root frame in the pinocchio model. */ pinocchio::FrameIndex root_frame_index_; /** @brief Jacobian of the root frame. */ pinocchio::Data::Matrix6x root_jacobian_; /** @brief Measured root frame placement. */ pinocchio::SE3 root_placement_; /** @brief Measured root frame velocity. */ pinocchio::Motion root_velocity_; /** @brief (urdf) name of the end frame. This is the controlled frame. */ std::string end_frame_name_; /** @brief Index of the end frame in the pinocchio model. */ pinocchio::FrameIndex end_frame_index_; /** @brief Jacobian of the end frame. */ pinocchio::Data::Matrix6x end_jacobian_; /** @brief Measured end frame placement. */ pinocchio::SE3 end_placement_; /** @brief Measured end frame velocity. */ pinocchio::Motion end_velocity_; /** @brief Impedance force. Accessible for machine learning purposes. */ Vector6d impedance_force_; /** @brief Jacobian used in the computation of the impedance. */ pinocchio::Data::Matrix6x impedance_jacobian_; /** @brief Output torques. */ Eigen::VectorXd torques_; }; } // namespace blmc_controllers
34.269231
80
0.65376
[ "object", "vector", "model" ]
59830d9520547d9c5dec2dba622c7f8b058ae175
3,153
cpp
C++
test/src/TotpTests.cpp
rhymu8354/Hash
35e0ec07343d81dd1ae4e13be168b60b2ad50101
[ "MIT" ]
null
null
null
test/src/TotpTests.cpp
rhymu8354/Hash
35e0ec07343d81dd1ae4e13be168b60b2ad50101
[ "MIT" ]
null
null
null
test/src/TotpTests.cpp
rhymu8354/Hash
35e0ec07343d81dd1ae4e13be168b60b2ad50101
[ "MIT" ]
null
null
null
/** * @file TotpTests.cpp * * This module contains the unit tests of the Totp functions. * * © 2018 by Richard Walters */ #include <gtest/gtest.h> #include <Hash/Sha1.hpp> #include <Hash/Sha2.hpp> #include <Hash/Templates.hpp> #include <Hash/Totp.hpp> #include <stddef.h> #include <stdint.h> #include <string> #include <sstream> #include <vector> TEST(TotpTests, TotpCodeTestVectors) { // These test vectors were taken from [RFC // 6238](https://tools.ietf.org/html/rfc6238) Appendix B. const uint64_t step = 30; const uint64_t base = 0; struct TestVector { const std::string secret; uint64_t time; int totp; Hash::HashFunction hashFunction; size_t blockSize; }; const std::vector< TestVector > testVectors{ {"12345678901234567890", 59, 94287082, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 59, 46119246, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 59, 90693936, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, {"12345678901234567890", 1111111109, 7081804, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 1111111109, 68084774, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 1111111109, 25091201, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, {"12345678901234567890", 1111111111, 14050471, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 1111111111, 67062674, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 1111111111, 99943326, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, {"12345678901234567890", 1234567890, 89005924, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 1234567890, 91819424, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 1234567890, 93441116, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, {"12345678901234567890", 2000000000, 69279037, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 2000000000, 90698825, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 2000000000, 38618901, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, {"12345678901234567890", 20000000000, 65353130, Hash::Sha1, Hash::SHA1_BLOCK_SIZE}, {"12345678901234567890123456789012", 20000000000, 77737706, Hash::Sha256, Hash::SHA256_BLOCK_SIZE}, {"1234567890123456789012345678901234567890123456789012345678901234", 20000000000, 47863826, Hash::Sha512, Hash::SHA512_BLOCK_SIZE}, }; for (const auto& testVector: testVectors) { EXPECT_EQ( testVector.totp, Hash::Totp( testVector.hashFunction, testVector.blockSize, testVector.secret, testVector.time, base, step, 8 ) ); } }
47.059701
139
0.697114
[ "vector" ]
59935e90e1b93e4a979bd002d6df612b358c0186
1,600
cpp
C++
src/parsers/ApacheParser.cpp
daladim/access-log-monitor
497751cd8ca99b0520c565579c6a53f4cf561c02
[ "MIT" ]
null
null
null
src/parsers/ApacheParser.cpp
daladim/access-log-monitor
497751cd8ca99b0520c565579c6a53f4cf561c02
[ "MIT" ]
null
null
null
src/parsers/ApacheParser.cpp
daladim/access-log-monitor
497751cd8ca99b0520c565579c6a53f4cf561c02
[ "MIT" ]
null
null
null
#include "ApacheParser.hpp" #include <string> using namespace std; namespace LogSupervisor::LogParser{ Apache::Apache(const string& filePath) : logFile(filePath) { if(logFile.fail()){ throw runtime_error(string("Unable to open file ") + filePath + ": " + strerror(errno)); } } std::string Apache::humanReadableLogType() const{ return "Apache log files"; } std::string Apache::shortName(){ return "apache"; } void Apache::parseLog(){ string currentLine; while(std::getline(logFile, currentLine)){ optional<Authentication> auth = parseLine(currentLine); if(auth){ m_auths.push_back(*auth); } } } optional<LogSupervisor::Authentication> Apache::parseLine(const std::string& line){ // Regexes can be expensive (both at building and at using) // We only build them once in the lifetime of the program // IP user static regex re_apache(R"raw(^\s?([^\s]+)\s+[^\s]+\s+([^\s]+)\s+\[.+)raw"); smatch matches; if(regex_search(line, matches, re_apache)){ bool success = (matches.str(2).compare("-") != 0); return authFromMatches(matches, success); }else{ return {}; } } LogSupervisor::Authentication Apache::authFromMatches(const smatch& matches, bool success){ Timestamp ts("Not supported yet"); Address origin = matches.str(1); User user = matches.str(2); return Authentication(user, origin, ts, success); } vector<LogSupervisor::Authentication> Apache::all(){ return m_auths; } } // namespace
24.615385
96
0.629375
[ "vector" ]
599c1681cab38fa69aa744e4fec1fffbffdf367f
1,404
cpp
C++
src/linear_interpolate_1.cpp
eodus/LinearInterpolator
4a488e40861233f53c7c981a9b47782e28f18701
[ "MIT" ]
null
null
null
src/linear_interpolate_1.cpp
eodus/LinearInterpolator
4a488e40861233f53c7c981a9b47782e28f18701
[ "MIT" ]
null
null
null
src/linear_interpolate_1.cpp
eodus/LinearInterpolator
4a488e40861233f53c7c981a9b47782e28f18701
[ "MIT" ]
null
null
null
#include "linear_interpolate_1.hpp" #include <algorithm> #include <vector> struct Vertex { double x, value; bool operator<(const Vertex &b) const { return x < b.x; } }; class LinearInterpolator_1 { public: LinearInterpolator_1(const double *points, const double *values, size_t npoints) { for (size_t i{0}; i < npoints; ++i) { vertices.push_back({points[i], values[i]}); } std::sort(vertices.begin(), vertices.end()); } double linearInterpolation(const double *x) const { Vertex p{*x, 0}; size_t u = std::lower_bound(vertices.begin(), vertices.end(), p) - vertices.begin(); size_t l = u - 1; if (u <= 0 || u >= vertices.size()) { return NA_REAL; } double b = (vertices[u].x - *x) / (vertices[u].x - vertices[l].x); return vertices[l].value * b + vertices[u].value * (1 - b); } private: std::vector<Vertex> vertices; }; SEXP linear_interpolate_1(SEXP points, SEXP values, SEXP xi) { const int d = 1; LinearInterpolator_1 li(REAL(points), REAL(values), length(values)); int result_length = length(xi) / d; SEXP results = PROTECT(allocVector(REALSXP, result_length)); for (size_t i{0}; i < result_length; ++i) { REAL(results)[i] = li.linearInterpolation(REAL(xi) + i*d); } UNPROTECT(1); return results; }
24.206897
88
0.593305
[ "vector" ]
599ee6bde32717954e4e1abd4c9203ba13dbf44d
2,389
cpp
C++
BAC_2nd/ch9/UVa1627.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC_2nd/ch9/UVa1627.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC_2nd/ch9/UVa1627.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa1627 Team them up! // Rujia Liu #include<cstdio> #include<cstring> #include<iostream> #include<vector> #include<algorithm> using namespace std; const int maxn = 100 + 5; int n, G[maxn][maxn], color[maxn], diff[maxn], cc; vector<int> team[maxn][2]; // team[cc][c] is the list of people in connected-component cc, color c // returns false if not bipartite graph bool dfs(int u, int c) { color[u] = c; team[cc][c-1].push_back(u); for(int v = 0; v < n; v++) { if(u != v && !(G[u][v] && G[v][u])) { // u and v must be in different groups if(color[v] > 0 && color[v] == color[u]) return false; if(!color[v] && !dfs(v, 3-c)) return false; } } return true; } bool build_graph() { memset(color, 0, sizeof(color)); cc = 0; // current connected-component for(int i = 0; i < n; i++) if(!color[i]) { team[cc][0].clear(); team[cc][1].clear(); if(!dfs(i, 1)) return false; diff[cc] = team[cc][0].size() - team[cc][1].size(); cc++; } return true; } // d[i][j+n] = 1 iff we can arrange first i cc so that team 1 has j more people than team 2. int d[maxn][maxn*2], teamno[maxn]; void print(int ans) { vector<int> team1, team2; for(int i = cc-1; i >= 0; i--) { int t; if(d[i][ans-diff[i]+n]) { t = 0; ans -= diff[i]; } else { t = 1; ans += diff[i]; } for(int j = 0; j < team[i][t].size(); j++) team1.push_back(team[i][t][j]); for(int j = 0; j < team[i][1^t].size(); j++) team2.push_back(team[i][1^t][j]); } printf("%d", team1.size()); for(int i = 0; i < team1.size(); i++) printf(" %d", team1[i]+1); printf("\n"); printf("%d", team2.size()); for(int i = 0; i < team2.size(); i++) printf(" %d", team2[i]+1); printf("\n"); } void dp() { memset(d, 0, sizeof(d)); d[0][0+n] = 1; for(int i = 0; i < cc; i++) for(int j = -n; j <= n; j++) if(d[i][j+n]) { d[i+1][j+diff[i]+n] = 1; d[i+1][j-diff[i]+n] = 1; } for(int ans = 0; ans <= n; ans++) { if(d[cc][ans+n]) { print(ans); return; } if(d[cc][-ans+n]) { print(-ans); return; } } } int main() { int T; cin >> T; while(T--) { cin >> n; memset(G, 0, sizeof(G)); for(int u = 0; u < n; u++) { int v; while(cin >> v && v) G[u][v-1] = 1; } if(n == 1 || !build_graph()) cout << "No solution\n"; else dp(); if(T) cout << "\n"; } return 0; }
24.377551
98
0.508581
[ "vector" ]
59a12229adaf4b7b4c495563e8ab314f38875af7
580
cpp
C++
Sparky-core/src/sp/graphics/TextureManager.cpp
LifeOrGame/Sparky
2ebcba2613b47011a224ddce5bc9267b46ba0119
[ "Apache-2.0" ]
1,303
2015-02-15T05:12:55.000Z
2022-03-18T18:23:28.000Z
Sparky-core/src/sp/graphics/TextureManager.cpp
WildFire212/Sparky
a679d0834e37eb3570dff18b01550210734cb97e
[ "Apache-2.0" ]
124
2015-04-02T14:15:05.000Z
2021-05-05T12:47:16.000Z
Sparky-core/src/sp/graphics/TextureManager.cpp
WildFire212/Sparky
a679d0834e37eb3570dff18b01550210734cb97e
[ "Apache-2.0" ]
538
2015-02-19T21:53:15.000Z
2022-03-11T06:18:05.000Z
#include "sp/sp.h" #include "sp/Common.h" #include "TextureManager.h" namespace sp { namespace graphics { std::vector<API::Texture*> TextureManager::m_Textures; API::Texture* TextureManager::Add(API::Texture* texture) { m_Textures.push_back(texture); return texture; } API::Texture* TextureManager::Get(const String& name) { for (API::Texture* texture : m_Textures) { if (texture->GetName() == name) return texture; } return nullptr; } void TextureManager::Clean() { for (uint i = 0; i < m_Textures.size(); i++) delete m_Textures[i]; } } }
18.125
57
0.667241
[ "vector" ]
59a2b8605c4ea15d6573222f1136d901b4813402
2,414
cpp
C++
codeforces/815d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/815d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/815d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll=long long; // when range [l, r), has property P~notP, want last P. // when return l-1, means not found. template <typename T> T bs_last(T l, T r, function<bool (T)> f) { assert(l < r); T mid; while (l != r) { mid = l + (r-l)/2; if (f(mid)) { l = mid + 1; }else { r = mid; } } return r-1; } // there're IEP method, segtree method. also below bs could be optim to linear, omit. since much easier. // first def AB[b] := max_{b_i>=b} a_i, i.e. if B doesn't hold > property, A would hold as long as A>AB[b]. // consider a triangle XYZ, view AB as direct-edge(similar to 2-sat.) // X->Y, X->Z, Y->Z, this is exactly valid answer. // if (ai<X)Ix=0, => Iy=Iz=1 // else Ix=1, Y->Z => at least Iy,Iz = 1 // so naive calc is iter(x), iter(y|Ix=0), iter(z|Ix=0 or Iy=0), then a naive O(n^2) loop, // bu notice r- max(ZX[x], ZY[y]), ZY[y] is dec.(any AB is dec), i.e. we just bs ZY[y] whether > ZX[x]. // then we know which would contribute, by maintain prefix-sum. // it's easy to argue included are valid, but one might confuse do we miss/exclude some valid? // just keep in mind, the only conditions, is the triangle, 0->1. // and the valid(x,y,z) sats. any (ai,bi,ci) with the triangle. void solve() { int n, p,q,r; cin >> n >> p >> q >> r; vector<int> YX(p+1), ZX(p+1), ZY(q+1); for (int _ = 0; _ < n; _++) { int x,y,z; cin >> x >> y >> z; YX[x] = max(YX[x], y); ZX[x] = max(ZX[x], z); ZY[y] = max(ZY[y], z); } for (int i = p-1; i >= 1; i--) { YX[i] = max(YX[i], YX[i+1]); ZX[i] = max(ZX[i], ZX[i+1]); } for (int i = q-1; i >= 1; i--) { ZY[i] = max(ZY[i], ZY[i+1]); } vector<ll> sumzy(q+1); for (int i = 1; i <= q; i++) { sumzy[i] = sumzy[i-1] + ZY[i]; } ll res = 0; for (int x = 1; x <= p; x++) { int y = YX[x]; if (y < q) { int z = ZX[x]; int b = bs_last<int>(y+1, q+1, [&](int b){ return ZY[b] > z; }); res += r*1ll*(q-y); res -= (sumzy[b] - sumzy[y]); res -= (q-b) *1ll* z; } } cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
30.948718
107
0.478873
[ "vector" ]
59ad6c2201658c8af5ca81f98aa617e1d87c96a2
8,225
cpp
C++
karp.cpp
nuno-cameira/Edmonds-Karp-Algorithm
8d79b149ec92a80644b8d92a49798f5b37951de4
[ "MIT" ]
null
null
null
karp.cpp
nuno-cameira/Edmonds-Karp-Algorithm
8d79b149ec92a80644b8d92a49798f5b37951de4
[ "MIT" ]
null
null
null
karp.cpp
nuno-cameira/Edmonds-Karp-Algorithm
8d79b149ec92a80644b8d92a49798f5b37951de4
[ "MIT" ]
null
null
null
//============================================================================ // Instituto Superior Tecnico // Analise e Sintese de Algoritmos // 2 Projecto // // Date: : Abril, 2014 // Author : Nuno Cameira, 69769 // Author : Vasco Loureiro, 70993 // Version : 1.0.7.0 // Description : //============================================================================ #ifdef DEBUG #define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false ) #else #define DEBUG_MSG(str) do { } while ( false ) #endif #include <vector> #include <stdio.h> #include <iostream> #include <list> using namespace std; class Node { private: int _id; int _father; bool _visited; bool _closed; list<int> _connections; public: Node() : _id(-1), _visited(false), _closed(false), _connections(0) {} Node(int id) : _id(id), _visited(false), _closed(false), _connections(0) {} //Clone pattern virtual Node* clone() const {return(new Node(*this));}; list<int> getConnections() { return _connections; } void addConnection(int id) { _connections.push_back(id); } void removeConnection(int id){ _connections.remove(id); } int getID() const { return _id; } int getFather() { return _father; } bool isVisited() { return _visited; } bool isClosed() { return _closed; } void setVisited(bool visited) { _visited = visited; } void setFather(int father) { _father = father; } void setClosed(bool closed) { _closed = closed; } void resetState(){ _father = -1; _visited = false; _closed = false; } std::list<int>::iterator firstConnection() { return _connections.begin(); } std::list<int>::iterator lastConnection() { return _connections.end(); } bool contains(int id) { for (std::list<int>::iterator it = this->firstConnection(); it != this->lastConnection(); ++it) { if(*it == id){ return true; } } return false; } bool operator!=(const Node &other) const { return (_id != other._id); } }; class Stack { private: list<int> visitedOrder; public: Stack() : visitedOrder(0) { } void pushBack(int val) { visitedOrder.push_back(val); } void popFront() { visitedOrder.pop_front(); } int size(){ return visitedOrder.size(); } int getFrontElement(){ return visitedOrder.front(); } list<int> getList(){ return visitedOrder; } void clear(){ visitedOrder.clear(); } // Prints out Stack info friend ostream &operator<<( ostream &output, Stack &s ){ output << "STACK: "; list<int> list = s.getList(); for(int i = 0; i < (int) s.getList().size(); i++){ output << list.front() << " " ; list.pop_front(); } return output; } }; // Prints out list info ostream &operator<<( std::ostream& output, list<int> &l){ list<int> listCopy = l; for(int i = 0; i < (int) l.size(); i++){ output << listCopy.front() << " " ; listCopy.pop_front(); } return output; } // Resets the state of each Node in the graph void resetStates(vector<Node> *graph, int graphSize){ for(int i = 0; i < graphSize; i++){ (*graph)[i].resetState(); } } // Does a Breadth-First Search // returns a list with the selected path, including the source and the end list<int> BFS(vector<Node> *graph, int source, int end){ list<int> answer; Node *nodeInProcess; bool asSolution = false; // tells if the BFS ended with a solution // FIFO list Stack stack = Stack(); stack.pushBack(source); while(stack.size() != 0){ DEBUG_MSG(stack); nodeInProcess = &(*graph)[stack.getFrontElement()]; stack.popFront(); Node *nextConnection = 0; for (std::list<int>::iterator it = nodeInProcess->firstConnection(); it != nodeInProcess->lastConnection(); ++it) { nextConnection = &(*graph)[*it]; if(nextConnection->getID() != nodeInProcess->getID()){ if(!nextConnection->isVisited() && !nextConnection->isClosed()) { nextConnection->setVisited(true); nextConnection->setFather(nodeInProcess->getID()); stack.pushBack(nextConnection->getID()); if(nextConnection->getID() == end){ stack.clear(); asSolution = true; DEBUG_MSG("SOLUTION - BREAK"); break; } } } } nodeInProcess->setClosed(true); } if(asSolution){ for (int node = (*graph)[end].getID(); node != source; node = (*graph)[node].getFather()){ answer.push_front(node); } answer.push_front(source); } else{ answer.push_front(-1); DEBUG_MSG("NO SOLUTION"); } DEBUG_MSG("PATH: " << answer); return answer; } // Sends the flow and updates the graph // the argument augmentedPath as the source and the end Node within void sendFlow(vector<Node> *graph, list<int> *augmentedPath){ int currentNode; int nextNode; int augmentedPathSize = augmentedPath->size() - 1; //the size is -1 so that the last node isn't processed //because the last node was updated on the previous iteration for (int i = 0; i < augmentedPathSize; i++) { currentNode = augmentedPath->front(); augmentedPath->pop_front(); nextNode = augmentedPath->front(); (*graph)[currentNode].removeConnection((*graph)[nextNode].getID()); DEBUG_MSG("REMOVE"); DEBUG_MSG("source: " << (*graph)[currentNode].getID() << " end: " << (*graph)[nextNode].getID()); if(!(*graph)[nextNode].contains((*graph)[currentNode].getID())){ (*graph)[nextNode].addConnection((*graph)[currentNode].getID()); DEBUG_MSG("ADICIONA"); DEBUG_MSG("source: " << (*graph)[nextNode].getID() << " end: " << (*graph)[currentNode].getID()); } } } // Applies an Edmonds–Karp based algorithm // returns the total flow of the end node int karpVisit(vector<Node> *graph, int source, int end, int graphSize){ vector<Node> graphCopy; // Makes a copy of the origial graph for(int j = 0; j < graphSize; j++){ graphCopy.push_back(*(*graph)[j].clone()); } int totalFlow = 0; list<int> augmentedPath; while(true){ //finds augmented paths augmentedPath = BFS(&graphCopy, source, end); if(augmentedPath.front() != -1){ sendFlow(&graphCopy, &augmentedPath); resetStates(&graphCopy, graphSize); totalFlow++; } else { break; } } DEBUG_MSG("TOTAL FLOW: " << totalFlow); return totalFlow; } int main() { int numberOfPoints = 0; int numberOfConnections = 0; //builds the graph scanf("%i %i", &numberOfPoints, &numberOfConnections); vector<Node> graph; for (int i = 0; i < numberOfPoints; i++) { graph.push_back(Node(i)); } int pointA = 0; int pointB = 0; //sets the connections on the graph for (int i = 0; i < numberOfConnections; i++) { scanf("%i %i", &pointA, &pointB); graph[pointA].addConnection(pointB); graph[pointB].addConnection(pointA); } int numberOfProblems = 0; //reads number of problems to solve scanf("%i", &numberOfProblems); int numberOfCriticalPoints = 0; int criticPoint = 0; //solves each problem for (int problem = 0; problem < numberOfProblems; problem++) { DEBUG_MSG("Solving problem #" << (problem + 1)); //reads number of critical points scanf("%i", &numberOfCriticalPoints); vector<int> criticalPoints; //stores the critical points for (int in = 0; in < numberOfCriticalPoints; in++) { scanf("%i", &criticPoint); criticalPoints.push_back(criticPoint); } //the answer starts with an unreal value //so that it gets replaced in the first comparison int answer = 9999; int karpAnswer; //applies algorithm with a source and an end point, both critical point for (int currentCriticalPoint = 0; currentCriticalPoint < (int) criticalPoints.size()-1; currentCriticalPoint++) { for (int nextCriticalPoint = currentCriticalPoint+1; nextCriticalPoint < (int) criticalPoints.size(); nextCriticalPoint++) { int source = criticalPoints[currentCriticalPoint]; int end = criticalPoints[nextCriticalPoint]; DEBUG_MSG("KARP source: " << source << " end: " << end); karpAnswer = karpVisit(&graph, source, end, numberOfPoints); // compares the previous answer with the new answer answer = min(answer, karpAnswer); } } //gives the answer of the problem cout << answer << endl; } return 0; }
21.25323
78
0.632948
[ "vector" ]
59bc55ad87894c8616215b741c21d25abb4bda0a
666
hpp
C++
detection/include/interfaces/IDetectionDataHandler.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
1
2021-12-10T06:27:47.000Z
2021-12-10T06:27:47.000Z
detection/include/interfaces/IDetectionDataHandler.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
detection/include/interfaces/IDetectionDataHandler.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "Card.hpp" #include "ImProcSettings.hpp" #include "Image.hpp" namespace detect { /** *\ingroup shared * @class IDetectionDataHandler * @author Julian Massing (julimassing@gmail.com) * @brief Interface for sending/receiving data from/to detection module * * @version 1.0 * @date 2020-12-07 * * @copyright Copyright (c) 2020 * */ class IDetectionDataHandler { public: virtual bool getLiveFrame(Image&) const = 0; virtual bool getProcessingSettings(ImProcSettings&) = 0; virtual bool sendDetectedCards(const std::vector<Card>&) const = 0; virtual ~IDetectionDataHandler() {}; }; }
20.8125
72
0.695195
[ "vector" ]
59bf3427e1ddd7d769647e4db6ecd90a9746869d
5,294
cpp
C++
BinaryTree/print_k_path.cpp
krayong/DS---Algo
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
2
2021-01-30T08:50:12.000Z
2021-05-30T19:56:53.000Z
BinaryTree/print_k_path.cpp
krayong/Data-Structures-and-Algorithms
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
null
null
null
BinaryTree/print_k_path.cpp
krayong/Data-Structures-and-Algorithms
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /************************************************************************************************************* * * Link : https://www.geeksforgeeks.org/print-k-sum-paths-binary-tree/ * Description: A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree. Examples: Input : k = 5 Root of below binary tree: 1 / \ 3 -1 / \ / \ 2 1 4 5 / / \ \ 1 1 2 6 Output : 3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5 * Resources: * * *************************************************************************************************************/ #define si(x) scanf("%d", &x) #define sll(x) scanf("%lld", &x) #define ss(s) getline(cin, s) #define pi(x) printf("%d\n", x) #define pll(x) printf("%lld\n", x) #define ps(s) cout << s << "\n" #define ll long long #define fo(i, k, n) for (ll i = k; i < n; i++) #define rof(i, k, n) for (ll i = k; i >= n; i--) #define deb(x) cout << #x << "=" << x << "\n" #define pb push_back #define mp make_pair #define fi first #define se second #define all(x) x.begin(), x.end() #define clr(x) memset(x, 0, sizeof(x)) #define set(x, i) memset(x, i, sizeof(x)) #define sortall(x) sort(all(x)) #define tr(a, it) for (auto it = a.begin(); it != a.end(); it++) #define present(c, x) (c.find(x) != c.end()) #define cpresent(c, x) (find(all(c), x) != c.end()) typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<string> vs; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vl> vvl; struct Node { int data; struct Node *left; struct Node *right; Node(int data) { this->data = data; left = right = NULL; } }; struct BinaryTree { Node *root; int size; BinaryTree() { root = NULL; size = 0; } void print_in_order() { print_in_order_util(this->root); cout << "\n"; } void print_pre_order() { print_pre_order_util(this->root); cout << "\n"; } void print_post_order() { print_post_order_util(this->root); cout << "\n"; } void build_level_order(int n) { this->size = n; int arr[n] = {0}; fo(i, 0, n) si(arr[i]); this->root = build_level_order_util(arr, this->root, 0); } void print_k_paths(Node *root, vi &path, vvi &paths_vector, int k) { if (root == NULL) return; path.pb(root->data); print_k_paths(root->left, path, paths_vector, k); print_k_paths(root->right, path, paths_vector, k); int sum = 0; for(int i = path.size() - 1; i >= 0; i--) { sum += path[i]; if (sum == k) paths_vector.pb(vi(path.begin() + i, path.end())); } path.pop_back(); } vvi print_k_paths(int k) { vvi paths_vector; vi path; print_k_paths(this->root, path, paths_vector, k); return paths_vector; } private: void print_in_order_util(Node *node) { if (node != NULL) { print_in_order_util(node->left); cout << node->data << ", "; print_in_order_util(node->right); } } void print_pre_order_util(Node *node) { if (node != NULL) { cout << node->data << ", "; print_pre_order_util(node->left); print_pre_order_util(node->right); } } void print_post_order_util(Node *node) { if (node != NULL) { print_post_order_util(node->left); print_post_order_util(node->right); cout << node->data << ", "; } } Node *build_level_order_util(int arr[], Node *node, int i) { if (i < this->size) { node = new Node(arr[i]); node->left = build_level_order_util(arr, node->left, 2 * i + 1); node->right = build_level_order_util(arr, node->right, 2 * i + 2); } return node; } }; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); int t; si(t); while (t--) { int n; si(n); BinaryTree bt; bt.build_level_order(n); int k; si(k); cout << "Inorder traversal:\n"; bt.print_in_order(); auto paths = bt.print_k_paths(k); cout << "Paths are:\n"; fo(i, 0, paths.size()) { fo(j, 0, paths[i].size()) { cout << paths[i][j] << " "; } cout << "\n"; } } return 0; }
22.432203
110
0.475066
[ "vector" ]
59c02b31591973355634edc573c67418d74e9a8c
1,258
cc
C++
day25/seabed.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
20
2021-12-04T04:53:22.000Z
2022-02-24T23:37:31.000Z
day25/seabed.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
null
null
null
day25/seabed.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
1
2022-01-04T22:12:05.000Z
2022-01-04T22:12:05.000Z
#include "seabed.h" #include <algorithm> #include <istream> #include <string> SeaBed parse_seabed(std::istream &s) { SeaBed result; std::string line; while (getline(s, line)) { result.push_back(std::vector<char>(line.begin(), line.end())); } return result; } std::pair<SeaBed, size_t> tick(const SeaBed &input) { std::pair<SeaBed, size_t> result{input, 0}; for (size_t i = 0; i < input.size(); i++) { for (size_t j = 0; j < input[i].size(); j++) { size_t src = (j + input[i].size() - 1) % input[i].size(); if (input[i][j] == '.' && input[i][src] == '>') { result.first[i][j] = '>'; result.first[i][src] = '.'; result.second++; } } } for (size_t i = 0; i < input.size(); i++) { for (size_t j = 0; j < input[i].size(); j++) { size_t src = (i + input.size() - 1) % input.size(); if (result.first[i][j] == '.' && input[i][j] != 'v' && input[src][j] == 'v') { result.first[i][j] = 'v'; result.first[src][j] = '.'; result.second++; } } } return result; } std::ostream &operator<<(std::ostream &s, const SeaBed &bed) { for (auto &row : bed) { std::ranges::copy(row, std::ostreambuf_iterator(s)); s << "\n"; } return s; }
26.208333
84
0.518283
[ "vector" ]
59c2dbd721002e4efaaa4308ed144bbda123837e
1,921
cpp
C++
src/mlpack/tests/main_tests/adaboost_classify_test.cpp
ahmedr2001/mlpack
127d7e76a61ef0e282db8eae644c4337fd54307a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/tests/main_tests/adaboost_classify_test.cpp
ahmedr2001/mlpack
127d7e76a61ef0e282db8eae644c4337fd54307a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/tests/main_tests/adaboost_classify_test.cpp
ahmedr2001/mlpack
127d7e76a61ef0e282db8eae644c4337fd54307a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file tests/main_tests/adaboost_classify_test.cpp * @author Nippun Sharma * * Test RUN_BINDING() of adaboost_predict_main.cpp. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #define BINDING_TYPE BINDING_TYPE_TEST #include <mlpack/core.hpp> #include <mlpack/methods/adaboost/adaboost_classify_main.cpp> #include <mlpack/core/util/mlpack_main.hpp> #include "main_test_fixture.hpp" #include "../catch.hpp" #include "../test_catch_tools.hpp" using namespace mlpack; BINDING_TEST_FIXTURE(AdaBoostPredictTestFixture); /** * Check that number of output labels and number of input * points are equal. */ TEST_CASE_METHOD(AdaBoostPredictTestFixture, "AdaBoostPredictOutputDimensionTest", "[AdaBoostPredictMainTest][BindingTests]") { arma::mat trainData; if (!data::Load("vc2.csv", trainData)) FAIL("Unable to load train dataset vc2.csv!"); arma::Row<size_t> labels; if (!data::Load("vc2_labels.txt", labels)) FAIL("Unable to load label dataset vc2_labels.txt!"); arma::mat testData; if (!data::Load("vc2_test.csv", testData)) FAIL("Unable to load test dataset vc2.csv!"); arma::Col<size_t> mappings = {0, 1, 2}; AdaBoostModel* model = new AdaBoostModel(mappings, 0); model->Train(trainData, labels, 3, (int) 20, (double) 0.0001); size_t testSize = testData.n_cols; SetInputParam("input_model", model); SetInputParam("test", std::move(testData)); RUN_BINDING(); // Check that number of predicted labels is equal to the input test points. REQUIRE(params.Get<arma::Row<size_t>>("predictions").n_cols == testSize); REQUIRE(params.Get<arma::Row<size_t>>("predictions").n_rows == 1); }
30.983871
78
0.715773
[ "model" ]
59c6c40aab3b8915b635e316923d239c32b5d529
9,489
cpp
C++
src/particle_filter.cpp
Jequirity0504/CarND-Kidnapped-Vehicle-Project
dd2b62ddea22a24bd4fed176c56e4fc46f50b908
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Jequirity0504/CarND-Kidnapped-Vehicle-Project
dd2b62ddea22a24bd4fed176c56e4fc46f50b908
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Jequirity0504/CarND-Kidnapped-Vehicle-Project
dd2b62ddea22a24bd4fed176c56e4fc46f50b908
[ "MIT" ]
null
null
null
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <math.h> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include "helper_functions.h" using std::string; using std::vector; using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * TODO: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * TODO: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ num_particles = 50; std::default_random_engine gen; normal_distribution<double> N_x_init(0, std[0]); normal_distribution<double> N_y_init(0, std[1]); normal_distribution<double> N_theta_init(0,std[2]); //weights = vector<double>(num_particles); //particles = vector<Particle>(num_particles); for(int i = 0; i < num_particles; i ++) { Particle p; p.id = i; p.x = x + N_x_init(gen); p.y = y + N_y_init(gen); p.theta = theta + N_theta_init(gen); p.weight = 1.0; particles.push_back(p); weights.push_back(p.weight); } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * TODO: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ std::default_random_engine gen; //define normal distributions for sensor noise normal_distribution<double> N_x(0, std_pos[0]); normal_distribution<double> N_y(0, std_pos[1]); normal_distribution<double> N_theta(0, std_pos[2]); for(int i = 0; i < num_particles; i ++) { //calculate new state if(fabs(yaw_rate) < 0.00001) { particles[i].x += velocity * delta_t * cos(particles[i].theta); particles[i].y += velocity * delta_t * sin(particles[i].theta); } else{ particles[i].x += velocity / yaw_rate * (sin(particles[i].theta + yaw_rate*delta_t) - sin(particles[i].theta)); particles[i].y += velocity / yaw_rate * (cos(particles[i].theta) - cos(particles[i].theta + yaw_rate*delta_t)); particles[i].theta += yaw_rate * delta_t; } //add noise particles[i].x += N_x(gen); particles[i].y += N_y(gen); particles[i].theta += N_theta(gen); } } void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) { /** * TODO: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ for (int i = 0; i < observations.size(); i++){ int matched_id = 0; double min_dist_square = INFINITY; for (int j = 0; j < predicted.size(); j++){ double dist_square = (predicted[j].x - observations[i].x)*(predicted[j].x - observations[i].x) + (predicted[j].y - observations[i].y)*(predicted[j].y - observations[i].y); if (dist_square < min_dist_square){ matched_id = predicted[j].id; min_dist_square = dist_square; } } observations[i].id = matched_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { /** * TODO: Update the weights of each particle using a mult-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ double sensor_range_square = sensor_range * sensor_range; for (int i = 0; i < num_particles; i++){ // get all landmarks in the sensor range std::vector<LandmarkObs> predictions; for (int j = 0; j < map_landmarks.landmark_list.size(); j++){ double delta_x = map_landmarks.landmark_list[j].x_f - particles[i].x; double delta_y = map_landmarks.landmark_list[j].y_f - particles[i].y; if (delta_x*delta_x + delta_y*delta_y < sensor_range_square){ LandmarkObs landmark_temp; landmark_temp.x = map_landmarks.landmark_list[j].x_f; landmark_temp.y = map_landmarks.landmark_list[j].y_f; landmark_temp.id = map_landmarks.landmark_list[j].id_i; predictions.push_back(landmark_temp); } } if (predictions.size() == 0){ particles[i].weight = 0.0; weights[i] = 0.0; continue; } //transform the measured landmarks from vehicle's coordinate to map's coordinate std::vector<LandmarkObs> transformed_obs; for (int k = 0; k < observations.size(); k++){ LandmarkObs obs; obs.id = observations[k].id; obs.x = particles[i].x + observations[k].x * cos(particles[i].theta) - observations[k].y * sin(particles[i].theta); obs.y = particles[i].y + observations[k].x * sin(particles[i].theta) + observations[k].y * cos(particles[i].theta); transformed_obs.push_back(obs); } //associate the measured landmarks to ones in map; dataAssociation(predictions, transformed_obs); //update weights double total_weights = 1.0; for (int s = 0; s < transformed_obs.size(); s++){ int index = transformed_obs[s].id - 1; double delta_x = map_landmarks.landmark_list[index].x_f - transformed_obs[s].x; double delta_y = map_landmarks.landmark_list[index].y_f - transformed_obs[s].y; double gauss_norm = 1/(2 * M_PI * std_landmark[0] * std_landmark[1]); double exponent = (delta_x * delta_x)/(2.0 * std_landmark[0] * std_landmark[0]) + (delta_y * delta_y)/(2.0 * std_landmark[1] * std_landmark[1]); total_weights *= gauss_norm * exp(-exponent); } particles[i].weight = total_weights; weights[i] = total_weights; } } void ParticleFilter::resample() { /** * TODO: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ std::default_random_engine gen; std::discrete_distribution<int> dist_weight(weights.begin(), weights.end()); std::vector<Particle> resampled_particles; for (int i = 0; i < num_particles; i++){ resampled_particles.push_back(particles[dist_weight(gen)]); } particles = resampled_particles; } void ParticleFilter::SetAssociations(Particle& particle, const vector<int>& associations, const vector<double>& sense_x, const vector<double>& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
38.108434
183
0.638213
[ "vector", "transform" ]
59ce7582affc0c385144e1876e33276010513940
4,282
hpp
C++
contracts/eden/include/distributions.hpp
guilledk/Eden
251d1b10d6ec1a9a8e1ec4c461ffac16fe425a32
[ "MIT" ]
35
2021-04-02T02:17:39.000Z
2021-11-23T17:46:50.000Z
contracts/eden/include/distributions.hpp
guilledk/Eden
251d1b10d6ec1a9a8e1ec4c461ffac16fe425a32
[ "MIT" ]
323
2021-04-07T15:07:39.000Z
2022-01-25T01:11:38.000Z
contracts/eden/include/distributions.hpp
guilledk/Eden
251d1b10d6ec1a9a8e1ec4c461ffac16fe425a32
[ "MIT" ]
8
2021-05-10T01:19:47.000Z
2022-01-24T23:05:00.000Z
#pragma once #include <eosio/asset.hpp> #include <eosio/multi_index.hpp> #include <eosio/name.hpp> #include <eosio/time.hpp> #include <utils.hpp> #include <variant> #include <vector> namespace eden { struct member; inline uint128_t distribution_account_key(eosio::name owner, eosio::block_timestamp distribution_time, uint8_t rank) { return (static_cast<uint128_t>(owner.value) << 64) | (static_cast<uint64_t>(distribution_time.slot) << 32) | rank; } struct pool_v0 { eosio::name name; uint8_t monthly_distribution_pct; uint64_t primary_key() const { return name.value; } }; EOSIO_REFLECT(pool_v0, name, monthly_distribution_pct) using pool_variant = std::variant<pool_v0>; struct pool { pool_variant value; EDEN_FORWARD_MEMBERS(value, name, monthly_distribution_pct) EDEN_FORWARD_FUNCTIONS(value, primary_key) }; EOSIO_REFLECT(pool, value) using pool_table_type = eosio::multi_index<"pools"_n, pool>; struct next_distribution { eosio::block_timestamp distribution_time; }; EOSIO_REFLECT(next_distribution, distribution_time) struct election_distribution { eosio::block_timestamp distribution_time; eosio::asset amount; }; EOSIO_REFLECT(election_distribution, distribution_time, amount) struct current_distribution { eosio::block_timestamp distribution_time; eosio::name last_processed; std::vector<eosio::asset> rank_distribution; }; EOSIO_REFLECT(current_distribution, distribution_time, last_processed, rank_distribution) using distribution_variant = std::variant<next_distribution, election_distribution, current_distribution>; struct distribution { distribution_variant value; EDEN_FORWARD_MEMBERS(value, distribution_time) uint64_t primary_key() const { return distribution_time().slot; } }; EOSIO_REFLECT(distribution, value) using distribution_table_type = eosio::multi_index<"distribution"_n, distribution>; class accounts; bool setup_distribution(eosio::name contract, eosio::block_timestamp init = {}); bool setup_distribution(eosio::name contract, accounts& accounts, eosio::block_timestamp init = {}); uint32_t distribute_monthly(eosio::name contract, uint32_t max_steps); void init_pools(eosio::name contract); void process_election_distribution(eosio::name contract); struct distribution_account_v0 { uint64_t id; eosio::name owner; eosio::block_timestamp distribution_time; uint8_t rank; eosio::asset balance; uint64_t primary_key() const { return id; } uint128_t by_owner() const { return distribution_account_key(owner, distribution_time, rank); } }; EOSIO_REFLECT(distribution_account_v0, id, owner, distribution_time, rank, balance); using distribution_account_variant = std::variant<distribution_account_v0>; struct distribution_account { distribution_account_variant value; EDEN_FORWARD_MEMBERS(value, id, owner, distribution_time, rank, balance); EDEN_FORWARD_FUNCTIONS(value, primary_key, by_owner) }; EOSIO_REFLECT(distribution_account, value) using distribution_account_table_type = eosio::multi_index< "distaccount"_n, distribution_account, eosio::indexed_by< "byowner"_n, eosio::const_mem_fun<distribution_account, uint128_t, &distribution_account::by_owner>>>; class distributions { private: eosio::name contract; distribution_account_table_type distribution_account_tb; public: explicit distributions(eosio::name contract) : contract(contract), distribution_account_tb(contract, default_scope) { } void sub_balance(eosio::name from, eosio::block_timestamp distribution_time, uint8_t rank, eosio::asset amount); uint32_t on_election_kick(eosio::name member, uint32_t max_steps); void on_resign(const member& member); void clear_all(); }; } // namespace eden
32.439394
100
0.686362
[ "vector" ]
59d7454700c66392fa71b00b19704f436ff9af0b
1,107
hpp
C++
src/ocr/Feature_Loader.hpp
bitwizeshift/Numeric-OCR
2f2c51bb169ea5614789a4e961392946177a4357
[ "MIT" ]
1
2018-12-25T07:58:39.000Z
2018-12-25T07:58:39.000Z
src/ocr/Feature_Loader.hpp
bitwizeshift/Numeric-Digit-OCR
2f2c51bb169ea5614789a4e961392946177a4357
[ "MIT" ]
null
null
null
src/ocr/Feature_Loader.hpp
bitwizeshift/Numeric-Digit-OCR
2f2c51bb169ea5614789a4e961392946177a4357
[ "MIT" ]
1
2021-02-14T20:25:44.000Z
2021-02-14T20:25:44.000Z
/** * @file Feature_Loader.hpp * * @todo Add description * * @author Matthew Rodusek (matthew.rodusek@gmail.com) * @date Nov 16, 2015 * */ /* * Change Log: * * Nov 16, 2015: * - Feature_Loader.hpp created */ #ifndef OCR_FEATURE_LOADER_HPP_ #define OCR_FEATURE_LOADER_HPP_ #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include "Image.hpp" #include "Feature_Vector.hpp" #include <vector> #include <cstddef> // std::size_t #include <iosfwd> // std::ostream fwd namespace ocr { struct boundary{ int top, left, bottom, right; }; typedef std::vector<Feature_Vector> feature_collection; typedef std::vector<boundary> boundary_collection; std::ostream& operator << (std::ostream& o, const boundary& b ); /// /// /// /// void load_features( const Image& image, feature_collection& features, boundary_collection& bounds, std::size_t horizontal_divs = 10, std::size_t vertical_divs = 10 ); } // namespace ocr #endif /* OCR_FEATURE_LOADER_HPP_ */
19.421053
66
0.626016
[ "vector" ]
59e6d7239a63eae4e7be810493f68d6e6e173a08
4,939
cpp
C++
src/renderer/main.cpp
kamilsan/ogl-renderer
c74f5c25276b8ae185e1f9cd8cc8d0497ef31521
[ "MIT" ]
null
null
null
src/renderer/main.cpp
kamilsan/ogl-renderer
c74f5c25276b8ae185e1f9cd8cc8d0497ef31521
[ "MIT" ]
null
null
null
src/renderer/main.cpp
kamilsan/ogl-renderer
c74f5c25276b8ae185e1f9cd8cc8d0497ef31521
[ "MIT" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <cmath> #include "window.hpp" #include "shaderProgram.hpp" #include "mesh.hpp" #include "matrix.hpp" #include "vertex.hpp" #include "camera.hpp" #include "texture.hpp" const unsigned int WINDOW_WIDTH = 800; const unsigned int WINDOW_HEIGHT = 600; void onResize(GLFWwindow*, int width, int height) { glViewport(0, 0, width, height); } void input(Window& window, Camera& camera) { const float movementSpeed = 0.06f; const float rotationSpeed = 0.02f; if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_ESCAPE) == GLFW_PRESS) window.close(); if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_W) == GLFW_PRESS) camera.move(Camera::CameraDirection::Forward, movementSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_S) == GLFW_PRESS) camera.move(Camera::CameraDirection::Back, movementSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_A) == GLFW_PRESS) camera.move(Camera::CameraDirection::Left, movementSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_D) == GLFW_PRESS) camera.move(Camera::CameraDirection::Right, movementSpeed); if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_UP) == GLFW_PRESS) camera.rotateX(rotationSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_DOWN) == GLFW_PRESS) camera.rotateX(-rotationSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_LEFT) == GLFW_PRESS) camera.rotateY(rotationSpeed); else if(glfwGetKey(window.getWindowPtr(), GLFW_KEY_RIGHT) == GLFW_PRESS) camera.rotateY(-rotationSpeed); } int main() { Window window{"OpenGL", WINDOW_WIDTH, WINDOW_HEIGHT}; window.setResizeCallback(onResize); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glFrontFace(GL_CW); glCullFace(GL_BACK); glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); try { ShaderProgram shaderProgram("vertexShader.vs.glsl", "fragmentShader.fs.glsl"); Mesh cube({Vertex({-1.0, -1.0, -1.0}, {0, 0}), // front Vertex({-1.0, 1.0, -1.0}, {0, 1}), Vertex({1.0, 1.0, -1.0}, {1, 1}), Vertex({1.0, -1.0, -1.0}, {1, 0}), Vertex({1.0, -1.0, -1.0}, {0, 0}), // right Vertex({1.0, 1.0, -1.0}, {0, 1}), Vertex({1.0, 1.0, 1.0}, {1, 1}), Vertex({1.0, -1.0, 1.0}, {1, 0}), Vertex({1.0, -1.0, 1.0}, {0, 0}), // back Vertex({1.0, 1.0, 1.0}, {0, 1}), Vertex({-1.0, 1.0, 1.0}, {1, 1}), Vertex({-1.0, -1.0, 1.0}, {1, 0}), Vertex({-1.0, -1.0, 1.0}, {0, 0}), // left Vertex({-1.0, 1.0, 1.0}, {0, 1}), Vertex({-1.0, 1.0, -1.0}, {1, 1}), Vertex({-1.0, -1.0, -1.0}, {1, 0}), Vertex({-1.0, 1.0, -1.0}, {0, 0}), // top Vertex({-1.0, 1.0, 1.0}, {0, 1}), Vertex({1.0, 1.0, 1.0}, {1, 1}), Vertex({1.0, 1.0, -1.0}, {1, 0}), Vertex({-1.0, -1.0, 1.0}, {0, 0}), // bottom Vertex({-1.0, -1.0, -1.0}, {0, 1}), Vertex({1.0, -1.0, -1.0}, {1, 1}), Vertex({1.0, -1.0, 1.0}, {1, 0}), }, { 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 }); try { Texture crateTexture{"res/crate.jpg"}; Camera camera{Vector3{0, 0, -3}, Vector3{0, 0, 1}, Vector3{0, 1, 0}}; shaderProgram.use(); auto mmLoc = shaderProgram.getUniformLocation("modelMatrix"); auto vmLoc = shaderProgram.getUniformLocation("viewMatrix"); auto pmLoc = shaderProgram.getUniformLocation("projectionMatrix"); auto diffuseLoc = shaderProgram.getUniformLocation("diffuse"); glUniform1i(diffuseLoc, 0); float aspectRatio = (float)window.getWidth() / window.getHeight(); Matrix projectionMatrix = Matrix::initPerspective(M_PI / 2, aspectRatio, 0.1, 1000); glUniformMatrix4fv(pmLoc, 1, GL_TRUE, projectionMatrix.getData()); float angle = M_PI / 2; while(window.isRunning()) { input(window, camera); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniformMatrix4fv(vmLoc, 1, GL_TRUE, camera.getViewMatrix().getData()); Matrix modelMatrix = Matrix::initRotation(angle, angle / 2, 0); glUniformMatrix4fv(mmLoc, 1, GL_TRUE, modelMatrix.getData()); crateTexture.bind(); cube.draw(); window.update(); angle += 0.015; } } catch(std::exception& ex) { std::cout << ex.what() << "\n"; } } catch(std::runtime_error& err) { std::cout << "ERROR: " << err.what() << std::endl; } return 0; }
32.071429
90
0.562462
[ "mesh" ]
59ed381fbaab65fff341f562f2c39c381fffc84f
51,650
cpp
C++
xiablo/Plugins/SketchFabPlugin/Source/GLTFExporter/Private/Tasks/GLTFMaterialTasks.cpp
jing-interactive/ucd
8fc8722291f086a0c0037a94d11c14562375e862
[ "MIT" ]
1
2022-02-02T23:36:07.000Z
2022-02-02T23:36:07.000Z
xiablo/Plugins/SketchFabPlugin/Source/GLTFExporter/Private/Tasks/GLTFMaterialTasks.cpp
jing-interactive/ucd
8fc8722291f086a0c0037a94d11c14562375e862
[ "MIT" ]
null
null
null
xiablo/Plugins/SketchFabPlugin/Source/GLTFExporter/Private/Tasks/GLTFMaterialTasks.cpp
jing-interactive/ucd
8fc8722291f086a0c0037a94d11c14562375e862
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "Tasks/SKGLTFMaterialTasks.h" #include "Converters/SKGLTFConverterUtility.h" #include "Converters/SKGLTFNameUtility.h" #include "Converters/SKGLTFMaterialUtility.h" #include "Builders/SKGLTFContainerBuilder.h" #include "MaterialPropertyEx.h" #include "Materials/MaterialExpressionConstant.h" #include "Materials/MaterialExpressionConstant2Vector.h" #include "Materials/MaterialExpressionConstant3Vector.h" #include "Materials/MaterialExpressionConstant4Vector.h" #include "Materials/MaterialExpressionScalarParameter.h" #include "Materials/MaterialExpressionVectorParameter.h" #include "Materials/MaterialExpressionTextureSample.h" #include "Materials/MaterialExpressionTextureSampleParameter2D.h" namespace { // Component masks const FLinearColor RedMask(1.0f, 0.0f, 0.0f, 0.0f); const FLinearColor GreenMask(0.0f, 1.0f, 0.0f, 0.0f); const FLinearColor BlueMask(0.0f, 0.0f, 1.0f, 0.0f); const FLinearColor AlphaMask(0.0f, 0.0f, 0.0f, 1.0f); const FLinearColor RgbMask = RedMask + GreenMask + BlueMask; const FLinearColor RgbaMask = RgbMask + AlphaMask; // Property-specific component masks const FLinearColor BaseColorMask = RgbMask; const FLinearColor OpacityMask = AlphaMask; const FLinearColor MetallicMask = BlueMask; const FLinearColor RoughnessMask = GreenMask; const FLinearColor OcclusionMask = RedMask; const FLinearColor ClearCoatMask = RedMask; const FLinearColor ClearCoatRoughnessMask = GreenMask; // Ideal masks for texture-inputs (doesn't require baking) const TArray<FLinearColor> DefaultColorInputMasks = { RgbMask, RgbaMask }; const TArray<FLinearColor> BaseColorInputMasks = { BaseColorMask }; const TArray<FLinearColor> OpacityInputMasks = { OpacityMask }; const TArray<FLinearColor> MetallicInputMasks = { MetallicMask }; const TArray<FLinearColor> RoughnessInputMasks = { RoughnessMask }; const TArray<FLinearColor> OcclusionInputMasks = { OcclusionMask }; const TArray<FLinearColor> ClearCoatInputMasks = { ClearCoatMask }; const TArray<FLinearColor> ClearCoatRoughnessInputMasks = { ClearCoatRoughnessMask }; } void FGLTFMaterialTask::Complete() { { const UMaterial* ParentMaterial = Material->GetMaterial(); if (ParentMaterial->MaterialDomain != MD_Surface) { // TODO: report warning (non-surface materials not supported, will be treated as surface) } } FGLTFJsonMaterial& JsonMaterial = Builder.GetMaterial(MaterialIndex); JsonMaterial.Name = GetMaterialName(); JsonMaterial.AlphaCutoff = Material->GetOpacityMaskClipValue(); JsonMaterial.DoubleSided = Material->IsTwoSided(); ConvertAlphaMode(JsonMaterial.AlphaMode, JsonMaterial.BlendMode); ConvertShadingModel(JsonMaterial.ShadingModel); if (JsonMaterial.ShadingModel != ESKGLTFJsonShadingModel::None) { const FMaterialPropertyEx BaseColorProperty = JsonMaterial.ShadingModel == ESKGLTFJsonShadingModel::Unlit ? MP_EmissiveColor : MP_BaseColor; const FMaterialPropertyEx OpacityProperty = JsonMaterial.AlphaMode == ESKGLTFJsonAlphaMode::Mask ? MP_OpacityMask : MP_Opacity; // TODO: check if a property is active before trying to get it (i.e. Material->IsPropertyActive) if (JsonMaterial.AlphaMode == ESKGLTFJsonAlphaMode::Opaque) { if (!TryGetConstantColor(JsonMaterial.PBRMetallicRoughness.BaseColorFactor, BaseColorProperty)) { if (!TryGetSourceTexture(JsonMaterial.PBRMetallicRoughness.BaseColorTexture, BaseColorProperty, DefaultColorInputMasks)) { if (!TryGetBakedMaterialProperty(JsonMaterial.PBRMetallicRoughness.BaseColorTexture, JsonMaterial.PBRMetallicRoughness.BaseColorFactor, BaseColorProperty, TEXT("BaseColor"))) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s for material %s"), *BaseColorProperty.ToString(), *Material->GetName())); } } } JsonMaterial.PBRMetallicRoughness.BaseColorFactor.A = 1.0f; // make sure base color is opaque } else { if (!TryGetBaseColorAndOpacity(JsonMaterial.PBRMetallicRoughness, BaseColorProperty, OpacityProperty)) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s and %s for material %s"), *BaseColorProperty.ToString(), *OpacityProperty.ToString(), *Material->GetName())); } } if (JsonMaterial.ShadingModel == ESKGLTFJsonShadingModel::Default || JsonMaterial.ShadingModel == ESKGLTFJsonShadingModel::ClearCoat) { const FMaterialPropertyEx MetallicProperty = MP_Metallic; const FMaterialPropertyEx RoughnessProperty = MP_Roughness; if (!TryGetMetallicAndRoughness(JsonMaterial.PBRMetallicRoughness, MetallicProperty, RoughnessProperty)) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s and %s for material %s"), *MetallicProperty.ToString(), *RoughnessProperty.ToString(), *Material->GetName())); } const FMaterialPropertyEx EmissiveProperty = MP_EmissiveColor; if (!TryGetEmissive(JsonMaterial, EmissiveProperty)) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s for material %s"), *EmissiveProperty.ToString(), *Material->GetName())); } const FMaterialPropertyEx NormalProperty = JsonMaterial.ShadingModel == ESKGLTFJsonShadingModel::ClearCoat ? FMaterialPropertyEx(TEXT("ClearCoatBottomNormal")) : FMaterialPropertyEx(MP_Normal); if (IsPropertyNonDefault(NormalProperty)) { if (!TryGetSourceTexture(JsonMaterial.NormalTexture, NormalProperty, DefaultColorInputMasks)) { if (!TryGetBakedMaterialProperty(JsonMaterial.NormalTexture, NormalProperty, TEXT("Normal"))) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s for material %s"), *NormalProperty.ToString(), *Material->GetName())); } } } const FMaterialPropertyEx AmbientOcclusionProperty = MP_AmbientOcclusion; if (IsPropertyNonDefault(AmbientOcclusionProperty)) { if (!TryGetSourceTexture(JsonMaterial.OcclusionTexture, AmbientOcclusionProperty, OcclusionInputMasks)) { if (!TryGetBakedMaterialProperty(JsonMaterial.OcclusionTexture, AmbientOcclusionProperty, TEXT("Occlusion"), true)) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s for material %s"), *AmbientOcclusionProperty.ToString(), *Material->GetName())); } } } if (JsonMaterial.ShadingModel == ESKGLTFJsonShadingModel::ClearCoat) { const FMaterialPropertyEx ClearCoatProperty = MP_CustomData0; const FMaterialPropertyEx ClearCoatRoughnessProperty = MP_CustomData1; if (!TryGetClearCoatRoughness(JsonMaterial.ClearCoat, ClearCoatProperty, ClearCoatRoughnessProperty)) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s and %s for material %s"), *ClearCoatProperty.ToString(), *ClearCoatRoughnessProperty.ToString(), *Material->GetName())); } const FMaterialPropertyEx ClearCoatNormalProperty = MP_Normal; if (IsPropertyNonDefault(ClearCoatNormalProperty)) { if (!TryGetSourceTexture(JsonMaterial.ClearCoat.ClearCoatNormalTexture, ClearCoatNormalProperty, DefaultColorInputMasks)) { if (!TryGetBakedMaterialProperty(JsonMaterial.ClearCoat.ClearCoatNormalTexture, ClearCoatNormalProperty, TEXT("ClearCoatNormal"))) { Builder.AddWarningMessage(FString::Printf(TEXT("Failed to export %s for material %s"), *ClearCoatNormalProperty.ToString(), *Material->GetName())); } } } } } } // Warn if properties baked using mesh data are using overlapping UVs if (MeshData != nullptr && MeshDataBakedProperties.Num() > 0) { const FGLTFMeshData* ParentMeshData = MeshData->GetParent(); const float UVOverlapThreshold = 1.0f / 100.0f; const float UVOverlap = UVOverlapChecker.GetOrAdd(&ParentMeshData->Description, SectionIndices, MeshData->TexCoord); if (UVOverlap > UVOverlapThreshold) { FString SectionString = TEXT("mesh section"); SectionString += SectionIndices.Num() > 1 ? TEXT("s ") : TEXT(" "); SectionString += FString::JoinBy(SectionIndices, TEXT(", "), FString::FromInt); Builder.AddWarningMessage(FString::Printf( TEXT("Material %s is baked using mesh data from %s but the lightmap UV (channel %d) are overlapping by %.2f%% (in %s) and may produce incorrect results"), *Material->GetName(), *ParentMeshData->Name, MeshData->TexCoord, UVOverlap * 100, *SectionString)); } } } void FGLTFMaterialTask::ConvertAlphaMode(ESKGLTFJsonAlphaMode& OutAlphaMode, ESKGLTFJsonBlendMode& OutBlendMode) const { const EBlendMode BlendMode = Material->GetBlendMode(); OutAlphaMode = FGLTFConverterUtility::ConvertAlphaMode(BlendMode); if (OutAlphaMode == ESKGLTFJsonAlphaMode::None) { OutAlphaMode = ESKGLTFJsonAlphaMode::Blend; OutBlendMode = ESKGLTFJsonBlendMode::None; Builder.AddWarningMessage(FString::Printf( TEXT("Unsupported blend mode (%s) in material %s, will export as %s"), *FGLTFNameUtility::GetName(BlendMode), *Material->GetName(), *FGLTFNameUtility::GetName(BLEND_Translucent))); return; } if (OutAlphaMode == ESKGLTFJsonAlphaMode::Blend) { OutBlendMode = FGLTFConverterUtility::ConvertBlendMode(BlendMode); if (OutBlendMode != ESKGLTFJsonBlendMode::None && !Builder.ExportOptions->bExportExtraBlendModes) { OutBlendMode = ESKGLTFJsonBlendMode::None; Builder.AddWarningMessage(FString::Printf( TEXT("Extra blend mode (%s) in material %s disabled by export options, will export as %s"), *FGLTFNameUtility::GetName(BlendMode), *Material->GetName(), *FGLTFNameUtility::GetName(BLEND_Translucent))); } } } void FGLTFMaterialTask::ConvertShadingModel(ESKGLTFJsonShadingModel& OutShadingModel) const { EMaterialShadingModel ShadingModel; { const FMaterialShadingModelField ShadingModels = Material->GetShadingModels(); if (Material->IsShadingModelFromMaterialExpression()) { const FMaterialShadingModelField Evaluation = FGLTFMaterialUtility::EvaluateShadingModelExpression(Material); if (Evaluation.CountShadingModels() == 1) { ShadingModel = Evaluation.GetFirstShadingModel(); } else if (Evaluation.CountShadingModels() > 1) { ShadingModel = FGLTFMaterialUtility::GetRichestShadingModel(Evaluation); Builder.AddWarningMessage(FString::Printf( TEXT("Evaluation of shading model expression in material %s is inconclusive (%s), will export as %s"), *Material->GetName(), *FGLTFMaterialUtility::ShadingModelsToString(Evaluation), *FGLTFNameUtility::GetName(ShadingModel))); } else { ShadingModel = FGLTFMaterialUtility::GetRichestShadingModel(ShadingModels); Builder.AddWarningMessage(FString::Printf( TEXT("Evaluation of shading model expression in material %s returned none, will export as %s"), *Material->GetName(), *FGLTFNameUtility::GetName(ShadingModel))); } } else { ShadingModel = ShadingModels.GetFirstShadingModel(); } } OutShadingModel = FGLTFConverterUtility::ConvertShadingModel(ShadingModel); if (OutShadingModel == ESKGLTFJsonShadingModel::None) { OutShadingModel = ESKGLTFJsonShadingModel::Default; Builder.AddWarningMessage(FString::Printf( TEXT("Unsupported shading model (%s) in material %s, will export as %s"), *FGLTFNameUtility::GetName(ShadingModel), *Material->GetName(), *FGLTFNameUtility::GetName(MSM_DefaultLit))); return; } if (OutShadingModel == ESKGLTFJsonShadingModel::Unlit && !Builder.ExportOptions->bExportUnlitMaterials) { OutShadingModel = ESKGLTFJsonShadingModel::Default; Builder.AddWarningMessage(FString::Printf( TEXT("Shading model (%s) in material %s disabled by export options, will export as %s"), *FGLTFNameUtility::GetName(ShadingModel), *Material->GetName(), *FGLTFNameUtility::GetName(MSM_DefaultLit))); return; } if (OutShadingModel == ESKGLTFJsonShadingModel::ClearCoat && !Builder.ExportOptions->bExportClearCoatMaterials) { OutShadingModel = ESKGLTFJsonShadingModel::Default; Builder.AddWarningMessage(FString::Printf( TEXT("Shading model (%s) in material %s disabled by export options, will export as %s"), *FGLTFNameUtility::GetName(ShadingModel), *Material->GetName(), *FGLTFNameUtility::GetName(MSM_DefaultLit))); } } bool FGLTFMaterialTask::TryGetBaseColorAndOpacity(FGLTFJsonPBRMetallicRoughness& OutPBRParams, const FMaterialPropertyEx& BaseColorProperty, const FMaterialPropertyEx& OpacityProperty) { const bool bIsBaseColorConstant = TryGetConstantColor(OutPBRParams.BaseColorFactor, BaseColorProperty); const bool bIsOpacityConstant = TryGetConstantScalar(OutPBRParams.BaseColorFactor.A, OpacityProperty); if (bIsBaseColorConstant && bIsOpacityConstant) { return true; } // NOTE: since we always bake the properties (for now) when atleast property is non-const, we need // to reset the constant factors to their defaults. Otherwise the baked value of a constant property // would be scaled with the factor, i.e a double scaling. OutPBRParams.BaseColorFactor = { 1.0f, 1.0f, 1.0f, 1.0f }; const UTexture2D* BaseColorTexture; const UTexture2D* OpacityTexture; int32 BaseColorTexCoord; int32 OpacityTexCoord; FGLTFJsonTextureTransform BaseColorTransform; FGLTFJsonTextureTransform OpacityTransform; const bool bHasBaseColorSourceTexture = TryGetSourceTexture(BaseColorTexture, BaseColorTexCoord, BaseColorTransform, BaseColorProperty, BaseColorInputMasks); const bool bHasOpacitySourceTexture = TryGetSourceTexture(OpacityTexture, OpacityTexCoord, OpacityTransform, OpacityProperty, OpacityInputMasks); // Detect the "happy path" where both inputs share the same texture and are correctly masked. if (bHasBaseColorSourceTexture && bHasOpacitySourceTexture && BaseColorTexture == OpacityTexture && BaseColorTexCoord == OpacityTexCoord && BaseColorTransform == OpacityTransform) { OutPBRParams.BaseColorTexture.Index = Builder.GetOrAddTexture(BaseColorTexture); OutPBRParams.BaseColorTexture.TexCoord = BaseColorTexCoord; OutPBRParams.BaseColorTexture.Transform = BaseColorTransform; return true; } if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s and %s for material %s needs to bake, but material baking is disabled by export options"), *BaseColorProperty.ToString(), *OpacityProperty.ToString(), *Material->GetName())); return false; } FIntPoint TextureSize = Builder.GetBakeSizeForMaterialProperty(Material, BaseColorProperty); const TextureAddress TextureAddress = Builder.GetBakeTilingForMaterialProperty(Material, BaseColorProperty); const ESKGLTFJsonTextureWrap TextureWrapS = FGLTFConverterUtility::ConvertWrap(TextureAddress); const ESKGLTFJsonTextureWrap TextureWrapT = FGLTFConverterUtility::ConvertWrap(TextureAddress); const TextureFilter TextureFilter = Builder.GetBakeFilterForMaterialProperty(Material, BaseColorProperty); const ESKGLTFJsonTextureFilter TextureMinFilter = FGLTFConverterUtility::ConvertMinFilter(TextureFilter); const ESKGLTFJsonTextureFilter TextureMagFilter = FGLTFConverterUtility::ConvertMagFilter(TextureFilter); const FGLTFPropertyBakeOutput BaseColorBakeOutput = BakeMaterialProperty(BaseColorProperty, BaseColorTexCoord, TextureSize); const FGLTFPropertyBakeOutput OpacityBakeOutput = BakeMaterialProperty(OpacityProperty, OpacityTexCoord, TextureSize, true); const float BaseColorScale = BaseColorProperty == MP_EmissiveColor ? BaseColorBakeOutput.EmissiveScale : 1; // Detect when both baked properties are constants, which means we can avoid exporting a texture if (BaseColorBakeOutput.bIsConstant && OpacityBakeOutput.bIsConstant) { FLinearColor BaseColorFactor(BaseColorBakeOutput.ConstantValue * BaseColorScale); BaseColorFactor.A = OpacityBakeOutput.ConstantValue.A; OutPBRParams.BaseColorFactor = FGLTFConverterUtility::ConvertColor(BaseColorFactor); return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { return true; } int32 TexCoord; if (BaseColorBakeOutput.bIsConstant) { TexCoord = OpacityTexCoord; } else if (OpacityBakeOutput.bIsConstant) { TexCoord = BaseColorTexCoord; } else if (BaseColorTexCoord == OpacityTexCoord) { TexCoord = BaseColorTexCoord; } else { // TODO: report error (texture coordinate conflict) return false; } TextureSize = BaseColorBakeOutput.Size.ComponentMax(OpacityBakeOutput.Size); BaseColorTexture = FGLTFMaterialUtility::CreateTransientTexture(BaseColorBakeOutput); OpacityTexture = FGLTFMaterialUtility::CreateTransientTexture(OpacityBakeOutput); const TArray<FGLTFTextureCombineSource> CombineSources = { { OpacityTexture, OpacityMask, SE_BLEND_Opaque }, { BaseColorTexture, BaseColorMask } }; const FGLTFJsonTextureIndex TextureIndex = FGLTFMaterialUtility::AddCombinedTexture( Builder, CombineSources, TextureSize, false, GetBakedTextureName(TEXT("BaseColor")), TextureMinFilter, TextureMagFilter, TextureWrapS, TextureWrapT); OutPBRParams.BaseColorTexture.TexCoord = TexCoord; OutPBRParams.BaseColorTexture.Index = TextureIndex; OutPBRParams.BaseColorFactor = { BaseColorScale, BaseColorScale, BaseColorScale }; return true; } bool FGLTFMaterialTask::TryGetMetallicAndRoughness(FGLTFJsonPBRMetallicRoughness& OutPBRParams, const FMaterialPropertyEx& MetallicProperty, const FMaterialPropertyEx& RoughnessProperty) { const bool bIsMetallicConstant = TryGetConstantScalar(OutPBRParams.MetallicFactor, MetallicProperty); const bool bIsRoughnessConstant = TryGetConstantScalar(OutPBRParams.RoughnessFactor, RoughnessProperty); if (bIsMetallicConstant && bIsRoughnessConstant) { return true; } // NOTE: since we always bake the properties (for now) when atleast one property is non-const, we need // to reset the constant factors to their defaults. Otherwise the baked value of a constant property // would be scaled with the factor, i.e a double scaling. OutPBRParams.MetallicFactor = 1.0f; OutPBRParams.RoughnessFactor = 1.0f; const UTexture2D* MetallicTexture; const UTexture2D* RoughnessTexture; int32 MetallicTexCoord; int32 RoughnessTexCoord; FGLTFJsonTextureTransform MetallicTransform; FGLTFJsonTextureTransform RoughnessTransform; const bool bHasMetallicSourceTexture = TryGetSourceTexture(MetallicTexture, MetallicTexCoord, MetallicTransform, MetallicProperty, MetallicInputMasks); const bool bHasRoughnessSourceTexture = TryGetSourceTexture(RoughnessTexture, RoughnessTexCoord, RoughnessTransform, RoughnessProperty, RoughnessInputMasks); // Detect the "happy path" where both inputs share the same texture and are correctly masked. if (bHasMetallicSourceTexture && bHasRoughnessSourceTexture && MetallicTexture == RoughnessTexture && MetallicTexCoord == RoughnessTexCoord && MetallicTransform == RoughnessTransform) { OutPBRParams.MetallicRoughnessTexture.Index = Builder.GetOrAddTexture(MetallicTexture); OutPBRParams.MetallicRoughnessTexture.TexCoord = MetallicTexCoord; OutPBRParams.MetallicRoughnessTexture.Transform = MetallicTransform; return true; } if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s and %s for material %s needs to bake, but material baking is disabled by export options"), *MetallicProperty.ToString(), *RoughnessProperty.ToString(), *Material->GetName())); return false; } // TODO: add support for calculating the ideal resolution to use for baking based on connected (texture) nodes FIntPoint TextureSize = Builder.GetBakeSizeForMaterialProperty(Material, MetallicProperty); const TextureAddress TextureAddress = Builder.GetBakeTilingForMaterialProperty(Material, MetallicProperty); const ESKGLTFJsonTextureWrap TextureWrapS = FGLTFConverterUtility::ConvertWrap(TextureAddress); const ESKGLTFJsonTextureWrap TextureWrapT = FGLTFConverterUtility::ConvertWrap(TextureAddress); const TextureFilter TextureFilter = Builder.GetBakeFilterForMaterialProperty(Material, MetallicProperty); const ESKGLTFJsonTextureFilter TextureMinFilter = FGLTFConverterUtility::ConvertMinFilter(TextureFilter); const ESKGLTFJsonTextureFilter TextureMagFilter = FGLTFConverterUtility::ConvertMagFilter(TextureFilter); FGLTFPropertyBakeOutput MetallicBakeOutput = BakeMaterialProperty(MetallicProperty, MetallicTexCoord, TextureSize); FGLTFPropertyBakeOutput RoughnessBakeOutput = BakeMaterialProperty(RoughnessProperty, RoughnessTexCoord, TextureSize); // Detect when both baked properties are constants, which means we can use factors and avoid exporting a texture if (MetallicBakeOutput.bIsConstant && RoughnessBakeOutput.bIsConstant) { OutPBRParams.MetallicFactor = MetallicBakeOutput.ConstantValue.R; OutPBRParams.RoughnessFactor = RoughnessBakeOutput.ConstantValue.R; return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { return true; } int32 TexCoord; if (MetallicBakeOutput.bIsConstant) { TexCoord = RoughnessTexCoord; } else if (MetallicBakeOutput.bIsConstant) { TexCoord = MetallicTexCoord; } else if (MetallicTexCoord == RoughnessTexCoord) { TexCoord = MetallicTexCoord; } else { // TODO: report error (texture coordinate conflict) return false; } FGLTFMaterialUtility::TransformToLinear(MetallicBakeOutput.Pixels); FGLTFMaterialUtility::TransformToLinear(RoughnessBakeOutput.Pixels); TextureSize = RoughnessBakeOutput.Size.ComponentMax(MetallicBakeOutput.Size); MetallicTexture = FGLTFMaterialUtility::CreateTransientTexture(MetallicBakeOutput); RoughnessTexture = FGLTFMaterialUtility::CreateTransientTexture(RoughnessBakeOutput); const TArray<FGLTFTextureCombineSource> CombineSources = { { MetallicTexture, MetallicMask + AlphaMask, SE_BLEND_Opaque }, { RoughnessTexture, RoughnessMask } }; const FGLTFJsonTextureIndex TextureIndex = FGLTFMaterialUtility::AddCombinedTexture( Builder, CombineSources, TextureSize, true, // NOTE: we can ignore alpha in everything but TryGetBaseColorAndOpacity GetBakedTextureName(TEXT("MetallicRoughness")), TextureMinFilter, TextureMagFilter, TextureWrapS, TextureWrapT); OutPBRParams.MetallicRoughnessTexture.TexCoord = TexCoord; OutPBRParams.MetallicRoughnessTexture.Index = TextureIndex; return true; } bool FGLTFMaterialTask::TryGetClearCoatRoughness(FGLTFJsonClearCoatExtension& OutExtParams, const FMaterialPropertyEx& IntensityProperty, const FMaterialPropertyEx& RoughnessProperty) { const bool bIsIntensityConstant = TryGetConstantScalar(OutExtParams.ClearCoatFactor, IntensityProperty); const bool bIsRoughnessConstant = TryGetConstantScalar(OutExtParams.ClearCoatRoughnessFactor, RoughnessProperty); if (bIsIntensityConstant && bIsRoughnessConstant) { return true; } // NOTE: since we always bake the properties (for now) when atleast one property is non-const, we need // to reset the constant factors to their defaults. Otherwise the baked value of a constant property // would be scaled with the factor, i.e a double scaling. OutExtParams.ClearCoatFactor = 1.0f; OutExtParams.ClearCoatRoughnessFactor = 1.0f; const UTexture2D* IntensityTexture; const UTexture2D* RoughnessTexture; int32 IntensityTexCoord; int32 RoughnessTexCoord; FGLTFJsonTextureTransform IntensityTransform; FGLTFJsonTextureTransform RoughnessTransform; const bool bHasIntensitySourceTexture = TryGetSourceTexture(IntensityTexture, IntensityTexCoord, IntensityTransform, IntensityProperty, ClearCoatInputMasks); const bool bHasRoughnessSourceTexture = TryGetSourceTexture(RoughnessTexture, RoughnessTexCoord, RoughnessTransform, RoughnessProperty, ClearCoatRoughnessInputMasks); // Detect the "happy path" where both inputs share the same texture and are correctly masked. if (bHasIntensitySourceTexture && bHasRoughnessSourceTexture && IntensityTexture == RoughnessTexture && IntensityTexCoord == RoughnessTexCoord && IntensityTransform == RoughnessTransform) { const FGLTFJsonTextureIndex TextureIndex = Builder.GetOrAddTexture(IntensityTexture); OutExtParams.ClearCoatTexture.Index = TextureIndex; OutExtParams.ClearCoatTexture.TexCoord = IntensityTexCoord; OutExtParams.ClearCoatRoughnessTexture.Index = TextureIndex; OutExtParams.ClearCoatRoughnessTexture.TexCoord = IntensityTexCoord; OutExtParams.ClearCoatRoughnessTexture.Transform = IntensityTransform; return true; } if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s and %s for material %s needs to bake, but material baking is disabled by export options"), *IntensityProperty.ToString(), *RoughnessProperty.ToString(), *Material->GetName())); return false; } FIntPoint TextureSize = Builder.GetBakeSizeForMaterialProperty(Material, IntensityProperty); const TextureAddress TextureAddress = Builder.GetBakeTilingForMaterialProperty(Material, IntensityProperty); const ESKGLTFJsonTextureWrap TextureWrapS = FGLTFConverterUtility::ConvertWrap(TextureAddress); const ESKGLTFJsonTextureWrap TextureWrapT = FGLTFConverterUtility::ConvertWrap(TextureAddress); const TextureFilter TextureFilter = Builder.GetBakeFilterForMaterialProperty(Material, IntensityProperty); const ESKGLTFJsonTextureFilter TextureMinFilter = FGLTFConverterUtility::ConvertMinFilter(TextureFilter); const ESKGLTFJsonTextureFilter TextureMagFilter = FGLTFConverterUtility::ConvertMagFilter(TextureFilter); const FGLTFPropertyBakeOutput IntensityBakeOutput = BakeMaterialProperty(IntensityProperty, IntensityTexCoord, TextureSize); const FGLTFPropertyBakeOutput RoughnessBakeOutput = BakeMaterialProperty(RoughnessProperty, RoughnessTexCoord, TextureSize); // Detect when both baked properties are constants, which means we can use factors and avoid exporting a texture if (IntensityBakeOutput.bIsConstant && RoughnessBakeOutput.bIsConstant) { OutExtParams.ClearCoatFactor = IntensityBakeOutput.ConstantValue.R; OutExtParams.ClearCoatRoughnessFactor = RoughnessBakeOutput.ConstantValue.R; return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { return true; } int32 TexCoord; if (IntensityBakeOutput.bIsConstant) { TexCoord = RoughnessTexCoord; } else if (IntensityBakeOutput.bIsConstant) { TexCoord = IntensityTexCoord; } else if (IntensityTexCoord == RoughnessTexCoord) { TexCoord = IntensityTexCoord; } else { // TODO: report error (texture coordinate conflict) return false; } TextureSize = RoughnessBakeOutput.Size.ComponentMax(IntensityBakeOutput.Size); IntensityTexture = FGLTFMaterialUtility::CreateTransientTexture(IntensityBakeOutput); RoughnessTexture = FGLTFMaterialUtility::CreateTransientTexture(RoughnessBakeOutput); const TArray<FGLTFTextureCombineSource> CombineSources = { { IntensityTexture, ClearCoatMask + AlphaMask, SE_BLEND_Opaque }, { RoughnessTexture, ClearCoatRoughnessMask } }; const FGLTFJsonTextureIndex TextureIndex = FGLTFMaterialUtility::AddCombinedTexture( Builder, CombineSources, TextureSize, true, // NOTE: we can ignore alpha in everything but TryGetBaseColorAndOpacity GetBakedTextureName(TEXT("ClearCoatRoughness")), TextureMinFilter, TextureMagFilter, TextureWrapS, TextureWrapT); OutExtParams.ClearCoatTexture.Index = TextureIndex; OutExtParams.ClearCoatTexture.TexCoord = TexCoord; OutExtParams.ClearCoatRoughnessTexture.Index = TextureIndex; OutExtParams.ClearCoatRoughnessTexture.TexCoord = TexCoord; return true; } bool FGLTFMaterialTask::TryGetEmissive(FGLTFJsonMaterial& JsonMaterial, const FMaterialPropertyEx& EmissiveProperty) { // TODO: right now we allow EmissiveFactor to be > 1.0 to support very bright emission, although it's not valid according to the glTF standard. // We may want to change this behaviour and store factors above 1.0 using a custom extension instead. if (TryGetConstantColor(JsonMaterial.EmissiveFactor, MP_EmissiveColor)) { return true; } if (TryGetSourceTexture(JsonMaterial.EmissiveTexture, EmissiveProperty, DefaultColorInputMasks)) { JsonMaterial.EmissiveFactor = FGLTFJsonColor3::White; // make sure texture is not multiplied with black return true; } if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s needs to bake, but material baking is disabled by export options"), *EmissiveProperty.ToString(), *Material->GetName())); return false; } const FGLTFPropertyBakeOutput PropertyBakeOutput = BakeMaterialProperty(EmissiveProperty, JsonMaterial.EmissiveTexture.TexCoord); const float EmissiveScale = PropertyBakeOutput.EmissiveScale; if (PropertyBakeOutput.bIsConstant) { const FLinearColor EmissiveColor = PropertyBakeOutput.ConstantValue; JsonMaterial.EmissiveFactor = FGLTFConverterUtility::ConvertColor(EmissiveColor * EmissiveScale); } else { if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { JsonMaterial.EmissiveTexture.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (!StoreBakedPropertyTexture(JsonMaterial.EmissiveTexture, PropertyBakeOutput, TEXT("Emissive"))) { return false; } JsonMaterial.EmissiveFactor = { EmissiveScale, EmissiveScale, EmissiveScale }; } return true; } bool FGLTFMaterialTask::IsPropertyNonDefault(const FMaterialPropertyEx& Property) const { const bool bUseMaterialAttributes = Material->GetMaterial()->bUseMaterialAttributes; if (bUseMaterialAttributes) { // TODO: check if attribute property connected, i.e. Material->GetMaterial()->MaterialAttributes.IsConnected(Property) return true; } const FExpressionInput* MaterialInput = FGLTFMaterialUtility::GetInputForProperty(Material, Property); if (MaterialInput == nullptr) { // TODO: report error return false; } const UMaterialExpression* Expression = MaterialInput->Expression; if (Expression == nullptr) { return false; } return true; } bool FGLTFMaterialTask::TryGetConstantColor(FGLTFJsonColor3& OutValue, const FMaterialPropertyEx& Property) const { FLinearColor Value; if (TryGetConstantColor(Value, Property)) { OutValue = FGLTFConverterUtility::ConvertColor(Value); return true; } return false; } bool FGLTFMaterialTask::TryGetConstantColor(FGLTFJsonColor4& OutValue, const FMaterialPropertyEx& Property) const { FLinearColor Value; if (TryGetConstantColor(Value, Property)) { OutValue = FGLTFConverterUtility::ConvertColor(Value); return true; } return false; } bool FGLTFMaterialTask::TryGetConstantColor(FLinearColor& OutValue, const FMaterialPropertyEx& Property) const { const bool bUseMaterialAttributes = Material->GetMaterial()->bUseMaterialAttributes; if (bUseMaterialAttributes) { // TODO: check if attribute property connected, i.e. Material->GetMaterial()->MaterialAttributes.IsConnected(Property) return false; } const FMaterialInput<FColor>* MaterialInput = FGLTFMaterialUtility::GetInputForProperty<FColor>(Material, Property); if (MaterialInput == nullptr) { // TODO: report error return false; } if (MaterialInput->UseConstant) { OutValue = { MaterialInput->Constant }; return true; } const UMaterialExpression* Expression = MaterialInput->Expression; if (Expression == nullptr) { OutValue = FLinearColor(FGLTFMaterialUtility::GetPropertyDefaultValue(Property)); return true; } if (const UMaterialExpressionVectorParameter* VectorParameter = ExactCast<UMaterialExpressionVectorParameter>(Expression)) { FLinearColor Value = VectorParameter->DefaultValue; const UMaterialInstance* MaterialInstance = Cast<UMaterialInstance>(Material); if (MaterialInstance != nullptr) { const FHashedMaterialParameterInfo ParameterInfo(VectorParameter->GetParameterName()); if (!MaterialInstance->GetVectorParameterValue(ParameterInfo, Value)) { // TODO: how to handle this? } } const uint32 MaskComponentCount = FGLTFMaterialUtility::GetMaskComponentCount(*MaterialInput); if (MaskComponentCount > 0) { const FLinearColor Mask = FGLTFMaterialUtility::GetMask(*MaterialInput); Value *= Mask; if (MaskComponentCount == 1) { const float ComponentValue = Value.R + Value.G + Value.B + Value.A; Value = { ComponentValue, ComponentValue, ComponentValue, ComponentValue }; } } OutValue = Value; return true; } if (const UMaterialExpressionScalarParameter* ScalarParameter = ExactCast<UMaterialExpressionScalarParameter>(Expression)) { float Value = ScalarParameter->DefaultValue; const UMaterialInstance* MaterialInstance = Cast<UMaterialInstance>(Material); if (MaterialInstance != nullptr) { const FHashedMaterialParameterInfo ParameterInfo(ScalarParameter->GetParameterName()); if (!MaterialInstance->GetScalarParameterValue(ParameterInfo, Value)) { // TODO: how to handle this? } } OutValue = { Value, Value, Value, Value }; return true; } if (const UMaterialExpressionConstant4Vector* Constant4Vector = ExactCast<UMaterialExpressionConstant4Vector>(Expression)) { OutValue = Constant4Vector->Constant; return true; } if (const UMaterialExpressionConstant3Vector* Constant3Vector = ExactCast<UMaterialExpressionConstant3Vector>(Expression)) { OutValue = Constant3Vector->Constant; return true; } if (const UMaterialExpressionConstant2Vector* Constant2Vector = ExactCast<UMaterialExpressionConstant2Vector>(Expression)) { OutValue = { Constant2Vector->R, Constant2Vector->G, 0, 0 }; return true; } if (const UMaterialExpressionConstant* Constant = ExactCast<UMaterialExpressionConstant>(Expression)) { OutValue = { Constant->R, Constant->R, Constant->R, Constant->R }; return true; } return false; } bool FGLTFMaterialTask::TryGetConstantScalar(float& OutValue, const FMaterialPropertyEx& Property) const { const bool bUseMaterialAttributes = Material->GetMaterial()->bUseMaterialAttributes; if (bUseMaterialAttributes) { // TODO: check if attribute property connected, i.e. Material->GetMaterial()->MaterialAttributes.IsConnected(Property) return false; } const FMaterialInput<float>* MaterialInput = FGLTFMaterialUtility::GetInputForProperty<float>(Material, Property); if (MaterialInput == nullptr) { // TODO: report error return false; } if (MaterialInput->UseConstant) { OutValue = MaterialInput->Constant; return true; } const UMaterialExpression* Expression = MaterialInput->Expression; if (Expression == nullptr) { OutValue = FGLTFMaterialUtility::GetPropertyDefaultValue(Property).X; return true; } if (const UMaterialExpressionVectorParameter* VectorParameter = ExactCast<UMaterialExpressionVectorParameter>(Expression)) { FLinearColor Value = VectorParameter->DefaultValue; const UMaterialInstance* MaterialInstance = Cast<UMaterialInstance>(Material); if (MaterialInstance != nullptr) { const FHashedMaterialParameterInfo ParameterInfo(VectorParameter->GetParameterName()); if (!MaterialInstance->GetVectorParameterValue(ParameterInfo, Value)) { // TODO: how to handle this? } } const uint32 MaskComponentCount = FGLTFMaterialUtility::GetMaskComponentCount(*MaterialInput); if (MaskComponentCount > 0) { const FLinearColor Mask = FGLTFMaterialUtility::GetMask(*MaterialInput); Value *= Mask; } // TODO: is this a correct assumption, that the max component should be used as value? OutValue = Value.GetMax(); return true; } if (const UMaterialExpressionScalarParameter* ScalarParameter = ExactCast<UMaterialExpressionScalarParameter>(Expression)) { float Value = ScalarParameter->DefaultValue; const UMaterialInstance* MaterialInstance = Cast<UMaterialInstance>(Material); if (MaterialInstance != nullptr) { const FHashedMaterialParameterInfo ParameterInfo(ScalarParameter->GetParameterName()); if (!MaterialInstance->GetScalarParameterValue(ParameterInfo, Value)) { // TODO: how to handle this? } } OutValue = Value; return true; } if (const UMaterialExpressionConstant4Vector* Constant4Vector = ExactCast<UMaterialExpressionConstant4Vector>(Expression)) { OutValue = Constant4Vector->Constant.R; return true; } if (const UMaterialExpressionConstant3Vector* Constant3Vector = ExactCast<UMaterialExpressionConstant3Vector>(Expression)) { OutValue = Constant3Vector->Constant.R; return true; } if (const UMaterialExpressionConstant2Vector* Constant2Vector = ExactCast<UMaterialExpressionConstant2Vector>(Expression)) { OutValue = Constant2Vector->R; return true; } if (const UMaterialExpressionConstant* Constant = ExactCast<UMaterialExpressionConstant>(Expression)) { OutValue = Constant->R; return true; } return false; } bool FGLTFMaterialTask::TryGetSourceTexture(FGLTFJsonTextureInfo& OutTexInfo, const FMaterialPropertyEx& Property, const TArray<FLinearColor>& AllowedMasks) const { const UTexture2D* Texture; int32 TexCoord; FGLTFJsonTextureTransform Transform; if (TryGetSourceTexture(Texture, TexCoord, Transform, Property, AllowedMasks)) { OutTexInfo.Index = Builder.GetOrAddTexture(Texture); OutTexInfo.TexCoord = TexCoord; OutTexInfo.Transform = Transform; return true; } return false; } bool FGLTFMaterialTask::TryGetSourceTexture(const UTexture2D*& OutTexture, int32& OutTexCoord, FGLTFJsonTextureTransform& OutTransform, const FMaterialPropertyEx& Property, const TArray<FLinearColor>& AllowedMasks) const { if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { return false; } const FExpressionInput* MaterialInput = FGLTFMaterialUtility::GetInputForProperty(Material, Property); if (MaterialInput == nullptr) { // TODO: report error return false; } const UMaterialExpression* Expression = MaterialInput->Expression; if (Expression == nullptr) { return false; } const FLinearColor InputMask = FGLTFMaterialUtility::GetMask(*MaterialInput); if (AllowedMasks.Num() > 0 && !AllowedMasks.Contains(InputMask)) { return false; } // TODO: add support or warning for texture sampler settings that override texture asset addressing (i.e. wrap, clamp etc)? if (const UMaterialExpressionTextureSampleParameter2D* TextureParameter = ExactCast<UMaterialExpressionTextureSampleParameter2D>(Expression)) { UTexture* ParameterValue = TextureParameter->Texture; const UMaterialInstance* MaterialInstance = Cast<UMaterialInstance>(Material); if (MaterialInstance != nullptr) { const FHashedMaterialParameterInfo ParameterInfo(TextureParameter->GetParameterName()); if (!MaterialInstance->GetTextureParameterValue(ParameterInfo, ParameterValue)) { // TODO: how to handle this? } } OutTexture = Cast<UTexture2D>(ParameterValue); if (OutTexture == nullptr) { if (ParameterValue == nullptr) { // TODO: report error (no texture parameter assigned) } else { // TODO: report error (incorrect texture type) } return false; } if (!FGLTFMaterialUtility::TryGetTextureCoordinateIndex(TextureParameter, OutTexCoord, OutTransform)) { // TODO: report error (failed to identify texture coordinate index) return false; } if (!Builder.ExportOptions->bExportTextureTransforms && OutTransform != FGLTFJsonTextureTransform()) { Builder.AddWarningMessage(FString::Printf( TEXT("Texture coordinates [%d] in %s for material %s are transformed, but texture transform is disabled by export options"), OutTexCoord, *Property.ToString(), *Material->GetName())); OutTransform = {}; } return true; } if (const UMaterialExpressionTextureSample* TextureSampler = ExactCast<UMaterialExpressionTextureSample>(Expression)) { // TODO: add support for texture object input expression OutTexture = Cast<UTexture2D>(TextureSampler->Texture); if (OutTexture == nullptr) { if (TextureSampler->Texture == nullptr) { // TODO: report error (no texture sample assigned) } else { // TODO: report error (incorrect texture type) } return false; } if (!FGLTFMaterialUtility::TryGetTextureCoordinateIndex(TextureSampler, OutTexCoord, OutTransform)) { // TODO: report error (failed to identify texture coordinate index) return false; } if (!Builder.ExportOptions->bExportTextureTransforms && OutTransform != FGLTFJsonTextureTransform()) { Builder.AddWarningMessage(FString::Printf( TEXT("Texture coordinates [%d] in %s for material %s are transformed, but texture transform is disabled by export options"), OutTexCoord, *Property.ToString(), *Material->GetName())); OutTransform = {}; } return true; } return false; } bool FGLTFMaterialTask::TryGetBakedMaterialProperty(FGLTFJsonTextureInfo& OutTexInfo, FGLTFJsonColor3& OutConstant, const FMaterialPropertyEx& Property, const FString& PropertyName, bool bTransformToLinear) { if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s needs to bake, but material baking is disabled by export options"), *Property.ToString(), *Material->GetName())); return false; } FGLTFPropertyBakeOutput PropertyBakeOutput = BakeMaterialProperty(Property, OutTexInfo.TexCoord); if (PropertyBakeOutput.bIsConstant) { OutConstant = FGLTFConverterUtility::ConvertColor(PropertyBakeOutput.ConstantValue); return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (bTransformToLinear) { FGLTFMaterialUtility::TransformToLinear(PropertyBakeOutput.Pixels); } if (StoreBakedPropertyTexture(OutTexInfo, PropertyBakeOutput, PropertyName)) { OutConstant = FGLTFJsonColor3::White; // make sure property is not zero return true; } return false; } bool FGLTFMaterialTask::TryGetBakedMaterialProperty(FGLTFJsonTextureInfo& OutTexInfo, FGLTFJsonColor4& OutConstant, const FMaterialPropertyEx& Property, const FString& PropertyName, bool bTransformToLinear) { if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s needs to bake, but material baking is disabled by export options"), *Property.ToString(), *Material->GetName())); return false; } FGLTFPropertyBakeOutput PropertyBakeOutput = BakeMaterialProperty(Property, OutTexInfo.TexCoord); if (PropertyBakeOutput.bIsConstant) { OutConstant = FGLTFConverterUtility::ConvertColor(PropertyBakeOutput.ConstantValue); return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (bTransformToLinear) { FGLTFMaterialUtility::TransformToLinear(PropertyBakeOutput.Pixels); } if (StoreBakedPropertyTexture(OutTexInfo, PropertyBakeOutput, PropertyName)) { OutConstant = FGLTFJsonColor4::White; // make sure property is not zero return true; } return false; } inline bool FGLTFMaterialTask::TryGetBakedMaterialProperty(FGLTFJsonTextureInfo& OutTexInfo, float& OutConstant, const FMaterialPropertyEx& Property, const FString& PropertyName, bool bTransformToLinear) { if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s needs to bake, but material baking is disabled by export options"), *Property.ToString(), *Material->GetName())); return false; } FGLTFPropertyBakeOutput PropertyBakeOutput = BakeMaterialProperty(Property, OutTexInfo.TexCoord); if (PropertyBakeOutput.bIsConstant) { OutConstant = PropertyBakeOutput.ConstantValue.R; return true; } if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (bTransformToLinear) { FGLTFMaterialUtility::TransformToLinear(PropertyBakeOutput.Pixels); } if (StoreBakedPropertyTexture(OutTexInfo, PropertyBakeOutput, PropertyName)) { OutConstant = 1; // make sure property is not zero return true; } return false; } bool FGLTFMaterialTask::TryGetBakedMaterialProperty(FGLTFJsonTextureInfo& OutTexInfo, const FMaterialPropertyEx& Property, const FString& PropertyName, bool bTransformToLinear) { if (Builder.ExportOptions->BakeMaterialInputs == ESKGLTFMaterialBakeMode::Disabled) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s needs to bake, but material baking is disabled by export options"), *Property.ToString(), *Material->GetName())); return false; } FGLTFPropertyBakeOutput PropertyBakeOutput = BakeMaterialProperty(Property, OutTexInfo.TexCoord); if (!PropertyBakeOutput.bIsConstant) { if (Builder.ExportOptions->TextureImageFormat == ESKGLTFTextureImageFormat::None) { OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (bTransformToLinear) { FGLTFMaterialUtility::TransformToLinear(PropertyBakeOutput.Pixels); } return StoreBakedPropertyTexture(OutTexInfo, PropertyBakeOutput, PropertyName); } const FVector4 MaskedConstant = FVector4(PropertyBakeOutput.ConstantValue) * FGLTFMaterialUtility::GetPropertyMask(Property); if (MaskedConstant == FGLTFMaterialUtility::GetPropertyDefaultValue(Property)) { // Constant value is the same as the property's default so we can set gltf to default. OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } if (FGLTFMaterialUtility::IsNormalMap(Property)) { // TODO: In some cases baking normal can result in constant vector that differs slight from default (i.e 0,0,1). // Yet often, when looking at such a material, it should be exactly default. Needs further investigation. // Maybe because of incorrect sRGB conversion? For now, assume a constant normal is always default. OutTexInfo.Index = FGLTFJsonTextureIndex(INDEX_NONE); return true; } // TODO: let function fail and investigate why in some cases a constant baking result is returned for a property // that is non-constant. This happens (for example) when baking AmbientOcclusion for a translucent material, // even though the same material when set to opaque will properly bake AmbientOcclusion to a texture. // For now, create a 1x1 texture with the constant value. const FGLTFJsonTextureIndex TextureIndex = FGLTFMaterialUtility::AddTexture( Builder, PropertyBakeOutput.Pixels, PropertyBakeOutput.Size, true, // NOTE: we can ignore alpha in everything but TryGetBaseColorAndOpacity false, // Normal and ClearCoatBottomNormal are handled above GetBakedTextureName(PropertyName), ESKGLTFJsonTextureFilter::Nearest, ESKGLTFJsonTextureFilter::Nearest, ESKGLTFJsonTextureWrap::ClampToEdge, ESKGLTFJsonTextureWrap::ClampToEdge); OutTexInfo.Index = TextureIndex; return true; } FGLTFPropertyBakeOutput FGLTFMaterialTask::BakeMaterialProperty(const FMaterialPropertyEx& Property, int32& OutTexCoord, bool bCopyAlphaFromRedChannel) { const FIntPoint TextureSize = Builder.GetBakeSizeForMaterialProperty(Material, Property); return BakeMaterialProperty(Property, OutTexCoord, TextureSize, bCopyAlphaFromRedChannel); } FGLTFPropertyBakeOutput FGLTFMaterialTask::BakeMaterialProperty(const FMaterialPropertyEx& Property, int32& OutTexCoord, const FIntPoint& TextureSize, bool bCopyAlphaFromRedChannel) { if (MeshData == nullptr) { FGLTFIndexArray TexCoords; FGLTFMaterialUtility::GetAllTextureCoordinateIndices(Material, Property, TexCoords); if (TexCoords.Num() > 0) { OutTexCoord = TexCoords[0]; if (TexCoords.Num() > 1) { Builder.AddWarningMessage(FString::Printf( TEXT("%s for material %s uses multiple texture coordinates (%s), baked texture will be sampled using only the first (%d)"), *Property.ToString(), *Material->GetName(), *FString::JoinBy(TexCoords, TEXT(", "), FString::FromInt), OutTexCoord)); } } else { OutTexCoord = 0; } } else { OutTexCoord = MeshData->TexCoord; MeshDataBakedProperties.Add(Property); } // TODO: add support for calculating the ideal resolution to use for baking based on connected (texture) nodes const FGLTFPropertyBakeOutput PropertyBakeOutput = FGLTFMaterialUtility::BakeMaterialProperty( TextureSize, Property, Material, OutTexCoord, MeshData != nullptr ? &MeshData->Description : nullptr, SectionIndices, bCopyAlphaFromRedChannel); return PropertyBakeOutput; } bool FGLTFMaterialTask::StoreBakedPropertyTexture(FGLTFJsonTextureInfo& OutTexInfo, const FGLTFPropertyBakeOutput& PropertyBakeOutput, const FString& PropertyName) const { const TextureAddress TextureAddress = Builder.GetBakeTilingForMaterialProperty(Material, PropertyBakeOutput.Property); const ESKGLTFJsonTextureWrap TextureWrapS = FGLTFConverterUtility::ConvertWrap(TextureAddress); const ESKGLTFJsonTextureWrap TextureWrapT = FGLTFConverterUtility::ConvertWrap(TextureAddress); const TextureFilter TextureFilter = Builder.GetBakeFilterForMaterialProperty(Material, PropertyBakeOutput.Property); const ESKGLTFJsonTextureFilter TextureMinFilter = FGLTFConverterUtility::ConvertMinFilter(TextureFilter); const ESKGLTFJsonTextureFilter TextureMagFilter = FGLTFConverterUtility::ConvertMagFilter(TextureFilter); const FGLTFJsonTextureIndex TextureIndex = FGLTFMaterialUtility::AddTexture( Builder, PropertyBakeOutput.Pixels, PropertyBakeOutput.Size, true, // NOTE: we can ignore alpha in everything but TryGetBaseColorAndOpacity FGLTFMaterialUtility::IsNormalMap(PropertyBakeOutput.Property), GetBakedTextureName(PropertyName), TextureMinFilter, TextureMagFilter, TextureWrapS, TextureWrapT); OutTexInfo.Index = TextureIndex; return true; } FString FGLTFMaterialTask::GetMaterialName() const { FString MaterialName = Material->GetName(); if (MeshData != nullptr) { MaterialName += TEXT("_") + MeshData->Name; } return MaterialName; } FString FGLTFMaterialTask::GetBakedTextureName(const FString& PropertyName) const { return GetMaterialName() + TEXT("_") + PropertyName; }
37.185025
221
0.764627
[ "mesh", "object", "vector", "model", "transform" ]
59f8f82faaa9f9f160b58dbc1ec728c05e46f08d
10,538
cpp
C++
src/phg/utils/point_cloud_export.cpp
kpilyugin/PhotogrammetryTasks2021
7da69f04909075340a220a7021efeeb42283d9dc
[ "MIT" ]
null
null
null
src/phg/utils/point_cloud_export.cpp
kpilyugin/PhotogrammetryTasks2021
7da69f04909075340a220a7021efeeb42283d9dc
[ "MIT" ]
null
null
null
src/phg/utils/point_cloud_export.cpp
kpilyugin/PhotogrammetryTasks2021
7da69f04909075340a220a7021efeeb42283d9dc
[ "MIT" ]
null
null
null
// // DataExporter.cpp // // Created by Cedric Leblond Menard on 16-06-27. // Copyright © 2016 Cedric Leblond Menard. All rights reserved. // #include "point_cloud_export.h" #include <stdio.h> #include <string> #include "opencv2/core/core.hpp" #include <fstream> #include <iomanip> #include <iostream> #include <algorithm> namespace { // Determine endianness of platform #define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1}) enum FileFormat {PLY_ASCII, PLY_BIN_BIGEND, PLY_BIN_LITEND}; class DataExporter { private: std::string filename = ""; FileFormat format; cv::Mat data; cv::Mat colors; std::ofstream filestream; unsigned long numElem; public: DataExporter(cv::Mat outputData, cv::Mat outputColor, std::string outputfile, FileFormat outputformat); ~DataExporter(); void exportToFile(); cv::Mat normals; }; // Dictionary for file format const char* enum2str[] = { "ascii", "binary_big_endian", "binary_little_endian" }; // Function to reverse float endianness float ReverseFloat( const float inFloat ) { float retVal; char *floatToConvert = ( char* ) & inFloat; char *returnFloat = ( char* ) & retVal; // swap the bytes into a temporary buffer returnFloat[0] = floatToConvert[3]; returnFloat[1] = floatToConvert[2]; returnFloat[2] = floatToConvert[1]; returnFloat[3] = floatToConvert[0]; return retVal; } // Check system endianness bool isLittleEndian() { uint16_t number = 0x1; char *numPtr = (char*)&number; return (numPtr[0] == 1); } DataExporter::DataExporter(cv::Mat outputData, cv::Mat outputColor, std::string outputfile, FileFormat outputformat) : filename(outputfile), format(outputformat), data(outputData), colors(outputColor) { // MARK: Init // Opening filestream switch (format) { case FileFormat::PLY_BIN_LITEND: case FileFormat::PLY_BIN_BIGEND: filestream.open(filename, std::ios::out | std::ios::binary); break; case FileFormat::PLY_ASCII: filestream.open(filename,std::ios::out); break; } // Calculating number of elements CV_Assert(data.total() == colors.total()); // If not same size, assert CV_Assert(data.type() == CV_32FC3 && colors.type() == CV_8UC3); // If not 3 channels and good type CV_Assert(data.isContinuous() && colors.isContinuous()); // If not continuous in memory numElem = data.total(); } void DataExporter::exportToFile() { // MARK: Header writing filestream << "ply" << std::endl << "format " << enum2str[format] << " 1.0" << std::endl << "comment file created using code by Cedric Menard" << std::endl << "element vertex " << numElem << std::endl << "property float x" << std::endl << "property float y" << std::endl << "property float z" << std::endl; if (!normals.empty() && format == FileFormat::PLY_BIN_BIGEND) { filestream << "property float nx" << std::endl << "property float ny" << std::endl << "property float nz" << std::endl; } filestream << "property uchar red" << std::endl << "property uchar green" << std::endl << "property uchar blue" << std::endl << "end_header" << std::endl; // MARK: Data writing // Pointer to data const float* pData = data.ptr<float>(0); const float* nData = nullptr; if (!normals.empty()) { nData = normals.ptr<float>(0); } const unsigned char* pColor = colors.ptr<unsigned char>(0); const unsigned long numIter = 3*numElem; // Number of iteration (3 channels * numElem) const bool hostIsLittleEndian = isLittleEndian(); float_t bufferXYZ; // Coordinate buffer for float type // Output format switch switch (format) { case FileFormat::PLY_BIN_BIGEND: // Looping through all for (unsigned long i = 0; i<numIter; i+=3) { // Loop through all elements for (unsigned int j = 0; j<3; j++) { // Loop through 3 coordinates if (hostIsLittleEndian) { bufferXYZ = ReverseFloat(pData[i+j]); // Convert from host to network (Big endian) filestream.write(reinterpret_cast<const char *>(&bufferXYZ), // Non compiled cast to char array sizeof(bufferXYZ)); } else { bufferXYZ = pData[i+j]; filestream.write(reinterpret_cast<const char *>(&bufferXYZ), // Non compiled cast to char array sizeof(bufferXYZ)); } } if (nData != nullptr) { for (unsigned int j = 0; j<3; j++) { // Loop through 3 coordinates if (hostIsLittleEndian) { bufferXYZ = ReverseFloat(nData[i+j]); // Convert from host to network (Big endian) filestream.write(reinterpret_cast<const char *>(&bufferXYZ), // Non compiled cast to char array sizeof(bufferXYZ)); } else { bufferXYZ = nData[i+j]; filestream.write(reinterpret_cast<const char *>(&bufferXYZ), // Non compiled cast to char array sizeof(bufferXYZ)); } } } for (int j = 2; j>=0; j--) { // OpenCV uses BGR format, so the order of writing is reverse to comply with the RGB format filestream.put(pColor[i+j]); // Loop through RGB } } break; case FileFormat::PLY_BIN_LITEND: // Assume host as little-endian for (unsigned long i = 0; i<numIter; i+=3) { // Loop through all elements for (unsigned int j = 0; j<3; j++) { // Loop through 3 coordinates if (hostIsLittleEndian) { filestream.write(reinterpret_cast<const char *>(pData+i+j), // Non compiled cast to char array sizeof(bufferXYZ)); } else { bufferXYZ = ReverseFloat(pData[i+j]); filestream.write(reinterpret_cast<const char *>(&bufferXYZ), sizeof(bufferXYZ)); } } for (int j = 2; j>=0; j--) { // OpenCV uses BGR format, so the order of writing is reverse to comply with the RGB format filestream.put(pColor[i+j]); // Loop through RGB } } break; case FileFormat::PLY_ASCII: for (unsigned long i = 0; i<numIter; i+=3) { // Loop through all elements for (unsigned int j = 0; j<3; j++) { // Loop through 3 coordinates filestream << std::setprecision(9) << pData[i+j] << " "; } for (int j = 2; j>=0; j--) { // OpenCV uses BGR format, so the order of writing is reverse to comply with the RGB format filestream << (unsigned short)pColor[i+j] << (j==0?"":" "); // Loop through RGB } filestream << std::endl; // End if element line } break; default: break; } } DataExporter::~DataExporter() { filestream.close(); } } void phg::exportPointCloud(const std::vector<cv::Vec3d> &point_cloud, const std::string &path, const std::vector<cv::Vec3b> &point_cloud_colors_bgr, const std::vector<cv::Vec3d> &point_cloud_normal) { if (!point_cloud_colors_bgr.empty() && point_cloud_colors_bgr.size() != point_cloud.size()) { throw std::runtime_error("!point_cloud_colors_bgr.empty() && point_cloud_colors_bgr.size() != point_cloud.size()"); } cv::Mat coords3d(1, point_cloud.size(), CV_32FC3); cv::Mat img(1, point_cloud.size(), CV_8UC3); cv::Mat normals(1, point_cloud.size(), CV_32FC3); cv::Vec3f min_point; cv::Vec3f max_point; for (int i = 0; i < (int) point_cloud.size(); ++i) { cv::Vec3f x = point_cloud[i]; if (i == 0) { min_point = x; max_point = x; } else { for (int j = 0; j < 3; ++j) { min_point[j] = std::min(min_point[j], x[j]); max_point[j] = std::max(max_point[j], x[j]); } } cv::Vec3b c = point_cloud_colors_bgr.empty() ? cv::Vec3b{200, 200, 200} : point_cloud_colors_bgr[i]; coords3d.at<cv::Vec3f>(0, i) = x; img.at<cv::Vec3b>(0, i) = c; if (!point_cloud_normal.empty()) { normals.at<cv::Vec3f>(0, i) = point_cloud_normal[i]; } } std::cout << "Resulting point cloud: num points = " << point_cloud.size() << ", min = " << min_point << ", max = " << max_point << "\n"; DataExporter data(coords3d, img, path, FileFormat::PLY_BIN_BIGEND); if (!point_cloud_normal.empty()) { data.normals = normals; } data.exportToFile(); }
41.81746
198
0.484532
[ "vector" ]
59f99100cd9f1197ab1fcf862dbba559223f4ff8
1,203
cpp
C++
src/ComponentFactory.cpp
Df458/DFEngine
67aea5e2fa14ccd446162fead1dd07f71b38c759
[ "Zlib" ]
null
null
null
src/ComponentFactory.cpp
Df458/DFEngine
67aea5e2fa14ccd446162fead1dd07f71b38c759
[ "Zlib" ]
null
null
null
src/ComponentFactory.cpp
Df458/DFEngine
67aea5e2fa14ccd446162fead1dd07f71b38c759
[ "Zlib" ]
null
null
null
#include "Component.h" #include "ComponentFactory.h" #include "Util.h" #include <algorithm> using namespace rapidxml; IComponent* ComponentFactory::buildComponent(xml_node<>* node, Actor* actor) const { if(!node) { error("Trying to create a component from null data."); return NULL; } std::string id = node->name(); std::transform(id.begin(), id.end(), id.begin(), ::tolower); IComponent* component; buildfunc builder; try { builder = u_builders.at(id); } catch(const std::out_of_range& e) { error(("Trying to create a component with no registered builder. (got " + id + ")").c_str()); return NULL; } component = builder(node, actor); if(xml_attribute<>* att = node->first_attribute("name", 4, false)) { component->setName(att->value()); } return component; } bool ComponentFactory::registerComponentBuilder(buildfunc builder, std::string component_type) { if(u_builders.find(component_type) != u_builders.end()) { warn("Trying to register a component builder for an existing component type."); return false; } u_builders[component_type] = builder; return true; }
28.642857
101
0.64921
[ "transform" ]
9402fc7da9c94254c601eab937a36f9a7961b79d
680
hpp
C++
output/FileOutputHandler.hpp
CaDS-Studentprojects/PixelGames
a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df
[ "MIT" ]
null
null
null
output/FileOutputHandler.hpp
CaDS-Studentprojects/PixelGames
a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df
[ "MIT" ]
null
null
null
output/FileOutputHandler.hpp
CaDS-Studentprojects/PixelGames
a1d7b57bdd9699fc36a64f8a86b92fbd61a3c3df
[ "MIT" ]
null
null
null
/* * FileOutputHandler.hpp * * Created on: Mar 7, 2018 * Author: daniel */ #ifndef FILEOUTPUTHANDLER_HPP_ #define FILEOUTPUTHANDLER_HPP_ #include <string> #include <fstream> #include "IOutputHandler.hpp" using namespace std; namespace pixelgames { namespace output { class FileOutputHandler: public IOutputHandler { public: FileOutputHandler(string output_file); ~FileOutputHandler(); void operator<<(vector<vector<uint32_t>> const & vect) override; static string vectToString(vector<vector<uint32_t>> const & vect); private: ofstream ofile_; }; } /* namespace output */ } /* namespace pixelgames */ #endif /* FILEOUTPUTHANDLER_HPP_ */
18.888889
70
0.720588
[ "vector" ]
940a4265937a21346e41bc2948cd7b537f5d8c4f
1,203
cpp
C++
utility/object.cpp
DFrye333/BD3GE
39a02f10273154f66238b4ea6a08845081f03f94
[ "MIT" ]
null
null
null
utility/object.cpp
DFrye333/BD3GE
39a02f10273154f66238b4ea6a08845081f03f94
[ "MIT" ]
null
null
null
utility/object.cpp
DFrye333/BD3GE
39a02f10273154f66238b4ea6a08845081f03f94
[ "MIT" ]
null
null
null
#include "object.h" namespace BD3GE { Object::Object() : renderable(nullptr), ogg(nullptr) {} Object::Object(const Vector3 position, const Vector3 velocity) : Object(position, velocity, nullptr) {} Object::Object(const Vector3 position, const Vector3 velocity, Renderable* renderable) : velocity(velocity), renderable(renderable), ogg(nullptr) { translate(position); // TODO: Revisit audio stuff later! // std::string fileName = std::string("/home/david/Development/Eclipse Workspace/Game Prototype 0/resource/audio/DH.ogg"); // ogg = new Ogg(fileName); // ogg->play(); } Object::~Object() { delete renderable; renderable = nullptr; delete ogg; ogg = nullptr; } void Object::move(void) { worldTransform.translate(get_position() + velocity); } void Object::translate(Vector3 translation) { worldTransform.translate(get_position() + translation); } void Object::scale(Vector3 scaler) { worldTransform.scale(scaler); } void Object::rotate(Vector3 rotation) { worldTransform.rotate(rotation); } void Object::render(Transform viewProjectionTransform) { if (renderable != nullptr) { renderable->render(worldTransform, viewProjectionTransform); } } }
26.152174
148
0.720698
[ "render", "object", "transform" ]
940d0f76855cbee198db4de61e72373c5739c5e5
55,251
cpp
C++
coh2_rgt_extractor/Rainman_src/CDoWModule.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
1
2016-09-24T14:57:56.000Z
2016-09-24T14:57:56.000Z
coh2_rgt_extractor/Rainman_src/CDoWModule.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
null
null
null
coh2_rgt_extractor/Rainman_src/CDoWModule.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
null
null
null
/* Rainman Library Copyright (C) 2006 Corsix <corsix@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef _DO_INCLUDE_C_DOW_MODULE_H_ #include "CDoWModule.h" #include <time.h> #include "memdebug.h" #include "Exception.h" static char* mystrdup(const char* sStr) { char* s = new char[strlen(sStr) + 1]; if(s == 0) return 0; strcpy(s, sStr); return s; } long CDoWModule::GetSgaOutputVersion() { return m_iSgaOutVer; } CDoWModule::CDoWModule(void) { m_sUIName = 0; m_sName = 0; m_sDescription = 0; m_sDllName = 0; m_sModFolder = 0; m_sPatcherUrl = 0; m_iModVersionMajor = 0; m_iModVersionMinor = 0; m_iModVersionRevision = 0; m_sTextureFE = 0; m_sTextureIcon = 0; m_sModFileName = 0; m_bInvalidVersionNumber = false; m_bLoadFSToCustom = false; m_bNoEngine = false; m_bIsCohMod = false; m_iSgaOutVer = 2; m_sLocale = mystrdup("english"); m_pFiles = 0; m_pFSO = 0; m_iFileViewState = _MakeFileSourcesHash(); } CDoWModule::~CDoWModule(void) { _Clean(); if(m_sLocale) { delete[] m_sLocale; } } unsigned long CDoWModule::GetFileviewHash() const { return m_iFileViewState; } #define QUICK_TRYCAT(op) try { op } CATCH_THROW("File view error") // IFileStore Interface void CDoWModule::VInit(void* pUnused) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(m_pFiles->VInit(pUnused);) } IFileStore::IStream* CDoWModule::VOpenStream(const char* sFile) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VOpenStream(sFile);) } IFileStore::IOutputStream* CDoWModule::VOpenOutputStream(const char* sIdentifier, bool bEraseIfPresent) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VOpenOutputStream(sIdentifier, bEraseIfPresent);) } // IDirectoryTraverser Interface tLastWriteTime CDoWModule::VGetLastWriteTime(const char* sPath) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VGetLastWriteTime(sPath);) } void CDoWModule::VCreateFolderIn(const char* sPath, const char* sNewFolderName) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VCreateFolderIn(sPath, sNewFolderName);) } IDirectoryTraverser::IIterator* CDoWModule::VIterate(const char* sPath) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VIterate(sPath);) } unsigned long CDoWModule::VGetEntryPointCount() { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VGetEntryPointCount();) } const char* CDoWModule::VGetEntryPoint(unsigned long iID) { if(m_pFiles == 0) QUICK_THROW("No file view") QUICK_TRYCAT(return m_pFiles->VGetEntryPoint(iID);) } #undef QUICK_TRYCAT void CDoWModule::SetLocale(const char* sLocale) { if(m_pFSO) QUICK_THROW("Can only set locale on a blank slate"); if(m_sLocale) delete[] m_sLocale; m_sLocale = mystrdup(sLocale); } const char* CDoWModule::GetLocale() const { return m_sLocale; } void CDoWModule::New() { _Clean(); m_pFiles = CHECK_MEM(new CDoWFileView()); try { m_pFiles->VInit(); } catch(CRainmanException* pE) { _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Cannot init file view", pE); } m_pFSO = CHECK_MEM(new CFileSystemStore()); try { m_pFSO->VInit(); } catch(CRainmanException* pE) { _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Cannot init file system store", pE); } } static char* fgetline(FILE *f, unsigned int iInitSize = 32) { unsigned int iTotalLen; if(f == 0) return 0; if(iInitSize < 4) iInitSize = 4; iTotalLen = iInitSize; char *sBuffer = new char[iInitSize]; char *sReadTo = sBuffer; if(sBuffer == 0) return 0; do { if(fgets(sReadTo, iInitSize, f) == 0) { if(feof(f)) { if(sReadTo[strlen(sReadTo) - 1] == '\n') sReadTo[strlen(sReadTo) - 1] = 0; return sBuffer; } delete[] sBuffer; return 0; } if(sReadTo[strlen(sReadTo) - 1] == '\n') { sReadTo[strlen(sReadTo) - 1] = 0; return sBuffer; } iTotalLen += iInitSize; char *sTmp = new char[iTotalLen]; if(sTmp == 0) { delete[] sBuffer; return 0; } strcpy(sTmp, sBuffer); delete[] sBuffer; sBuffer = sTmp; sReadTo = sBuffer + strlen(sBuffer); }while(1); } // VERY hacky function this one static void _CountWS(const char* s, unsigned long* iBegin, unsigned long* iEnd) { *iBegin = 0; *iEnd = 0; if(s) { while(1) { switch(s[*iBegin]) { case ' ': case '\t': case 10: case 13: break; default: goto scan_end; } ++*iBegin; } scan_end: size_t l = strlen(s)-1; while(1) { switch(s[l-*iEnd]) { case ' ': case '\t': case 10: case 13: break; default: return; } ++*iEnd; } } } // Will duplicate a string, replacing the following: // %LOCALE% -> Locale\{sLocale} // %TEXTURE-LEVEL% -> Full // %SOUND-LEVEL% -> Full // %MODEL-LEVEL% -> High static char* DupStrResolveDynamics(const char* sInputString, const char* sLocale, const char* sExtraAppend = "") { unsigned long iLocaleCount = 0; char* sLoc; char* sTmp = (char*) sInputString; while(sLoc = strstr(sTmp, "%LOCALE%")) ++iLocaleCount, sTmp = sLoc + 1; char* sNewString = new char[strlen(sInputString) + (strlen(sLocale) * iLocaleCount) + strlen(sExtraAppend) + 1]; if(sNewString == 0) return 0; sTmp = sNewString; while(*sInputString) { if(*sInputString == '%') { if(strncmp(sInputString, "%LOCALE%", 8) == 0) { strcpy(sTmp, "Locale\\"); strcat(sTmp, sLocale); sTmp += 7 + strlen(sLocale); sInputString += 8; continue; } if(strncmp(sInputString, "%TEXTURE-LEVEL%", 15) == 0) { strcpy(sTmp, "Full"); sTmp += 4; sInputString += 15; continue; } if(strncmp(sInputString, "%SOUND-LEVEL%", 13) == 0) { strcpy(sTmp, "Full"); sTmp += 4; sInputString += 13; continue; } if(strncmp(sInputString, "%MODEL-LEVEL%", 13) == 0) { strcpy(sTmp, "High"); sTmp += 4; sInputString += 13; continue; } } *sTmp = *sInputString; ++sInputString; ++sTmp; } *sTmp = 0; strcat(sNewString, sExtraAppend); return sNewString; } const char* CDoWModule::GetFilesModName() const { return m_sModFileName; } const char* CDoWModule::GetEngineModName() { return "(Engine)"; } void CDoWModule::_TryLoadDataGeneric(const char* sModName, const char* sDoWPath, bool bReq, const char* sModFSName) { char* sDGFolder = 0; // Look in pipeline.ini to begin with char* sPipeline = CHECK_MEM(new char[strlen(sDoWPath) + 14]); strcpy(sPipeline, sDoWPath); strcat(sPipeline, "\\pipeline.ini"); FILE* fPipeline = fopen(sPipeline, "rb"); if(fPipeline) { bool bInThisProject = false; while(!feof(fPipeline)) { char *sLine = fgetline(fPipeline); if(sLine == 0) { fclose(fPipeline); delete[] sPipeline; delete[] sDGFolder; throw new CRainmanException(__FILE__, __LINE__, "fgetline() failed"); } char *sCommentBegin = strstr(sLine, ";"); if(sCommentBegin) *sCommentBegin = 0; char *sEquals = strchr(sLine,'='); char *sLeftBrace = strchr(sLine,'['); if(sLeftBrace && !sEquals) { char *sRightBrace = strchr(sLeftBrace,']'); if(sRightBrace) { *sRightBrace = 0; if(strncmp(sLeftBrace + 1, "project:", 8) == 0) { if(stricmp(sLeftBrace + 9, sModName) == 0) { bInThisProject = true; } } } } else if(bInThisProject && sEquals) { char* sKey = sLine; char* sValue = sEquals + 1; *sEquals = 0; unsigned long iWSBefore, iWSAfter; _CountWS(sKey, &iWSBefore, &iWSAfter); sKey += iWSBefore; sKey[strlen(sKey) - iWSAfter] = 0; _CountWS(sValue, &iWSBefore, &iWSAfter); sValue += iWSBefore; sValue[strlen(sValue) - iWSAfter] = 0; if(stricmp(sKey, "DataGeneric") == 0) { if(!sDGFolder) sDGFolder = mystrdup(sValue); if(!sDGFolder) { fclose(fPipeline); delete[] sPipeline; delete[] sLine; throw new CRainmanException(__FILE__, __LINE__, "mystrdup() failed"); } } } delete[] sLine; } fclose(fPipeline); } delete[] sPipeline; // Assume it's the default path if not found if(!sDGFolder) { sDGFolder = CHECK_MEM(new char[strlen(sModName) + 23]); strcpy(sDGFolder, "ModTools\\DataGeneric\\"); strcat(sDGFolder, sModName); } // Try and iterate the folder char* sFullPath = new char[strlen(sDGFolder) + strlen(sDoWPath) + 2]; if(sFullPath == 0) { delete[] sDGFolder; throw new CRainmanException(__FILE__, __LINE__, "memory allocation problem"); } strcpy(sFullPath, sDoWPath); strcat(sFullPath, "\\"); strcat(sFullPath, sDGFolder); delete[] sDGFolder; IDirectoryTraverser::IIterator *pDirItr; try { pDirItr = m_pFSO->VIterate(sFullPath); } catch(CRainmanException *pE) { delete pE; delete[] sFullPath; return; } delete[] sFullPath; try { m_pFiles->AddFileSource(m_pFSO, pDirItr, m_pFSO, sModFSName, "Data Generic", bReq, !bReq, false); } catch(CRainmanException *pE) { delete pDirItr; throw new CRainmanException(__FILE__, __LINE__, "Cannot add data generic as file source", pE); } delete pDirItr; } #ifndef DOXY_NODOC /* Quick "Catch, Clean, Throw" */ #define QCCT(msg) \ catch(CRainmanException *pE) \ { \ _Clean(); \ throw new CRainmanException(__FILE__, __LINE__, msg, pE); \ } #define QCZ(var) \ if(var == 0) \ { \ _Clean(); \ throw new CRainmanException(__FILE__, __LINE__, #var " is zero"); \ } #endif void CDoWModule::Load(const char* sFile, CALLBACK_ARG) { CDoWFileView *pTempFileViewPtr = m_pFiles; bool bTempCustomFS = m_bLoadFSToCustom; // Load up module file char* sTempLocale = CHECK_MEM(strdup(m_sLocale)); _Clean(); char* sModuleFilename = (strrchr(sFile, '\\')) + 1; m_sModFileName = CHECK_MEM(mystrdup(sModuleFilename)); if(sModuleFilename = strstr(m_sModFileName, ".module")) *sModuleFilename = 0; try { SetLocale(sTempLocale); } QCCT("Cannot set locale") free(sTempLocale); try { CallCallback(THE_CALLBACK, "Processing module file directives in \'%s\'", m_sModFileName); } QCCT("Cannot call callback") if(sFile == 0) { _Clean(); throw new CRainmanException(__FILE__, __LINE__, "No filename passed"); } FILE *fFile = fopen(sFile, "rb"); if(fFile == 0) { _Clean(); throw new CRainmanException(0, __FILE__, __LINE__, "Could not open \'%s\'", sFile); } bool bInGlobal = false; m_iSgaOutVer = 0; while(!feof(fFile)) { char *sLine = fgetline(fFile); char *sCommentBegin = strstr(sLine, ";;"); if(sCommentBegin) *sCommentBegin = 0; char *sEquals = strchr(sLine,'='); char *sLeftBrace = strchr(sLine,'['); if(sLeftBrace && !sEquals) { char *sRightBrace = strchr(sLeftBrace,']'); if(sRightBrace) { bInGlobal = (strnicmp(sLeftBrace + 1, "global", sRightBrace - sLeftBrace - 1) == 0); } } else if(bInGlobal && sEquals) { char* sKey = sLine; char* sValue = sEquals + 1; *sEquals = 0; unsigned long iWSBefore, iWSAfter; _CountWS(sKey, &iWSBefore, &iWSAfter); sKey += iWSBefore; sKey[strlen(sKey) - iWSAfter] = 0; _CountWS(sValue, &iWSBefore, &iWSAfter); sValue += iWSBefore; sValue[strlen(sValue) - iWSAfter] = 0; if(stricmp(sKey, "UIName") == 0) { if(m_sUIName) delete[] m_sUIName; m_sUIName = mystrdup(sValue); QCZ(m_sUIName) } if(stricmp(sKey, "Name") == 0) { if(m_sName) delete[] m_sName; m_sName = mystrdup(sValue); QCZ(m_sName) } else if(stricmp(sKey, "Description") == 0) { if(m_sDescription) delete[] m_sDescription; m_sDescription = mystrdup(sValue); QCZ(m_sDescription) } else if(stricmp(sKey, "NoEngine") == 0) { m_bNoEngine = true; } else if(stricmp(sKey, "ForceSga4") == 0) { m_iSgaOutVer = 4; } else if(stricmp(sKey, "DllName") == 0) { if(m_sDllName) delete[] m_sDllName; m_sDllName = mystrdup(sValue); QCZ(m_sDllName) } else if(stricmp(sKey, "ModFolder") == 0) { if(m_sModFolder) delete[] m_sModFolder; m_sModFolder = mystrdup(sValue); QCZ(m_sModFolder) } else if(stricmp(sKey, "PatcherUrl") == 0) { if(m_sPatcherUrl) delete[] m_sPatcherUrl; m_sPatcherUrl = mystrdup(sValue); QCZ(m_sPatcherUrl) } else if(stricmp(sKey, "TextureFE") == 0) { if(m_sTextureFE) delete[] m_sTextureFE; m_sTextureFE = mystrdup(sValue); QCZ(m_sTextureFE) } else if(stricmp(sKey, "TextureIcon") == 0) { if(m_sTextureIcon) delete[] m_sTextureIcon; m_sTextureIcon = mystrdup(sValue); QCZ(m_sTextureIcon) } else if(stricmp(sKey, "ModVersion") == 0) { long *lCurrentPart = &m_iModVersionMajor; char *sTmp = sValue; while(*sTmp) { if(*sTmp == '.') { if(lCurrentPart == &m_iModVersionMajor) { lCurrentPart = &m_iModVersionMinor; } else if(lCurrentPart == &m_iModVersionMinor) { lCurrentPart = &m_iModVersionRevision; } else if(lCurrentPart == &m_iModVersionRevision) { m_bInvalidVersionNumber = true; break; } } else if(*sTmp >= '0' && *sTmp <= '9') { *lCurrentPart *= 10; *lCurrentPart += (*sTmp - '0'); } else { m_bInvalidVersionNumber = true; } ++sTmp; } } else if(strnicmp("DataFolder.",sKey,11) == 0) { long iNum = atol(sKey + 11); if(m_mapDataFolders[iNum] == 0) { m_mapDataFolders[iNum] = strdup(sValue); QCZ(m_mapDataFolders[iNum]) } } else if(strnicmp("ArchiveFile.",sKey,12) == 0) { long iNum = atol(sKey + 12); if(m_mapArchiveFiles[iNum] == 0) { m_mapArchiveFiles[iNum] = strdup(sValue); QCZ(m_mapArchiveFiles[iNum]) } } else if(strnicmp("RequiredMod.",sKey,12) == 0) { long iNum = atol(sKey + 12); if(m_mapRequiredMods[iNum] == 0) { m_mapRequiredMods[iNum] = strdup(sValue); QCZ(m_mapRequiredMods[iNum]) } } else if(strnicmp("CompatableMod.",sKey,14) == 0) { long iNum = atol(sKey + 14); if(m_mapCompatableMods[iNum] == 0) { m_mapCompatableMods[iNum] = strdup(sValue); QCZ(m_mapCompatableMods[iNum]) } } } delete[] sLine; } fclose(fFile); // Is it a CoH or DoW mod? if(m_sName != 0 && m_sUIName == 0 && m_mapDataFolders.size() == 0 && m_mapArchiveFiles.size() == 0) { m_bIsCohMod = true; m_mapDataFolders[1] = strdup("Data"); } if(m_iSgaOutVer == 0) { m_iSgaOutVer = m_bIsCohMod ? 4 : 2; } // Load Filesystem m_pFSO = new CFileSystemStore; QCZ(m_pFSO) try { m_pFSO->VInit(); } QCCT("Cannot init file system object") m_bLoadFSToCustom = bTempCustomFS; if(!m_bLoadFSToCustom) { m_pFiles = new CDoWFileView; QCZ(m_pFiles) try { m_pFiles->VInit(); } QCCT("Cannot init file system object") } else { m_pFiles = pTempFileViewPtr; } char* sDoWPath = strdup(sFile); QCZ(sDoWPath) char* sSlashPos = strrchr(sDoWPath, '\\'); if(sSlashPos) *sSlashPos = 0; char* sModFolder = new char[strlen(sDoWPath) + strlen(m_sModFolder) + 2]; if(sModFolder == 0) { free(sDoWPath); _Clean(); QUICK_THROW("Memory error") } strcpy(sModFolder, sDoWPath); strcat(sModFolder, "\\"); strcat(sModFolder, m_sModFolder); if(m_bIsCohMod) { char* sSgaFolderPath = new char[strlen(sModFolder) + 11]; if(sSgaFolderPath == 0) { free(sDoWPath); delete[] sModFolder; _Clean(); QUICK_THROW("Memory error") } strcpy(sSgaFolderPath, sModFolder); strcat(sSgaFolderPath, "\\Archives\\"); IDirectoryTraverser::IIterator *pItr; try { pItr = m_pFSO->VIterate(sSgaFolderPath); } catch(CRainmanException *pE) { free(sDoWPath); delete[] sModFolder; _Clean(); pE = new CRainmanException(pE, __FILE__, __LINE__, "Unable to iterate \'%s\'", sSgaFolderPath); delete[] sSgaFolderPath; throw pE; } delete[] sSgaFolderPath; if(pItr) { try { if(pItr->VGetType() != IDirectoryTraverser::IIterator::T_Nothing) { do { if(pItr->VGetType() == IDirectoryTraverser::IIterator::T_File) { const char* sPotentialFileName = pItr->VGetName(); sPotentialFileName = strrchr(sPotentialFileName, '.'); if(sPotentialFileName && (stricmp(sPotentialFileName + 1, "sga") == 0)) { m_mapArchiveFiles[m_mapArchiveFiles.size() + 1] = CHECK_MEM(strdup(pItr->VGetName())); } } } while(pItr->VNextItem() == IDirectoryTraverser::IIterator::E_OK); } delete pItr; } catch(CRainmanException *pE) { free(sDoWPath); delete[] sModFolder; _Clean(); pE = new CRainmanException(pE, __FILE__, __LINE__, "(rethrow)"); delete pItr; throw pE; } } } // Pick an output folder char* sOutFolder = 0; if(!m_bLoadFSToCustom) { // Look for one called data for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { if(stricmp(itr->second, "data") == 0) { sOutFolder = itr->second; break; } } if(!sOutFolder) { // Look for one with no dynamics for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { if(strchr(itr->second, '%') == 0) { sOutFolder = itr->second; break; } } } } for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { char* sWithoutDynamics = DupStrResolveDynamics(itr->second, m_sLocale); if(sWithoutDynamics == 0) continue; CallCallback(THE_CALLBACK, "Loading data folder \'%s\' for \'%s\'", sWithoutDynamics, m_sModFileName); char* sFolderFullPath = new char[strlen(sModFolder) + strlen(sWithoutDynamics) + 2]; if(sFolderFullPath == 0) { delete[] sWithoutDynamics; continue; } strcpy(sFolderFullPath, sModFolder); strcat(sFolderFullPath, "\\"); strcat(sFolderFullPath, sWithoutDynamics); IDirectoryTraverser::IIterator *pDirItr = 0; try { pDirItr = m_pFSO->VIterate(sFolderFullPath); if(pDirItr) m_pFiles->AddFileSource(m_pFSO, pDirItr, m_pFSO, m_sModFileName, itr->second, m_bLoadFSToCustom, !m_bLoadFSToCustom, (!m_bLoadFSToCustom && sOutFolder == itr->second)); } catch(CRainmanException *pE) {delete pE;} delete[] sFolderFullPath; delete[] sWithoutDynamics; delete pDirItr; } for(std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); itr != m_mapArchiveFiles.end(); ++itr) { char* sWithoutDynamics = DupStrResolveDynamics(itr->second, m_sLocale, m_bIsCohMod ? "" : ".sga"); CallCallback(THE_CALLBACK, "Loading data archive \'%s\' for \'%s\'", sWithoutDynamics, m_sModFileName); if(sWithoutDynamics == 0) continue; char* sFolderFullPath = new char[strlen(sModFolder) + strlen(sWithoutDynamics) + 16]; if(sFolderFullPath == 0) { delete[] sWithoutDynamics; continue; } strcpy(sFolderFullPath, sModFolder); strcat(sFolderFullPath, m_bIsCohMod ? "\\Archives\\" : "\\"); strcat(sFolderFullPath, sWithoutDynamics); CSgaFile* pSga = new CSgaFile; if(pSga) { IFileStore::IStream *pInputStream = 0; IDirectoryTraverser::IIterator *pDirItr = 0; try { pInputStream = m_pFSO->VOpenStream(sFolderFullPath); } catch(CRainmanException *pE) { delete pE; delete pSga; pSga = 0; goto archive_not_present; } try { pSga->Load(pInputStream, m_pFSO->VGetLastWriteTime(sFolderFullPath)); pSga->VInit(pInputStream); pDirItr = pSga->VIterate(pSga->VGetEntryPoint(0)); if(pDirItr) m_pFiles->AddFileSource(pSga, pDirItr, pSga, m_sModFileName, itr->second, m_bLoadFSToCustom); delete pDirItr; } catch(CRainmanException *pE) { free(sDoWPath); delete[] sWithoutDynamics; delete[] sFolderFullPath; delete[] sModFolder; _Clean(); pE = new CRainmanException(pE, __FILE__, __LINE__, "(rethrow)"); delete pDirItr; delete pInputStream; delete pSga; throw pE; } archive_not_present: m_vSgas.push_back(pSga); } delete[] sFolderFullPath; delete[] sWithoutDynamics; } if(!m_bLoadFSToCustom) { for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { CallCallback(THE_CALLBACK, "Loading required mod \'%s\' for \'%s\'", itr->second, m_sModFileName); char* sFolderFullPath = new char[strlen(sDoWPath) + strlen(itr->second) + 9]; if(sFolderFullPath == 0) { continue; } strcpy(sFolderFullPath, sDoWPath); strcat(sFolderFullPath, "\\"); strcat(sFolderFullPath, itr->second); strcat(sFolderFullPath, ".module"); CDoWModule *pReqMod = new CDoWModule(); if(pReqMod == 0) { delete[] sFolderFullPath; continue; } pReqMod->m_bLoadFSToCustom = true; pReqMod->m_pFiles = m_pFiles; m_vInheritedMods.push_back(pReqMod); try { pReqMod->SetLocale(m_sLocale); pReqMod->Load(sFolderFullPath, THE_CALLBACK); } catch(CRainmanException *pE) { free(sDoWPath); delete[] sModFolder; delete[] sFolderFullPath; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Problem loading required mod", pE); } delete[] sFolderFullPath; } if(!m_bNoEngine) { CallCallback(THE_CALLBACK, "Loading engine files"); char* sEngineFile = new char[strlen(sDoWPath) + 40]; if(!sEngineFile) { free(sDoWPath); delete[] sModFolder; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Memory allocation error"); } strcpy(sEngineFile, sDoWPath); strcat(sEngineFile, "\\Engine\\Data"); IDirectoryTraverser::IIterator *pEngineDirItr; try { pEngineDirItr = m_pFSO->VIterate(sEngineFile); } catch(CRainmanException *pE) { delete pE; pEngineDirItr = 0; } if(pEngineDirItr) m_pFiles->AddFileSource(m_pFSO, pEngineDirItr, m_pFSO, GetEngineModName(), "Data", true); delete pEngineDirItr; strcpy(sEngineFile, sDoWPath); strcat(sEngineFile, m_bIsCohMod ? "\\Engine\\Archives\\Engine.sga" : "\\Engine\\Engine.sga"); CSgaFile* pEngineSga = new CSgaFile; if(!pEngineSga) { free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Memory allocation error"); } IFileStore::IStream *pInputStream = 0; IDirectoryTraverser::IIterator *pDirItr = 0; try { pInputStream = m_pFSO->VOpenStream(sEngineFile); pEngineSga->Load(pInputStream, m_pFSO->VGetLastWriteTime(sEngineFile)); pEngineSga->VInit(pInputStream); pDirItr = pEngineSga->VIterate(pEngineSga->VGetEntryPoint(0)); if(pDirItr) m_pFiles->AddFileSource(pEngineSga, pDirItr, pEngineSga, GetEngineModName(), "Engine.sga", true); delete pDirItr; } catch(CRainmanException *pE) { delete pInputStream; delete pDirItr; free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Problem loading in engine SGA file", pE); } m_vSgas.push_back(pEngineSga); if(m_bIsCohMod) { strcpy(sEngineFile, sDoWPath); strcat(sEngineFile, "\\RelicOnline\\Archives\\RelicOnline.sga"); pEngineSga = new CSgaFile; if(!pEngineSga) { free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Memory allocation error"); } IFileStore::IStream *pInputStream = 0; IDirectoryTraverser::IIterator *pDirItr = 0; try { pInputStream = m_pFSO->VOpenStream(sEngineFile); pEngineSga->Load(pInputStream, m_pFSO->VGetLastWriteTime(sEngineFile)); pEngineSga->VInit(pInputStream); pDirItr = pEngineSga->VIterate(pEngineSga->VGetEntryPoint(0)); if(pDirItr) m_pFiles->AddFileSource(pEngineSga, pDirItr, pEngineSga, GetEngineModName(), "RelicOnline.sga", true); delete pDirItr; } catch(CRainmanException *pE) { delete pInputStream; delete pDirItr; free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Cannot load RelicOnline.sga", pE); } m_vSgas.push_back(pEngineSga); } delete[] sEngineFile; } } else { for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { m_vInheritedMods.push_back(0); } } // Map in Data generic (done after ALL other data to avoid conflicts) if(!m_bLoadFSToCustom) { CallCallback(THE_CALLBACK, "Loading data generic for \'%s\'", m_sModFileName); _TryLoadDataGeneric(m_sModFileName, sDoWPath, false, m_sModFileName); for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { CallCallback(THE_CALLBACK, "Loading data generic for \'%s\'", itr->second); _TryLoadDataGeneric(itr->second, sDoWPath, true, itr->second); } CallCallback(THE_CALLBACK, "Loading data generic for engine"); _TryLoadDataGeneric("Engine", sDoWPath, true, GetEngineModName()); } // UCS Files char* sUcsFilesPath = new char[strlen(sModFolder) + strlen(m_sLocale) + 9]; if(sUcsFilesPath == 0) { free(sDoWPath); delete[] sModFolder; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Memory allocation error"); } strcpy(sUcsFilesPath, sModFolder); strcat(sUcsFilesPath, "\\Locale\\"); strcat(sUcsFilesPath, m_sLocale); IDirectoryTraverser::IIterator *pItr = m_pFSO->VIterate(sUcsFilesPath); delete[] sUcsFilesPath; if(pItr) { if(pItr->VGetType() != IDirectoryTraverser::IIterator::T_Nothing) { do { if(pItr->VGetType() == IDirectoryTraverser::IIterator::T_File) { const char* sPotentialFileName = pItr->VGetName(); sPotentialFileName = strrchr(sPotentialFileName, '.'); if(sPotentialFileName && (stricmp(sPotentialFileName + 1, "ucs") == 0)) { CallCallback(THE_CALLBACK, "Loading UCS file \'%s\' for \'%s\'", pItr->VGetName(), m_sModFileName); IFileStore::IStream *pFileStream; try { pFileStream = pItr->VOpenFile(); } catch(CRainmanException *pE) { free(sDoWPath); delete[] sModFolder; delete pItr; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Cannot open UCS file", pE); } CUcsFile* pUcs = new CUcsFile; if(!pUcs) { delete pFileStream; free(sDoWPath); delete[] sModFolder; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Memory allocation error"); } try { pUcs->Load(pFileStream); m_vUcsFiles.push_back(pUcs); m_vUcsNames.push_back(strdup(pItr->VGetName())); delete pFileStream; } catch(CRainmanException *pE) { delete pUcs; delete pFileStream; free(sDoWPath); delete[] sModFolder; _Clean(); throw new CRainmanException(__FILE__, __LINE__, "Cannot load UCS file", pE); } } } } while(pItr->VNextItem() == IDirectoryTraverser::IIterator::E_OK); } delete pItr; } free(sDoWPath); delete[] sModFolder; m_iFileViewState = _MakeFileSourcesHash(); } void CDoWModule::Save(const char* sFile) { if(sFile == 0) QUICK_THROW("No file specified") FILE *f = fopen(sFile, "wb"); if(!f) throw new CRainmanException(0, __FILE__, __LINE__, "Cannot open file \'%s\'", sFile); // Print nice header fputs(";; //////////////////////////////////////////////////////////////////\xD\n", f); fputs(";; ", f); fputs(strrchr(sFile, '\\') ? strrchr(sFile, '\\') + 1 : sFile, f); fputs("\xD\n;; \xD\n;; ", f); time_t tt; time(&tt); tm *ptm; ptm = localtime(&tt); const char* sModName = "mod"; bool bWasDollar = false; if(m_sUIName && strlen(m_sUIName)) { if(IsDollarString(m_sUIName)) { bWasDollar = true; const wchar_t *tw = ResolveUCS(m_sUIName); size_t twl = wcslen(tw) + 1; sModName = new char[twl]; for(size_t i = 0; i < twl; ++i) { ((char*)sModName)[i] = tw[i]; } } else sModName = m_sUIName; } fprintf(f, "(c) Copyright %li/%li The %s team\xD\n", ptm->tm_year + 1900, ptm->tm_year + 1901, sModName); if(bWasDollar) delete[] ((char*)sModName); // General fputs(";; \xD\n\xD\n[global]\xD\n", f); fputs("\xD\nUIName = ", f); fputs(m_sUIName ? m_sUIName : "", f); fputs("\xD\nDescription = ", f); fputs(m_sDescription ? m_sDescription : "", f); fputs("\xD\nDllName = ", f); fputs(m_sDllName ? m_sDllName : "", f); fputs("\xD\nModFolder = ", f); fputs(m_sModFolder ? m_sModFolder : "", f); fprintf(f, "\xD\nModVersion = %li.%li.%li", m_iModVersionMajor, m_iModVersionMinor, m_iModVersionRevision); fputs("\xD\nTextureFE = ", f); fputs(m_sTextureFE ? m_sTextureFE : "", f); fputs("\xD\nTextureIcon = ", f); fputs(m_sTextureIcon ? m_sTextureIcon : "", f); // Data folders fputs("\xD\n\xD\n;; //////////////////////////////////////////////////////////////////\xD\n;; List of folders to map for this MOD \xD\n;; order is important - the first folders registered will be scanned for files first\xD\n\xD\n", f); for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { fprintf(f, "DataFolder.%li = %s\xD\n", itr->first, itr->second ? itr->second : ""); } // Data archives fputs("\xD\n;; //////////////////////////////////////////////////////////////////\xD\n;; List of archives to map for this MOD \xD\n;; order is important - the first archives registered will be scanned for files first\xD\n\xD\n", f); for(std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); itr != m_mapArchiveFiles.end(); ++itr) { fprintf(f, "ArchiveFile.%li = %s\xD\n", itr->first, itr->second ? itr->second : ""); } // Required mods fputs("\xD\n;; //////////////////////////////////////////////////////////////////\xD\n;; List of MODs that this MOD requires to work\xD\n\xD\n", f); for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { fprintf(f, "RequiredMod.%li = %s\xD\n", itr->first, itr->second ? itr->second : ""); } // Compatible mods fputs("\xD\n;; //////////////////////////////////////////////////////////////////\xD\n;; List of mods that have scenarios compatible with this mod\xD\n\xD\n", f); for(std::map<long, char*>::iterator itr = m_mapCompatableMods.begin(); itr != m_mapCompatableMods.end(); ++itr) { fprintf(f, "CompatableMod.%li = %s\xD\n", itr->first, itr->second ? itr->second : ""); } fclose(f); } /* void CDoWModule::RebuildFileview(const char* sRefFile) { if(m_bLoadFSToCustom) return false; if(m_pFiles) m_pFiles->Reset(); // it cannot fail else { m_pFiles = new CDoWFileView; if(m_pFiles == 0 || !m_pFiles->VInit()) { return false; } } if(!m_pFSO) { m_pFSO = new CFileSystemStore; if(m_pFSO == 0 || !m_pFSO->VInit()) { return false; } } // Do build char* sDoWPath = strdup(sRefFile); char* sSlashPos = strrchr(sDoWPath, '\\'); if(sSlashPos) *sSlashPos = 0; char* sModFolder = new char[strlen(sDoWPath) + strlen(m_sModFolder) + 2]; if(sModFolder == 0) { free(sDoWPath); m_pFiles->Reset(); return false; } strcpy(sModFolder, sDoWPath); strcat(sModFolder, "\\"); strcat(sModFolder, m_sModFolder); for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { char* sWithoutDynamics = DupStrResolveDynamics(itr->second, m_sLocale); if(sWithoutDynamics == 0) continue; char* sFolderFullPath = new char[strlen(sModFolder) + strlen(sWithoutDynamics) + 2]; if(sFolderFullPath == 0) { delete[] sWithoutDynamics; continue; } strcpy(sFolderFullPath, sModFolder); strcat(sFolderFullPath, "\\"); strcat(sFolderFullPath, sWithoutDynamics); IDirectoryTraverser::IIterator *pDirItr = m_pFSO->VIterate(sFolderFullPath); if(pDirItr) m_pFiles->AddFileSource(m_pFSO, pDirItr, m_pFSO, m_sUIName, sWithoutDynamics); delete[] sFolderFullPath; delete[] sWithoutDynamics; delete pDirItr; } for(std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); itr != m_mapArchiveFiles.end(); ++itr) { char* sWithoutDynamics = DupStrResolveDynamics(itr->second, m_sLocale, ".sga"); if(sWithoutDynamics == 0) continue; char* sFolderFullPath = new char[strlen(sModFolder) + strlen(sWithoutDynamics) + 2]; if(sFolderFullPath == 0) { delete[] sWithoutDynamics; continue; } strcpy(sFolderFullPath, sModFolder); strcat(sFolderFullPath, "\\"); strcat(sFolderFullPath, sWithoutDynamics); CSgaFile* pSga = new CSgaFile; if(pSga) { IFileStore::IStream *pInputStream = m_pFSO->VOpenStream(sFolderFullPath); if(pInputStream && pSga->Load(pInputStream) && pSga->VInit(pInputStream)) { IDirectoryTraverser::IIterator *pDirItr = pSga->VIterate(pSga->VGetEntryPoint(0)); if(pDirItr) m_pFiles->AddFileSource(pSga, pDirItr, pSga, m_sUIName, sWithoutDynamics); delete pDirItr; } else { delete pInputStream; } m_vSgas.push_back(pSga); } delete[] sFolderFullPath; delete[] sWithoutDynamics; } for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { char* sFolderFullPath = new char[strlen(sDoWPath) + strlen(itr->second) + 9]; if(sFolderFullPath == 0) { continue; } strcpy(sFolderFullPath, sDoWPath); strcat(sFolderFullPath, "\\"); strcat(sFolderFullPath, itr->second); strcat(sFolderFullPath, ".module"); CDoWModule *pReqMod = new CDoWModule(); if(pReqMod == 0) { delete[] sFolderFullPath; continue; } pReqMod->m_bLoadFSToCustom = true; pReqMod->m_pFiles = m_pFiles; m_vInheritedMods.push_back(pReqMod); if(!pReqMod->SetLocale(m_sLocale) || !pReqMod->Load(sFolderFullPath)) { free(sDoWPath); delete[] sModFolder; delete[] sFolderFullPath; m_pFiles->Reset(); return false; } delete[] sFolderFullPath; } if(!m_bLoadFSToCustom) { char* sEngineFile = new char[strlen(sDoWPath) + 13]; if(!sEngineFile) { free(sDoWPath); delete[] sModFolder; m_pFiles->Reset(); return false; } strcpy(sEngineFile, sDoWPath); strcat(sEngineFile, "\\Engine\\Data"); IDirectoryTraverser::IIterator *pEngineDirItr = m_pFSO->VIterate(sEngineFile); if(!pEngineDirItr) { free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; m_pFiles->Reset(); return false; } m_pFiles->AddFileSource(m_pFSO, pEngineDirItr, m_pFSO, "(Engine)", "Data"); delete[] sEngineFile; sEngineFile = new char[strlen(sDoWPath) + 19]; if(!sEngineFile) { free(sDoWPath); delete[] sModFolder; m_pFiles->Reset(); return false; } strcpy(sEngineFile, sDoWPath); strcat(sEngineFile, "\\Engine\\Engine.sga"); //IDirectoryTraverser::IIterator *pEngineDirItr = m_pFSO->VIterate(sEngineFile); CSgaFile* pEngineSga = new CSgaFile; if(!pEngineSga) { free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; m_pFiles->Reset(); return false; } IFileStore::IStream *pInputStream = m_pFSO->VOpenStream(sEngineFile); if(pInputStream && pEngineSga->Load(pInputStream) && pEngineSga->VInit(pInputStream)) { IDirectoryTraverser::IIterator *pDirItr = pEngineSga->VIterate(pEngineSga->VGetEntryPoint(0)); if(pDirItr) m_pFiles->AddFileSource(pEngineSga, pDirItr, pEngineSga, "(Engine)", "Engine.sga"); delete pDirItr; } else { delete pInputStream; free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; m_pFiles->Reset(); return false; } m_vSgas.push_back(pEngineSga); if(!pEngineDirItr) { free(sDoWPath); delete[] sModFolder; delete[] sEngineFile; m_pFiles->Reset(); return false; } m_pFiles->AddFileSource(m_pFSO, pEngineDirItr, m_pFSO, "(Engine)", "Data"); delete[] sEngineFile; } return true; } */ void CDoWModule::_Clean() { if(m_sModFileName) delete[] m_sModFileName; m_sModFileName = 0; if(m_sUIName) delete[] m_sUIName; m_sUIName = 0; if(m_sName) delete[] m_sName; m_sName = 0; if(m_sDescription) delete[] m_sDescription; m_sDescription = 0; if(m_sDllName) delete[] m_sDllName; m_sDllName = 0; if(m_sModFolder) delete[] m_sModFolder; m_sModFolder = 0; if(m_sPatcherUrl) delete[] m_sPatcherUrl; m_sPatcherUrl = 0; if(m_sTextureFE) delete[] m_sTextureFE; m_sTextureFE = 0; if(m_sTextureIcon) delete[] m_sTextureIcon; m_sTextureIcon = 0; if(m_sLocale) { delete[] m_sLocale; m_sLocale = mystrdup("english"); } std::map<long, char*>::iterator itr; for(itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { if(itr->second) free(itr->second); } m_mapDataFolders.clear(); for(itr = m_mapArchiveFiles.begin(); itr != m_mapArchiveFiles.end(); ++itr) { if(itr->second) free(itr->second); } m_mapArchiveFiles.clear(); for(itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr) { if(itr->second) free(itr->second); } m_mapRequiredMods.clear(); for(itr = m_mapCompatableMods.begin(); itr != m_mapCompatableMods.end(); ++itr) { if(itr->second) free(itr->second); } m_mapCompatableMods.clear(); if(m_pFiles) { if(!m_bLoadFSToCustom) delete m_pFiles; m_pFiles = 0; } if(m_pFSO) { delete m_pFSO; m_pFSO = 0; } for(std::vector<CSgaFile*>::iterator itr = m_vSgas.begin(); itr != m_vSgas.end(); ++itr) { if(*itr) { try { delete (*itr)->GetInputStream(); } catch(CRainmanException *pE) {delete pE;} delete *itr; } } m_vSgas.clear(); for(std::vector<CDoWModule*>::iterator itr = m_vInheritedMods.begin(); itr != m_vInheritedMods.end(); ++itr) { delete *itr; } m_vInheritedMods.clear(); for(std::vector<CUcsFile*>::iterator itr = m_vUcsFiles.begin(); itr != m_vUcsFiles.end(); ++itr) { delete *itr; } m_vUcsFiles.clear(); for(std::vector<char*>::iterator itr = m_vUcsNames.begin(); itr != m_vUcsNames.end(); ++itr) { delete[] *itr; } m_vUcsNames.clear(); m_iModVersionMajor = 0; m_iModVersionMinor = 0; m_iModVersionRevision = 0; m_bInvalidVersionNumber = false; m_bLoadFSToCustom = false; m_bNoEngine = false; m_bIsCohMod = false; m_iSgaOutVer = 2; m_iFileViewState = _MakeFileSourcesHash(); } const char* CDoWModule::GetUIName() const { return m_sUIName; } const char* CDoWModule::GetDescription() const { return m_sDescription; } const char* CDoWModule::GetDllName() const { return m_sDllName; } const char* CDoWModule::GetModFolder() const { return m_sModFolder; } const char* CDoWModule::GetTextureFE() const { return m_sTextureFE; } const char* CDoWModule::GetTextureIcon() const { return m_sTextureIcon; } long CDoWModule::GetVersionMajor() const { return m_iModVersionMajor; } long CDoWModule::GetVersionMinor() const { return m_iModVersionMinor; } long CDoWModule::GetVersionRevision() const { return m_iModVersionRevision; } #define AUTO_SET(valname) char* sTmp = CHECK_MEM(mystrdup(sValue ? sValue : ""));if(valname) delete[] valname;valname = sTmp; void CDoWModule::SetUIName(const char* sValue) { AUTO_SET(m_sUIName) } void CDoWModule::SetDescription(const char* sValue) { AUTO_SET(m_sDescription) } void CDoWModule::SetDllName(const char* sValue) { AUTO_SET(m_sDllName) } void CDoWModule::SetModFolder(const char* sValue) { AUTO_SET(m_sModFolder) } void CDoWModule::SetTextureFE(const char* sValue) { AUTO_SET(m_sTextureFE) } void CDoWModule::SetTextureIcon(const char* sValue) { AUTO_SET(m_sTextureIcon) } void CDoWModule::SetVersionMajor(long iValue) { m_iModVersionMajor = iValue; } void CDoWModule::SetVersionMinor(long iValue) { m_iModVersionMinor = iValue; } void CDoWModule::SetVersionRevision(long iValue) { m_iModVersionRevision = iValue; } long CDoWModule::GetDataFolderCount() const { return (long)m_mapDataFolders.size(); } const char* CDoWModule::GetDataFolder(long iIndex) { if(iIndex < 0 || iIndex >= GetDataFolderCount()) return 0; std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); while(iIndex) --iIndex, ++itr; return itr->second; } long CDoWModule::GetDataFolderID(long iIndex) { if(iIndex < 0 || iIndex >= GetDataFolderCount()) return -1; std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); while(iIndex) --iIndex, ++itr; return itr->first; } void CDoWModule::SwapDataFolders(long iIndexA, long iIndexB) { if(iIndexA < 0 || iIndexA >= GetDataFolderCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexA %li is beyond %li or below 0", iIndexA, GetDataFolderCount()); if(iIndexB < 0 || iIndexB >= GetDataFolderCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexB %li is beyond %li or below 0", iIndexB, GetDataFolderCount()); std::map<long, char*>::iterator itrA = m_mapDataFolders.begin(); while(iIndexA) --iIndexA, ++itrA; std::map<long, char*>::iterator itrB = m_mapDataFolders.begin(); while(iIndexB) --iIndexB, ++itrB; char* sTmp = itrA->second; itrA->second = itrB->second; itrB->second = sTmp; } void CDoWModule::AddDataFolder(const char* sName) { long iNextID = 1; if(m_mapDataFolders.size()) iNextID = m_mapDataFolders.rbegin()->first + 1; char* sTmp = CHECK_MEM(mystrdup(sName)); m_mapDataFolders[iNextID] = sTmp; } void CDoWModule::RemoveDataFolder(long iIndex) { if(iIndex < 0 || iIndex >= GetDataFolderCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetDataFolderCount()); std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); while(iIndex) --iIndex, ++itr; delete[] itr->second; long iToEraseID, iActualErase; std::map<long, char*>::reverse_iterator ritr = m_mapDataFolders.rbegin(); iToEraseID = itr->first; iActualErase = ritr->first; char* sOld, *sTmp; if(ritr->first != iToEraseID) { sOld = ritr->second; do { ++ritr; sTmp = ritr->second; ritr->second = sOld; sOld = sTmp; } while(ritr->first != iToEraseID); } m_mapDataFolders.erase(iActualErase); } long CDoWModule::GetArchiveCount() const { return (long)m_mapArchiveFiles.size(); } const char* CDoWModule::GetArchive(long iIndex) { if(iIndex < 0 || iIndex >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetArchiveCount()); std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); while(iIndex) --iIndex, ++itr; return itr->second; } long CDoWModule::GetArchiveID(long iIndex) { if(iIndex < 0 || iIndex >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetArchiveCount()); std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); while(iIndex) --iIndex, ++itr; return itr->first; } CSgaFile* CDoWModule::GetArchiveHandle(long iIndex) const { if(iIndex < 0 || iIndex >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetArchiveCount()); return m_vSgas[iIndex]; } void CDoWModule::SwapArchives(long iIndexA, long iIndexB) { if(iIndexA < 0 || iIndexA >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexA %li is beyond %li or below 0", iIndexA, GetArchiveCount()); if(iIndexB < 0 || iIndexB >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexB %li is beyond %li or below 0", iIndexB, GetArchiveCount()); std::map<long, char*>::iterator itrA = m_mapArchiveFiles.begin(); while(iIndexA) --iIndexA, ++itrA; std::map<long, char*>::iterator itrB = m_mapArchiveFiles.begin(); while(iIndexB) --iIndexB, ++itrB; char* sTmp = itrA->second; itrA->second = itrB->second; itrB->second = sTmp; CSgaFile* pTmpSga = m_vSgas[iIndexA]; m_vSgas[iIndexA] = m_vSgas[iIndexB]; m_vSgas[iIndexB] = pTmpSga; } void CDoWModule::AddArchive(const char* sName) { long iNextID = 1; if(m_mapArchiveFiles.size()) iNextID = m_mapArchiveFiles.rbegin()->first + 1; char* sTmp = CHECK_MEM(mystrdup(sName)); m_mapArchiveFiles[iNextID] = sTmp; m_vSgas.push_back(0); } void CDoWModule::RemoveArchive(long iIndex) { if(iIndex < 0 || iIndex >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetArchiveCount()); std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); while(iIndex) --iIndex, ++itr; delete[] itr->second; long iToEraseID, iActualErase; std::map<long, char*>::reverse_iterator ritr = m_mapArchiveFiles.rbegin(); iToEraseID = itr->first; iActualErase = ritr->first; char* sOld, *sTmp; if(ritr->first != iToEraseID) { sOld = ritr->second; do { ++ritr; sTmp = ritr->second; ritr->second = sOld; sOld = sTmp; } while(ritr->first != iToEraseID); } m_mapArchiveFiles.erase(iActualErase); m_vSgas.erase(m_vSgas.begin() + iIndex); } long CDoWModule::GetRequiredCount() const { return (long)m_mapRequiredMods.size(); } const char* CDoWModule::GetRequired(long iIndex) { if(iIndex < 0 || iIndex >= GetRequiredCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetRequiredCount()); std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); while(iIndex) --iIndex, ++itr; return itr->second; } long CDoWModule::GetRequiredID(long iIndex) { if(iIndex < 0 || iIndex >= GetRequiredCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetRequiredCount()); std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); while(iIndex) --iIndex, ++itr; return itr->first; } CDoWModule* CDoWModule::GetRequiredHandle(long iIndex) const { if(iIndex < 0 || iIndex >= GetArchiveCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetRequiredCount()); return m_vInheritedMods[iIndex]; } void CDoWModule::SwapRequireds(long iIndexA, long iIndexB) { if(iIndexA < 0 || iIndexA >= GetRequiredCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexA %li is beyond %li or below 0", iIndexA, GetRequiredCount()); if(iIndexA < 0 || iIndexB >= GetRequiredCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexB %li is beyond %li or below 0", iIndexB, GetRequiredCount()); std::map<long, char*>::iterator itrA = m_mapRequiredMods.begin(); while(iIndexA) --iIndexA, ++itrA; std::map<long, char*>::iterator itrB = m_mapRequiredMods.begin(); while(iIndexB) --iIndexB, ++itrB; char* sTmp = itrA->second; itrA->second = itrB->second; itrB->second = sTmp; CDoWModule* pTmpSga = m_vInheritedMods[iIndexA]; m_vInheritedMods[iIndexA] = m_vInheritedMods[iIndexB]; m_vInheritedMods[iIndexB] = pTmpSga; } void CDoWModule::AddRequired(const char* sName) { long iNextID = 1; if(m_mapRequiredMods.size()) iNextID = m_mapRequiredMods.rbegin()->first + 1; char* sTmp = CHECK_MEM(mystrdup(sName)); m_mapRequiredMods[iNextID] = sTmp; m_vInheritedMods.push_back(0); } void CDoWModule::RemoveRequired(long iIndex) { if(iIndex < 0 || iIndex >= GetRequiredCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetRequiredCount()); std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); while(iIndex) --iIndex, ++itr; delete[] itr->second; long iToEraseID, iActualErase; std::map<long, char*>::reverse_iterator ritr = m_mapRequiredMods.rbegin(); iToEraseID = itr->first; iActualErase = ritr->first; char* sOld, *sTmp; if(ritr->first != iToEraseID) { sOld = ritr->second; do { ++ritr; sTmp = ritr->second; ritr->second = sOld; sOld = sTmp; } while(ritr->first != iToEraseID); } m_mapRequiredMods.erase(iActualErase); m_vInheritedMods.erase(m_vInheritedMods.begin() + iIndex); } long CDoWModule::GetCompatableCount() const { return (long)m_mapCompatableMods.size(); } const char* CDoWModule::GetCompatable(long iIndex) { if(iIndex < 0 || iIndex >= GetCompatableCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetCompatableCount()); std::map<long, char*>::iterator itr = m_mapCompatableMods.begin(); while(iIndex) --iIndex, ++itr; return itr->second; } long CDoWModule::GetCompatableID(long iIndex) { if(iIndex < 0 || iIndex >= GetCompatableCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetCompatableCount()); std::map<long, char*>::iterator itr = m_mapCompatableMods.begin(); while(iIndex) --iIndex, ++itr; return itr->first; } void CDoWModule::SwapCompatables(long iIndexA, long iIndexB) { if(iIndexA < 0 || iIndexA >= GetCompatableCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexA %li is beyond %li or below 0", iIndexA, GetCompatableCount()); if(iIndexA < 0 || iIndexB >= GetCompatableCount()) throw new CRainmanException(0, __FILE__, __LINE__, "IndexB %li is beyond %li or below 0", iIndexB, GetCompatableCount()); std::map<long, char*>::iterator itrA = m_mapCompatableMods.begin(); while(iIndexA) --iIndexA, ++itrA; std::map<long, char*>::iterator itrB = m_mapCompatableMods.begin(); while(iIndexB) --iIndexB, ++itrB; char* sTmp = itrA->second; itrA->second = itrB->second; itrB->second = sTmp; } void CDoWModule::AddCompatable(const char* sName) { long iNextID = 1; if(m_mapCompatableMods.size()) iNextID = m_mapCompatableMods.rbegin()->first + 1; char* sTmp = CHECK_MEM(mystrdup(sName)); m_mapCompatableMods[iNextID] = sTmp; } void CDoWModule::RemoveCompatable(long iIndex) { if(iIndex < 0 || iIndex >= GetCompatableCount()) throw new CRainmanException(0, __FILE__, __LINE__, "Index %li is beyond %li or below 0", iIndex, GetCompatableCount()); std::map<long, char*>::iterator itr = m_mapCompatableMods.begin(); while(iIndex) --iIndex, ++itr; delete[] itr->second; long iToEraseID, iActualErase; std::map<long, char*>::reverse_iterator ritr = m_mapCompatableMods.rbegin(); iToEraseID = itr->first; iActualErase = ritr->first; char* sOld, *sTmp; if(ritr->first != iToEraseID) { sOld = ritr->second; do { ++ritr; sTmp = ritr->second; ritr->second = sOld; sOld = sTmp; } while(ritr->first != iToEraseID); } m_mapCompatableMods.erase(iActualErase); } bool CDoWModule::IsDollarString(const char* s) { if(!s || *s != '$') return false; ++s; if(*s == 0) return false; while(*s) { if(*s < '0' || *s > '9') return false; ++s; } return true; } bool CDoWModule::IsDollarString(const wchar_t* s) { if(!s || *s != '$') return false; ++s; if(*s == 0) return false; while(*s) { if(*s < '0' || *s > '9') return false; ++s; } return true; } const wchar_t* CDoWModule::ResolveUCS(const char* sDollarString) { if(!IsDollarString(sDollarString)) throw new CRainmanException(__FILE__, __LINE__, "sDollarString must be a dollar string"); try { return ResolveUCS((unsigned long)atol(sDollarString + 1)); } CATCH_THROW("Cannot resolve value as integer") } const wchar_t* CDoWModule::ResolveUCS(const wchar_t* sDollarString) { if(!IsDollarString(sDollarString)) throw new CRainmanException(__FILE__, __LINE__, "sDollarString must be a dollar string"); try { return ResolveUCS(wcstoul(sDollarString + 1, 0, 10)); } CATCH_THROW("Cannot resolve value as integer") } const wchar_t* CDoWModule::ResolveUCS(unsigned long iStringID) { for(std::vector<CUcsFile*>::iterator itr = m_vUcsFiles.begin(); itr != m_vUcsFiles.end(); ++itr) { const wchar_t *t; if(t = (*itr)->ResolveStringID(iStringID)) { return t; } } for(std::vector<CDoWModule*>::iterator itr = m_vInheritedMods.begin(); itr != m_vInheritedMods.end(); ++itr) { const wchar_t *t; if((*itr) && (t = (*itr)->ResolveUCS(iStringID))) { return t; } } throw new CRainmanException(0, __FILE__, __LINE__, "$%lu no key!", iStringID); } long CDoWModule::GetUcsFileCount() const { return (long)m_vUcsFiles.size(); } const char* CDoWModule::GetUcsFileName(long iIndex) const { if(iIndex < 0 || iIndex >= GetUcsFileCount()) return 0; return m_vUcsNames[iIndex]; } CUcsFile* CDoWModule::GetUcsFile(long iIndex) const { if(iIndex < 0 || iIndex >= GetUcsFileCount()) return 0; return m_vUcsFiles[iIndex]; } unsigned long CDoWModule::_MakeFileSourcesHash(unsigned long iBase) { long lval; // Head lval = 'HEAD'; iBase = crc32(iBase, (const Bytef*)&lval, 4); if(m_sModFolder) iBase = crc32(iBase, (const Bytef*)m_sModFolder, strlen(m_sModFolder)); // Data folders for(std::map<long, char*>::iterator itr = m_mapDataFolders.begin(); itr != m_mapDataFolders.end(); ++itr) { lval = 'DFOR'; iBase = crc32(iBase, (const Bytef*)&lval, 4); iBase = crc32(iBase, (const Bytef*)&itr->first, 4); iBase = crc32(iBase, (const Bytef*)itr->second, strlen(itr->second)); } // Data archives std::vector<CSgaFile*>::iterator itrsga = m_vSgas.begin(); for(std::map<long, char*>::iterator itr = m_mapArchiveFiles.begin(); itr != m_mapArchiveFiles.end(); ++itr, ++itrsga) { lval = 'GSGA'; iBase = crc32(iBase, (const Bytef*)&lval, 4); iBase = crc32(iBase, (const Bytef*)&itr->first, 4); iBase = crc32(iBase, (const Bytef*)itr->second, strlen(itr->second)); iBase = crc32(iBase, (const Bytef*)*itrsga, 4); } // Required mods std::vector<CDoWModule*>::iterator itrmod = m_vInheritedMods.begin(); for(std::map<long, char*>::iterator itr = m_mapRequiredMods.begin(); itr != m_mapRequiredMods.end(); ++itr, ++itrmod) { lval = 'RQUM'; iBase = crc32(iBase, (const Bytef*)&lval, 4); iBase = crc32(iBase, (const Bytef*)&itr->first, 4); iBase = crc32(iBase, (const Bytef*)itr->second, strlen(itr->second)); if((*itrmod)) iBase = (**itrmod)._MakeFileSourcesHash(iBase); } // Tail lval = 'TAIL'; iBase = crc32(iBase, (const Bytef*)&lval, 4); return iBase; } void CDoWModule::RegisterNewUCS(const char* sFile, CUcsFile* pUcs) { if(sFile == 0) throw new CRainmanException(__FILE__, __LINE__, "Invalid argument: sFile"); if(pUcs == 0) throw new CRainmanException(__FILE__, __LINE__, "Invalid argument: pUcs"); sFile = CHECK_MEM(mystrdup(sFile)); m_vUcsFiles.push_back(pUcs); m_vUcsNames.push_back((char*)sFile); } long CDoWModule::GetEngineDataFolderCount() const { return 1; } const char* CDoWModule::GetEngineDataFolder(long iIndex) { if(iIndex == 0) return "Data"; throw new CRainmanException(0, __FILE__, __LINE__, "Invalid index %li", iIndex); } long CDoWModule::GetEngineArchiveCount() const { return m_bIsCohMod ? 2 : 1; } const char* CDoWModule::GetEngineArchive(long iIndex) { if(iIndex == 0) return "Engine.sga"; if(iIndex == 1 && m_bIsCohMod) return "RelicOnline.sga"; throw new CRainmanException(0, __FILE__, __LINE__, "Invalid index %li", iIndex); } #endif
26.160511
236
0.671445
[ "object", "vector", "model" ]
941ea4d8a4b4dd8f03fed0edd233fd4abd51aadc
988
cpp
C++
AtCoder/arc014/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/arc014/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/arc014/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> #include <unordered_map> using namespace std; int main() { int n; cin >> n; unordered_map<string, bool> Map; char c = '-'; for (int i = 0; i < n; i++) { string s; cin >> s; if (c == '-') c = s[0]; if (i % 2 == 0) { if (s[0] != c) { cout << "LOSE" << endl; return 0; } else c = s[s.length() - 1]; if (Map[s]) { cout << "LOSE" << endl; return 0; } else Map[s] = true; } else { if (s[0] != c) { cout << "WIN" << endl; return 0; } else c = s[s.length() - 1]; if (Map[s]) { cout << "WIN" << endl; return 0; } else Map[s] = true; } } cout << "DRAW" << endl; return 0; }
23.52381
39
0.347166
[ "vector" ]
94248c522fafd69f516ed63180b02cf3d61d50ed
2,858
cpp
C++
Progression/Progression.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
Progression/Progression.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
Progression/Progression.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Progression.cpp - Signal Progression Utility //********************************************************* #include "Progression.hpp" char * Progression::LINK_EQUIVALENCE_FILE = "LINK_EQUIVALENCE_FILE"; char * Progression::CLEAR_EXISTING_OFFSETS = "CLEAR_EXISTING_OFFSETS"; char * Progression::EVALUATE_EXISTING_OFFSETS= "EVALUATE_EXISTING_OFFSETS"; char * Progression::PROGRESSION_TIME_PERIODS = "PROGRESSION_TIME_PERIODS"; char * Progression::PROGRESSION_PERIOD_SPEED = "PROGRESSION_PERIOD_SPEED"; char * Progression::OPTIMIZATION_METHOD = "OPTIMIZATION_METHOD"; char * Progression::GROUP_PERIOD_WEIGHT_FILE = "GROUP_PERIOD_WEIGHT_FILE"; char * Progression::KEEP_LINK_GROUP_ORDER = "KEEP_LINK_GROUP_ORDER"; char * Progression::ARCVIEW_PROGRESSION_FILE = "ARCVIEW_PROGRESSION_FILE"; char * Progression::LINK_DIRECTION_OFFSET = "LINK_DIRECTION_OFFSET"; //--------------------------------------------------------- // Progression constructor //--------------------------------------------------------- Progression::Progression (void) : Demand_Service () { Program ("Progression"); Version ("4.0.7"); Title ("Signal Progression Offset"); Network_File required_network [] = { NODE, LINK, LANE_CONNECTIVITY, SIGNALIZED_NODE, TIMING_PLAN, PHASING_PLAN, NEW_SIGNALIZED_NODE, END_NETWORK }; Network_File optional_network [] = { DIRECTORY, SHAPE, UNSIGNALIZED_NODE, NEW_DIRECTORY, END_NETWORK }; Demand_File optional_demand [] = { LINK_DELAY, END_DEMAND }; char *keys [] = { LINK_EQUIVALENCE_FILE, CLEAR_EXISTING_OFFSETS, EVALUATE_EXISTING_OFFSETS, PROGRESSION_TIME_PERIODS, PROGRESSION_PERIOD_SPEED, OPTIMIZATION_METHOD, GROUP_PERIOD_WEIGHT_FILE, KEEP_LINK_GROUP_ORDER, ARCVIEW_PROGRESSION_FILE, LINK_DIRECTION_OFFSET, NULL }; char *reports [] = { "PRINT_LINK_EQUIVALENCIES", "GROUP_PERIOD_WEIGHTS", NULL }; Required_Network_Files (required_network); Optional_Network_Files (optional_network); Optional_Demand_Files (optional_demand); Key_List (keys); Report_List (reports); projection.Add_Keys (); fixed = updated = progression_time = period = mid_period = method = max_period = 0; progression_speed = 0.0; link_offset = 5.0; equiv_flag = clear_flag = speed_flag = period_flag = arcview_flag = delay_flag = false; weight_flag = order_flag = eval_flag = false; } //--------------------------------------------------------- // Progression destructor //--------------------------------------------------------- Progression::~Progression (void) { } //--------------------------------------------------------- // main program //--------------------------------------------------------- int main (int commands, char *control []) { Progression *exe = new Progression (); return (exe->Start_Execution (commands, control)); }
30.404255
88
0.641358
[ "shape" ]
942a7305b5f8c157c2f73cb1519a161cfcfe2c8e
658
cpp
C++
game/src/ballistic.cpp
Maddy1107/Speed_Racer
8012f8a087d471ff574ebb462e80fec2de0fd639
[ "MIT" ]
null
null
null
game/src/ballistic.cpp
Maddy1107/Speed_Racer
8012f8a087d471ff574ebb462e80fec2de0fd639
[ "MIT" ]
null
null
null
game/src/ballistic.cpp
Maddy1107/Speed_Racer
8012f8a087d471ff574ebb462e80fec2de0fd639
[ "MIT" ]
null
null
null
#include "pch.h" #include "Ballistic.h" ballistic::ballistic() {} ballistic::~ballistic() {} void ballistic::initialise(engine::ref<engine::game_object> object) { m_object = object; } void ballistic::fire(engine::ref<engine::game_object> object, float speed) { m_object->set_position(object->position()); m_object->set_forward(object->forward()); m_speed = speed; } void ballistic::on_update(const engine::timestep& time_step) { m_object->set_position(m_object->position() + m_object->forward() * (float) time_step * m_speed); } void ballistic::on_render(const engine::ref<engine::shader>& shader) { engine::renderer::submit(shader, m_object); }
21.225806
98
0.729483
[ "object" ]
942c6781e9c7cb3b91120925b43b1c17a9493ddb
1,692
cpp
C++
Code/Framework/AzFramework/AzFramework/Logging/MissingAssetLogger.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzFramework/AzFramework/Logging/MissingAssetLogger.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzFramework/AzFramework/Logging/MissingAssetLogger.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzFramework/Logging/MissingAssetLogger.h> #include <AzCore/std/string/string.h> #include <AzCore/IO/FileIO.h> #include <AzFramework/Logging/LogFile.h> namespace AzFramework { constexpr const char StartLogFileDelimiter[] = "------------------------ START LOG ------------------------"; constexpr const char LogFileBaseName[] = "PakMissingAssets"; constexpr int RolloverLength = 4 * 1024 * 1024; MissingAssetLogger::MissingAssetLogger() { AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); if (!fileIO) { return; } const char* logDirectory = fileIO->GetAlias("@log@"); if (!logDirectory) { //We will not log anything if the log alias is empty AZ_Warning("Log Component", logDirectory, "Please set the log alias first, before trying to log data"); return; } m_logFile = AZStd::make_unique<LogFile>(logDirectory, LogFileBaseName, RolloverLength); m_logFile->AppendLog(AzFramework::LogFile::SEV_NORMAL, StartLogFileDelimiter); BusConnect(); } MissingAssetLogger::~MissingAssetLogger() { BusDisconnect(); } void MissingAssetLogger::FileMissing(const char* filePath) { if (m_logFile) { m_logFile->AppendLog(AzFramework::LogFile::SEV_WARNING, AZStd::string::format("Missing from bundle: %s", filePath).c_str()); } } }
29.684211
136
0.631206
[ "3d" ]
94437060cd43ec12b64e420340d303449c25ff05
5,122
cpp
C++
src/filters/connect.cpp
zengyuxing007/pipy
c60e08560b08728fa181940a4b9d67807a0ee625
[ "BSL-1.0" ]
null
null
null
src/filters/connect.cpp
zengyuxing007/pipy
c60e08560b08728fa181940a4b9d67807a0ee625
[ "BSL-1.0" ]
null
null
null
src/filters/connect.cpp
zengyuxing007/pipy
c60e08560b08728fa181940a4b9d67807a0ee625
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019 by flomesh.io * * Unless prior written consent has been obtained from the copyright * owner, the following shall not be allowed. * * 1. The distribution of any source codes, header files, make files, * or libraries of the software. * * 2. Disclosure of any source codes pertaining to the software to any * additional parties. * * 3. Alteration or removal of any notices in or on the software or * within the documentation included within the software. * * ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS * SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "connect.hpp" #include "worker.hpp" #include "pipeline.hpp" #include "session.hpp" #include "outbound.hpp" #include "context.hpp" #include "utils.hpp" #include "logging.hpp" namespace pipy { Connect::Connect() { } Connect::Connect(const pjs::Value &target, pjs::Object *options) : m_target(target) { if (options) { pjs::Value buffer_limit, retry_count, retry_delay, tls; options->get("bufferLimit", buffer_limit); options->get("retryCount", retry_count); options->get("retryDelay", retry_delay); options->get("tls", tls); if (!buffer_limit.is_undefined()) { if (buffer_limit.is_string()) { m_buffer_limit = utils::get_byte_size(buffer_limit.s()->str()); } else { m_buffer_limit = buffer_limit.to_number(); } } if (!retry_count.is_undefined()) m_retry_count = retry_count.to_number(); if (!retry_delay.is_undefined()) { if (retry_delay.is_string()) { m_retry_delay = utils::get_seconds(retry_delay.s()->str()); } else { m_retry_delay = retry_delay.to_number(); } } if (!tls.is_undefined()) { if (!tls.is_object()) throw std::runtime_error("option tls must be an object"); if (auto *o = tls.o()) { m_ssl_context = std::make_shared<asio::ssl::context>(asio::ssl::context::sslv23_client); pjs::Value cert, key; o->get("cert", cert); o->get("key", key); if (!cert.is_undefined()) { auto *s = cert.to_string(); m_ssl_context->use_certificate(asio::const_buffer(s->c_str(), s->length()), asio::ssl::context::pem); s->release(); } if (!key.is_undefined()) { auto *s = key.to_string(); m_ssl_context->use_private_key(asio::const_buffer(s->c_str(), s->length()), asio::ssl::context::pem); s->release(); } } } } } Connect::Connect(const Connect &r) : m_target(r.m_target) , m_buffer_limit(r.m_buffer_limit) , m_retry_count(r.m_retry_count) , m_retry_delay(r.m_retry_delay) , m_ssl_context(r.m_ssl_context) { } Connect::~Connect() { } auto Connect::help() -> std::list<std::string> { return { "connect(target[, options])", "Sends data to a remote endpoint and receives data from it", "target = <string|function> Remote endpoint in the form of `<ip>:<port>`", "options = <object> Includes bufferLimit, tls.cert, tls.key", }; } void Connect::dump(std::ostream &out) { out << "connect"; } auto Connect::clone() -> Filter* { return new Connect(*this); } void Connect::reset() { if (m_outbound) { m_outbound->on_receive(nullptr); m_outbound->on_delete(nullptr); m_outbound->end(); m_outbound = nullptr; } m_session_end = false; } void Connect::process(Context *ctx, Event *inp) { if (m_session_end) return; if (inp->is<SessionEnd>()) { if (m_outbound) { m_outbound->end(); } m_session_end = true; return; } if (!m_outbound) { pjs::Value target; if (eval(*ctx, m_target, target)) { auto s = target.to_string(); std::string host; int port; if (utils::get_host_port(s->str(), host, port)) { auto outbound = m_ssl_context ? new Outbound(*m_ssl_context) : new Outbound(m_buffer_limit); outbound->set_buffer_limit(m_buffer_limit); outbound->set_retry_count(m_retry_count); outbound->set_retry_delay(m_retry_delay); outbound->on_delete([this]() { m_outbound = nullptr; }); outbound->on_receive([=](Event *inp) { output(inp); ctx->group()->notify(ctx); }); outbound->connect(host, port); m_outbound = outbound; } else { m_session_end = true; Log::warn("[connect] invalid target: %s", s->c_str()); } s->release(); } } if (m_outbound) { if (auto *data = inp->as<Data>()) { m_outbound->send(data); } else if (inp->is<MessageEnd>()) { m_outbound->flush(); } } } } // namespace pipy
28.455556
111
0.630418
[ "object" ]
9444a6841f9bd66caf56ded1c3d5a3dc1b60d4d4
729
cpp
C++
Shape/Shape.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
Shape/Shape.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
Shape/Shape.cpp
AKoudounis/refactored-journey
81719c57104f14b141f0f7cd2aa805f9007ed79e
[ "MIT" ]
null
null
null
//Andreas Koudounis 40089191 #include "Shape.h" #include <iomanip> //Default Constructor Shape::Shape() { } //Default Constructor Shape::~Shape() { std::cout << "Shape object deleted"; } void Shape::print() const { } void Shape::outputLine(const char* const object, const char* const Field1, const char* const Field2, const char* const Field3, const char* const Field4, const char* const Field5, const char* const Field6, const char* const Field7) { cout << left << setw(10) << object << setw(5) << Field1 << setw(5) << Field2 << Field3 << setw(5) << Field4 << setw(5) << Field5 << setw(5) << Field6 << setw(5) << Field7 << endl; }
18.225
154
0.584362
[ "object", "shape" ]
9449cc1e4242c84e767ba2ddb31af37a4d6e8d9f
2,391
cpp
C++
Chapter_8_Advanced_Topics/8.6_NP_Hard_or_Complete_Problems/kattis_europeantrip.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_8_Advanced_Topics/8.6_NP_Hard_or_Complete_Problems/kattis_europeantrip.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_8_Advanced_Topics/8.6_NP_Hard_or_Complete_Problems/kattis_europeantrip.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/**Kattis - europeantrip * This is the Euclidean Steiner Tree problem with 3 terminal and 1 internal vertex. We can try to find the fermat point * with a lot of mathematics. But we can also use some very very very sketchy iterative optimization to find this... * * At first I did what CP4 hint suggested: 2 ternary searches, but I was having problems passing certain testcases. I * implemented to alternate between cutting the search space of x and y. When one was being searched, i let the other * coordinate be the average of the high and low bounds. * * Since it didn't work, I opted to use gradient descent. I found that the best starting point was the average of the * high and low bounds for each of the coordinates... I also just played around with the alpha (initial learning rate) * to see how it would fair... It's honestly mega mega sketchy but it works. * * Time: O(1), Space: O(1) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long double ld; typedef vector<int> vi; #define fast_cin() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); pair<ld, ld> a, b, c; ld dist(pair<ld, ld> p) { return (hypot(p.first - a.first, p.second - a.second) + hypot(p.first - b.first, p.second - b.second) + hypot(p.first - c.first, p.second - c.second)); } int main() { ld x, y; cin >> x >> y; a = make_pair(x, y); cin >> x >> y; b = make_pair(x, y); cin >> x >> y; c = make_pair(x, y); ld x_l = min(min(a.first, b.first), c.first); ld x_h = max(max(a.first, b.first), c.first); ld y_l = min(min(a.second, b.second), c.second); ld y_h = max(max(a.second, b.second), c.second); cout << fixed << setprecision(10); ld cx = (x_h + x_l)/2, cy = (y_h + y_l)/2; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; for (ld d=x_h; d > 1e-12; d *=0.999){ for (int dir=0; dir < 4; dir++){ ld nx = cx + dx[dir]*d; ld ny = cy + dy[dir]*d; if (dist(make_pair(nx, ny)) < dist(make_pair(cx, cy))){ cx = nx; cy = ny; } } } cout << cx << " " << cy << endl; return 0; }
35.686567
120
0.590548
[ "vector" ]
9453e616c603aa6cfc9d3531409649ef54db6302
4,868
cpp
C++
game.cpp
jasonhutchens/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
4
2016-06-05T04:36:12.000Z
2016-08-21T20:11:49.000Z
game.cpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
game.cpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
//============================================================================== #include <game.hpp> #include <engine.hpp> #include <entity.hpp> #include <entity_manager.hpp> #include <viewport.hpp> #include <score.hpp> #include <droplet.hpp> #include <girder.hpp> #include <hgeresource.h> #include <algorithm> #include <set> namespace { static const float FLOW( 0.01f ); static const int MAX_COUNT( 250 ); } //============================================================================== Game::Game() : Context(), m_flow( FLOW ), m_count( 0 ) { } //------------------------------------------------------------------------------ Game::~Game() { } //------------------------------------------------------------------------------ // public: //------------------------------------------------------------------------------ void Game::init() { HGE * hge( Engine::hge() ); b2World * b2d( Engine::b2d() ); hgeResourceManager * rm( Engine::rm() ); ViewPort * vp( Engine::vp() ); Droplet::registerEntity(); Girder::registerEntity(); Engine::em()->init(); vp->offset().x = 0.0f; vp->offset().y = 0.0f; vp->centre().x = 0.0f; vp->centre().y = 0.0f; vp->bounds().x = 1280.0f; vp->bounds().y = 720.0f; vp->setAngle( 0.0f ); vp->setScale( 100.0f ); _initArena(); Engine::instance()->setMouse("cursor"); Engine::instance()->showMouse(); m_flow = FLOW; m_count = 0; } //------------------------------------------------------------------------------ void Game::fini() { Engine::instance()->hideMouse(); Engine::em()->fini(); } //------------------------------------------------------------------------------ bool Game::update( float dt ) { const Controller & pad( Engine::instance()->getController() ); HGE * hge( Engine::hge() ); ViewPort * vp( Engine::vp() ); if ( Engine::instance()->isPaused() || m_count >= MAX_COUNT ) { return false; } // TODO: if mouse down, spawn droplet at certain rate m_flow -= dt; while ( m_flow < 0.0f && m_count < MAX_COUNT ) { m_flow += FLOW; m_count += 1; Droplet * droplet( static_cast< Droplet * >( Engine::em()->factory( Droplet::TYPE ) ) ); droplet->setScale( 0.0015f ); droplet->init(); b2Vec2 position( Engine::hge()->Random_Float( -0.01f, 0.01f ) + 1.0f, 1.0f ); droplet->getBody()->SetXForm( position, 0.0f ); } return false; } //------------------------------------------------------------------------------ void Game::render() { hgeResourceManager * rm( Engine::rm() ); hgeFont* font = Engine::rm()->GetFont("menu"); ViewPort * vp( Engine::vp() ); vp->setTransform(); float scale( 1.0f ); std::vector< Entity * > entities; for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL; body = body->GetNext() ) { Entity * entity( static_cast< Entity * >( body->GetUserData() ) ); if ( entity ) { entity->render( scale ); } } vp->reset(); char message[8]; sprintf_s( message, "%03d", m_count ); font->printf( 100.0f, 10.0f, HGETEXT_CENTER, message ); } //------------------------------------------------------------------------------ // private: //------------------------------------------------------------------------------ void Game::_initArena() { b2Vec2 position( 0.0f, 0.0f ); b2Vec2 dimensions( 0.0f, 0.0f ); Entity * entity( 0 ); for ( int i = 0; i < 4; ++i ) { switch( i ) { case 0: { dimensions.x = 128.0f; dimensions.y = 0.1f; position.x = 0.0f; position.y = -36.1f; continue; break; } case 1: { dimensions.x = 0.1f; dimensions.y = 72.0f; position.x = 64.1f; position.y = 0.0f; break; } case 2: { dimensions.x = 128.0f; dimensions.y = 0.1f; position.x = 0.0f; position.y = 36.1f; break; } case 3: { dimensions.x = 0.1f; dimensions.y = 72.0f; position.x = -64.1f; position.y = 0.0f; break; } } Girder * girder( static_cast< Girder * >( Engine::em()->factory( Girder::TYPE ) ) ); girder->setScale( 1.0f ); girder->setDimensions( dimensions ); girder->init(); girder->getBody()->SetXForm( 0.1f * position, 0.0f ); } } //------------------------------------------------------------------------------
24.964103
96
0.400781
[ "render", "vector" ]
94590a37a02976b0c687e8bdbe2f3db6eb5cce24
3,519
cpp
C++
Graph/CSES Problem Set [ Graph Algorithms ]/Investigation.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Graph/CSES Problem Set [ Graph Algorithms ]/Investigation.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Graph/CSES Problem Set [ Graph Algorithms ]/Investigation.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Problem: Investigation // Contest: CSES - CSES Problem Set // URL: https://cses.fi/problemset/task/1202 // Memory Limit: 512 MB // Time Limit: 1000 ms // Parsed on: 02-03-2021 12:42:28 IST (UTC+05:30) // Author: Kapil Choudhary // ******************************************************************** // कर्मण्येवाधिकारस्ते मा फलेषु कदाचन | // मा कर्मफलहेतुर्भूर्मा ते सङ्गोऽस्त्वकर्मणि || १.४७ || // ******************************************************************** #include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pb push_back #define mp make_pair #define F first #define S second #define PI 3.1415926535897932384626 #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<ull> vull; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vll> vvll; typedef vector<vull> vvull; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } const ll INF = 1e17; const ll mod = 1e9+7; // adjacency list representation of input graph vector<vpll> g; // cost[i] = minimum cost required to reach vertex 'i' from // soucre vertex (which is = 1, in this problem) vll cost; // routes[i] = (total #min price routes) % mod, from 1 to i vll routes; // min_f[i] = minimum #flights in minimum-price route from 1 to i vi min_f; // max_f[i] = maximum #flights in minimum-price route from 1 to i vi max_f; int n, m; void dijkstra() { for(int i = 1; i <= n; i++) cost[i] = INF; cost[1] = 0LL; routes[1] = 1LL; priority_queue<pll, vpll, greater<pll>> q; q.push({0, 1}); while(!q.empty()) { ll d = q.top().F; int cur = q.top().S; q.pop(); if(cost[cur] < d) continue; // Current cost to nbr = cost[nbr] // Proposed cost to nbr through cur = d + wt for(auto &[nbr, wt]: g[cur]) { // If Proposed cost > Current cost, do nothing if(d + wt > cost[nbr]) continue; // If Proposed cost = Current cost, do incerments // and other necessary changes else if(d + wt == cost[nbr]) { routes[nbr] = (routes[nbr] + routes[cur]) % mod; min_f[nbr] = min(min_f[nbr], min_f[cur] + 1); max_f[nbr] = max(max_f[nbr], max_f[cur] + 1); } // If Proposed cost < Current cost, do resetting // as we've found a more optimal cost to reach nbr else { cost[nbr] = d + wt; q.push({cost[nbr], nbr}); routes[nbr] = routes[cur]; min_f[nbr] = min_f[cur] + 1; max_f[nbr] = max_f[cur] + 1; } } } } void solve() { cin >> n >> m; g.resize(n + 1); cost.resize(n + 1); routes.resize(n + 1); min_f.resize(n + 1); max_f.resize(n + 1); for(int i = 0; i < m; i++) { int u, v, wt; cin >> u >> v >> wt; g[u].pb({v, wt}); } dijkstra(); cout << cost[n] << " " << routes[n] << " " << min_f[n] << " " << max_f[n]; cout << "\n"; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif int t = 1; // cin >> t; while(t--) { solve(); } return 0; }
24.608392
81
0.56607
[ "vector" ]
94594f4de2f786dc872c37cf98e785369664f7d0
5,291
cc
C++
IR/src/FunctionOp.cc
avartak/DIMPLE
b117baa2880cdae4afdeecea733c301e54980ef6
[ "MIT" ]
3
2021-04-04T08:49:38.000Z
2021-07-03T02:01:26.000Z
IR/src/FunctionOp.cc
avartak/DIMPLE
b117baa2880cdae4afdeecea733c301e54980ef6
[ "MIT" ]
null
null
null
IR/src/FunctionOp.cc
avartak/DIMPLE
b117baa2880cdae4afdeecea733c301e54980ef6
[ "MIT" ]
null
null
null
#include <FunctionOp.h> #include <BinaryOp.h> #include <FunctionType.h> #include <PrimitiveType.h> #include <Statement.h> #include <CodeBlock.h> #include <LST.h> #include <Globals.h> namespace avl { std::shared_ptr<Value> FunctionOp::call(const std::shared_ptr<Function>& func, const std::vector<std::shared_ptr<Value> >& args) { std::shared_ptr<Value> fail; auto ft = static_cast<FunctionType*>(func->type.get()); if (args.size() != ft->args.size()) { return fail; } std::shared_ptr<Variable> retv; if (!ft->ret->retDirectly() || ft->ret->isCompound()) { retv = std::make_shared<Variable>(STORAGE_LOCAL, "", ft->ret); retv->declare(); retv->init(); } return call(func, args, retv); } std::shared_ptr<Value> FunctionOp::call(const std::shared_ptr<Function>& func, const std::vector<std::shared_ptr<Value> >& args, const std::shared_ptr<Variable>& retv) { std::shared_ptr<Value> ex; auto ft = static_cast<FunctionType*>(func->type.get()); std::vector<llvm::Value*> fargs; if (!ft->ret->retDirectly() || ft->ret->isCompound()) { if (!retv) { return ex; } } if (!ft->ret->retDirectly()) { fargs.push_back(retv->ptr()); } for (std::size_t i = 0; i < args.size(); i++) { if (*ft->args[i].type != *args[i]->type) { return ex; } if (ft->args[i].passByRef()) { if (!args[i]->isVar()) { return ex; } fargs.push_back(static_cast<Variable*>(args[i].get())->ptr()); } else if (ft->args[i].type->passDirectly()) { fargs.push_back(args[i]->val()); } else { const auto& v = std::make_shared<Variable>(STORAGE_LOCAL, "", args[i]->type); v->declare(); if (!BinaryOp::assign(v, args[i])) { return ex; } fargs.push_back(v->ptr()); } } auto fptr = func->ptr(); if (ft->ret->retDirectly()) { llvm::Value* lv; if (fargs.size() == 0) { lv = TheBuilder.CreateCall(llvm::cast<llvm::FunctionType>(ft->llvm_type), fptr); } else { lv = TheBuilder.CreateCall(llvm::cast<llvm::FunctionType>(ft->llvm_type), fptr, fargs); } if (!ft->ret->isCompound()) { ex = std::make_shared<Value>(ft->ret, lv); } else { auto ptr = TheBuilder.CreateBitCast(retv->ptr(), TheBuilder.getInt64Ty()); TheBuilder.CreateStore(lv, ptr); } } else { TheBuilder.CreateCall(llvm::cast<llvm::FunctionType>(ft->llvm_type), fptr, fargs); } if (!ft->ret->retDirectly() || ft->ret->isCompound()) { ex = retv; } return ex; } bool FunctionOp::ret(const std::shared_ptr<Function>& func, const std::shared_ptr<Value>& retval) { auto ft = static_cast<FunctionType*>(func->type.get()); if (!retval && !ft->ret->isVoid()) { return false; } if (retval && ft->ret->isVoid()) { return false; } if (ft->ret->isVoid()) { TheBuilder.CreateRetVoid(); return true; } if (*retval->type != *ft->ret) { return false; } llvm::Function* fn = llvm::cast<llvm::Function>(func->ptr()); if (!ft->ret->retDirectly()) { if (!BinaryOp::assign(func->retvar, retval)) { return false; } TheBuilder.CreateRetVoid(); return true; } llvm::Value* v; if (ft->ret->isCompound()) { if (retval->is != VALUE_VAR) { return false; } auto retvar = std::static_pointer_cast<Variable>(retval); auto ptr = TheBuilder.CreateBitCast(retvar->ptr(), TheBuilder.getInt64Ty()); v = TheBuilder.CreateAlignedLoad(TheBuilder.getInt64Ty(), ptr, llvm::MaybeAlign(8)); } else { v = retval->val(); } if (!func->lst->prev) { if (func->retvar) { TheBuilder.CreateStore(v, func->retvar->ptr()); CodeBlock::jump(func->retblock); CodeBlock::insert(func->retblock); TheBuilder.CreateRet(func->retvar->val()); } else { TheBuilder.CreateRet(v); } } else { if (!func->retvar) { auto ty = ft->ret->isCompound() ? std::make_shared<PrimitiveType>(TYPE_UINT64) : ft->ret; func->retvar = std::make_shared<Variable>(STORAGE_LOCAL, "", ty); func->retblock = std::make_shared<CodeBlock>(); func->retvar->declare(); } TheBuilder.CreateStore(v, func->retvar->ptr()); CodeBlock::jump(func->retblock); } return true; } }
32.460123
173
0.483084
[ "vector" ]
945eddfa63b5925fd94f497a0bb8caa16f5f2b4c
2,445
hpp
C++
source/audio/Recorder.hpp
RobertDamerius/CKeys
3a861e033abee595472770e85acba47b17f37bf8
[ "MIT" ]
3
2020-08-13T18:43:40.000Z
2020-08-14T08:58:56.000Z
source/audio/Recorder.hpp
RobertDamerius/CKeys
3a861e033abee595472770e85acba47b17f37bf8
[ "MIT" ]
null
null
null
source/audio/Recorder.hpp
RobertDamerius/CKeys
3a861e033abee595472770e85acba47b17f37bf8
[ "MIT" ]
null
null
null
#pragma once #include <SequenceTrack.hpp> class Recorder { public: SequenceTrack track; ///< Track data for visualization. std::mutex mtxTrack; ///< Protect @ref track. std::vector<std::pair<double, std::vector<unsigned char>>> rawRecordedData; ///< Raw MIDI data received during recording (delta time [s], data bytes). /** * @brief Create an empty recorder. */ Recorder(); /** * @brief Delete the recorder object. */ ~Recorder(); /** * @brief Get the current time pointer. * @return Current time pointer in seconds. */ double GetTimePointer(void); /** * @brief Start recording. * @return True if success, false otherwise. * @details The @ref track is cleared before the actual recording is started. */ bool StartRecording(void); /** * @brief Stop recording. */ void StopRecording(void); /** * @brief Check whether the recorder is in recording mode or not. * @return True if recording, false otherwise. */ inline bool IsRecording(void){ return (nullptr != midiIn); } /** * @brief Save recording to a MIDI file. * @return True if success, false otherwise. */ bool Save(void); private: RtMidiIn* midiIn; ///< MIDI input object. uint8_t runningStatus; ///< Running status byte (latest status). std::chrono::time_point<std::chrono::steady_clock> timeOfStart; ///< Time when first MIDI message was received. std::atomic<bool> isRecording; ///< True if actual recording has been started, false otherwise. double latestTimePointer; ///< The latest timepointer. /** * @brief Callback function that receives MIDI data. * @param [in] timestamp Timestamp in seconds. * @param [in] message Received MIDI message. */ void ReceiveMIDI(double timestamp, std::vector<unsigned char>& message); static void CallbackMidiIn(double timestamp, std::vector<unsigned char> *message, void *userData){ ((Recorder*)userData)->ReceiveMIDI(timestamp, *message); } };
35.434783
165
0.549693
[ "object", "vector" ]
9467591ea4a1800d0d660d7d5c825dfc081d7ba6
5,365
hpp
C++
attic/include/boost/afio/v2/detail/ErrorHandling.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
356
2018-07-09T23:00:22.000Z
2022-03-27T11:41:35.000Z
attic/include/boost/afio/v2/detail/ErrorHandling.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
80
2018-07-22T13:05:36.000Z
2022-01-12T11:34:57.000Z
attic/include/boost/afio/v2/detail/ErrorHandling.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
35
2018-11-08T20:44:11.000Z
2022-02-27T16:03:01.000Z
/* NiallsCPP11Utilities (C) 2012 Niall Douglas http://www.nedprod.com/ File Created: Nov 2012 Boost Software License - Version 1.0 - August 17th, 2003 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 <stdexcept> #include <string> #if defined(BOOST_MSVC) && BOOST_MSVC<=1800 && !defined(__func__) #define __func__ __FUNCTION__ #endif #ifdef BOOST_AFIO_EXCEPTION_DISABLESOURCEINFO #define BOOST_AFIO_EXCEPTION_FILE(p) (const char *) 0 #define BOOST_AFIO_EXCEPTION_FUNCTION(p) (const char *) 0 #define BOOST_AFIO_EXCEPTION_LINE(p) 0 #else #define BOOST_AFIO_EXCEPTION_FILE(p) __FILE__ #define BOOST_AFIO_EXCEPTION_FUNCTION(p) __func__ #define BOOST_AFIO_EXCEPTION_LINE(p) __LINE__ #endif BOOST_AFIO_V2_NAMESPACE_BEGIN class path; namespace detail{ #ifdef WIN32 BOOST_AFIO_HEADERS_ONLY_FUNC_SPEC void int_throwWinError(const char *file, const char *function, int lineno, unsigned code, std::function<BOOST_AFIO_V2_NAMESPACE::path()> filename); extern "C" unsigned __stdcall GetLastError(); #define BOOST_AFIO_ERRGWIN(code) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwWinError(BOOST_AFIO_EXCEPTION_FILE(0), BOOST_AFIO_EXCEPTION_FUNCTION(0), BOOST_AFIO_EXCEPTION_LINE(0), code, nullptr); } #define BOOST_AFIO_ERRGWINFN(code, filename) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwWinError(BOOST_AFIO_EXCEPTION_FILE(0), BOOST_AFIO_EXCEPTION_FUNCTION(0), BOOST_AFIO_EXCEPTION_LINE(0), code, std::function<BOOST_AFIO_V2_NAMESPACE::path()>(filename)); } #define BOOST_AFIO_ERRHWIN(exp) { unsigned __errcode=(unsigned)(exp); if(!__errcode) BOOST_AFIO_ERRGWIN(GetLastError()); } #define BOOST_AFIO_ERRHWINFN(exp, filename) { unsigned __errcode=(unsigned)(exp); if(!__errcode) BOOST_AFIO_ERRGWINFN(GetLastError(), filename); } BOOST_AFIO_HEADERS_ONLY_FUNC_SPEC void int_throwNTError(const char *file, const char *function, int lineno, unsigned code, std::function<BOOST_AFIO_V2_NAMESPACE::path()> filename); #define BOOST_AFIO_ERRGNT(code) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwNTError(BOOST_AFIO_EXCEPTION_FILE(0), BOOST_AFIO_EXCEPTION_FUNCTION(0), BOOST_AFIO_EXCEPTION_LINE(0), code, nullptr); } #define BOOST_AFIO_ERRGNTFN(code, filename) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwNTError(BOOST_AFIO_EXCEPTION_FILE(0), BOOST_AFIO_EXCEPTION_FUNCTION(0), BOOST_AFIO_EXCEPTION_LINE(0), code, std::function<BOOST_AFIO_V2_NAMESPACE::path()>(filename)); } #define BOOST_AFIO_ERRHNT(exp) { unsigned __errcode=(unsigned)(exp); if(0/*STATUS_SUCCESS*/!=__errcode) BOOST_AFIO_ERRGNT(__errcode); } #define BOOST_AFIO_ERRHNTFN(exp, filename) { unsigned __errcode=(unsigned)(exp); if(0/*STATUS_SUCCESS*/!=__errcode) BOOST_AFIO_ERRGNTFN(__errcode, filename); } #endif // WIN32 BOOST_AFIO_HEADERS_ONLY_FUNC_SPEC void int_throwOSError(const char *file, const char *function, int lineno, int code, std::function<BOOST_AFIO_V2_NAMESPACE::path()> filename); #define BOOST_AFIO_ERRGOS(code) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwOSError(BOOST_AFIO_EXCEPTION_FILE(code), BOOST_AFIO_EXCEPTION_FUNCTION(code), BOOST_AFIO_EXCEPTION_LINE(code), code, nullptr); } #define BOOST_AFIO_ERRGOSFN(code, filename) { BOOST_AFIO_V2_NAMESPACE::detail::int_throwOSError(BOOST_AFIO_EXCEPTION_FILE(code), BOOST_AFIO_EXCEPTION_FUNCTION(code), BOOST_AFIO_EXCEPTION_LINE(code), code, std::function<BOOST_AFIO_V2_NAMESPACE::path()>(filename)); } /*! Use this macro to wrap POSIX, UNIX or CLib functions. On BOOST_WINDOWS, the includes anything in MSVCRT which sets errno */ #define BOOST_AFIO_ERRHOS(exp) { int __errcode=(int)(exp); if(__errcode<0) BOOST_AFIO_ERRGOS(errno); } /*! Use this macro to wrap POSIX, UNIX or CLib functions taking a filename. On BOOST_WINDOWS, the includes anything in MSVCRT which sets errno */ #define BOOST_AFIO_ERRHOSFN(exp, filename) { int __errcode=(int)(exp); if(__errcode<0) BOOST_AFIO_ERRGOSFN(errno, filename); } }//namespace detail BOOST_AFIO_V2_NAMESPACE_END
65.426829
265
0.7726
[ "object" ]
9468082318c7ba976e7f3102be414d38694df169
11,127
cpp
C++
local_task_planner/test/DrawingByTrajectorysTest_old.cpp
AlexeiOvcharov/kuka_kr6r900_simulation
0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c
[ "Apache-2.0" ]
10
2020-06-12T08:00:16.000Z
2022-03-23T09:54:35.000Z
local_task_planner/test/DrawingByTrajectorysTest_old.cpp
airalab/kuka_kr6r900_simulation
0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c
[ "Apache-2.0" ]
7
2020-11-17T19:58:58.000Z
2021-04-19T12:01:24.000Z
local_task_planner/test/DrawingByTrajectorysTest_old.cpp
airalab/kuka_kr6r900_simulation
0d9125fe0cf56ca0a48aa1be2eb6ec72884bda4c
[ "Apache-2.0" ]
2
2020-11-16T14:33:45.000Z
2021-05-31T02:02:14.000Z
#include <ros/ros.h> #include <ros/package.h> #include <kuka_manipulation_moveit/KukaMoveit.hpp> #include <kuka_cv/Color.h> #include <kuka_cv/RequestPalette.h> #include <kuka_cv/RequestCanvas.h> #include <std_srvs/Empty.h> #include <visualization_msgs/Marker.h> #include <boost/thread/thread.hpp> // TF #include <tf2_ros/transform_listener.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2/LinearMath/Matrix3x3.h> #include <tf2/LinearMath/Vector3.h> #include <tf2/convert.h> #include <tf2/impl/utils.h> #include <tf2/utils.h> #include <geometry_msgs/TransformStamped.h> #include <geometry_msgs/PoseArray.h> #include <std_msgs/String.h> #include <rosbag/bag.h> #include <rosbag/view.h> #include <boost/foreach.hpp> #define foreach BOOST_FOREACH #define START_POSE_DEBUG false #define DEBUG false // TODO try using TF as main linear math. bool start = false; size_t printedMarkers = 0; tf2::Matrix3x3 R; tf2::Vector3 v; //const double COLOR_BOTLE_HEIGHT = 0.06; //const double COLOR_HEIGHT = 0.045; //const double HEIGHT_OFFSET = COLOR_BOTLE_HEIGHT - COLOR_HEIGHT + 0.02; //const double BRUSH_HEIGHT = 0.01; //const double BRUSH_WIDTH = 0.01; //testing const double COLOR_BOTLE_HEIGHT = 0.08; const double COLOR_HEIGHT = 0.038; const double HEIGHT_OFFSET = 0.02; const double BRUSH_HEIGHT = 0.215;//from j6 center const double BRUSH_WIDTH = 0.01; const std::string BAG_FILE_PATH = ros::package::getPath("picture_preprocessing") + "/data/test.bag"; const std::string TRAJECTORY_TOPIC_NAME = "/path"; void collectPaintOnBrush(KukaMoveit & manipulator, geometry_msgs::Pose & pose) { geometry_msgs::Pose p; p.position.x = pose.position.x; p.position.y = pose.position.y; //p.position.z = pose.position.z + COLOR_BOTLE_HEIGHT + HEIGHT_OFFSET; p.position.z = pose.position.z + COLOR_BOTLE_HEIGHT + HEIGHT_OFFSET + BRUSH_HEIGHT; p.orientation.w = 1; manipulator.move(p, DEBUG); //p.position.z = pose.position.z + COLOR_HEIGHT - BRUSH_HEIGHT p.position.z = pose.position.z + COLOR_HEIGHT + BRUSH_HEIGHT - 0.003; manipulator.move(p, DEBUG); //p.position.z = pose.position.z + COLOR_BOTLE_HEIGHT + HEIGHT_OFFSET; p.position.z = pose.position.z + COLOR_BOTLE_HEIGHT + HEIGHT_OFFSET + BRUSH_HEIGHT; manipulator.move(p, DEBUG); } void doSmear(KukaMoveit & manipulator, std::vector<geometry_msgs::Pose> & waypoints) { moveit::planning_interface::MoveGroupInterface::Plan plan; moveit_msgs::RobotTrajectory trajectory; const double jump_threshold = 0.0; const double eef_step = 0.01; geometry_msgs::Pose first, last; first = waypoints.front(); first.position.z += HEIGHT_OFFSET; last = waypoints.back(); last.position.z += COLOR_BOTLE_HEIGHT + HEIGHT_OFFSET; ROS_INFO_STREAM("P: [" << first.position.x << ", " << first.position.y << ", " << first.position.z << "]"); // Move to start position manipulator.move(first, DEBUG); // Modify and execute waypoints // Set slow motion manipulator.getMoveGroup()->setMaxVelocityScalingFactor(0.8); double fraction = manipulator.getMoveGroup()->computeCartesianPath( waypoints, eef_step, jump_threshold, trajectory ); for (size_t i = 0; i < trajectory.joint_trajectory.points.size(); ++i) { std::cout << "(" << i << ")\t" << trajectory.joint_trajectory.points[i].time_from_start << " | " << trajectory.joint_trajectory.points[i].positions[0] << std::endl; } plan.trajectory_ = trajectory; manipulator.getMoveGroup()->execute(plan); // Complete of trajectory manipulator.move(last, DEBUG); manipulator.getMoveGroup()->setMaxVelocityScalingFactor(1.2); } void transformFromCanvasToBase(std::vector<geometry_msgs::Pose> & poses) { // Transform: // R*p + v // R - canvas transform matrix, v - translation or canvas frame, p - painting point tf2::Vector3 result, p; for (size_t i = 0; i < poses.size(); ++i) { p = tf2::Vector3( poses[i].position.x, poses[i].position.y, poses[i].position.z ); result = R*p + v; poses[i].position.x = result.m_floats[0]; poses[i].position.y = result.m_floats[1]; poses[i].position.z = result.m_floats[2]; } } std::vector<geometry_msgs::PoseArray> readBagFile(const std::string filepath, const std::string topicName) { rosbag::Bag bag; bag.open(filepath, rosbag::bagmode::Read); rosbag::View view(bag, rosbag::TopicQuery(topicName)); std::vector<geometry_msgs::PoseArray> trajectoryArray; geometry_msgs::PoseArray p; foreach (rosbag::MessageInstance const m, view) { geometry_msgs::PoseArray::ConstPtr parr = m.instantiate<geometry_msgs::PoseArray>(); p.poses = parr->poses; trajectoryArray.push_back(p); } bag.close(); return trajectoryArray; } void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data.c_str()); start = true; } int main(int argc, char ** argv) { ros::init(argc, argv, "camera_test"); ros::NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); // Service client ros::ServiceClient paletteClient = nh.serviceClient<kuka_cv::RequestPalette>("/request_palette"); ros::ServiceClient canvasClient = nh.serviceClient<kuka_cv::RequestCanvas>("/request_canvas"); ros::ServiceClient startImgProcClient = nh.serviceClient<std_srvs::Empty>("/convert_text"); /* AIRA Stack */ ros::Subscriber runSubscriber = nh.subscribe("run", 10, chatterCallback); ros::ServiceClient liabilityFinishClient = nh.serviceClient<std_srvs::Empty>("liability/finish"); // Initialize manipulator KukaMoveit manipulator("manipulator"); /* Set joint constraints */ // Joint a1 moveit_msgs::Constraints constraints; constraints.joint_constraints.resize(2); constraints.joint_constraints[0].joint_name = "joint_a1"; constraints.joint_constraints[0].position = 0.0; constraints.joint_constraints[0].tolerance_above = 1; constraints.joint_constraints[0].tolerance_below = 1; constraints.joint_constraints[0].weight = 1.0; // Joint a4 constraints.joint_constraints[1].joint_name = "joint_a4"; constraints.joint_constraints[1].position = 0.0; constraints.joint_constraints[1].tolerance_above = 1; constraints.joint_constraints[1].tolerance_below = 1; constraints.joint_constraints[1].weight = 1.0; manipulator.getMoveGroup()->setPathConstraints(constraints); kuka_cv::RequestPalette::Response palette; kuka_cv::RequestPalette paletteInfo; kuka_cv::RequestCanvas canvasInfo; while(ros::ok()) { if (start) { /* Palette info */ paletteInfo.request.mode = 0; ROS_INFO_STREAM("[LTP] Receive palette message."); do { if (paletteClient.call(paletteInfo)) { palette = paletteInfo.response; break; } ROS_WARN_STREAM("[LTP] Receive Colors array size = 0"); } while ((palette.colors.empty() || palette.poses.empty()) && ros::ok()); /* Canvas info */ canvasInfo.request.mode = 0; ROS_INFO_STREAM("[LTP] Receive canvas message: "); do { if (canvasClient.call(canvasInfo)) { break; } ROS_WARN_STREAM("[LTP] Receive wrong canvas info"); } while (canvasInfo.response.width == 0 && ros::ok()); R.setRPY(canvasInfo.response.p.phi, canvasInfo.response.p.theta, canvasInfo.response.p.psi); v = tf2::Vector3(canvasInfo.response.p.x, canvasInfo.response.p.y, canvasInfo.response.p.z); if (START_POSE_DEBUG) { ROS_INFO("[LTP] START_POSE_DEBUG --------------"); double offset = 0.02; geometry_msgs::Pose c; std::vector<geometry_msgs::Pose> p; std::vector<tf2::Vector3> vp(4); p.resize(4); vp[0] = R*tf2::Vector3( canvasInfo.response.height/2, -canvasInfo.response.width/2, 0), vp[1] = R*tf2::Vector3(-canvasInfo.response.height/2, -canvasInfo.response.width/2, 0), vp[2] = R*tf2::Vector3(-canvasInfo.response.height/2, canvasInfo.response.width/2, 0), vp[3] = R*tf2::Vector3( canvasInfo.response.height/2, canvasInfo.response.width/2, 0), // Fille center of paper c.position.x = v.m_floats[0]; c.position.y = v.m_floats[1]; c.position.z = v.m_floats[2]; // Move to center point manipulator.move(c, DEBUG); // p = center + R*vp for (size_t i = 0; i < 4; ++i) { p[i].position.x = c.position.x + vp[i].m_floats[0]; p[i].position.y = c.position.y + vp[i].m_floats[1]; p[i].position.z = c.position.z + vp[i].m_floats[2] + offset; // move between points manipulator.move(p[i], DEBUG); } } /* Image palette info */ std_srvs::Empty emptyMsg; ROS_INFO_STREAM("[LTP] START image processing."); if (!startImgProcClient.call(emptyMsg)) { ROS_ERROR_STREAM("\t ERROR"); return 0; } // TODO Add rosbag file read function std::vector<geometry_msgs::PoseArray> trajectorys = readBagFile(BAG_FILE_PATH, TRAJECTORY_TOPIC_NAME); // Draw Params bool isDraw = true; size_t numberOfSmears = trajectorys.size(); size_t currentSmearNumber = 0; // Convert kuka_cv::Pose to geometry_msgs::Pose geometry_msgs::Pose colorPose; colorPose.position.x = palette.poses[0].x; colorPose.position.y = palette.poses[0].y; colorPose.position.z = palette.poses[0].z; ROS_INFO_STREAM("Drawing inforation: "); ROS_INFO_STREAM("Trajectorys number: " << numberOfSmears); // Global drawing circle collectPaintOnBrush(manipulator, colorPose); while (ros::ok() && isDraw) { if (currentSmearNumber == numberOfSmears) { ROS_ERROR("Drawing image complete"); isDraw = false; break; } transformFromCanvasToBase(trajectorys[currentSmearNumber].poses); doSmear(manipulator, trajectorys[currentSmearNumber].poses); collectPaintOnBrush(manipulator, colorPose) ; ROS_INFO_STREAM("[LTP] POINT (" << currentSmearNumber << ")"); ++currentSmearNumber; ++numberOfSmears; } std_srvs::Empty empty; if (!liabilityFinishClient.call(empty)) { return 0; } start = false; } } return 0; }
34.880878
114
0.624427
[ "vector", "transform" ]
9468ad2e45b5bd7b7f797ea00f5fff7ee723195c
65,833
cpp
C++
src/srcnn.cpp
Cuda-Chen/SRCNN-cpp
4e8d4ef3e41f48f20fbdbe60ead58cb805d19b84
[ "MIT" ]
4
2020-01-28T20:38:43.000Z
2020-11-23T13:07:46.000Z
src/srcnn.cpp
Cuda-Chen/SRCNN-cpp
4e8d4ef3e41f48f20fbdbe60ead58cb805d19b84
[ "MIT" ]
2
2020-01-29T14:25:45.000Z
2020-07-03T02:02:43.000Z
src/srcnn.cpp
Cuda-Chen/SRCNN-cpp
4e8d4ef3e41f48f20fbdbe60ead58cb805d19b84
[ "MIT" ]
1
2020-05-29T09:41:19.000Z
2020-05-29T09:41:19.000Z
#include <iostream> #include <iomanip> #include <string> #include <tuple> #include <fstream> #include <cassert> #include <chrono> #include "opencv2/opencv.hpp" #include "srcnn.hpp" #include "datatype.hpp" #include "gaussian.hpp" #ifdef __x86_64__ #include <immintrin.h> #else #include "sse2neon.h" #endif //#define IM2COL 0 #define VECTOR_ALIGNEMENT 64 //#define BLOCK_SIZE 256 #define TILE_M 4 // 4 ops #define TILE_N 16 // AVX2 = 2 ops * 8 floats #define TILE_K 16 // loop #define PUT_IN_REGISTER register using namespace std; using namespace cv; SRCNN::SRCNN() { for(unsigned int i = 0; i < this->weights.size(); i++) { this->weights[i] = this->weights[i].insert(0, this->basePath); } } void SRCNN::generate(string filename) { this->img = imread(filename, IMREAD_COLOR); cvtColor(this->img, this->gray, COLOR_BGR2GRAY); // my SRCNN can only accept grayscale image // downsample to half size of width and height resize(this->gray, this->downsample, Size(), 1.0 / this->scale, 1.0 / this->scale, INTER_CUBIC); // using bicubic to resize input image Mat bicubicTemp; resize(this->downsample, this->bicubic, Size(), this->scale, this->scale, INTER_CUBIC); //this->bicubic = bicubicTemp; // prepare input, output, and conv data cout << "prepare data" << endl; int inputWidth = this->bicubic.cols; int inputHeight = this->bicubic.rows; cout << "input width height " << inputWidth << " " << inputHeight << endl; ImageDim inputDim = make_tuple(1, inputHeight, inputWidth); data_t *input = new data_t[inputHeight * inputWidth]; ImageDim conv1Dim = make_tuple(64, inputHeight, inputWidth); ImageDim conv2Dim = make_tuple(32, inputHeight, inputWidth); ImageDim conv3Dim = make_tuple(1, inputHeight, inputWidth); data_t *conv1Data = new data_t[getTotalDimension(conv1Dim)]; data_t *conv2Data = new data_t[getTotalDimension(conv2Dim)]; data_t *conv3Data = new data_t[getTotalDimension(conv3Dim)]; int outputWidth = inputWidth; int outputHeight = inputHeight; cout << "output width height " << outputWidth << " " << outputHeight << endl; data_t *dst = new data_t[outputHeight * outputWidth]; cout << "assign input and output value" << endl; #pragma omp parallel for for(int i = 0; i < inputHeight; i++) { for(int j = 0; j < inputWidth; j++) { input[(i * inputWidth) + j] = (data_t)this->bicubic.at<uchar>(i, j) / 255.0; dst[(i * inputWidth) + j] = 0; } } // read conv and bias weights cout << "read conv and bias weights" << endl; cout << "kernelDim" << endl; KernelDim conv1WeightsDim = make_tuple(64, 1, 9, 9); KernelDim conv2WeightsDim = make_tuple(32, 64, 5, 5); KernelDim conv3WeightsDim = make_tuple(1, 32, 5, 5); cout << "biasDim" << endl; ImageDim bias1Dim = make_tuple(64, 1, 1); ImageDim bias2Dim = make_tuple(32, 1, 1); ImageDim bias3Dim = make_tuple(1, 1, 1); cout << "finish setting bias dim" << endl; data_t *conv1Weights = new data_t[getTotalDimension(conv1WeightsDim)]; data_t *conv1Weights_transposed = new data_t[getTotalDimension(conv1WeightsDim)]; data_t *conv2Weights = new data_t[getTotalDimension(conv2WeightsDim)]; data_t *conv2Weights_transposed = new data_t[getTotalDimension(conv2WeightsDim)]; data_t *conv3Weights = new data_t[getTotalDimension(conv3WeightsDim)]; data_t *conv3Weights_transposed = new data_t[getTotalDimension(conv3WeightsDim)]; data_t *bias1Weights = new data_t[getTotalDimension(bias1Dim)]; data_t *bias2Weights = new data_t[getTotalDimension(bias2Dim)]; data_t *bias3Weights = new data_t[getTotalDimension(bias3Dim)]; cout << "finish allocating conv and bias weights' space" << endl; #if IM2COL int conv1_col_height = get<2>(conv1WeightsDim) * get<3>(conv1WeightsDim) * get<1>(conv1WeightsDim); int conv1_col_width = get<1>(conv1Dim) * get<2>(conv1Dim); data_t *conv1Workspace = new data_t[conv1_col_height * conv1_col_width]; int conv2_col_height = get<2>(conv2WeightsDim) * get<3>(conv2WeightsDim) * get<1>(conv2WeightsDim); int conv2_col_width = get<1>(conv2Dim) * get<2>(conv2Dim); data_t *conv2Workspace = new data_t[conv2_col_height * conv2_col_width]; int conv3_col_height = get<2>(conv3WeightsDim) * get<3>(conv3WeightsDim) * get<1>(conv3WeightsDim); int conv3_col_width = get<1>(conv3Dim) * get<2>(conv3Dim); data_t *conv3Workspace = new data_t[conv3_col_height * conv3_col_width]; #endif readConvWeights(this->weights[0], conv1Weights, conv1WeightsDim, NCWH, false); cout << "weight[0]" << endl; readConvWeights(this->weights[1], conv2Weights, conv2WeightsDim, CHWN, true); cout << "weight[1]" << endl; transpose(conv2Weights_transposed, conv2Weights, 64 * 5 * 5, 32);// CHWN -> NCHW readConvWeights(this->weights[2], conv3Weights, conv3WeightsDim, CHWN, false); cout << "weights[2]" << endl; readBiasWeights(this->weights[3], bias1Weights); cout << "weight[3]" << endl; readBiasWeights(this->weights[4], bias2Weights); cout << "weight[4]" << endl; readBiasWeights(this->weights[5], bias3Weights); cout << "weight[5]" << endl; auto start = chrono::steady_clock::now(); // conv1 (feature extraction) //cout << "conv1" << endl; #if IM2COL convolution(input, conv1Data, inputDim, conv1Dim, conv1Weights, conv1WeightsDim, 1, bias1Weights, bias1Dim, conv1Workspace); #else naiveConvolution(input, conv1Data, inputDim, conv1Dim, conv1Weights, conv1WeightsDim, 1, bias1Weights, bias1Dim); #endif activation(conv1Data, conv1Data, conv1Dim, RELU); #if 0 data_t *conv1arr = new data_t[get<1>(conv1Dim) * get<2>(conv1Dim)]; for(int i = 0; i < get<0>(conv1Dim); i++) { for(int j = 0; j < get<1>(conv1Dim); j++) { for(int k = 0; k < get<2>(conv1Dim); k++) { conv1arr[j * get<2>(conv1Dim) + k] = conv1Data[(i * get<1>(conv1Dim) + j) * get<2>(conv1Dim) + k]; } } Mat conv1(get<1>(conv1Dim), get<2>(conv1Dim), CV_32FC1, conv1arr); conv1.convertTo(conv1, CV_8UC1, 255.0); string outputname = "conv1_" + to_string(i) + ".jpg"; imwrite(outputname, conv1); } delete [] conv1arr; #endif // conv2 (non-linear mapping) //cout << "conv2" << endl; #if IM2COL convolution(conv1Data, conv2Data, conv1Dim, conv2Dim, conv2Weights_transposed, conv2WeightsDim, 1, bias2Weights, bias2Dim, conv2Workspace); #else naiveConvolution(conv1Data, conv2Data, conv1Dim, conv2Dim, conv2Weights_transposed, conv2WeightsDim, 1, bias2Weights, bias2Dim); #endif activation(conv2Data, conv2Data, conv2Dim, RELU); #if 0 data_t *conv2arr = new data_t[get<1>(conv2Dim) * get<2>(conv2Dim)]; for(int i = 0; i < 32; i++) { for(int j = 0; j < get<1>(conv2Dim); j++) { for(int k = 0; k < get<2>(conv2Dim); k++) { conv2arr[j * get<2>(conv2Dim) + k] = conv2Data[(i * get<1>(conv2Dim) + j) * get<2>(conv2Dim) + k]; } } Mat conv2(get<1>(conv2Dim), get<2>(conv2Dim), CV_32FC1, conv2arr); conv2.convertTo(conv2, CV_8UC1, 255.0); string outputname = "conv2_" + to_string(i) + ".jpg"; imwrite(outputname, conv2); } delete [] conv2arr; #endif // conv3 (reconstruction) //cout << "conv3" << endl; #if IM2COL convolution(conv2Data, conv3Data, conv2Dim, conv3Dim, conv3Weights, conv3WeightsDim, 1, bias3Weights, bias3Dim, conv3Workspace); #else naiveConvolution(conv2Data, conv3Data, conv2Dim, conv3Dim, conv3Weights, conv3WeightsDim, 1, bias3Weights, bias3Dim); #endif #if 0 unsigned char *conv3arr = new unsigned char[get<1>(conv3Dim) * get<2>(conv3Dim)]; for(int i = 0; i < get<0>(conv3Dim); i++) { for(int j = 0; j < get<1>(conv3Dim); j++) { for(int k = 0; k < get<2>(conv3Dim); k++) { conv3arr[j * get<2>(conv3Dim) + k] = (unsigned char) (conv3Data[(i * get<1>(conv3Dim) + j) * get<2>(conv3Dim) + k] * 255.0f); if(conv3arr[j * get<2>(conv3Dim) + k] > 255) conv3arr[j * get<2>(conv3Dim) + k] = 255; //cout << (int)conv3arr[j * get<2>(conv3Dim) + k] << endl; //cout << conv3Data[(i * get<1>(conv3Dim) + j) * get<2>(conv3Dim) + k] << endl; } } Mat conv3(get<1>(conv3Dim), get<2>(conv3Dim), CV_8UC1, conv3arr); //conv3.convertTo(conv3, CV_8UC1, 255.0); string outputname = "conv3_" + to_string(i) + ".jpg"; imwrite(outputname, conv3); } //delete [] conv3arr; #endif auto end = chrono::steady_clock::now(); auto diff = end - start; cout << chrono::duration<data_t>(diff).count() << " s" << endl; cout << "prepare output" << endl; #pragma omp parallel for for(int i = 0; i < outputHeight; i++) { for(int j = 0; j < outputWidth; j++) { //cout << i << " " << j << " fine" << endl; dst[(i * outputWidth) + j] = conv3Data[((1 - 1) * get<1>(conv3Dim) + i) * get<2>(conv3Dim) + j]; //cout << dst[(i * outputWidth) + j] << endl; //dst[(i * outputWidth) + j] = conv3Data[(i * outputWidth) + j]; #if 0 if(dst[(i * outputWidth) + j] != 0) { cout << "index " << i << " " << j << " " << conv3Data[(i * outputWidth) + j] << endl; } #endif } } // copy to output OpenCV Mat cout << "copy to output OpenCV Mat" << endl; #if USEFLOAT Mat SRCNN(outputHeight, outputWidth, CV_32FC1, dst); #else Mat SRCNN(outputHeight, outputWidth, CV_64FC1, dst); #endif SRCNN.convertTo(SRCNN, CV_8UC1, 255); this->output = SRCNN; delete [] input; delete [] conv1Data; delete [] conv2Data; delete [] conv3Data; delete [] conv1Weights; delete [] conv1Weights_transposed; delete [] conv2Weights; delete [] conv2Weights_transposed; delete [] conv3Weights; delete [] conv3Weights_transposed; delete [] bias1Weights; delete [] bias2Weights; delete [] bias3Weights; #if IM2COL delete [] conv1Workspace; delete [] conv2Workspace; delete [] conv3Workspace; #endif } void SRCNN::showOutput() { namedWindow("input"); imshow("input", this->img); waitKey(0); namedWindow("downsample"); imshow("downsample", this->downsample); waitKey(0); namedWindow("bicubic"); imshow("bicubic", this->bicubic); waitKey(0); namedWindow("SRCNN"); imshow("SRCNN", this->output); waitKey(0); } void SRCNN::outputImage() { imwrite("srcnnResult.bmp", this->output); } int SRCNN::getTotalDimension(ImageDim dim) { return get<0>(dim) * get<1>(dim) * get<2>(dim); } int SRCNN::getTotalDimension(KernelDim dim) { return get<0>(dim) * get<1>(dim) * get<2>(dim) * get<3>(dim); } void SRCNN::checkWeightStatus() { for(string weightPath: this->weights) { ifstream input(weightPath); if(!input.is_open()) { cerr << "file " << weightPath << " opened unsuccessfully" << endl; continue; } vector<data_t> contents; data_t temp; while(input >> temp) { contents.push_back(temp); } cout << weightPath << " " << contents.size() << "\t"; for(unsigned int i = 0; i < 3; i++) { cout << contents[i] << " "; } cout << endl; input.close(); } } void SRCNN::testImageConv(string filename) { Mat gray = imread(filename, IMREAD_GRAYSCALE); imshow("gray", gray); waitKey(0); // ordinary Gaussian filter int width = gray.cols; int height = gray.rows; unsigned char *source = new unsigned char[height * width]; unsigned char *destination = new unsigned char[height * width]; // Conv test data_t *input = new data_t[1 * height * width]; data_t *output = new data_t[1 * height * width]; ImageDim inputDim = make_tuple(1, height, width); ImageDim outputDim = make_tuple(1, height, width); unsigned char *dst = new unsigned char[height * width]; int kernelWidth = 3; int kernelHeight = 3; data_t sigma = 3.0; // Conv test data_t *kernel = new data_t[kernelHeight * kernelWidth]; data_t *kernel_data_t = new data_t[kernelHeight * kernelWidth]; KernelDim kernelDim = make_tuple(1, 1, kernelHeight, kernelWidth); #pragma omp parallel for for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { source[(i * width) + j] = gray.at<uchar>(i, j); destination[(i * width) + j] = source[(i * width) + j]; input[(i * width) + j] = gray.at<uchar>(i, j) / 255.0; output[(i * width) + j] = input[(i * width) + j]; } } generateKernel(kernelWidth, kernelHeight, sigma, kernel); for(int i = 0; i < kernelHeight; i++) { for(int j = 0; j < kernelWidth; j++) { kernel_data_t[i * kernelWidth + j] = (data_t)kernel[i * kernelWidth + j]; } } gaussianFilter(source, destination, width, height, kernelWidth, kernelHeight, sigma); Mat result(height, width, CV_8UC1, destination); imshow("gaussian", result); waitKey(0); convolution(input, output, inputDim, outputDim, kernel_data_t, kernelDim); /*testConvolution(input, output, inputDim, outputDim, kernel_data_t, kernelDim, 1, NULL, std::make_tuple(0, 0, 0), "deadbeef", "deadbeef");*/ int counter = 0; #pragma omp parallel for for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { dst[(i * width) + j] = output[(i * width) + j] * 255.0; if(dst[(i * width) + j] != destination[(i * width) + j]) { counter++; } } } cout << "total " << counter << " differences" << endl; cout << "height: " << height << " width: " << width << endl; Mat result1(height, width, CV_8UC1, dst); //Mat result1(height, width, CV_64FC1, output); imshow("gaussian 1", result1); waitKey(0); } void SRCNN::testConv1Channel() { // input ImageDim inputDim = make_tuple(1, 5, 5); data_t input[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; // kernel KernelDim kernelDim = make_tuple(1, 1, 3, 3); data_t kernel[] { 0, 0, 0, 0, 1, 0, 0, 0, 0 }; // output ImageDim outputDim = make_tuple(1, 5, 5); data_t *output = new data_t[getTotalDimension(outputDim)]; // bias ImageDim biasDim = make_tuple(1, 1, 1); data_t bias[] = { 0 }; // apply convolution convolution(input, output, inputDim, outputDim, kernel, kernelDim, 1, bias, biasDim); /*testConvolution(input, output, inputDim, outputDim, kernel, kernelDim, 1, bias, biasDim, "deadbeef", "deadmilk");*/ // print the convoluted result int outputHeight = get<1>(outputDim); int outputWidth = get<2>(outputDim); for(int i = 0; i < get<0>(outputDim); i++) { #pragma omp parallel for for(int j = 0; j < outputHeight; j++) { for(int k = 0; k < outputWidth; k++) { cout << output[((i) * outputHeight + j) * outputWidth + k] << " "; } cout << endl; } cout << endl; } } // http://cs231n.github.io/convolutional-networks/ void SRCNN::testConv3Channels() { // input ImageDim inputDim = make_tuple(3, 5, 5); data_t input[] = { /* channel 0 */ 2, 1, 1, 0, 1, 1, 1, 0, 2, 1, 2, 0, 0, 2, 2, 2, 0, 1, 1, 1, 1, 2, 2, 2, 0, /* channel 1 */ 0, 0, 0, 2, 1, 0, 0, 2, 0, 2, 0, 2, 2, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 1, 1, /* channel 2 */ 0, 2, 2, 0, 2, 0, 1, 1, 0, 2, 1, 2, 1, 1, 0, 2, 2, 0, 2, 2, 2, 0, 2, 2, 0 }; // output int outputDepth = 2; int outputHeight = 3; int outputWidth = 3; ImageDim outputDim = make_tuple(2, 3, 3); data_t *output = new data_t[getTotalDimension(outputDim)]; for(int i = 0; i < outputDepth; i++) { #pragma omp parallel for for(int j = 0; j < outputHeight; j++) { for(int k = 0; k < outputWidth; k++) { output[(i * outputHeight + j) * outputWidth + k] = 0; } } } // kernel KernelDim filtersDim = make_tuple(2, 3, 3, 3); data_t filters[] = { /* filter w0 */ /* channel 0 */ 0, 0, 1, 0, 0, -1, 1, 0, 0, /* channel 1 */ -1, 0, 1, 1, 1, 0, 0, 0, 0, /* channel 2 */ 1, -1, -1, 1, 0, -1, 1, -1, 0, /* filter w1 */ /* channel 0 */ 1, 1, 0, 0, 1, 1, 1, 1, 0, /* channel 1 */ -1, 1, -1, -1, 0, 1, -1, 0, 1, /* channel 2 */ 1, -1, 1, 1, 1, 0, -1, -1, 1 }; // bias ImageDim biasesDim = make_tuple(2, 1, 1); data_t biases[] = {/* b0 */ 1, /* b1 */ 0 }; // operate convolution on test data convolution(input, output, inputDim, outputDim, filters, filtersDim, 2, biases, biasesDim); /*testConvolution(input, output, inputDim, outputDim, filters, filtersDim, 2, biases, biasesDim, "deadbeef", "deadmilk");*/ // print the convoluted result for(int i = 0; i < get<0>(outputDim); i++) { for(int j = 0; j < get<1>(outputDim); j++) { for(int k = 0; k < get<2>(outputDim); k++) { cout << output[((i) * outputHeight + j) * outputWidth + k] << " "; } cout << endl; } cout << endl; } } // matrix transpose test void SRCNN::testTranspose() { // kernel KernelDim filtersDim = make_tuple(2, 3, 3, 3); int kernel_num = 2; int kernel_c = 3; int kernel_h = 3; int kernel_w = 3; data_t testKernel[] = { /* filter w0 */ /* channel 0 */ 0, 0, 1, 0, 0, -1, 1, 0, 0, /* channel 1 */ -1, 0, 1, 1, 1, 0, 0, 0, 0, /* channel 2 */ 1, -1, -1, 1, 0, -1, 1, -1, 0, /* filter w1 */ /* channel 0 */ 1, 1, 0, 0, 1, 1, 1, 1, 0, /* channel 1 */ -1, 1, -1, -1, 0, 1, -1, 0, 1, /* channel 2 */ 1, -1, 1, 1, 1, 0, -1, -1, 1 }; data_t *filters_transposed = new data_t[getTotalDimension(filtersDim)]; int filters_transposed_h = kernel_c * kernel_h * kernel_w; int filters_transposed_w = kernel_num; data_t *result = new data_t[getTotalDimension(filtersDim)]; int result_h = kernel_num; int result_w = kernel_c * kernel_h * kernel_w; transpose(filters_transposed, testKernel, kernel_num, kernel_c * kernel_h * kernel_w); cout << "transpose: " << endl; for(int i = 0; i < filters_transposed_h; i++) { for(int j = 0; j < filters_transposed_w; j++) { cout << filters_transposed[i * filters_transposed_w + j] << " "; } cout << endl; } cout << endl; transpose(result, filters_transposed, filters_transposed_h, filters_transposed_w); cout << "result: " << endl; for(int i = 0; i < kernel_num; i++) { for(int j = 0; j < kernel_c * kernel_h * kernel_w; j++) { cout << result[i * kernel_c * kernel_h * kernel_w + j] << " "; } cout << endl; } delete [] filters_transposed; delete [] result; } void SRCNN::testReadAndTranspose() { KernelDim conv1WeightsDim = make_tuple(64, 1, 9, 9); KernelDim conv2WeightsDim = make_tuple(32, 64, 5, 5); KernelDim conv3WeightsDim = make_tuple(1, 32, 5, 5); data_t *conv1Weights = new data_t[getTotalDimension(conv1WeightsDim)]; data_t *conv1Weights_transposed = new data_t[getTotalDimension(conv1WeightsDim)]; data_t *conv1Weights_tt = new data_t[getTotalDimension(conv1WeightsDim)]; data_t *conv2Weights = new data_t[getTotalDimension(conv2WeightsDim)]; data_t *conv2Weights_transposed = new data_t[getTotalDimension(conv2WeightsDim)]; data_t *conv2Weights_tt = new data_t[getTotalDimension(conv2WeightsDim)]; data_t *conv3Weights = new data_t[getTotalDimension(conv3WeightsDim)]; data_t *conv3Weights_transposed = new data_t[getTotalDimension(conv3WeightsDim)]; data_t *conv3Weights_tt = new data_t[getTotalDimension(conv3WeightsDim)]; readConvWeights(this->weights[0], conv1Weights); cout << "weight[0]" << endl; readConvWeights(this->weights[1], conv2Weights, true); cout << "weight[1]" << endl; readConvWeights(this->weights[2], conv3Weights, false, true); cout << "weight[2]" << endl; int conv1_row = 64, conv1_col = 1*9*9; transpose(conv1Weights_transposed, conv1Weights, conv1_row, conv1_col); transpose(conv1Weights_tt, conv1Weights_transposed, conv1_col, conv1_row); for(int i = 0; i < conv1_row; i++) { for(int j = 0; j < conv1_col; j++) { if(conv1Weights_tt[i * conv1_col + j] != conv1Weights[i * conv1_col + j]) { cout << "index " << i * conv1_col + j << " not same after transpose and transpose" << endl; } } } } void SRCNN::testReadWeightFormat() { KernelDim conv1Dim = make_tuple(64, 1, 9, 9); KernelDim conv2Dim = make_tuple(32, 64, 5, 5); KernelDim conv3Dim = make_tuple(1, 32, 5, 5); data_t *conv1Weight = new data_t[getTotalDimension(conv1Dim)]; data_t *conv2Weight = new data_t[getTotalDimension(conv2Dim)]; data_t *conv2Weight_transposed = new data_t[getTotalDimension(conv2Dim)]; data_t *conv3Weight = new data_t[getTotalDimension(conv3Dim)]; readConvWeights(this->weights[0], conv1Weight, conv1Dim, NCWH); readConvWeights(this->weights[1], conv2Weight, conv2Dim, CHWN, true); readConvWeights(this->weights[2], conv3Weight, conv3Dim, CHWN); transpose(conv2Weight_transposed, conv2Weight, 64*5*5, 32); // weight format write test testWriteWeights("myWeightConv1Dump", conv1Weight, conv1Dim); testWriteWeights("myWeightConv2Dump", conv2Weight_transposed, conv2Dim); testWriteWeights("myWeightConv3Dump", conv3Weight, conv3Dim); delete [] conv1Weight; delete [] conv2Weight; delete [] conv2Weight_transposed; delete [] conv3Weight; } void SRCNN::naiveConvolution(data_t *input, data_t *output, ImageDim inputDim, ImageDim outputDim, data_t *kernels, KernelDim kernelDim, int stride/* = 1*/, data_t *bias/* = NULL*/, ImageDim biasDim/* = make_tuple(0, 0, 0)*/) { int kernelOutputChannel = get<0>(kernelDim); int kernelInputChannel = get<1>(kernelDim); int kernelHeight = get<2>(kernelDim); int kernelWidth = get<3>(kernelDim); int kernelHeightSize = kernelHeight / 2; int kernelWidthSize = kernelWidth / 2; int inputChannel = get<0>(inputDim); int inputHeight = get<1>(inputDim); int inputWidth = get<2>(inputDim); int outputChannel = get<0>(outputDim); int outputHeight = get<1>(outputDim); int outputWidth = get<2>(outputDim); for(int k = 0; k < outputChannel; k++) { for(int n = 0; n < inputChannel; n++) { #pragma omp parallel for for(int i = 0; i < inputHeight; i += stride) { for(int j = 0; j < inputWidth; j += stride) { data_t sum = 0.0; for(int l = -kernelHeightSize; l <= kernelHeightSize; l++) { for(int m = -kernelWidthSize; m <= kernelWidthSize; m++) { int y = i + l; int x = j + m; // valid padding x = x >= 0 ? (x < inputWidth ? x : inputWidth - stride) : 0; y = y >= 0 ? (y < inputHeight ? y : inputHeight - stride) : 0; int inputIdx = (n * inputHeight * inputWidth) + (y * inputWidth) + x; int kernelIdx = ((k * kernelInputChannel + n) * kernelHeight + (l + kernelHeightSize)) * kernelWidth + (m + kernelWidthSize); sum += input[inputIdx] * kernels[kernelIdx]; } } output[(k * outputHeight * outputWidth) + (i * outputWidth) + j] += sum; } } } if(bias != NULL) { #pragma omp parallel for for(int i = 0; i < outputHeight; i++) { for(int j = 0; j < outputWidth; j++) { output[(k * outputHeight * outputWidth) + (i * outputWidth) + j] += bias[k]; } } } } } // standard convolution void SRCNN::convolution(data_t *input, data_t *output, ImageDim inputDim, ImageDim outputDim, data_t *kernels, KernelDim kernelDim, int stride/* = 1*/, data_t *bias/* = NULL*/, ImageDim biasDim/* = make_tuple(0, 0, 0)*/, data_t *workspace /*= NULL*/) { int kernelOutputChannel = get<0>(kernelDim); int kernelInputChannel = get<1>(kernelDim); int kernelHeight = get<2>(kernelDim); int kernelWidth = get<3>(kernelDim); int kernelHeightSize = kernelHeight / 2; int kernelWidthSize = kernelWidth / 2; int inputChannel = get<0>(inputDim); int inputHeight = get<1>(inputDim); int inputWidth = get<2>(inputDim); int outputChannel = get<0>(outputDim); int outputHeight = get<1>(outputDim); int outputWidth = get<2>(outputDim); /* Add assertion here in the future */ // input dimension = C * H * W = (K * K * C) * N // where N = out_h * out_w data_t *input_col; int input_col_height = kernelHeight * kernelWidth * inputChannel; int input_col_width = outputHeight * outputWidth; if(!workspace) { input_col = new data_t[input_col_height * input_col_width]; } else { input_col = workspace; } int padding = kernelHeightSize; // temporary setting, may be changed in the future im2col(input, inputDim, kernelDim, stride, padding, input_col); // Output input_col #if 0 int line_counter = 0; cout << "input_col content:" << endl; for(int i = 0; i < input_col_height * input_col_width; i++) { cout << setw(2) << input_col[i] << " "; line_counter++; if(line_counter % (outputHeight * outputWidth) == 0) { cout << endl; } } #endif // Output kernel // Note the dimension is changed from NCHW to Nx(CxKxK) int kernel_col_height = kernelOutputChannel; int kernel_col_width = kernelInputChannel * kernelHeight * kernelWidth; #if 0 line_counter = 0; cout << endl << "kernel content:" << endl; for(int i = 0; i < kernel_col_height; i++) { for(int j = 0; j < kernel_col_width; j++) { cout << setw(2) << kernels[i * kernel_col_width + j] << " "; line_counter++; if(line_counter % kernel_col_width == 0) { cout << endl; } } } #endif matMul(output, kernels, input_col, bias, kernel_col_height, kernel_col_width, input_col_height, input_col_width); if(!workspace) { delete [] input_col; } } /* From Berkeley Vision's Caffe! * https://github.com/BVLC/caffe/blob/master/LICENSE */ void SRCNN::im2col(data_t *data_im, ImageDim imageDim, KernelDim kernelDim, int stride, int pad, data_t *data_col) { int imageHeight = get<1>(imageDim); int imageWidth = get<2>(imageDim); int kernelHeight = get<2>(kernelDim); int kernelWidth = get<3>(kernelDim); int col_height = (imageHeight + 2 * pad - kernelHeight) / stride + 1; int col_width = (imageWidth + 2 * pad - kernelWidth) / stride + 1; int imageChannel = get<0>(imageDim); int col_channel = imageChannel * kernelHeight * kernelWidth; for(int c = 0; c < col_channel; c++) { int w_offset = c % kernelWidth; int h_offset = (c / kernelWidth) % kernelHeight; int c_im = c / kernelWidth / kernelHeight; //#pragma omp parallel for for(int h = 0; h < col_height; h++) { for(int w = 0; w < col_width; w++) { int im_row = h_offset + h * stride; int im_col = w_offset + w * stride; int col_idx = (c * col_height + h) * col_width + w; data_col[col_idx] = im2colGetPixel(data_im, imageDim, im_row, im_col, c_im, pad); } } } } void SRCNN::col2im(data_t *data_col, ImageDim imageDim, KernelDim kernelDim, int stride, int pad, data_t *data_im) { int imageHeight = get<1>(imageDim); int imageWidth = get<2>(imageDim); int kernelHeight = get<2>(kernelDim); int kernelWidth = get<3>(kernelDim); int col_height = (imageHeight + 2 * pad - kernelHeight) / stride + 1; int col_width = (imageWidth + 2 * pad - kernelWidth) / stride + 1; int imageChannel = get<0>(imageDim); int col_channel = imageChannel * kernelHeight * kernelWidth; for(int c = 0; c < col_channel; c++) { int w_offset = c % kernelWidth; int h_offset = (c / kernelWidth) % kernelHeight; int c_im = c / kernelWidth / kernelHeight; //#pragma omp parallel for for(int h = 0; h < col_height; h++) { for(int w = 0; w < col_width; w++) { int im_row = h_offset + h * stride; int im_col = w_offset + w * stride; int col_idx = (c * col_height + h) * col_width + w; data_t value = data_col[col_idx]; col2imAddPixel(data_im, imageDim, im_row, im_col, c_im, pad, value); } } } } data_t SRCNN::im2colGetPixel(data_t *im, ImageDim imageDim, int row, int col, int channel, int pad) { int height = get<1>(imageDim); int width = get<2>(imageDim); row -= pad; col -= pad; // zero padding #if 0 if(row < 0 || col < 0 || row >= height || col >= width) { return 0; } #endif // reflect padding //#if 0 if(row < 0) row = 0; if(col < 0) col = 0; if(row >= height) row = height - 1; if(col >= width) col = width - 1; //#endif return im[col + width * (row + height * channel)]; } void SRCNN::col2imAddPixel(data_t *im, ImageDim imageDim, int row, int col, int channel, int pad, data_t value) { int height = get<1>(imageDim); int width = get<2>(imageDim); row -= pad; col -= pad; // zero padding if(row < 0 || col < 0 || row >= height || col >= width) { return; } im[col + width * (row + height * channel)] += value; } void SRCNN::matMul(data_t *out, data_t *kernel, data_t *in, data_t *bias, int kernel_row, int kernel_col, int in_row, int in_col) { if(bias == NULL) { naiveGEMM(out, kernel, in, kernel_row, kernel_col, in_row, in_col); } else { /*naiveGEMM_addBias(out, kernel, in, bias, kernel_row, kernel_col, in_row, in_col);*/ #ifdef ISX86 /*intrinsicGEMM_addBias(out, kernel, in, bias, kernel_row, kernel_col, in_row, in_col);*/ /*intrinsicGEMM_microkernel_addBias(out, kernel, in, bias, kernel_row, kernel_col, in_row, in_col);*/ intrinsicGEMM_microkernel_with_packing_addBias(out, kernel, in, bias, kernel_row, kernel_col, in_row, in_col); #else tiledNVectorizedGEMM_addBias(out, kernel, in, bias, kernel_row, kernel_col, in_row, in_col); #endif } } void SRCNN::naiveGEMM(data_t *out, data_t *kernel, data_t *in, int kernel_row, int kernel_col, int in_row, int in_col) { /* The output matrix dimension will be kernel_row * in_col */ assert(kernel_col == in_row); memset(out, 0, sizeof(data_t) * kernel_row * in_col); #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { //for(int j = 0; j < in_col; j++) for(int k = 0; k < in_row; k++) { //out[i * in_col + j] = 0; //for(int k = 0; k < in_row; k++) for(int j = 0; j < in_col; j++) { out[i * in_col + j] += kernel[i * kernel_col + k] * in[k * in_col + j]; } } } } void SRCNN::naiveGEMM_addBias(data_t *out, data_t *kernel, data_t *in, data_t *bias, int kernel_row, int kernel_col, int in_row, int in_col) { /* The output matrix dimension will be kernel_row * in_col */ assert(kernel_col == in_row); memset(out, 0, sizeof(data_t) * kernel_row * in_col); #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) //for(int k = 0; k < in_row; k++) { //out[i * in_col + j] = 0; for(int k = 0; k < in_row; k++) //for(int j = 0; j < in_col; j++) { out[i * in_col + j] += kernel[i * kernel_col + k] * in[k * in_col + j]; } } } #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) { out[i * in_col + j] += bias[i]; } } } void SRCNN::tiledNVectorizedGEMM_addBias(data_t * __restrict__ pout, data_t * __restrict__ pkernel, data_t * __restrict__ pin, data_t *bias, int kernel_row, int kernel_col, int in_row, int in_col) { /* The output matrix dimension will be kernel_row * in_col */ assert(kernel_col == in_row); const data_t *kernel = (const data_t *)__builtin_assume_aligned(pkernel, VECTOR_ALIGNEMENT); const data_t *in = (const data_t *)__builtin_assume_aligned(pin, VECTOR_ALIGNEMENT); data_t *out = (data_t *)__builtin_assume_aligned(pout, VECTOR_ALIGNEMENT); memset(out, 0, sizeof(data_t) * kernel_row * in_col); for(int ii = 0; ii < kernel_row; ii += BLOCK_SIZE_X) { for(int kk = 0; kk < in_row; kk += BLOCK_SIZE_Z) { for(int jj = 0; jj < in_col; jj += BLOCK_SIZE_Y) { int maxi = min(ii + BLOCK_SIZE_X, kernel_row); int maxk = min(kk + BLOCK_SIZE_Z, in_row); int maxj = min(jj + BLOCK_SIZE_Y, in_col); #pragma omp parallel for for(int i = ii; i < maxi; i++) { for(int k = kk; k < maxk; k++) { data_t temp = kernel[i * kernel_col + k]; for(int j = jj; j < maxj; j++) { out[i * in_col + j] += temp * in[k * in_col + j]; } } } } } } #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) { out[i * in_col + j] += bias[i]; } } } #ifdef ISX86 void SRCNN::intrinsicGEMM_addBias(float *out, float *kernel, float *in, float *bias, int kernel_row, int kernel_col, int in_row, int in_col) { /* The output matrix dimension will be kernel_row * in_col */ assert(kernel_col == in_row); memset(out, 0, sizeof(float) * kernel_row * in_col); /*#pragma omp parallel for for(int t = 0; t < kernel_row; t++) gemm_nn(1, in_col, kernel_col, 1.0, kernel + t * kernel_col, kernel_col, in, in_col, out + t * in_col, in_col);*/ for(int ii = 0; ii < kernel_row; ii += BLOCK_SIZE_X) { for(int kk = 0; kk < in_row; kk += BLOCK_SIZE_Z) { for(int jj = 0; jj < in_col; jj += BLOCK_SIZE_Y) { int maxi = min(ii + BLOCK_SIZE_X, kernel_row); int maxk = min(kk + BLOCK_SIZE_Z, in_row); int maxj = min(jj + BLOCK_SIZE_Y, in_col); /*#pragma omp parallel for for(int i = ii; i < maxi; i++) { for(int k = kk; k < maxk; k++) { data_t temp = kernel[i * kernel_col + k]; for(int j = jj; j < maxj; j++) { out[i * in_col + j] += temp * in[k * in_col + j]; } } }*/ #pragma omp parallel for for(int i = ii; i < maxi; i++) { for(int k = kk; k < maxk; k++) { float temp = kernel[i * kernel_col + k]; __m256 temp256, in256, out256, result256; temp256 = _mm256_set1_ps(temp); for(int j = jj; j < maxj - 8; j += 8) { in256 = _mm256_loadu_ps(&in[k * in_col + j]); out256 = _mm256_loadu_ps(&out[i * in_col + j]); // FMA result256 = _mm256_fmadd_ps(temp256, in256, out256); /*result256 = _mm256_mul_ps(temp256, in256); result256 = _mm256_add_ps(result256, out256);*/ _mm256_storeu_ps(&out[i * in_col + j], result256); } int prev_end = (maxj % 8 == 0) ? (maxj - 8) : (maxj / 8) * 8; for(int j = prev_end; j < maxj; j++) out[i * in_col + j] += temp * in[k * in_col + j]; } } } } } #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) { out[i * in_col + j] += bias[i]; } } } void SRCNN::gemm_nn(int M, int N, int K, float ALPHA, float *A, int lda, float *B, int ldb, float *C, int ldc) { for(int i = 0; i < M; i++) { for(int k = 0; k < K; k++) { float A_PART = ALPHA * A[i * lda + k]; __m256 a256, b256, c256, result256; a256 = _mm256_set1_ps(A_PART); for(int j = 0; j < N - 8; j += 8) { b256 = _mm256_loadu_ps(&B[k * ldb + j]); c256 = _mm256_loadu_ps(&C[i * ldc + j]); result256 = _mm256_mul_ps(a256, b256); result256 = _mm256_add_ps(result256, c256); _mm256_storeu_ps(&C[i * ldc + j], result256); } int prev_end = (N % 8 == 0) ? (N - 8) : (N / 8) * 8; for(int j = prev_end; j < N; j++) C[i * ldc + j] += A_PART * B[k * ldb + j]; } } /*for(int i = 0; i < M; i++) { for(int k = 0; k < K; k++) { float A_PART = ALPHA * A[i * lda + k]; for(int j = 0; j < N; j++) { C[i * ldc + j] += A_PART * B[k * ldb + j]; } } }*/ } // from https://github.com/AlexeyAB/darknet/blob/master/src/gemm.c#L779 void SRCNN::intrinsicGEMM_microkernel_addBias(float *out, float *kernel, float *in, float *bias, int kernel_row, int kernel_col, int in_row, int in_col) { int M = kernel_row, N = in_col, K = kernel_col; float *A = kernel, *B = in, *C = out; int lda = kernel_col, ldb = in_col, ldc = in_col; float ALPHA = 1.0f; int i; #pragma omp parallel for for (i = 0; i < (M / TILE_M)*TILE_M; i += TILE_M) { int j, k; int i_d, k_d; for (k = 0; k < (K / TILE_K)*TILE_K; k += TILE_K) { for (j = 0; j < (N / TILE_N)*TILE_N; j += TILE_N) { // L1 - 6 bits tag [11:6] - cache size 32 KB, conflict for each 4 KB // L2 - 9 bits tag [14:6] - cache size 256 KB, conflict for each 32 KB // L3 - 13 bits tag [18:6] - cache size 8 MB, conflict for each 512 KB __m256 result256; __m256 a256_0, b256_0; // AVX __m256 a256_1, b256_1; // AVX __m256 a256_2;// , b256_2; // AVX __m256 a256_3;// , b256_3; // AVX __m256 c256_0, c256_1, c256_2, c256_3; __m256 c256_4, c256_5, c256_6, c256_7; c256_0 = _mm256_loadu_ps(&C[(0 + i)*ldc + (0 + j)]); c256_1 = _mm256_loadu_ps(&C[(1 + i)*ldc + (0 + j)]); c256_2 = _mm256_loadu_ps(&C[(0 + i)*ldc + (8 + j)]); c256_3 = _mm256_loadu_ps(&C[(1 + i)*ldc + (8 + j)]); c256_4 = _mm256_loadu_ps(&C[(2 + i)*ldc + (0 + j)]); c256_5 = _mm256_loadu_ps(&C[(3 + i)*ldc + (0 + j)]); c256_6 = _mm256_loadu_ps(&C[(2 + i)*ldc + (8 + j)]); c256_7 = _mm256_loadu_ps(&C[(3 + i)*ldc + (8 + j)]); for (k_d = 0; k_d < (TILE_K); ++k_d) { a256_0 = _mm256_set1_ps(ALPHA*A[(0 + i)*lda + (k_d + k)]); a256_1 = _mm256_set1_ps(ALPHA*A[(1 + i)*lda + (k_d + k)]); a256_2 = _mm256_set1_ps(ALPHA*A[(2 + i)*lda + (k_d + k)]); a256_3 = _mm256_set1_ps(ALPHA*A[(3 + i)*lda + (k_d + k)]); b256_0 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (0 + j)]); b256_1 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (8 + j)]); // FMA - Intel Haswell (2013), AMD Piledriver (2012) //c256_0 = _mm256_fmadd_ps(a256_0, b256_0, c256_0); //c256_1 = _mm256_fmadd_ps(a256_1, b256_0, c256_1); //c256_2 = _mm256_fmadd_ps(a256_0, b256_1, c256_2); //c256_3 = _mm256_fmadd_ps(a256_1, b256_1, c256_3); //c256_4 = _mm256_fmadd_ps(a256_2, b256_0, c256_4); //c256_5 = _mm256_fmadd_ps(a256_3, b256_0, c256_5); //c256_6 = _mm256_fmadd_ps(a256_2, b256_1, c256_6); //c256_7 = _mm256_fmadd_ps(a256_3, b256_1, c256_7); result256 = _mm256_mul_ps(a256_0, b256_0); c256_0 = _mm256_add_ps(result256, c256_0); result256 = _mm256_mul_ps(a256_1, b256_0); c256_1 = _mm256_add_ps(result256, c256_1); result256 = _mm256_mul_ps(a256_0, b256_1); c256_2 = _mm256_add_ps(result256, c256_2); result256 = _mm256_mul_ps(a256_1, b256_1); c256_3 = _mm256_add_ps(result256, c256_3); result256 = _mm256_mul_ps(a256_2, b256_0); c256_4 = _mm256_add_ps(result256, c256_4); result256 = _mm256_mul_ps(a256_3, b256_0); c256_5 = _mm256_add_ps(result256, c256_5); result256 = _mm256_mul_ps(a256_2, b256_1); c256_6 = _mm256_add_ps(result256, c256_6); result256 = _mm256_mul_ps(a256_3, b256_1); c256_7 = _mm256_add_ps(result256, c256_7); } _mm256_storeu_ps(&C[(0 + i)*ldc + (0 + j)], c256_0); _mm256_storeu_ps(&C[(1 + i)*ldc + (0 + j)], c256_1); _mm256_storeu_ps(&C[(0 + i)*ldc + (8 + j)], c256_2); _mm256_storeu_ps(&C[(1 + i)*ldc + (8 + j)], c256_3); _mm256_storeu_ps(&C[(2 + i)*ldc + (0 + j)], c256_4); _mm256_storeu_ps(&C[(3 + i)*ldc + (0 + j)], c256_5); _mm256_storeu_ps(&C[(2 + i)*ldc + (8 + j)], c256_6); _mm256_storeu_ps(&C[(3 + i)*ldc + (8 + j)], c256_7); } for (j = (N / TILE_N)*TILE_N; j < N; ++j) { for (i_d = i; i_d < (i + TILE_M); ++i_d) { for (k_d = k; k_d < (k + TILE_K); ++k_d) { PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k_d]; C[i_d*ldc + j] += A_PART*B[k_d*ldb + j]; } } } } for (k = (K / TILE_K)*TILE_K; k < K; ++k) { for (i_d = i; i_d < (i + TILE_M); ++i_d) { PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k]; for (j = 0; j < N; ++j) { C[i_d*ldc + j] += A_PART*B[k*ldb + j]; } } } } for (i = (M / TILE_M)*TILE_M; i < M; ++i) { int j, k; for (k = 0; k < K; ++k) { PUT_IN_REGISTER float A_PART = ALPHA*A[i*lda + k]; for (j = 0; j < N; ++j) { C[i*ldc + j] += A_PART*B[k*ldb + j]; } } } #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) { out[i * in_col + j] += bias[i]; } } } void SRCNN::intrinsicGEMM_microkernel_with_packing_addBias(float *out, float *kernel, float *in, float *bias, int kernel_row, int kernel_col, int in_row, int in_col) { { int M = kernel_row, N = in_col, K = kernel_col; float *A = kernel, *B = in, *C = out; int lda = kernel_col, ldb = in_col, ldc = in_col; float ALPHA = 1.0f; int i; #pragma omp parallel for for (i = 0; i < (M / TILE_M)*TILE_M; i += TILE_M) { int j, k; int i_d, k_d; for (k = 0; k < (K / TILE_K)*TILE_K; k += TILE_K) { for (j = 0; j < (N / TILE_N)*TILE_N; j += TILE_N) { // L1 - 6 bits tag [11:6] - cache size 32 KB, conflict for each 4 KB // L2 - 9 bits tag [14:6] - cache size 256 KB, conflict for each 32 KB // L3 - 13 bits tag [18:6] - cache size 8 MB, conflict for each 512 KB __m256 result256; __m256 a256_0, b256_0; // AVX __m256 a256_1, b256_1; // AVX __m256 a256_2;// , b256_2; // AVX __m256 a256_3;// , b256_3; // AVX __m256 c256_0, c256_1, c256_2, c256_3; __m256 c256_4, c256_5, c256_6, c256_7; c256_0 = _mm256_loadu_ps(&C[(0 + i)*ldc + (0 + j)]); c256_1 = _mm256_loadu_ps(&C[(1 + i)*ldc + (0 + j)]); c256_2 = _mm256_loadu_ps(&C[(0 + i)*ldc + (8 + j)]); c256_3 = _mm256_loadu_ps(&C[(1 + i)*ldc + (8 + j)]); c256_4 = _mm256_loadu_ps(&C[(2 + i)*ldc + (0 + j)]); c256_5 = _mm256_loadu_ps(&C[(3 + i)*ldc + (0 + j)]); c256_6 = _mm256_loadu_ps(&C[(2 + i)*ldc + (8 + j)]); c256_7 = _mm256_loadu_ps(&C[(3 + i)*ldc + (8 + j)]); // Pack up A float packedA[TILE_M * TILE_K]; if(j == 0) { for(int a = 0; a < TILE_M; a++) { for(int b = 0; b < TILE_K; b++) packedA[a * TILE_K + b] = A[(a + i) * lda + (b + k)]; } } // Pack up B // This packing method is faster on multi-thread, but slower // on single thread. //float packedB[TILE_N]; for (k_d = 0; k_d < (TILE_K); ++k_d) { /*a256_0 = _mm256_set1_ps(ALPHA*A[(0 + i)*lda + (k_d + k)]); a256_1 = _mm256_set1_ps(ALPHA*A[(1 + i)*lda + (k_d + k)]); a256_2 = _mm256_set1_ps(ALPHA*A[(2 + i)*lda + (k_d + k)]); a256_3 = _mm256_set1_ps(ALPHA*A[(3 + i)*lda + (k_d + k)]);*/ a256_0 = _mm256_set1_ps(ALPHA * packedA[0 * TILE_K + k_d]); a256_1 = _mm256_set1_ps(ALPHA * packedA[1 * TILE_K + k_d]); a256_2 = _mm256_set1_ps(ALPHA * packedA[2 * TILE_K + k_d]); a256_3 = _mm256_set1_ps(ALPHA * packedA[3 * TILE_K + k_d]); b256_0 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (0 + j)]); b256_1 = _mm256_loadu_ps(&B[(k_d + k)*ldb + (8 + j)]); /*for(int j_d = 0; j_d < TILE_N; j_d++) packedB[j_d] = B[(k_d + k) * ldb + (j_d + j)]; b256_0 = _mm256_loadu_ps(&packedB[0]); b256_1 = _mm256_loadu_ps(&packedB[8]);*/ // FMA - Intel Haswell (2013), AMD Piledriver (2012) //c256_0 = _mm256_fmadd_ps(a256_0, b256_0, c256_0); //c256_1 = _mm256_fmadd_ps(a256_1, b256_0, c256_1); //c256_2 = _mm256_fmadd_ps(a256_0, b256_1, c256_2); //c256_3 = _mm256_fmadd_ps(a256_1, b256_1, c256_3); //c256_4 = _mm256_fmadd_ps(a256_2, b256_0, c256_4); //c256_5 = _mm256_fmadd_ps(a256_3, b256_0, c256_5); //c256_6 = _mm256_fmadd_ps(a256_2, b256_1, c256_6); //c256_7 = _mm256_fmadd_ps(a256_3, b256_1, c256_7); result256 = _mm256_mul_ps(a256_0, b256_0); c256_0 = _mm256_add_ps(result256, c256_0); result256 = _mm256_mul_ps(a256_1, b256_0); c256_1 = _mm256_add_ps(result256, c256_1); result256 = _mm256_mul_ps(a256_0, b256_1); c256_2 = _mm256_add_ps(result256, c256_2); result256 = _mm256_mul_ps(a256_1, b256_1); c256_3 = _mm256_add_ps(result256, c256_3); result256 = _mm256_mul_ps(a256_2, b256_0); c256_4 = _mm256_add_ps(result256, c256_4); result256 = _mm256_mul_ps(a256_3, b256_0); c256_5 = _mm256_add_ps(result256, c256_5); result256 = _mm256_mul_ps(a256_2, b256_1); c256_6 = _mm256_add_ps(result256, c256_6); result256 = _mm256_mul_ps(a256_3, b256_1); c256_7 = _mm256_add_ps(result256, c256_7); } _mm256_storeu_ps(&C[(0 + i)*ldc + (0 + j)], c256_0); _mm256_storeu_ps(&C[(1 + i)*ldc + (0 + j)], c256_1); _mm256_storeu_ps(&C[(0 + i)*ldc + (8 + j)], c256_2); _mm256_storeu_ps(&C[(1 + i)*ldc + (8 + j)], c256_3); _mm256_storeu_ps(&C[(2 + i)*ldc + (0 + j)], c256_4); _mm256_storeu_ps(&C[(3 + i)*ldc + (0 + j)], c256_5); _mm256_storeu_ps(&C[(2 + i)*ldc + (8 + j)], c256_6); _mm256_storeu_ps(&C[(3 + i)*ldc + (8 + j)], c256_7); } for (j = (N / TILE_N)*TILE_N; j < N; ++j) { for (i_d = i; i_d < (i + TILE_M); ++i_d) { for (k_d = k; k_d < (k + TILE_K); ++k_d) { PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k_d]; C[i_d*ldc + j] += A_PART*B[k_d*ldb + j]; } } } } for (k = (K / TILE_K)*TILE_K; k < K; ++k) { for (i_d = i; i_d < (i + TILE_M); ++i_d) { PUT_IN_REGISTER float A_PART = ALPHA*A[i_d*lda + k]; for (j = 0; j < N; ++j) { C[i_d*ldc + j] += A_PART*B[k*ldb + j]; } } } } for (i = (M / TILE_M)*TILE_M; i < M; ++i) { int j, k; for (k = 0; k < K; ++k) { PUT_IN_REGISTER float A_PART = ALPHA*A[i*lda + k]; for (j = 0; j < N; ++j) { C[i*ldc + j] += A_PART*B[k*ldb + j]; } } } #pragma omp parallel for for(int i = 0; i < kernel_row; i++) { for(int j = 0; j < in_col; j++) { out[i * in_col + j] += bias[i]; } } } } #endif void SRCNN::transpose(data_t *out, data_t *in, int in_row, int in_col) { for(int i = 0; i < in_row; i++) { for(int j = 0; j < in_col; j++) { out[j * in_row + i] = in[i * in_col + j]; } } } void SRCNN::activation(data_t *input, data_t *output, ImageDim inputDim, ACTIVATION activationType) { switch(activationType) { case RELU: for(int k = 0; k < get<0>(inputDim); k++) { for(int i = 0; i < get<1>(inputDim); i++) { for(int j = 0; j < get<2>(inputDim); j++) { output[(k * get<1>(inputDim) * get<2>(inputDim)) + (i * get<1>(inputDim)) + j] = relu_activate(input[(k * get<1>(inputDim) * get<2>(inputDim)) + (i * get<1>(inputDim)) + j]); } } } break; default: cerr << "no such operation" << endl; exit(1); break; } } void SRCNN::readConvWeights(string filename, data_t *kernel, bool special/* = false*/, bool isReverse/* = false*/) { ifstream input(filename); if(!input.is_open()) { cerr << "file " << filename << " opened unsuccessfully" << endl; exit(1); } int currentChannels = 1; if(special) { input >> currentChannels; } int kernelSizeSquare; input >> kernelSizeSquare; int nextChannels = 1; input >> nextChannels; if(isReverse) { for(int i = 0; i < currentChannels * kernelSizeSquare * nextChannels; i++) { input >> kernel[i]; } } else { for(int i = 0; i < currentChannels * kernelSizeSquare * nextChannels; i++) { input >> kernel[i]; } } input.close(); } // read filter weight and change to NCHW format void SRCNN::readConvWeights(string filename, data_t *kernel, KernelDim kernelDim, WeightFormat format, bool special) { ifstream input(filename); if(!input.is_open()) { cerr << "file " << filename << " opened unsuccessfully" << endl; exit(1); } int currentChannels = 1; if(special) { input >> currentChannels; } int kernelSizeSquare; input >> kernelSizeSquare; int nextChannels = 1; input >> nextChannels; int totalSize = currentChannels * kernelSizeSquare * nextChannels; assert(totalSize == getTotalDimension(kernelDim)); int num_filter = get<0>(kernelDim); int num_channel = get<1>(kernelDim); int num_height = get<2>(kernelDim); int num_width = get<3>(kernelDim); switch(format) { case NCHW: cout << "nchw" << endl; for(int n = 0; n < num_filter; n++) { for(int c = 0; c < num_channel; c++) { for(int h = 0; h < num_height; h++) { for(int w = 0; w < num_width; w++) { input >> kernel[((n * num_channel + c) * num_height + h) * num_width + w]; /*cout << "index " << ((n * num_channel + c) * num_height + h) * num_width + w << " n " << n << " c " << c << " h " << h << " w " << w << " " << kernel[((n * num_channel + c) * num_height + h) * num_width + w] << endl;*/ } } } } break; case NHWC: cout << "nhwc" << endl; for(int n = 0; n < num_filter; n++) { for(int h = 0; h < num_height; h++) { for(int w = 0; w < num_width; w++) { for(int c = 0; c < num_channel; c++) { input >> kernel[((n * num_height + h) * num_width + w) * num_channel + c]; } } } } break; case CHWN: cout << "chwn" << endl; for(int n = 0; n < num_filter; n++) { for(int h = 0; h < num_height; h++) { for(int w = 0; w < num_width; w++) { for(int c = 0; c < num_channel; c++) { input >> kernel[((c * num_height + h) * num_width + w) * num_filter + n]; /*cout << "index " << ((c * num_height + h) * num_width + w) * num_filter + n << " c " << c << " h " << h << " w " << w << " n " << n << " " << kernel[((c * num_height + h) * num_width + w) * num_filter + n] << endl;*/ } } } } break; case NCWH: cout << "ncwh" << endl; for(int n = 0; n < num_filter; n++) { for(int c = 0; c < num_channel; c++) { for(int h = 0; h < num_height; h++) { for(int w = 0; w < num_width; w++) { input >> kernel[((n * num_channel + c) * num_width + w) * num_height + h]; /*cout << "index " << ((n * num_channel + c) * num_width + w) * num_height + h << " n " << n << " c " << c << " w " << w << " h " << h << " " << kernel[((n * num_channel + c) * num_width + w) * num_height + h] << endl;*/ } } } } break; default: cerr << "no such format" << endl; exit(1); break; } input.close(); } void SRCNN::readBiasWeights(string filename, data_t *kernel) { ifstream input(filename); if(!input.is_open()) { cerr << "file " << filename << " opened unsuccessfully" << endl; exit(1); } int nextChannels; input >> nextChannels; int kernelSizeSquare; input >> kernelSizeSquare; for(int i = 0; i < nextChannels * kernelSizeSquare; i++) { input >> kernel[i]; } input.close(); } void SRCNN::testConvolution(data_t *input, data_t *output, ImageDim inputDim, ImageDim outputDim, data_t *kernels, KernelDim kernelDim, int stride/* = 1*/, data_t *bias/* = NULL*/, ImageDim biasDim/* = make_tuple(0, 0, 0)*/, string outputConvWeightPath, string outputBiasWeightPath) { int kernelOutputChannel = get<0>(kernelDim); int kernelInputChannel = get<1>(kernelDim); int kernelHeight = get<2>(kernelDim); int kernelWidth = get<3>(kernelDim); int kernelHeightSize = kernelHeight / 2; int kernelWidthSize = kernelWidth / 2; int inputChannel = get<0>(inputDim); int inputHeight = get<1>(inputDim); int inputWidth = get<2>(inputDim); int outputChannel = get<0>(outputDim); int outputHeight = get<1>(outputDim); int outputWidth = get<2>(outputDim); cout << outputConvWeightPath << endl; ofstream outputConvWeight(outputConvWeightPath); if(!outputConvWeight.is_open()) { cout << "conv weight unsuccessful" << endl; exit(1); } cout << outputBiasWeightPath << endl; ofstream outputBiasWeight(outputBiasWeightPath); if(!outputBiasWeight.is_open()) { cout << "bias weight unsuccessful" << endl; exit(1); } for(int k = 0; k < outputChannel; k++) { for(int n = 0; n < inputChannel; n++) { #pragma omp parallel for for(int i = 0; i < inputHeight; i += stride) { for(int j = 0; j < inputWidth; j += stride) { data_t sum = 0.0; //output[(k * outputHeight * outputWidth) + (i * outputWidth) + j] = 0; for(int l = -kernelHeightSize; l <= kernelHeightSize; l++) { for(int m = -kernelWidthSize; m <= kernelWidthSize; m++) { int y = i + l; int x = j + m; // valid padding x = x >= 0 ? (x < inputWidth ? x : inputWidth - stride) : 0; y = y >= 0 ? (y < inputHeight ? y : inputHeight - stride) : 0; int inputIdx = (n * inputHeight * inputWidth) + (y * inputWidth) + x; int kernelIdx = ((k * kernelInputChannel + n) * kernelHeight + (l + kernelHeightSize)) * kernelWidth + (m + kernelWidthSize); sum += input[inputIdx] * kernels[kernelIdx]; outputConvWeight << kernels[kernelIdx] << " "; } } output[(k * outputHeight * outputWidth) + (i * outputWidth) + j] += sum; } } } if(bias != NULL) { #pragma omp parallel for for(int i = 0; i < outputHeight; i++) { for(int j = 0; j < outputWidth; j++) { output[(k * outputHeight * outputWidth) + (i * outputWidth) + j] += bias[k]; outputBiasWeight << bias[(k * get<1>(biasDim) * get<2>(biasDim))] << " "; } } } } outputConvWeight.close(); outputBiasWeight.close(); } void SRCNN::testReadConvWeights(string filename, string outputfile, data_t *kernel, bool special/* = false*/, bool isReverse/* = false*/) { ifstream input(filename); if(!input.is_open()) { cerr << "file " << filename << " opened unsuccessfully" << endl; exit(1); } ofstream output(outputfile); if(!output.is_open()) { cerr << "file " << outputfile << " opened unsuccessfully" << endl; exit(1); } int currentChannels = 1; if(special) { input >> currentChannels; } int kernelSizeSquare; input >> kernelSizeSquare; int nextChannels = 1; input >> nextChannels; if(isReverse) { for(int i = 0; i < currentChannels * kernelSizeSquare * nextChannels; i++) { input >> kernel[i]; output << kernel[i] << " "; } } else { for(int i = 0; i < currentChannels * kernelSizeSquare * nextChannels; i++) { input >> kernel[i]; output << kernel[i] << " "; } } input.close(); output.close(); } void SRCNN::testReadBiasWeights(string filename, string outputfile, data_t *kernel) { ifstream input(filename); if(!input.is_open()) { cerr << "file " << filename << " opened unsuccessfully" << endl; exit(1); } ofstream output(outputfile); if(!output.is_open()) { cerr << "file " << outputfile << " opened unsuccessfully" << endl; exit(1); } int nextChannels; input >> nextChannels; int kernelSizeSquare; input >> kernelSizeSquare; for(int i = 0; i < nextChannels * kernelSizeSquare; i++) { input >> kernel[i]; output << kernel[i] << " "; } input.close(); output.close(); } void SRCNN::testWriteWeights(std::string outputfile, data_t *weights, ImageDim imageDim) { ofstream out; out.open(outputfile); for(int i = 0; i < getTotalDimension(imageDim); i++) { out << weights[i] << endl; } out.close(); } void SRCNN::testWriteWeights(std::string outputfile, data_t *weights, KernelDim kernelDim) { ofstream out; out.open(outputfile); for(int i = 0; i < getTotalDimension(kernelDim); i++) { out << weights[i] << endl; } out.close(); }
33.571137
143
0.502423
[ "vector" ]
20dfae213bd2c0cddfa3a5d709a6a569de089fcb
5,699
cpp
C++
mariadb/src/v20170312/model/DescribeDBSlowLogsResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
mariadb/src/v20170312/model/DescribeDBSlowLogsResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
mariadb/src/v20170312/model/DescribeDBSlowLogsResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/mariadb/v20170312/model/DescribeDBSlowLogsResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mariadb::V20170312::Model; using namespace std; DescribeDBSlowLogsResponse::DescribeDBSlowLogsResponse() : m_dataHasBeenSet(false), m_lockTimeSumHasBeenSet(false), m_queryCountHasBeenSet(false), m_totalHasBeenSet(false), m_queryTimeSumHasBeenSet(false) { } CoreInternalOutcome DescribeDBSlowLogsResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("Data") && !rsp["Data"].IsNull()) { if (!rsp["Data"].IsArray()) return CoreInternalOutcome(Error("response `Data` is not array type")); const rapidjson::Value &tmpValue = rsp["Data"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { SlowLogData item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_data.push_back(item); } m_dataHasBeenSet = true; } if (rsp.HasMember("LockTimeSum") && !rsp["LockTimeSum"].IsNull()) { if (!rsp["LockTimeSum"].IsLosslessDouble()) { return CoreInternalOutcome(Error("response `LockTimeSum` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_lockTimeSum = rsp["LockTimeSum"].GetDouble(); m_lockTimeSumHasBeenSet = true; } if (rsp.HasMember("QueryCount") && !rsp["QueryCount"].IsNull()) { if (!rsp["QueryCount"].IsInt64()) { return CoreInternalOutcome(Error("response `QueryCount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_queryCount = rsp["QueryCount"].GetInt64(); m_queryCountHasBeenSet = true; } if (rsp.HasMember("Total") && !rsp["Total"].IsNull()) { if (!rsp["Total"].IsInt64()) { return CoreInternalOutcome(Error("response `Total` IsInt64=false incorrectly").SetRequestId(requestId)); } m_total = rsp["Total"].GetInt64(); m_totalHasBeenSet = true; } if (rsp.HasMember("QueryTimeSum") && !rsp["QueryTimeSum"].IsNull()) { if (!rsp["QueryTimeSum"].IsLosslessDouble()) { return CoreInternalOutcome(Error("response `QueryTimeSum` IsLosslessDouble=false incorrectly").SetRequestId(requestId)); } m_queryTimeSum = rsp["QueryTimeSum"].GetDouble(); m_queryTimeSumHasBeenSet = true; } return CoreInternalOutcome(true); } vector<SlowLogData> DescribeDBSlowLogsResponse::GetData() const { return m_data; } bool DescribeDBSlowLogsResponse::DataHasBeenSet() const { return m_dataHasBeenSet; } double DescribeDBSlowLogsResponse::GetLockTimeSum() const { return m_lockTimeSum; } bool DescribeDBSlowLogsResponse::LockTimeSumHasBeenSet() const { return m_lockTimeSumHasBeenSet; } int64_t DescribeDBSlowLogsResponse::GetQueryCount() const { return m_queryCount; } bool DescribeDBSlowLogsResponse::QueryCountHasBeenSet() const { return m_queryCountHasBeenSet; } int64_t DescribeDBSlowLogsResponse::GetTotal() const { return m_total; } bool DescribeDBSlowLogsResponse::TotalHasBeenSet() const { return m_totalHasBeenSet; } double DescribeDBSlowLogsResponse::GetQueryTimeSum() const { return m_queryTimeSum; } bool DescribeDBSlowLogsResponse::QueryTimeSumHasBeenSet() const { return m_queryTimeSumHasBeenSet; }
30.805405
132
0.670644
[ "object", "vector", "model" ]
20e813c4a1d0569a245db55b501aff1af4634e6e
3,855
cpp
C++
eip/src/v2/model/ProfileResp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
eip/src/v2/model/ProfileResp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
eip/src/v2/model/ProfileResp.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/eip/v2/model/ProfileResp.h" namespace HuaweiCloud { namespace Sdk { namespace Eip { namespace V2 { namespace Model { ProfileResp::ProfileResp() { orderId_ = ""; orderIdIsSet_ = false; productId_ = ""; productIdIsSet_ = false; regionId_ = ""; regionIdIsSet_ = false; userId_ = ""; userIdIsSet_ = false; } ProfileResp::~ProfileResp() = default; void ProfileResp::validate() { } web::json::value ProfileResp::toJson() const { web::json::value val = web::json::value::object(); if(orderIdIsSet_) { val[utility::conversions::to_string_t("order_id")] = ModelBase::toJson(orderId_); } if(productIdIsSet_) { val[utility::conversions::to_string_t("product_id")] = ModelBase::toJson(productId_); } if(regionIdIsSet_) { val[utility::conversions::to_string_t("region_id")] = ModelBase::toJson(regionId_); } if(userIdIsSet_) { val[utility::conversions::to_string_t("user_id")] = ModelBase::toJson(userId_); } return val; } bool ProfileResp::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("order_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("order_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOrderId(refVal); } } if(val.has_field(utility::conversions::to_string_t("product_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("product_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setProductId(refVal); } } if(val.has_field(utility::conversions::to_string_t("region_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("region_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setRegionId(refVal); } } if(val.has_field(utility::conversions::to_string_t("user_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("user_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setUserId(refVal); } } return ok; } std::string ProfileResp::getOrderId() const { return orderId_; } void ProfileResp::setOrderId(const std::string& value) { orderId_ = value; orderIdIsSet_ = true; } bool ProfileResp::orderIdIsSet() const { return orderIdIsSet_; } void ProfileResp::unsetorderId() { orderIdIsSet_ = false; } std::string ProfileResp::getProductId() const { return productId_; } void ProfileResp::setProductId(const std::string& value) { productId_ = value; productIdIsSet_ = true; } bool ProfileResp::productIdIsSet() const { return productIdIsSet_; } void ProfileResp::unsetproductId() { productIdIsSet_ = false; } std::string ProfileResp::getRegionId() const { return regionId_; } void ProfileResp::setRegionId(const std::string& value) { regionId_ = value; regionIdIsSet_ = true; } bool ProfileResp::regionIdIsSet() const { return regionIdIsSet_; } void ProfileResp::unsetregionId() { regionIdIsSet_ = false; } std::string ProfileResp::getUserId() const { return userId_; } void ProfileResp::setUserId(const std::string& value) { userId_ = value; userIdIsSet_ = true; } bool ProfileResp::userIdIsSet() const { return userIdIsSet_; } void ProfileResp::unsetuserId() { userIdIsSet_ = false; } } } } } }
20.614973
101
0.639689
[ "object", "model" ]
20e99a58997209cf08e3b9cce65535554aba7053
1,461
cpp
C++
test/src/test_infix_ostream_iterator.cpp
steinwurf/tables
fd6fa3a4dc7949621ca4e33ee8d3a63a08100d64
[ "BSD-3-Clause" ]
3
2017-12-09T20:49:43.000Z
2020-06-27T23:25:04.000Z
test/src/test_infix_ostream_iterator.cpp
steinwurf/tables
fd6fa3a4dc7949621ca4e33ee8d3a63a08100d64
[ "BSD-3-Clause" ]
3
2015-04-11T01:26:23.000Z
2015-05-26T19:01:23.000Z
test/src/test_infix_ostream_iterator.cpp
steinwurf/tables
fd6fa3a4dc7949621ca4e33ee8d3a63a08100d64
[ "BSD-3-Clause" ]
4
2015-05-06T06:16:51.000Z
2020-05-13T01:22:58.000Z
// Copyright (c) 2014 Steinwurf ApS // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #include <algorithm> #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> #include <tables/infix_ostream_iterator.hpp> template <typename T> void test_infix_ostream_iterator(std::vector<T> values, const std::string& delimiter, const std::string& expected_result) { std::stringstream ss; tables::infix_ostream_iterator<T> printer(ss, delimiter.c_str()); std::copy(values.begin(), values.end(), printer); EXPECT_EQ(expected_result, ss.str()); } TEST(TestInfix, test_infix_ostream_iterator) { static const uint32_t a_ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<uint32_t> v_ints(a_ints, a_ints + sizeof(a_ints) / sizeof(a_ints[0])); static const std::string a_strings[] = {"s1", "s2", "s3", "s4", "s5", "s6", "s7"}; std::vector<std::string> v_strings( a_strings, a_strings + sizeof(a_strings) / sizeof(a_strings[0])); test_infix_ostream_iterator(v_ints, ",", "1,2,3,4,5,6,7,8,9"); test_infix_ostream_iterator(v_ints, "¤", "1¤2¤3¤4¤5¤6¤7¤8¤9"); test_infix_ostream_iterator(v_strings, ",", "s1,s2,s3,s4,s5,s6,s7"); test_infix_ostream_iterator(v_strings, "¤", "s1¤s2¤s3¤s4¤s5¤s6¤s7"); }
33.976744
78
0.616701
[ "vector" ]
20ebb4ec2336b8cfc81f7718337106529ee2d7c5
1,130
cpp
C++
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Exercise_2019/05_noiseTestGenerator.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
C++/C++ Fundamentals Sept 2019/04. Exercise/codecpp/src/NoiseTestGenerator.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
C++/C++ Fundamentals Sept 2019/04. Exercise/codecpp/src/NoiseTestGenerator.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include<cstdlib> #include <ctime> #include<cctype> using namespace std; char generateRandomSymbol() { int randomNumber = rand(); char symbol = randomNumber % 255; return symbol; } void print(const vector<char> &randomText) { int size = (int) randomText.size(); for (int i = 0; i < size; ++i) { char currentChar = randomText[i]; if (isprint(currentChar)) { cout << currentChar; } } cout << endl; } int main() { srand(time(NULL)); int digitCounter = 0; vector<char> randomText; while (true) { char symbol = generateRandomSymbol(); if (symbol == '.' && digitCounter > 0) { randomText.push_back(symbol); break; } if (symbol != '.') { randomText.push_back(symbol); if (isdigit(symbol)) { digitCounter++; if (digitCounter >= 18) { randomText.push_back('.'); break; } } } } print(randomText); return 0; }
19.152542
48
0.50708
[ "vector" ]
20f24aac0d6bbc10491d418df7a04b102e5135d0
2,866
cc
C++
Sources/Hilbert/doubled_hilbert.cc
vigsterkr/netket
1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a
[ "Apache-2.0" ]
null
null
null
Sources/Hilbert/doubled_hilbert.cc
vigsterkr/netket
1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a
[ "Apache-2.0" ]
null
null
null
Sources/Hilbert/doubled_hilbert.cc
vigsterkr/netket
1e187ae2b9d2aa3f2e53b09fe743e50763d04c9a
[ "Apache-2.0" ]
null
null
null
// // Created by Filippo Vicentini on 12/11/2019. // #include "doubled_hilbert.hpp" namespace netket { DoubledHilbert::DoubledHilbert( std::shared_ptr<const AbstractHilbert> hilbert, std::unique_ptr<const AbstractGraph> doubled_graph) : hilbert_physical_(std::move(hilbert)), graph_doubled_(std::move(doubled_graph)) { size_ = graph_doubled_->Size(); } bool DoubledHilbert::IsDiscrete() const { return hilbert_physical_->IsDiscrete(); } int DoubledHilbert::LocalSize() const { return hilbert_physical_->LocalSize(); } int DoubledHilbert::Size() const { return size_; // it is 2 times the number of physical sites } int DoubledHilbert::SizePhysical() const { return hilbert_physical_->Size(); } std::vector<double> DoubledHilbert::LocalStates() const { return hilbert_physical_->LocalStates(); } void DoubledHilbert::RandomVals(Eigen::Ref<Eigen::VectorXd> state, netket::default_random_engine& rgen) const { assert(state.size() == size_); auto N = SizePhysical(); hilbert_physical_->RandomVals(state.head(N), rgen); hilbert_physical_->RandomVals(state.tail(N), rgen); } void DoubledHilbert::UpdateConf(Eigen::Ref<Eigen::VectorXd> v, nonstd::span<const int> tochange, nonstd::span<const double> newconf) const { assert(v.size() == size_); int i = 0; for (auto sf : tochange) { v(sf) = newconf[i]; i++; } } void DoubledHilbert::RandomValsRows(Eigen::Ref<Eigen::VectorXd> state, netket::default_random_engine& rgen) const { assert(state.size() == size_); hilbert_physical_->RandomVals(state.head(SizePhysical()), rgen); } void DoubledHilbert::RandomValsCols(Eigen::Ref<Eigen::VectorXd> state, netket::default_random_engine& rgen) const { assert(state.size() == size_); hilbert_physical_->RandomVals(state.tail(SizePhysical()), rgen); } void DoubledHilbert::RandomValsPhysical( Eigen::Ref<Eigen::VectorXd> state, netket::default_random_engine& rgen) const { assert(state.size() == size_); hilbert_physical_->RandomVals(state, rgen); } void DoubledHilbert::UpdateConfPhysical( Eigen::Ref<Eigen::VectorXd> v, nonstd::span<const int> tochange, nonstd::span<const double> newconf) const { hilbert_physical_->UpdateConf(v, tochange, newconf); } const AbstractHilbert& DoubledHilbert::GetHilbertPhysical() const noexcept { return *hilbert_physical_; } std::shared_ptr<const AbstractHilbert> DoubledHilbert::GetHilbertPhysicalShared() const { return hilbert_physical_; } const AbstractGraph& DoubledHilbert::GetGraphPhysical() const noexcept { return hilbert_physical_->GetGraph(); } const AbstractGraph& DoubledHilbert::GetGraph() const noexcept { return *graph_doubled_; } } // namespace netket
28.949495
80
0.696441
[ "vector" ]
20f7e1efe480bdbb15f6b4aab3514a573bc8ca8c
11,070
cpp
C++
moveit_ros/hybrid_planning/test/test_basic_integration.cpp
ruelj2/moveit2
c5cc837597f85e01a262c66b7ef66e80c6746d5d
[ "BSD-3-Clause" ]
null
null
null
moveit_ros/hybrid_planning/test/test_basic_integration.cpp
ruelj2/moveit2
c5cc837597f85e01a262c66b7ef66e80c6746d5d
[ "BSD-3-Clause" ]
2
2022-01-11T13:47:07.000Z
2022-03-31T10:44:25.000Z
moveit_ros/hybrid_planning/test/test_basic_integration.cpp
ruelj2/moveit2
c5cc837597f85e01a262c66b7ef66e80c6746d5d
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2022, PickNik Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * 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 PickNik Inc. 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. *********************************************************************/ /* Author: Andy Zelenak Desc: Launch hybrid planning and test basic functionality */ #include <gtest/gtest.h> #include <moveit/kinematic_constraints/utils.h> #include <moveit/planning_scene_monitor/planning_scene_monitor.h> #include <moveit/robot_state/conversions.h> #include <rclcpp/rclcpp.hpp> #include <rclcpp_action/rclcpp_action.hpp> #include <tf2_ros/buffer.h> #include <moveit_msgs/action/hybrid_planner.hpp> #include <moveit_msgs/msg/display_robot_state.hpp> #include <moveit_msgs/msg/motion_plan_response.hpp> namespace moveit_hybrid_planning { using namespace std::chrono_literals; class HybridPlanningFixture : public ::testing::Test { public: HybridPlanningFixture() : node_(std::make_shared<rclcpp::Node>("hybrid_planning_testing")) { action_successful_ = false; action_aborted_ = false; action_complete_ = false; executor_.add_node(node_); std::string hybrid_planning_action_name = ""; node_->declare_parameter("hybrid_planning_action_name", ""); if (node_->has_parameter("hybrid_planning_action_name")) { node_->get_parameter<std::string>("hybrid_planning_action_name", hybrid_planning_action_name); } else { RCLCPP_ERROR(node_->get_logger(), "hybrid_planning_action_name parameter was not defined"); std::exit(EXIT_FAILURE); } hp_action_client_ = rclcpp_action::create_client<moveit_msgs::action::HybridPlanner>(node_, hybrid_planning_action_name); // Add new collision object as soon as global trajectory is available. global_solution_subscriber_ = node_->create_subscription<moveit_msgs::msg::MotionPlanResponse>( "global_trajectory", rclcpp::SystemDefaultsQoS(), [this](const moveit_msgs::msg::MotionPlanResponse::SharedPtr /* unused */) {}); RCLCPP_INFO(node_->get_logger(), "Initialize Planning Scene Monitor"); tf_buffer_ = std::make_shared<tf2_ros::Buffer>(node_->get_clock()); planning_scene_monitor_ = std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(node_, "robot_description", "planning_scene_monitor"); if (!planning_scene_monitor_->getPlanningScene()) { RCLCPP_ERROR(node_->get_logger(), "The planning scene was not retrieved!"); std::exit(EXIT_FAILURE); } else { planning_scene_monitor_->startStateMonitor(); planning_scene_monitor_->setPlanningScenePublishingFrequency(100); planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE, "/planning_scene"); planning_scene_monitor_->startSceneMonitor(); } if (!planning_scene_monitor_->waitForCurrentRobotState(node_->now(), 5)) { RCLCPP_ERROR(node_->get_logger(), "Timeout when waiting for /joint_states updates. Is the robot running?"); std::exit(EXIT_FAILURE); } if (!hp_action_client_->wait_for_action_server(20s)) { RCLCPP_ERROR(node_->get_logger(), "Hybrid planning action server not available after waiting"); std::exit(EXIT_FAILURE); } // Setup motion planning goal taken from motion_planning_api tutorial const std::string planning_group = "panda_arm"; robot_model_loader::RobotModelLoader robot_model_loader(node_, "robot_description"); const moveit::core::RobotModelPtr& robot_model = robot_model_loader.getModel(); // Create a RobotState and JointModelGroup const auto robot_state = std::make_shared<moveit::core::RobotState>(robot_model); const moveit::core::JointModelGroup* joint_model_group = robot_state->getJointModelGroup(planning_group); // Configure a valid robot state robot_state->setToDefaultValues(joint_model_group, "ready"); robot_state->update(); // Lock the planning scene as briefly as possible { planning_scene_monitor::LockedPlanningSceneRW locked_planning_scene(planning_scene_monitor_); locked_planning_scene->setCurrentState(*robot_state); } const moveit::core::RobotState goal_state([robot_model, joint_model_group]() { moveit::core::RobotState goal_state(robot_model); std::vector<double> joint_values = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.571, 0.785 }; goal_state.setJointGroupPositions(joint_model_group, joint_values); return goal_state; }()); // Create desired motion goal const moveit_msgs::msg::MotionPlanRequest goal_motion_request( [robot_state, planning_group, goal_state, joint_model_group]() { moveit_msgs::msg::MotionPlanRequest goal_motion_request; moveit::core::robotStateToRobotStateMsg(*robot_state, goal_motion_request.start_state); goal_motion_request.group_name = planning_group; goal_motion_request.num_planning_attempts = 10; goal_motion_request.max_velocity_scaling_factor = 0.1; goal_motion_request.max_acceleration_scaling_factor = 0.1; goal_motion_request.allowed_planning_time = 2.0; goal_motion_request.planner_id = "ompl"; goal_motion_request.pipeline_id = "ompl"; goal_motion_request.goal_constraints.resize(1); goal_motion_request.goal_constraints[0] = kinematic_constraints::constructGoalConstraints(goal_state, joint_model_group); return goal_motion_request; }()); // Create Hybrid Planning action request moveit_msgs::msg::MotionSequenceItem sequence_item; sequence_item.req = goal_motion_request; sequence_item.blend_radius = 0.0; // Single goal moveit_msgs::msg::MotionSequenceRequest sequence_request; sequence_request.items.push_back(sequence_item); goal_action_request_ = moveit_msgs::action::HybridPlanner::Goal(); goal_action_request_.planning_group = planning_group; goal_action_request_.motion_sequence = sequence_request; send_goal_options_ = rclcpp_action::Client<moveit_msgs::action::HybridPlanner>::SendGoalOptions(); send_goal_options_.result_callback = [this](const rclcpp_action::ClientGoalHandle<moveit_msgs::action::HybridPlanner>::WrappedResult& result) { switch (result.code) { case rclcpp_action::ResultCode::SUCCEEDED: action_successful_ = true; RCLCPP_INFO(node_->get_logger(), "Hybrid planning goal succeeded"); break; case rclcpp_action::ResultCode::ABORTED: action_aborted_ = true; RCLCPP_ERROR(node_->get_logger(), "Hybrid planning goal was aborted"); break; case rclcpp_action::ResultCode::CANCELED: RCLCPP_ERROR(node_->get_logger(), "Hybrid planning goal was canceled"); break; default: RCLCPP_ERROR(node_->get_logger(), "Unknown hybrid planning result code"); break; } action_complete_ = true; return; }; send_goal_options_.feedback_callback = [this](rclcpp_action::ClientGoalHandle<moveit_msgs::action::HybridPlanner>::SharedPtr /*unused*/, const std::shared_ptr<const moveit_msgs::action::HybridPlanner::Feedback> feedback) { RCLCPP_INFO(node_->get_logger(), feedback->feedback.c_str()); }; } rclcpp::executors::MultiThreadedExecutor executor_; protected: rclcpp::Node::SharedPtr node_; rclcpp_action::Client<moveit_msgs::action::HybridPlanner>::SharedPtr hp_action_client_; rclcpp::Subscription<moveit_msgs::msg::MotionPlanResponse>::SharedPtr global_solution_subscriber_; std::shared_ptr<tf2_ros::Buffer> tf_buffer_; planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor_; std::atomic_bool action_successful_; std::atomic_bool action_complete_; std::atomic_bool action_aborted_; // Action request moveit_msgs::action::HybridPlanner::Goal goal_action_request_; rclcpp_action::Client<moveit_msgs::action::HybridPlanner>::SendGoalOptions send_goal_options_; }; // class HybridPlanningFixture // Make a hybrid planning request and verify it completes TEST_F(HybridPlanningFixture, ActionCompletion) { std::thread run_thread([this]() { // Send the goal auto goal_handle_future = hp_action_client_->async_send_goal(goal_action_request_, send_goal_options_); }); rclcpp::Rate rate(10); while (!action_complete_) { executor_.spin_once(); rate.sleep(); } run_thread.join(); ASSERT_TRUE(action_successful_); } // Make a hybrid planning request then abort it TEST_F(HybridPlanningFixture, ActionAbortion) { std::thread run_thread([this]() { // Send the goal auto goal_handle_future = hp_action_client_->async_send_goal(goal_action_request_, send_goal_options_); // Cancel the goal hp_action_client_->async_cancel_all_goals(); }); rclcpp::Rate rate(10); while (!action_complete_) { executor_.spin_once(); rate.sleep(); } run_thread.join(); ASSERT_FALSE(action_successful_); ASSERT_TRUE(action_aborted_); } } // namespace moveit_hybrid_planning int main(int argc, char** argv) { rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); rclcpp::shutdown(); return ret; }
41.152416
120
0.710388
[ "object", "vector" ]
20ff4ad9fee5343e95d3c11f4fac405608ca0b96
772
hpp
C++
video_file_hdl/include/video_file_hdl.hpp
majorx234/qt_videocam_hough
bb8c5ac8045a1d312e3428705967960496688846
[ "BSD-2-Clause" ]
null
null
null
video_file_hdl/include/video_file_hdl.hpp
majorx234/qt_videocam_hough
bb8c5ac8045a1d312e3428705967960496688846
[ "BSD-2-Clause" ]
null
null
null
video_file_hdl/include/video_file_hdl.hpp
majorx234/qt_videocam_hough
bb8c5ac8045a1d312e3428705967960496688846
[ "BSD-2-Clause" ]
null
null
null
#ifndef VIDEO_FILE_HDL_HPP #define VIDEO_FILE_HDL_HPP #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" class VideoFile_hdl{ int imagecount; std::vector<cv::Mat>::iterator frame_iter; cv::Size videoSize; //std::string path; std::vector<cv::Mat> video_vec; bool videoLoadedBool; public: VideoFile_hdl(); VideoFile_hdl(cv::Size newVideoSize); ~VideoFile_hdl(); int saveVideoRaw(std::string filename); int saveVideo(std::string filename); int loadVideo(std::string filename); int loadVideo(std::string filename,int num_frames); int loadVideoRaw(std::string filename); int clear(); int addFrame(cv::Mat frame); int getFrame(cv::Mat &frame); int get_size(); int videoStep(); }; #endif // VIDEO_FILE_HDL_HPP
20.864865
53
0.722798
[ "vector" ]
1f0266b1448065183639fb6d7a5b909087af6b39
57,343
cpp
C++
mediaMicroservices/gen-cpp/MovieInfoService.cpp
rodrigo-bruno/DeathStarBench
c9ce09aaf7c1298a7c88efacd1010a71db0fa59d
[ "Apache-2.0" ]
364
2019-04-28T01:45:37.000Z
2022-03-31T15:08:03.000Z
mediaMicroservices/gen-cpp/MovieInfoService.cpp
rodrigo-bruno/DeathStarBench
c9ce09aaf7c1298a7c88efacd1010a71db0fa59d
[ "Apache-2.0" ]
111
2019-04-15T11:08:49.000Z
2022-03-31T17:39:16.000Z
mediaMicroservices/gen-cpp/MovieInfoService.cpp
rodrigo-bruno/DeathStarBench
c9ce09aaf7c1298a7c88efacd1010a71db0fa59d
[ "Apache-2.0" ]
229
2019-05-14T08:55:57.000Z
2022-03-31T03:14:55.000Z
/** * Autogenerated by Thrift Compiler (0.12.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "MovieInfoService.h" namespace media_service { MovieInfoService_WriteMovieInfo_args::~MovieInfoService_WriteMovieInfo_args() throw() { } uint32_t MovieInfoService_WriteMovieInfo_args::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->req_id); this->__isset.req_id = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->movie_id); this->__isset.movie_id = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->title); this->__isset.title = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->casts.clear(); uint32_t _size334; ::apache::thrift::protocol::TType _etype337; xfer += iprot->readListBegin(_etype337, _size334); this->casts.resize(_size334); uint32_t _i338; for (_i338 = 0; _i338 < _size334; ++_i338) { xfer += this->casts[_i338].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.casts = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->plot_id); this->__isset.plot_id = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->thumbnail_ids.clear(); uint32_t _size339; ::apache::thrift::protocol::TType _etype342; xfer += iprot->readListBegin(_etype342, _size339); this->thumbnail_ids.resize(_size339); uint32_t _i343; for (_i343 = 0; _i343 < _size339; ++_i343) { xfer += iprot->readString(this->thumbnail_ids[_i343]); } xfer += iprot->readListEnd(); } this->__isset.thumbnail_ids = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->photo_ids.clear(); uint32_t _size344; ::apache::thrift::protocol::TType _etype347; xfer += iprot->readListBegin(_etype347, _size344); this->photo_ids.resize(_size344); uint32_t _i348; for (_i348 = 0; _i348 < _size344; ++_i348) { xfer += iprot->readString(this->photo_ids[_i348]); } xfer += iprot->readListEnd(); } this->__isset.photo_ids = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->video_ids.clear(); uint32_t _size349; ::apache::thrift::protocol::TType _etype352; xfer += iprot->readListBegin(_etype352, _size349); this->video_ids.resize(_size349); uint32_t _i353; for (_i353 = 0; _i353 < _size349; ++_i353) { xfer += iprot->readString(this->video_ids[_i353]); } xfer += iprot->readListEnd(); } this->__isset.video_ids = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->avg_rating); this->__isset.avg_rating = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->num_rating); this->__isset.num_rating = true; } else { xfer += iprot->skip(ftype); } break; case 11: if (ftype == ::apache::thrift::protocol::T_MAP) { { this->carrier.clear(); uint32_t _size354; ::apache::thrift::protocol::TType _ktype355; ::apache::thrift::protocol::TType _vtype356; xfer += iprot->readMapBegin(_ktype355, _vtype356, _size354); uint32_t _i358; for (_i358 = 0; _i358 < _size354; ++_i358) { std::string _key359; xfer += iprot->readString(_key359); std::string& _val360 = this->carrier[_key359]; xfer += iprot->readString(_val360); } xfer += iprot->readMapEnd(); } this->__isset.carrier = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_WriteMovieInfo_args::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_WriteMovieInfo_args"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->req_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->movie_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("title", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->title); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("casts", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->casts.size())); std::vector<Cast> ::const_iterator _iter361; for (_iter361 = this->casts.begin(); _iter361 != this->casts.end(); ++_iter361) { xfer += (*_iter361).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("plot_id", ::apache::thrift::protocol::T_I64, 5); xfer += oprot->writeI64(this->plot_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("thumbnail_ids", ::apache::thrift::protocol::T_LIST, 6); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->thumbnail_ids.size())); std::vector<std::string> ::const_iterator _iter362; for (_iter362 = this->thumbnail_ids.begin(); _iter362 != this->thumbnail_ids.end(); ++_iter362) { xfer += oprot->writeString((*_iter362)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("photo_ids", ::apache::thrift::protocol::T_LIST, 7); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->photo_ids.size())); std::vector<std::string> ::const_iterator _iter363; for (_iter363 = this->photo_ids.begin(); _iter363 != this->photo_ids.end(); ++_iter363) { xfer += oprot->writeString((*_iter363)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("video_ids", ::apache::thrift::protocol::T_LIST, 8); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->video_ids.size())); std::vector<std::string> ::const_iterator _iter364; for (_iter364 = this->video_ids.begin(); _iter364 != this->video_ids.end(); ++_iter364) { xfer += oprot->writeString((*_iter364)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("avg_rating", ::apache::thrift::protocol::T_STRING, 9); xfer += oprot->writeString(this->avg_rating); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("num_rating", ::apache::thrift::protocol::T_I32, 10); xfer += oprot->writeI32(this->num_rating); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 11); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->carrier.size())); std::map<std::string, std::string> ::const_iterator _iter365; for (_iter365 = this->carrier.begin(); _iter365 != this->carrier.end(); ++_iter365) { xfer += oprot->writeString(_iter365->first); xfer += oprot->writeString(_iter365->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_WriteMovieInfo_pargs::~MovieInfoService_WriteMovieInfo_pargs() throw() { } uint32_t MovieInfoService_WriteMovieInfo_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_WriteMovieInfo_pargs"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64((*(this->req_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString((*(this->movie_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("title", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString((*(this->title))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("casts", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>((*(this->casts)).size())); std::vector<Cast> ::const_iterator _iter366; for (_iter366 = (*(this->casts)).begin(); _iter366 != (*(this->casts)).end(); ++_iter366) { xfer += (*_iter366).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("plot_id", ::apache::thrift::protocol::T_I64, 5); xfer += oprot->writeI64((*(this->plot_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("thumbnail_ids", ::apache::thrift::protocol::T_LIST, 6); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->thumbnail_ids)).size())); std::vector<std::string> ::const_iterator _iter367; for (_iter367 = (*(this->thumbnail_ids)).begin(); _iter367 != (*(this->thumbnail_ids)).end(); ++_iter367) { xfer += oprot->writeString((*_iter367)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("photo_ids", ::apache::thrift::protocol::T_LIST, 7); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->photo_ids)).size())); std::vector<std::string> ::const_iterator _iter368; for (_iter368 = (*(this->photo_ids)).begin(); _iter368 != (*(this->photo_ids)).end(); ++_iter368) { xfer += oprot->writeString((*_iter368)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("video_ids", ::apache::thrift::protocol::T_LIST, 8); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->video_ids)).size())); std::vector<std::string> ::const_iterator _iter369; for (_iter369 = (*(this->video_ids)).begin(); _iter369 != (*(this->video_ids)).end(); ++_iter369) { xfer += oprot->writeString((*_iter369)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("avg_rating", ::apache::thrift::protocol::T_STRING, 9); xfer += oprot->writeString((*(this->avg_rating))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("num_rating", ::apache::thrift::protocol::T_I32, 10); xfer += oprot->writeI32((*(this->num_rating))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 11); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->carrier)).size())); std::map<std::string, std::string> ::const_iterator _iter370; for (_iter370 = (*(this->carrier)).begin(); _iter370 != (*(this->carrier)).end(); ++_iter370) { xfer += oprot->writeString(_iter370->first); xfer += oprot->writeString(_iter370->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_WriteMovieInfo_result::~MovieInfoService_WriteMovieInfo_result() throw() { } uint32_t MovieInfoService_WriteMovieInfo_result::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_WriteMovieInfo_result::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MovieInfoService_WriteMovieInfo_result"); if (this->__isset.se) { xfer += oprot->writeFieldBegin("se", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->se.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_WriteMovieInfo_presult::~MovieInfoService_WriteMovieInfo_presult() throw() { } uint32_t MovieInfoService_WriteMovieInfo_presult::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } MovieInfoService_ReadMovieInfo_args::~MovieInfoService_ReadMovieInfo_args() throw() { } uint32_t MovieInfoService_ReadMovieInfo_args::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->req_id); this->__isset.req_id = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->movie_id); this->__isset.movie_id = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_MAP) { { this->carrier.clear(); uint32_t _size371; ::apache::thrift::protocol::TType _ktype372; ::apache::thrift::protocol::TType _vtype373; xfer += iprot->readMapBegin(_ktype372, _vtype373, _size371); uint32_t _i375; for (_i375 = 0; _i375 < _size371; ++_i375) { std::string _key376; xfer += iprot->readString(_key376); std::string& _val377 = this->carrier[_key376]; xfer += iprot->readString(_val377); } xfer += iprot->readMapEnd(); } this->__isset.carrier = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_ReadMovieInfo_args::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_ReadMovieInfo_args"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->req_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->movie_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 3); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->carrier.size())); std::map<std::string, std::string> ::const_iterator _iter378; for (_iter378 = this->carrier.begin(); _iter378 != this->carrier.end(); ++_iter378) { xfer += oprot->writeString(_iter378->first); xfer += oprot->writeString(_iter378->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_ReadMovieInfo_pargs::~MovieInfoService_ReadMovieInfo_pargs() throw() { } uint32_t MovieInfoService_ReadMovieInfo_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_ReadMovieInfo_pargs"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64((*(this->req_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString((*(this->movie_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 3); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->carrier)).size())); std::map<std::string, std::string> ::const_iterator _iter379; for (_iter379 = (*(this->carrier)).begin(); _iter379 != (*(this->carrier)).end(); ++_iter379) { xfer += oprot->writeString(_iter379->first); xfer += oprot->writeString(_iter379->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_ReadMovieInfo_result::~MovieInfoService_ReadMovieInfo_result() throw() { } uint32_t MovieInfoService_ReadMovieInfo_result::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 0: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->success.read(iprot); this->__isset.success = true; } else { xfer += iprot->skip(ftype); } break; case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_ReadMovieInfo_result::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MovieInfoService_ReadMovieInfo_result"); if (this->__isset.success) { xfer += oprot->writeFieldBegin("success", ::apache::thrift::protocol::T_STRUCT, 0); xfer += this->success.write(oprot); xfer += oprot->writeFieldEnd(); } else if (this->__isset.se) { xfer += oprot->writeFieldBegin("se", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->se.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_ReadMovieInfo_presult::~MovieInfoService_ReadMovieInfo_presult() throw() { } uint32_t MovieInfoService_ReadMovieInfo_presult::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 0: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += (*(this->success)).read(iprot); this->__isset.success = true; } else { xfer += iprot->skip(ftype); } break; case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } MovieInfoService_UpdateRating_args::~MovieInfoService_UpdateRating_args() throw() { } uint32_t MovieInfoService_UpdateRating_args::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->req_id); this->__isset.req_id = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->movie_id); this->__isset.movie_id = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->sum_uncommitted_rating); this->__isset.sum_uncommitted_rating = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->num_uncommitted_rating); this->__isset.num_uncommitted_rating = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_MAP) { { this->carrier.clear(); uint32_t _size380; ::apache::thrift::protocol::TType _ktype381; ::apache::thrift::protocol::TType _vtype382; xfer += iprot->readMapBegin(_ktype381, _vtype382, _size380); uint32_t _i384; for (_i384 = 0; _i384 < _size380; ++_i384) { std::string _key385; xfer += iprot->readString(_key385); std::string& _val386 = this->carrier[_key385]; xfer += iprot->readString(_val386); } xfer += iprot->readMapEnd(); } this->__isset.carrier = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_UpdateRating_args::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_UpdateRating_args"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->req_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->movie_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("sum_uncommitted_rating", ::apache::thrift::protocol::T_I32, 3); xfer += oprot->writeI32(this->sum_uncommitted_rating); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("num_uncommitted_rating", ::apache::thrift::protocol::T_I32, 4); xfer += oprot->writeI32(this->num_uncommitted_rating); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 5); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->carrier.size())); std::map<std::string, std::string> ::const_iterator _iter387; for (_iter387 = this->carrier.begin(); _iter387 != this->carrier.end(); ++_iter387) { xfer += oprot->writeString(_iter387->first); xfer += oprot->writeString(_iter387->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_UpdateRating_pargs::~MovieInfoService_UpdateRating_pargs() throw() { } uint32_t MovieInfoService_UpdateRating_pargs::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; ::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("MovieInfoService_UpdateRating_pargs"); xfer += oprot->writeFieldBegin("req_id", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64((*(this->req_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("movie_id", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString((*(this->movie_id))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("sum_uncommitted_rating", ::apache::thrift::protocol::T_I32, 3); xfer += oprot->writeI32((*(this->sum_uncommitted_rating))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("num_uncommitted_rating", ::apache::thrift::protocol::T_I32, 4); xfer += oprot->writeI32((*(this->num_uncommitted_rating))); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("carrier", ::apache::thrift::protocol::T_MAP, 5); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>((*(this->carrier)).size())); std::map<std::string, std::string> ::const_iterator _iter388; for (_iter388 = (*(this->carrier)).begin(); _iter388 != (*(this->carrier)).end(); ++_iter388) { xfer += oprot->writeString(_iter388->first); xfer += oprot->writeString(_iter388->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_UpdateRating_result::~MovieInfoService_UpdateRating_result() throw() { } uint32_t MovieInfoService_UpdateRating_result::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t MovieInfoService_UpdateRating_result::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("MovieInfoService_UpdateRating_result"); if (this->__isset.se) { xfer += oprot->writeFieldBegin("se", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->se.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } MovieInfoService_UpdateRating_presult::~MovieInfoService_UpdateRating_presult() throw() { } uint32_t MovieInfoService_UpdateRating_presult::read(::apache::thrift::protocol::TProtocol* iprot) { ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->se.read(iprot); this->__isset.se = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } void MovieInfoServiceClient::WriteMovieInfo(const int64_t req_id, const std::string& movie_id, const std::string& title, const std::vector<Cast> & casts, const int64_t plot_id, const std::vector<std::string> & thumbnail_ids, const std::vector<std::string> & photo_ids, const std::vector<std::string> & video_ids, const std::string& avg_rating, const int32_t num_rating, const std::map<std::string, std::string> & carrier) { send_WriteMovieInfo(req_id, movie_id, title, casts, plot_id, thumbnail_ids, photo_ids, video_ids, avg_rating, num_rating, carrier); recv_WriteMovieInfo(); } void MovieInfoServiceClient::send_WriteMovieInfo(const int64_t req_id, const std::string& movie_id, const std::string& title, const std::vector<Cast> & casts, const int64_t plot_id, const std::vector<std::string> & thumbnail_ids, const std::vector<std::string> & photo_ids, const std::vector<std::string> & video_ids, const std::string& avg_rating, const int32_t num_rating, const std::map<std::string, std::string> & carrier) { int32_t cseqid = 0; oprot_->writeMessageBegin("WriteMovieInfo", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_WriteMovieInfo_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.title = &title; args.casts = &casts; args.plot_id = &plot_id; args.thumbnail_ids = &thumbnail_ids; args.photo_ids = &photo_ids; args.video_ids = &video_ids; args.avg_rating = &avg_rating; args.num_rating = &num_rating; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); } void MovieInfoServiceClient::recv_WriteMovieInfo() { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; iprot_->readMessageBegin(fname, mtype, rseqid); if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("WriteMovieInfo") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } MovieInfoService_WriteMovieInfo_presult result; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.se) { throw result.se; } return; } void MovieInfoServiceClient::ReadMovieInfo(MovieInfo& _return, const int64_t req_id, const std::string& movie_id, const std::map<std::string, std::string> & carrier) { send_ReadMovieInfo(req_id, movie_id, carrier); recv_ReadMovieInfo(_return); } void MovieInfoServiceClient::send_ReadMovieInfo(const int64_t req_id, const std::string& movie_id, const std::map<std::string, std::string> & carrier) { int32_t cseqid = 0; oprot_->writeMessageBegin("ReadMovieInfo", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_ReadMovieInfo_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); } void MovieInfoServiceClient::recv_ReadMovieInfo(MovieInfo& _return) { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; iprot_->readMessageBegin(fname, mtype, rseqid); if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("ReadMovieInfo") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } MovieInfoService_ReadMovieInfo_presult result; result.success = &_return; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.success) { // _return pointer has now been filled return; } if (result.__isset.se) { throw result.se; } throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "ReadMovieInfo failed: unknown result"); } void MovieInfoServiceClient::UpdateRating(const int64_t req_id, const std::string& movie_id, const int32_t sum_uncommitted_rating, const int32_t num_uncommitted_rating, const std::map<std::string, std::string> & carrier) { send_UpdateRating(req_id, movie_id, sum_uncommitted_rating, num_uncommitted_rating, carrier); recv_UpdateRating(); } void MovieInfoServiceClient::send_UpdateRating(const int64_t req_id, const std::string& movie_id, const int32_t sum_uncommitted_rating, const int32_t num_uncommitted_rating, const std::map<std::string, std::string> & carrier) { int32_t cseqid = 0; oprot_->writeMessageBegin("UpdateRating", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_UpdateRating_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.sum_uncommitted_rating = &sum_uncommitted_rating; args.num_uncommitted_rating = &num_uncommitted_rating; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); } void MovieInfoServiceClient::recv_UpdateRating() { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; iprot_->readMessageBegin(fname, mtype, rseqid); if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("UpdateRating") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } MovieInfoService_UpdateRating_presult result; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.se) { throw result.se; } return; } bool MovieInfoServiceProcessor::dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext) { ProcessMap::iterator pfn; pfn = processMap_.find(fname); if (pfn == processMap_.end()) { iprot->skip(::apache::thrift::protocol::T_STRUCT); iprot->readMessageEnd(); iprot->getTransport()->readEnd(); ::apache::thrift::TApplicationException x(::apache::thrift::TApplicationException::UNKNOWN_METHOD, "Invalid method name: '"+fname+"'"); oprot->writeMessageBegin(fname, ::apache::thrift::protocol::T_EXCEPTION, seqid); x.write(oprot); oprot->writeMessageEnd(); oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); return true; } (this->*(pfn->second))(seqid, iprot, oprot, callContext); return true; } void MovieInfoServiceProcessor::process_WriteMovieInfo(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext) { void* ctx = NULL; if (this->eventHandler_.get() != NULL) { ctx = this->eventHandler_->getContext("MovieInfoService.WriteMovieInfo", callContext); } ::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "MovieInfoService.WriteMovieInfo"); if (this->eventHandler_.get() != NULL) { this->eventHandler_->preRead(ctx, "MovieInfoService.WriteMovieInfo"); } MovieInfoService_WriteMovieInfo_args args; args.read(iprot); iprot->readMessageEnd(); uint32_t bytes = iprot->getTransport()->readEnd(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postRead(ctx, "MovieInfoService.WriteMovieInfo", bytes); } MovieInfoService_WriteMovieInfo_result result; try { iface_->WriteMovieInfo(args.req_id, args.movie_id, args.title, args.casts, args.plot_id, args.thumbnail_ids, args.photo_ids, args.video_ids, args.avg_rating, args.num_rating, args.carrier); } catch (ServiceException &se) { result.se = se; result.__isset.se = true; } catch (const std::exception& e) { if (this->eventHandler_.get() != NULL) { this->eventHandler_->handlerError(ctx, "MovieInfoService.WriteMovieInfo"); } ::apache::thrift::TApplicationException x(e.what()); oprot->writeMessageBegin("WriteMovieInfo", ::apache::thrift::protocol::T_EXCEPTION, seqid); x.write(oprot); oprot->writeMessageEnd(); oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); return; } if (this->eventHandler_.get() != NULL) { this->eventHandler_->preWrite(ctx, "MovieInfoService.WriteMovieInfo"); } oprot->writeMessageBegin("WriteMovieInfo", ::apache::thrift::protocol::T_REPLY, seqid); result.write(oprot); oprot->writeMessageEnd(); bytes = oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postWrite(ctx, "MovieInfoService.WriteMovieInfo", bytes); } } void MovieInfoServiceProcessor::process_ReadMovieInfo(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext) { void* ctx = NULL; if (this->eventHandler_.get() != NULL) { ctx = this->eventHandler_->getContext("MovieInfoService.ReadMovieInfo", callContext); } ::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "MovieInfoService.ReadMovieInfo"); if (this->eventHandler_.get() != NULL) { this->eventHandler_->preRead(ctx, "MovieInfoService.ReadMovieInfo"); } MovieInfoService_ReadMovieInfo_args args; args.read(iprot); iprot->readMessageEnd(); uint32_t bytes = iprot->getTransport()->readEnd(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postRead(ctx, "MovieInfoService.ReadMovieInfo", bytes); } MovieInfoService_ReadMovieInfo_result result; try { iface_->ReadMovieInfo(result.success, args.req_id, args.movie_id, args.carrier); result.__isset.success = true; } catch (ServiceException &se) { result.se = se; result.__isset.se = true; } catch (const std::exception& e) { if (this->eventHandler_.get() != NULL) { this->eventHandler_->handlerError(ctx, "MovieInfoService.ReadMovieInfo"); } ::apache::thrift::TApplicationException x(e.what()); oprot->writeMessageBegin("ReadMovieInfo", ::apache::thrift::protocol::T_EXCEPTION, seqid); x.write(oprot); oprot->writeMessageEnd(); oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); return; } if (this->eventHandler_.get() != NULL) { this->eventHandler_->preWrite(ctx, "MovieInfoService.ReadMovieInfo"); } oprot->writeMessageBegin("ReadMovieInfo", ::apache::thrift::protocol::T_REPLY, seqid); result.write(oprot); oprot->writeMessageEnd(); bytes = oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postWrite(ctx, "MovieInfoService.ReadMovieInfo", bytes); } } void MovieInfoServiceProcessor::process_UpdateRating(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext) { void* ctx = NULL; if (this->eventHandler_.get() != NULL) { ctx = this->eventHandler_->getContext("MovieInfoService.UpdateRating", callContext); } ::apache::thrift::TProcessorContextFreer freer(this->eventHandler_.get(), ctx, "MovieInfoService.UpdateRating"); if (this->eventHandler_.get() != NULL) { this->eventHandler_->preRead(ctx, "MovieInfoService.UpdateRating"); } MovieInfoService_UpdateRating_args args; args.read(iprot); iprot->readMessageEnd(); uint32_t bytes = iprot->getTransport()->readEnd(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postRead(ctx, "MovieInfoService.UpdateRating", bytes); } MovieInfoService_UpdateRating_result result; try { iface_->UpdateRating(args.req_id, args.movie_id, args.sum_uncommitted_rating, args.num_uncommitted_rating, args.carrier); } catch (ServiceException &se) { result.se = se; result.__isset.se = true; } catch (const std::exception& e) { if (this->eventHandler_.get() != NULL) { this->eventHandler_->handlerError(ctx, "MovieInfoService.UpdateRating"); } ::apache::thrift::TApplicationException x(e.what()); oprot->writeMessageBegin("UpdateRating", ::apache::thrift::protocol::T_EXCEPTION, seqid); x.write(oprot); oprot->writeMessageEnd(); oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); return; } if (this->eventHandler_.get() != NULL) { this->eventHandler_->preWrite(ctx, "MovieInfoService.UpdateRating"); } oprot->writeMessageBegin("UpdateRating", ::apache::thrift::protocol::T_REPLY, seqid); result.write(oprot); oprot->writeMessageEnd(); bytes = oprot->getTransport()->writeEnd(); oprot->getTransport()->flush(); if (this->eventHandler_.get() != NULL) { this->eventHandler_->postWrite(ctx, "MovieInfoService.UpdateRating", bytes); } } ::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::TProcessor > MovieInfoServiceProcessorFactory::getProcessor(const ::apache::thrift::TConnectionInfo& connInfo) { ::apache::thrift::ReleaseHandler< MovieInfoServiceIfFactory > cleanup(handlerFactory_); ::apache::thrift::stdcxx::shared_ptr< MovieInfoServiceIf > handler(handlerFactory_->getHandler(connInfo), cleanup); ::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::TProcessor > processor(new MovieInfoServiceProcessor(handler)); return processor; } void MovieInfoServiceConcurrentClient::WriteMovieInfo(const int64_t req_id, const std::string& movie_id, const std::string& title, const std::vector<Cast> & casts, const int64_t plot_id, const std::vector<std::string> & thumbnail_ids, const std::vector<std::string> & photo_ids, const std::vector<std::string> & video_ids, const std::string& avg_rating, const int32_t num_rating, const std::map<std::string, std::string> & carrier) { int32_t seqid = send_WriteMovieInfo(req_id, movie_id, title, casts, plot_id, thumbnail_ids, photo_ids, video_ids, avg_rating, num_rating, carrier); recv_WriteMovieInfo(seqid); } int32_t MovieInfoServiceConcurrentClient::send_WriteMovieInfo(const int64_t req_id, const std::string& movie_id, const std::string& title, const std::vector<Cast> & casts, const int64_t plot_id, const std::vector<std::string> & thumbnail_ids, const std::vector<std::string> & photo_ids, const std::vector<std::string> & video_ids, const std::string& avg_rating, const int32_t num_rating, const std::map<std::string, std::string> & carrier) { int32_t cseqid = this->sync_.generateSeqId(); ::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_); oprot_->writeMessageBegin("WriteMovieInfo", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_WriteMovieInfo_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.title = &title; args.casts = &casts; args.plot_id = &plot_id; args.thumbnail_ids = &thumbnail_ids; args.photo_ids = &photo_ids; args.video_ids = &video_ids; args.avg_rating = &avg_rating; args.num_rating = &num_rating; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); sentry.commit(); return cseqid; } void MovieInfoServiceConcurrentClient::recv_WriteMovieInfo(const int32_t seqid) { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; // the read mutex gets dropped and reacquired as part of waitForWork() // The destructor of this sentry wakes up other clients ::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid); while(true) { if(!this->sync_.getPending(fname, mtype, rseqid)) { iprot_->readMessageBegin(fname, mtype, rseqid); } if(seqid == rseqid) { if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); sentry.commit(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("WriteMovieInfo") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); // in a bad state, don't commit using ::apache::thrift::protocol::TProtocolException; throw TProtocolException(TProtocolException::INVALID_DATA); } MovieInfoService_WriteMovieInfo_presult result; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.se) { sentry.commit(); throw result.se; } sentry.commit(); return; } // seqid != rseqid this->sync_.updatePending(fname, mtype, rseqid); // this will temporarily unlock the readMutex, and let other clients get work done this->sync_.waitForWork(seqid); } // end while(true) } void MovieInfoServiceConcurrentClient::ReadMovieInfo(MovieInfo& _return, const int64_t req_id, const std::string& movie_id, const std::map<std::string, std::string> & carrier) { int32_t seqid = send_ReadMovieInfo(req_id, movie_id, carrier); recv_ReadMovieInfo(_return, seqid); } int32_t MovieInfoServiceConcurrentClient::send_ReadMovieInfo(const int64_t req_id, const std::string& movie_id, const std::map<std::string, std::string> & carrier) { int32_t cseqid = this->sync_.generateSeqId(); ::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_); oprot_->writeMessageBegin("ReadMovieInfo", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_ReadMovieInfo_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); sentry.commit(); return cseqid; } void MovieInfoServiceConcurrentClient::recv_ReadMovieInfo(MovieInfo& _return, const int32_t seqid) { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; // the read mutex gets dropped and reacquired as part of waitForWork() // The destructor of this sentry wakes up other clients ::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid); while(true) { if(!this->sync_.getPending(fname, mtype, rseqid)) { iprot_->readMessageBegin(fname, mtype, rseqid); } if(seqid == rseqid) { if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); sentry.commit(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("ReadMovieInfo") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); // in a bad state, don't commit using ::apache::thrift::protocol::TProtocolException; throw TProtocolException(TProtocolException::INVALID_DATA); } MovieInfoService_ReadMovieInfo_presult result; result.success = &_return; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.success) { // _return pointer has now been filled sentry.commit(); return; } if (result.__isset.se) { sentry.commit(); throw result.se; } // in a bad state, don't commit throw ::apache::thrift::TApplicationException(::apache::thrift::TApplicationException::MISSING_RESULT, "ReadMovieInfo failed: unknown result"); } // seqid != rseqid this->sync_.updatePending(fname, mtype, rseqid); // this will temporarily unlock the readMutex, and let other clients get work done this->sync_.waitForWork(seqid); } // end while(true) } void MovieInfoServiceConcurrentClient::UpdateRating(const int64_t req_id, const std::string& movie_id, const int32_t sum_uncommitted_rating, const int32_t num_uncommitted_rating, const std::map<std::string, std::string> & carrier) { int32_t seqid = send_UpdateRating(req_id, movie_id, sum_uncommitted_rating, num_uncommitted_rating, carrier); recv_UpdateRating(seqid); } int32_t MovieInfoServiceConcurrentClient::send_UpdateRating(const int64_t req_id, const std::string& movie_id, const int32_t sum_uncommitted_rating, const int32_t num_uncommitted_rating, const std::map<std::string, std::string> & carrier) { int32_t cseqid = this->sync_.generateSeqId(); ::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_); oprot_->writeMessageBegin("UpdateRating", ::apache::thrift::protocol::T_CALL, cseqid); MovieInfoService_UpdateRating_pargs args; args.req_id = &req_id; args.movie_id = &movie_id; args.sum_uncommitted_rating = &sum_uncommitted_rating; args.num_uncommitted_rating = &num_uncommitted_rating; args.carrier = &carrier; args.write(oprot_); oprot_->writeMessageEnd(); oprot_->getTransport()->writeEnd(); oprot_->getTransport()->flush(); sentry.commit(); return cseqid; } void MovieInfoServiceConcurrentClient::recv_UpdateRating(const int32_t seqid) { int32_t rseqid = 0; std::string fname; ::apache::thrift::protocol::TMessageType mtype; // the read mutex gets dropped and reacquired as part of waitForWork() // The destructor of this sentry wakes up other clients ::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid); while(true) { if(!this->sync_.getPending(fname, mtype, rseqid)) { iprot_->readMessageBegin(fname, mtype, rseqid); } if(seqid == rseqid) { if (mtype == ::apache::thrift::protocol::T_EXCEPTION) { ::apache::thrift::TApplicationException x; x.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); sentry.commit(); throw x; } if (mtype != ::apache::thrift::protocol::T_REPLY) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); } if (fname.compare("UpdateRating") != 0) { iprot_->skip(::apache::thrift::protocol::T_STRUCT); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); // in a bad state, don't commit using ::apache::thrift::protocol::TProtocolException; throw TProtocolException(TProtocolException::INVALID_DATA); } MovieInfoService_UpdateRating_presult result; result.read(iprot_); iprot_->readMessageEnd(); iprot_->getTransport()->readEnd(); if (result.__isset.se) { sentry.commit(); throw result.se; } sentry.commit(); return; } // seqid != rseqid this->sync_.updatePending(fname, mtype, rseqid); // this will temporarily unlock the readMutex, and let other clients get work done this->sync_.waitForWork(seqid); } // end while(true) } } // namespace
33.47519
439
0.649582
[ "vector" ]
1f1240cb9ab72e2a357a4b9feab62a107d3cdf61
3,346
cpp
C++
RenderOverlays/DebugHotKeys.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
RenderOverlays/DebugHotKeys.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
RenderOverlays/DebugHotKeys.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "DebugHotKeys.h" #include "DebuggingDisplay.h" #include "../Assets/Assets.h" #include "../ConsoleRig/Console.h" #include "../Utility/Streams/FileUtils.h" #include "../Utility/Streams/StreamDOM.h" #include "../Utility/Streams/StreamFormatter.h" #include "../Utility/PtrUtils.h" #include "../Utility/Conversion.h" namespace RenderOverlays { class HotKeyInputHandler : public DebuggingDisplay::IInputListener { public: bool OnInputEvent(const DebuggingDisplay::InputSnapshot& evnt); HotKeyInputHandler(const ::Assets::rstring& filename) : _filename(filename) {} protected: ::Assets::rstring _filename; }; class TableOfKeys { public: const std::vector<std::pair<uint32, std::string>>& GetTable() const { return _table; } const ::Assets::DepValPtr& GetDependencyValidation() const { return _validationCallback; } TableOfKeys(const char filename[]); ~TableOfKeys(); private: ::Assets::DepValPtr _validationCallback; std::vector<std::pair<uint32, std::string>> _table; }; TableOfKeys::TableOfKeys(const char filename[]) { size_t fileSize = 0; auto sourceFile = LoadFileAsMemoryBlock(filename, &fileSize); InputStreamFormatter<utf8> formatter( MemoryMappedInputStream(sourceFile.get(), PtrAdd(sourceFile.get(), fileSize))); Document<InputStreamFormatter<utf8>> doc(formatter); auto attrib = doc.FirstAttribute(); while (attrib) { auto executeString = attrib.Value(); if (!executeString.Empty()) { auto keyName = attrib.Name(); auto p = std::make_pair( RenderOverlays::DebuggingDisplay::KeyId_Make( StringSection<char>((const char*)keyName.begin(), (const char*)keyName.end())), Conversion::Convert<std::string>(executeString.AsString())); _table.push_back(p); } attrib = attrib.Next(); } _validationCallback = std::make_shared<Assets::DependencyValidation>(); Assets::RegisterFileDependency(_validationCallback, filename); } TableOfKeys::~TableOfKeys() {} bool HotKeyInputHandler::OnInputEvent(const RenderOverlays::DebuggingDisplay::InputSnapshot& evnt) { using namespace RenderOverlays::DebuggingDisplay; static KeyId ctrlKey = KeyId_Make("control"); if (evnt.IsHeld(ctrlKey)) { auto& t = Assets::GetAssetDep<TableOfKeys>(_filename.c_str()); // (todo -- cash the hash value, rather than rebuilding every time) for (auto i=t.GetTable().cbegin(); i!=t.GetTable().cend(); ++i) { if (evnt.IsPress(i->first)) { ConsoleRig::Console::GetInstance().Execute(i->second); return true; } } } return false; } std::unique_ptr<DebuggingDisplay::IInputListener> MakeHotKeysHandler(const char filename[]) { return std::make_unique<HotKeyInputHandler>(filename); } }
34.142857
143
0.621339
[ "vector" ]
1f124389110938bc579ab1f249cfda5bd4cbe6d7
650
cpp
C++
src/tools.cpp
schafer14/Unscented-Kalman-Filter
749fc7fd432f38fba159a06578ef5295a31b75bf
[ "MIT" ]
null
null
null
src/tools.cpp
schafer14/Unscented-Kalman-Filter
749fc7fd432f38fba159a06578ef5295a31b75bf
[ "MIT" ]
null
null
null
src/tools.cpp
schafer14/Unscented-Kalman-Filter
749fc7fd432f38fba159a06578ef5295a31b75bf
[ "MIT" ]
null
null
null
#include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** TODO: * Calculate the RMSE here. */ VectorXd error = VectorXd(4); error << 0, 0, 0, 0; for (int i = 0; i < estimations.size(); i++) { VectorXd residual = estimations[i] - ground_truth[i]; residual = residual.array() * residual.array(); error += residual; } error = error / estimations.size(); return error.array().sqrt(); }
19.117647
69
0.612308
[ "vector" ]
1f2ea035a4adeb4d63558d2204514840992ddcf6
3,016
cpp
C++
emitter.cpp
JulioC/Particles
267d7a058be7b36f09ff34d6b7e63739aebfd778
[ "MIT" ]
2
2020-03-30T01:53:08.000Z
2021-03-27T03:46:52.000Z
emitter.cpp
JulioC/Particles
267d7a058be7b36f09ff34d6b7e63739aebfd778
[ "MIT" ]
null
null
null
emitter.cpp
JulioC/Particles
267d7a058be7b36f09ff34d6b7e63739aebfd778
[ "MIT" ]
2
2021-03-27T03:46:53.000Z
2021-12-27T10:01:51.000Z
#include "emitter.h" #include <stddef.h> #include "particle.h" #include "renderer.h" #include "operator.h" #include "initializer.h" Emitter::Emitter(const Vector3D &pos, float itv, int max) : _position(pos), _interval(itv), _maxParticles(max), _renderer(NULL), _initializers(NULL), _operators(NULL), _particles(NULL), _elapsed(itv) { _particles = new Particle*[_maxParticles]; for(int i = 0; i < _maxParticles; i++) { _particles[i] = NULL; } _initializers = new Initializer*[MAX_INITIALIZERS]; for(int i = 0; i < MAX_INITIALIZERS; i++) { _initializers[i] = NULL; } _operators = new Operator*[MAX_OPERATORS]; for(int i = 0; i < MAX_OPERATORS; i++) { _operators[i] = NULL; } } Emitter::~Emitter() { for(int i = 0; i < _maxParticles; i++) { if(_particles[i]) { delete _particles[i]; _particles[i] = NULL; } } delete[] _particles; } void Emitter::update(float elapsed) { for(int i = 0; i < _maxParticles; i++) { if(_particles[i]) { Particle* p = _particles[i]; p->update(elapsed); applyOperators(p, elapsed); if(p->dead) { removeParticle(i); } } } _elapsed += elapsed; while(_elapsed > _interval) { createParticle(); _elapsed -= _interval; } } void Emitter::draw() { if(_renderer) { for(int i = 0; i < _maxParticles; i++) { if(_particles[i]) { _renderer->render(_particles[i]); } } } } void Emitter::renderer(Renderer *rend) { if(_renderer) { delete[] _renderer; } _renderer = rend; } bool Emitter::addInitializer(Initializer *initr) { int index; // We should store the top of the array for(index = 0; index < MAX_INITIALIZERS; index++) { if(!_initializers[index]) break; } if(index >= MAX_INITIALIZERS) return false; _initializers[index] = initr; return true; } bool Emitter::addOperator(Operator *opr) { int index; // We should store the top of the array for(index = 0; index < MAX_OPERATORS; index++) { if(!_operators[index]) break; } if(index >= MAX_OPERATORS) return false; _operators[index] = opr; return true; } bool Emitter::createParticle() { int index; for(index = 0; index < _maxParticles; index++) { if(!_particles[index]) break; } if(index >= _maxParticles) return false; Particle* particle = new Particle(_position); applyInitializers(particle); _particles[index] = particle; return true; } void Emitter::removeParticle(int index) { delete _particles[index]; _particles[index] = NULL; //@TODO: Keep track of free indexes (?) } void Emitter::applyInitializers(Particle *p) { int index; for(index = 0; index < MAX_INITIALIZERS; index++) { if(_initializers[index]) { _initializers[index]->apply(p, this); } } } void Emitter::applyOperators(Particle *p, float elapsed) { int index; for(index = 0; index < MAX_OPERATORS; index++) { if(_operators[index]) { _operators[index]->apply(p, elapsed); } } }
19.712418
59
0.631631
[ "render" ]
1f394a6c24834a0e8a423a5cd166afd766b26a5d
14,115
hpp
C++
mtlpp_ue4_ex_03/renderer/mtlpp/device.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/device.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
mtlpp_ue4_ex_03/renderer/mtlpp/device.hpp
dtonna/mtlpp_ue4_ex_03
80b945c5b5dbbf6efbe525fb371a2e77657cd595
[ "Unlicense" ]
null
null
null
/* * Copyright 2016-2017 Nikolay Aleksiev. All rights reserved. * License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE */ // Copyright Epic Games, Inc. All Rights Reserved. // Modifications for Unreal Engine #pragma once #include "declare.hpp" #include "imp_Device.hpp" #include "types.hpp" #include "pixel_format.hpp" #include "resource.hpp" #include "library.hpp" #include "validation.hpp" MTLPP_BEGIN namespace ue4 { template<> struct ITable<id<MTLDevice>, void> : public IMPTable<id<MTLDevice>, void> { ITable() : TableCache(new ITableCache) { } ITable(Class C) : IMPTable<id<MTLDevice>, void>(C) , TableCache(new ITableCache) { } ~ITable() { if (TableCache) delete TableCache; } ITableCache* TableCache; }; template<> inline ITable<MTLArgumentDescriptor*, void>* CreateIMPTable(MTLArgumentDescriptor* handle) { static ITable<MTLArgumentDescriptor*, void> Table(object_getClass(handle)); return &Table; } } namespace mtlpp { class ArgumentEncoder; class CommandQueue; class Device; class Buffer; class DepthStencilState; class Function; class Library; class Texture; class SamplerState; class RenderPipelineState; class ComputePipelineState; class Heap; class Fence; class SamplerDescriptor; class RenderPipelineColorAttachmentDescriptor; class DepthStencilDescriptor; class TextureDescriptor; class CompileOptions; class RenderPipelineDescriptor; class RenderPassDescriptor; class RenderPipelineReflection; typedef ns::AutoReleased<RenderPipelineReflection> AutoReleasedRenderPipelineReflection; class TileRenderPipelineDescriptor; class ComputePipelineDescriptor; class MTLPP_EXPORT ComputePipelineReflection; typedef ns::AutoReleased<ComputePipelineReflection> AutoReleasedComputePipelineReflection; class CommandQueueDescriptor; class HeapDescriptor; enum class FeatureSet { iOS_GPUFamily1_v1 MTLPP_AVAILABLE_IOS(8_0) = 0, iOS_GPUFamily2_v1 MTLPP_AVAILABLE_IOS(8_0) = 1, iOS_GPUFamily1_v2 MTLPP_AVAILABLE_IOS(8_0) = 2, iOS_GPUFamily2_v2 MTLPP_AVAILABLE_IOS(8_0) = 3, iOS_GPUFamily3_v1 MTLPP_AVAILABLE_IOS(9_0) = 4, iOS_GPUFamily1_v3 MTLPP_AVAILABLE_IOS(10_0) = 5, iOS_GPUFamily2_v3 MTLPP_AVAILABLE_IOS(10_0) = 6, iOS_GPUFamily3_v2 MTLPP_AVAILABLE_IOS(10_0) = 7, iOS_GPUFamily1_v4 MTLPP_AVAILABLE_IOS(11_0) = 8, iOS_GPUFamily2_v4 MTLPP_AVAILABLE_IOS(11_0) = 9, iOS_GPUFamily3_v3 MTLPP_AVAILABLE_IOS(11_0) = 10, iOS_GPUFamily4_v1 MTLPP_AVAILABLE_IOS(11_0) = 11, iOS_GPUFamily1_v5 MTLPP_AVAILABLE_IOS(12_0) = 12, iOS_GPUFamily2_v5 MTLPP_AVAILABLE_IOS(12_0) = 13, iOS_GPUFamily3_v4 MTLPP_AVAILABLE_IOS(12_0) = 14, iOS_GPUFamily4_v2 MTLPP_AVAILABLE_IOS(12_0) = 15, iOS_GPUFamily5_v1 MTLPP_AVAILABLE_IOS(12_0) = 16, macOS_GPUFamily1_v1 MTLPP_AVAILABLE_MAC(10_11) = 10000, macOS_GPUFamily1_v2 MTLPP_AVAILABLE_MAC(10_12) = 10001, macOS_ReadWriteTextureTier2 MTLPP_AVAILABLE_MAC(10_12) = 10002, macOS_GPUFamily1_v3 MTLPP_AVAILABLE_MAC(10_13) = 10003, macOS_GPUFamily1_v4 MTLPP_AVAILABLE_MAC(10_14) = 10004, macOS_GPUFamily2_v1 MTLPP_AVAILABLE_MAC(10_14) = 10005, tvOS_GPUFamily1_v1 MTLPP_AVAILABLE_TVOS(9_0) = 30000, tvOS_GPUFamily1_v2 MTLPP_AVAILABLE_TVOS(10_0) = 30001, tvOS_GPUFamily1_v3 MTLPP_AVAILABLE_TVOS(11_0) = 30002, tvOS_GPUFamily2_v1 MTLPP_AVAILABLE_TVOS(11_0) = 30003, tvOS_GPUFamily1_v4 MTLPP_AVAILABLE_TVOS(12_0) = 30004, tvOS_GPUFamily2_v2 MTLPP_AVAILABLE_TVOS(12_0) = 30005, } MTLPP_AVAILABLE(10_11, 8_0); enum PipelineOption : NSUInteger { NoPipelineOption = 0, ArgumentInfo = 1 << 0, BufferTypeInfo = 1 << 1, } MTLPP_AVAILABLE(10_11, 8_0); enum class ReadWriteTextureTier { None = 0, Tier1 = 1, Tier2 = 2, } MTLPP_AVAILABLE(10_13, 11_0); enum class ArgumentBuffersTier { Tier1 = 0, Tier2 = 1, } MTLPP_AVAILABLE(10_13, 11_0); struct SizeAndAlign { NSUInteger Size; NSUInteger Align; }; class MTLPP_EXPORT ArgumentDescriptor : public ns::Object<MTLArgumentDescriptor*> { public: ArgumentDescriptor(); ArgumentDescriptor(ns::Ownership const retain); ArgumentDescriptor(MTLArgumentDescriptor* handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<MTLArgumentDescriptor*>(handle, retain) {} DataType GetDataType() const; NSUInteger GetIndex() const; NSUInteger GetArrayLength() const; ArgumentAccess GetAccess() const; TextureType GetTextureType() const; NSUInteger GetConstantBlockAlignment() const; void SetDataType(DataType Type); void SetIndex(NSUInteger Index); void SetArrayLength(NSUInteger Len); void SetAccess(ArgumentAccess Access); void SetTextureType(TextureType Type); void SetConstantBlockAlignment(NSUInteger Align); } MTLPP_AVAILABLE(10_13, 11_0); MTLPP_CLOSURE(DeviceHandler, void, const Device&, ns::String const&); MTLPP_CLOSURE(BufferDeallocHandler, void, void* pointer, NSUInteger length); MTLPP_CLOSURE(LibraryHandler, void, const Library&, const ns::AutoReleasedError&); MTLPP_CLOSURE(RenderPipelineStateHandler, void, const RenderPipelineState&, const ns::AutoReleasedError&); MTLPP_CLOSURE(RenderPipelineStateReflectionHandler, void, const RenderPipelineState&, const AutoReleasedRenderPipelineReflection&, const ns::AutoReleasedError&); MTLPP_CLOSURE(ComputePipelineStateHandler, void, const ComputePipelineState&, const ns::AutoReleasedError&); MTLPP_CLOSURE(ComputePipelineStateReflectionHandler, void, const ComputePipelineState&, const AutoReleasedComputePipelineReflection&, const ns::AutoReleasedError&); class MTLPP_EXPORT Device : public ns::Object<ns::Protocol<id<MTLDevice>>::type> { public: Device(ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<ns::Protocol<id<MTLDevice>>::type>(retain) { } Device(ns::Protocol<id<MTLDevice>>::type handle, ns::Ownership const retain = ns::Ownership::Retain) : ns::Object<ns::Protocol<id<MTLDevice>>::type>(handle, retain) { } static ns::AutoReleased<ns::String> GetWasAddedNotification() MTLPP_AVAILABLE_MAC(10_13); static ns::AutoReleased<ns::String> GetRemovalRequestedNotification() MTLPP_AVAILABLE_MAC(10_13); static ns::AutoReleased<ns::String> GetWasRemovedNotification() MTLPP_AVAILABLE_MAC(10_13); static ns::Array<Device> CopyAllDevicesWithObserver(ns::Object<id <NSObject>>& observer, DeviceHandler handler) MTLPP_AVAILABLE_MAC(10_13); static void RemoveDeviceObserver(ns::Object<id <NSObject>> observer) MTLPP_AVAILABLE_MAC(10_13); static Device CreateSystemDefaultDevice() MTLPP_AVAILABLE(10_11, 8_0); static ns::Array<Device> CopyAllDevices() MTLPP_AVAILABLE(10_11, NA); ns::AutoReleased<ns::String> GetName() const; Size GetMaxThreadsPerThreadgroup() const MTLPP_AVAILABLE(10_11, 9_0); bool IsLowPower() const MTLPP_AVAILABLE_MAC(10_11); bool IsHeadless() const MTLPP_AVAILABLE_MAC(10_11); bool IsRemovable() const MTLPP_AVAILABLE_MAC(10_13); uint64_t GetRecommendedMaxWorkingSetSize() const MTLPP_AVAILABLE_MAC(10_12); bool IsDepth24Stencil8PixelFormatSupported() const MTLPP_AVAILABLE_MAC(10_11); uint64_t GetRegistryID() const MTLPP_AVAILABLE(10_13, 11_0); ReadWriteTextureTier GetReadWriteTextureSupport() const MTLPP_AVAILABLE(10_13, 11_0); ArgumentBuffersTier GetArgumentsBufferSupport() const MTLPP_AVAILABLE(10_13, 11_0); bool AreRasterOrderGroupsSupported() const MTLPP_AVAILABLE(10_13, 11_0); uint64_t GetCurrentAllocatedSize() const MTLPP_AVAILABLE(10_13, 11_0); CommandQueue NewCommandQueue(); CommandQueue NewCommandQueue(NSUInteger maxCommandBufferCount); SizeAndAlign HeapTextureSizeAndAlign(const TextureDescriptor& desc) MTLPP_AVAILABLE(10_13, 10_0); SizeAndAlign HeapBufferSizeAndAlign(NSUInteger length, ResourceOptions options) MTLPP_AVAILABLE(10_13, 10_0); Heap NewHeap(const HeapDescriptor& descriptor) MTLPP_AVAILABLE(10_13, 10_0); MTLPP_VALIDATED Buffer NewBuffer(NSUInteger length, ResourceOptions options); MTLPP_VALIDATED Buffer NewBuffer(const void* pointer, NSUInteger length, ResourceOptions options); MTLPP_VALIDATED Buffer NewBuffer(void* pointer, NSUInteger length, ResourceOptions options, BufferDeallocHandler deallocator); DepthStencilState NewDepthStencilState(const DepthStencilDescriptor& descriptor); MTLPP_VALIDATED Texture NewTexture(const TextureDescriptor& descriptor); MTLPP_VALIDATED Texture NewTextureWithDescriptor(const TextureDescriptor& descriptor, ns::IOSurface& iosurface, NSUInteger plane) MTLPP_AVAILABLE(10_11, NA); SamplerState NewSamplerState(const SamplerDescriptor& descriptor); Library NewDefaultLibrary(); Library NewDefaultLibraryWithBundle(const ns::Bundle& bundle, ns::AutoReleasedError* error) MTLPP_AVAILABLE(10_12, 10_0); Library NewLibrary(const ns::String& filepath, ns::AutoReleasedError* error); Library NewLibrary(dispatch_data_t data, ns::AutoReleasedError* error); Library NewLibrary(ns::String source, const CompileOptions& options, ns::AutoReleasedError* error); Library NewLibrary(ns::URL const& url, ns::AutoReleasedError* error) MTLPP_AVAILABLE(10_13, 11_0); void NewLibrary(ns::String source, const CompileOptions& options, LibraryHandler completionHandler); RenderPipelineState NewRenderPipelineState(const RenderPipelineDescriptor& descriptor, ns::AutoReleasedError* error); RenderPipelineState NewRenderPipelineState(const RenderPipelineDescriptor& descriptor, PipelineOption options, AutoReleasedRenderPipelineReflection* outReflection, ns::AutoReleasedError* error); void NewRenderPipelineState(const RenderPipelineDescriptor& descriptor, RenderPipelineStateHandler completionHandler); void NewRenderPipelineState(const RenderPipelineDescriptor& descriptor, PipelineOption options, RenderPipelineStateReflectionHandler completionHandler); ComputePipelineState NewComputePipelineState(const Function& computeFunction, ns::AutoReleasedError* error); ComputePipelineState NewComputePipelineState(const Function& computeFunction, PipelineOption options, AutoReleasedComputePipelineReflection* outReflection, ns::AutoReleasedError* error); void NewComputePipelineState(const Function& computeFunction, ComputePipelineStateHandler completionHandler); void NewComputePipelineState(const Function& computeFunction, PipelineOption options, ComputePipelineStateReflectionHandler completionHandler); ComputePipelineState NewComputePipelineState(const ComputePipelineDescriptor& descriptor, PipelineOption options, AutoReleasedComputePipelineReflection* outReflection, ns::AutoReleasedError* error); void NewComputePipelineState(const ComputePipelineDescriptor& descriptor, PipelineOption options, ComputePipelineStateReflectionHandler completionHandler) MTLPP_AVAILABLE(10_11, 9_0); Fence NewFence() const MTLPP_AVAILABLE(10_13, 10_0); bool SupportsFeatureSet(FeatureSet featureSet) const; bool SupportsTextureSampleCount(NSUInteger sampleCount) const MTLPP_AVAILABLE(10_11, 9_0); NSUInteger GetMinimumLinearTextureAlignmentForPixelFormat(PixelFormat format) const MTLPP_AVAILABLE(10_13, 11_0); NSUInteger GetMaxThreadgroupMemoryLength() const MTLPP_AVAILABLE(10_13, 11_0); bool AreProgrammableSamplePositionsSupported() const MTLPP_AVAILABLE(10_13, 11_0); void GetDefaultSamplePositions(SamplePosition* positions, NSUInteger count) MTLPP_AVAILABLE(10_13, 11_0); ArgumentEncoder NewArgumentEncoderWithArguments(ns::Array<ArgumentDescriptor> const& arguments) MTLPP_AVAILABLE(10_13, 11_0); RenderPipelineState NewRenderPipelineState(const TileRenderPipelineDescriptor& descriptor, PipelineOption options, AutoReleasedRenderPipelineReflection* outReflection, ns::AutoReleasedError* error) MTLPP_AVAILABLE_IOS(11_0); void NewRenderPipelineState(const TileRenderPipelineDescriptor& descriptor, PipelineOption options, RenderPipelineStateReflectionHandler completionHandler) MTLPP_AVAILABLE_IOS(11_0); } MTLPP_AVAILABLE(10_11, 8_0); #if MTLPP_CONFIG_VALIDATE class MTLPP_EXPORT ValidatedDevice : public ns::AutoReleased<Device> { DeviceValidationTable Validator; public: static void Register(Device& Wrapped) { DeviceValidationTable Register(Wrapped); } ValidatedDevice() : Validator(nullptr) { } ValidatedDevice(Device& Wrapped) : ns::AutoReleased<Device>(Wrapped) , Validator(Wrapped.GetAssociatedObject<DeviceValidationTable>(DeviceValidationTable::kTableAssociationKey).GetPtr()) { } MTLPP_VALIDATED Buffer NewBuffer(NSUInteger length, ResourceOptions options); MTLPP_VALIDATED Buffer NewBuffer(const void* pointer, NSUInteger length, ResourceOptions options); MTLPP_VALIDATED Buffer NewBuffer(void* pointer, NSUInteger length, ResourceOptions options, BufferDeallocHandler deallocator); MTLPP_VALIDATED Texture NewTexture(const TextureDescriptor& descriptor); MTLPP_VALIDATED Texture NewTextureWithDescriptor(const TextureDescriptor& descriptor, ns::IOSurface& iosurface, NSUInteger plane) MTLPP_AVAILABLE(10_11, NA); }; template <> class MTLPP_EXPORT Validator<Device> { public: Validator(Device& Val, bool bEnable) : Resource(Val) { if (bEnable) { Validation = ValidatedDevice(Val); } } ValidatedDevice& operator*() { assert(Validation.GetPtr() != nullptr); return Validation; } Device* operator->() { return Validation.GetPtr() == nullptr ? &Resource : &Validation; } private: Device& Resource; ValidatedDevice Validation; }; #endif } MTLPP_END
42.902736
226
0.763018
[ "object" ]
1f406896de376ffc24c7a4958b9f6f0f9441d0dc
6,358
cpp
C++
src/utility.reader.urdf/parsers/RobotElementParser.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/utility.reader.urdf/parsers/RobotElementParser.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
src/utility.reader.urdf/parsers/RobotElementParser.cpp
toeb/sine
96bcde571218f89a2b0b3cc51c19ad2b7be89c13
[ "MIT" ]
null
null
null
#include "RobotElementParser.h" #include <utility.reader.urdf/parsers/UrdfExtensionParser.h> #include <utility.reader.urdf/parsers/LinkParser.h> #include <utility.reader.urdf/parsers/JointParser.h> #include <utility.reader.urdf/structs/UrdfConnection.h> using namespace nspace; using namespace std; RobotElementParser::RobotElementParser(IModelBuilder & builder):NamedElementParser("robot"),ModelBuilderHolder(builder){ _children.composite().add(new UrdfExtensionParser(builder)); //order is important because joint parser needs the links to be present _children.composite().add(new LinkParser(builder)); _children.composite().add(new JointParser(builder)); } ModelNode * RobotElementParser::findRoot(){ return model().get<ModelNode*>("root"); } void RobotElementParser::convertLink(ModelNode * node){ UrdfLink * link=0; node->get(link,"urdflink"); if(!link)return; Body* body = new Body; node->set("body",body); body->inertia = link->inertia; body->mass = link->mass; CoordinateSystem preceedingCoordinates; ModelNode * connector = node->predecessors().first(); //get preceeding coordinates if they are set if(connector){ CoordinateSystem preceedingCoordinates; connector->get(preceedingCoordinates,"initialcoordinates"); } // get relative coordinates CoordinateSystem relativeCoordinates = link->origin; CoordinateSystem linkCoordinates; preceedingCoordinates.fromObjectCoordinates(relativeCoordinates,linkCoordinates); node->set("initialcoordinates",linkCoordinates); node->set("relativecoordinates",relativeCoordinates); if(connector){ //calculate connectors offset Vector3D offset; linkCoordinates.toObjectCoordinates(preceedingCoordinates.position(),offset); connector->set("offset",offset); } } void RobotElementParser::convertConnector(ModelNode * node){ UrdfConnector* urdfConnector=0; node->get(urdfConnector,"urdfconnector"); if(!urdfConnector)return; //create connector Connector * connector = new Connector; node->set("connector", connector); // get preceeding body (urdfconnector always is a successor) ModelNode * body = node->predecessors().first(); if(!body)return; // get body coordinates CoordinateSystem bodyCoordinates; body->get(bodyCoordinates,"initialcoordinates"); //set relative coordinates of connector CoordinateSystem relativeCoordinates= urdfConnector->origin; node->set("relativecoordinates",relativeCoordinates); // "calculate" connectors offset vector in object coordinates connector->offset() = relativeCoordinates.position(); node->set("offset",connector->offset()); // calculate initial coordinates of current connector CoordinateSystem initialCoordinates; bodyCoordinates.fromObjectCoordinates(relativeCoordinates,initialCoordinates); node->set("initialcoordinates", initialCoordinates); } void RobotElementParser::convertConnection(ModelNode * node){ UrdfConnection * connection =0; node->get(connection,"urdfconnection"); if(!connection )return; //todo: implement } void RobotElementParser::convertJoint(ModelNode * node){ UrdfJoint * joint=0; node->get(joint,"urdfjoint"); if(!joint)return; //set connection struct Connection * connection = new Connection; node->set("connection",connection); //set struct info connection->axis = joint->axis; connection->type = joint->type; // get connectors and bodies ModelNode * connectorNodeA = node->predecessors().first(); ModelNode * connectorNodeB = node->successors().first(); Connector * connectorA = new Connector; Connector * connectorB = new Connector; connectorNodeA->set("connector",connectorA); connectorNodeB->set("connector",connectorB); ModelNode * bodyA = connectorNodeA->predecessors().first(); //ModelNode * bodyB = connectorNodeB->successors().first(); CoordinateSystem bodyCoordinatesA; //CoordinateSystem bodyCoordinatesB; CoordinateSystem connectorCoordinatesA; CoordinateSystem connectorCoordinatesB; CoordinateSystem coordinatesJ; // get initial coordinates of previous body bodyA->get(bodyCoordinatesA,"initialcoordinates"); // calculate position of connectorA CoordinateSystem relativeJointCoordinates = joint->origin; bodyCoordinatesA.fromObjectCoordinates(relativeJointCoordinates,connectorCoordinatesA); coordinatesJ = connectorCoordinatesA; connectorCoordinatesB = connectorCoordinatesA; // calculate offset of connector in object coordinates bodyCoordinatesA.toObjectCoordinates(connectorCoordinatesA.position(),connectorA->offset()); connectorNodeA->set("offset",connectorA->offset()); connectorNodeA->set("initialcoordinates",connectorCoordinatesA); connectorNodeA->set("relativecoordinates",relativeJointCoordinates); node->set("initialcoordinates",coordinatesJ); node->set("relativecoordinates",CoordinateSystem::identity()); connectorNodeB->set("initialcoordinates",connectorCoordinatesB); connectorNodeB->set("relativecoordinates", relativeJointCoordinates); } void RobotElementParser::convertSpring(ModelNode * node){ ExtendedUrdfSpring * urdfSpring ; node->get(urdfSpring,"urdfspring"); if(!urdfSpring)return; } void RobotElementParser::convert(){ ModelNode * root = findRoot(); if(!root){ // ERROR("could not find root"); return; } Origin rootOrigin = model().get<Origin>("origin"); CoordinateSystem current = rootOrigin; //roots position and coordinates initial positions root->set("initialcoordinates",(CoordinateSystem)rootOrigin); root->set("relativecoordinates", (CoordinateSystem)rootOrigin); // iterate through the tree depth first (note: dfs currently crashes if cycles exist) root->dfs([this](ModelNode * node){ convertLink(node); convertJoint(node); convertConnector(node); convertSpring(node); }); } bool RobotElementParser::parseNamedElement(XMLElement * element){ builder().beginModel(); //get name for model parseName(&model(),element); // parse children _children.parse(element); // calculate the positions and convert graph to my data format (connection / connecotr / body) convert(); builder().endModel(); return true; }
33.640212
121
0.738754
[ "object", "vector", "model" ]
1f47bb6e6ca86be08e997d23f0b83456809972b4
2,066
cpp
C++
graph-source-code/327-D/6610527.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/327-D/6610527.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/327-D/6610527.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++0x #include <algorithm> #include <numeric> #include <string> #include <cstring> #include <set> #include <map> #include <vector> #include <queue> #include <iostream> #include <iterator> #include <cmath> #include <cstdio> #include <cstdlib> #include <sstream> #include <utility> #include <functional> #include <bitset> #include <deque> #include <tuple> #include <unordered_map> #include <unordered_set> using namespace std; typedef long long ll; typedef vector<int> VI; typedef vector<vector<int> > VVI; typedef pair<int, int> pii; #define FOR(i, x, y) for(ll i=x; i<=y; i++) #define FORD(i, x, y) for (ll i = x; i >= y; --i) #define REP(i, n) for(ll i=0; i<n; i++) #define REPD(i, n) for(ll i = n - 1; i >= 0; --i) #define ALL(c) (c).begin(), (c).end() #define SORT(c) sort(ALL(c)) #define UNIQ(c) SORT(c),(c).resize(unique(ALL(c))-(c).begin()) #define SZ(c) (int)(c).size() #define CONTAINS(s,obj) (s.find(obj)!=s.end()) #define CLEAR(x) memset(x,0,sizeof x) #define COPY(from,to) memcpy(to, from, sizeof to) #define sq(x) ((x)*(x)) #define pb push_back #define mp make_pair #define X first #define Y second const double eps = 1.0e-11; const double pi = acos(-1.0); int n, m; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; string d[550]; bool used[550][550]; vector<pair<char, pii> > res; void dfs(int x, int y, int root = true) { used[x][y] = true; res.push_back(mp('B', mp(x, y))); REP(dir, 4) { int nx = x + dx[dir], ny = y + dy[dir]; if (nx >= 0 && nx < n && ny >= 0 && ny < m && !used[nx][ny] && d[nx][ny] == '.') dfs(nx, ny, false); } if (!root) { res.push_back(mp('D', mp(x, y))); res.push_back(mp('R', mp(x, y))); } } int main() { ios_base::sync_with_stdio(0); cin >> n >> m; REP(i, n) cin >> d[i]; REP(i, n) REP(j, m) { if (d[i][j] == '.' && !used[i][j]) dfs(i, j); } cout << SZ(res) << endl; for (auto x : res) cout << x.X << " " << x.Y.X + 1 << " " << x.Y.Y + 1 << "\n"; return 0; }
23.213483
105
0.550823
[ "vector" ]
48faf695afe2ec9b8dad480f1185dda90c52e454
10,892
cpp
C++
engine/scene/Animators.cpp
tsukoyumi/ouzel
43f4f4871d49a310529366a4a4db061a96097164
[ "Unlicense" ]
null
null
null
engine/scene/Animators.cpp
tsukoyumi/ouzel
43f4f4871d49a310529366a4a4db061a96097164
[ "Unlicense" ]
null
null
null
engine/scene/Animators.cpp
tsukoyumi/ouzel
43f4f4871d49a310529366a4a4db061a96097164
[ "Unlicense" ]
null
null
null
// Ouzel by Elviss Strazdins #include <cmath> #include <limits> #include "Animators.hpp" #include "Actor.hpp" #include "../core/Engine.hpp" #include "../hash/Fnv1.hpp" #include "../utils/Utils.hpp" namespace ouzel::scene { Ease::Ease(Animator& animator, easing::Func initFunc, easing::Mode initMode): Animator{animator.getLength()}, func{initFunc}, mode{initMode} { addAnimator(animator); } void Ease::updateProgress() { Animator::updateProgress(); if (animators.empty()) return; progress = easing::ease(func, mode, progress); animators.front()->setProgress(progress); } Fade::Fade(float initLength, float initOpacity, bool initRelative): Animator{initLength}, opacity{initOpacity}, relative{initRelative} { } void Fade::play() { Animator::play(); if (targetActor) { startOpacity = targetActor->getOpacity(); targetOpacity = relative ? startOpacity + opacity : opacity; diff = targetOpacity - startOpacity; } } void Fade::updateProgress() { Animator::updateProgress(); if (targetActor) targetActor->setOpacity(startOpacity + (diff * progress)); } Move::Move(float initLength, const math::Vector<float, 3>& initPosition, bool initRelative): Animator{initLength}, position{initPosition}, relative{initRelative} { } void Move::play() { Animator::play(); if (targetActor) { startPosition = targetActor->getPosition(); targetPosition = relative ? startPosition + position : position; diff = targetPosition - startPosition; } } void Move::updateProgress() { Animator::updateProgress(); if (targetActor) targetActor->setPosition(startPosition + (diff * progress)); } Parallel::Parallel(const std::vector<Animator*>& initAnimators): Animator(0.0F) { for (auto animator : initAnimators) { assert(animator); addAnimator(*animator); if (animator->getLength() > length) length = animator->getLength(); } } Parallel::Parallel(const std::vector<std::unique_ptr<Animator>>& initAnimators): Animator(0.0F) { for (const std::unique_ptr<Animator>& animator : initAnimators) { assert(animator.get()); addAnimator(*animator); if (animator->getLength() > length) length = animator->getLength(); } } void Parallel::updateProgress() { Animator::updateProgress(); for (auto animator : animators) { const float animationLength = animator->getLength(); if (animationLength <= 0.0F || currentTime > animationLength) animator->setProgress(1.0F); else animator->setProgress(currentTime / animationLength); } } Repeat::Repeat(Animator& animator, std::uint32_t initCount): Animator{animator.getLength() * static_cast<float>(initCount)}, count{initCount} { addAnimator(animator); } void Repeat::reset() { Animator::reset(); currentCount = 0; } void Repeat::updateProgress() { if (animators.empty()) return; if (animators.front()->getLength() != 0.0F) { currentCount = static_cast<std::uint32_t>(currentTime / animators.front()->getLength()); if (count == 0 || currentCount < count) { done = false; running = true; const float remainingTime = currentTime - animators.front()->getLength() * static_cast<float>(currentCount); animators.front()->setProgress(remainingTime / animators.front()->getLength()); auto resetEvent = std::make_unique<AnimationEvent>(); resetEvent->type = Event::Type::animationReset; resetEvent->component = this; engine->getEventDispatcher().dispatchEvent(std::move(resetEvent)); } else { done = true; running = false; currentTime = length; progress = 1.0F; auto finishEvent = std::make_unique<AnimationEvent>(); finishEvent->type = Event::Type::animationFinish; finishEvent->component = this; engine->getEventDispatcher().dispatchEvent(std::move(finishEvent)); } } } Rotate::Rotate(float initLength, const math::Vector<float, 3>& initRotation, bool initRelative): Animator{initLength}, rotation{initRotation}, relative{initRelative} { } void Rotate::play() { Animator::play(); if (targetActor) { startRotation = getEulerAngles(targetActor->getRotation()); targetRotation = relative ? startRotation + rotation : rotation; diff = targetRotation - startRotation; } } void Rotate::updateProgress() { Animator::updateProgress(); if (targetActor) targetActor->setRotation(startRotation + diff * progress); } Scale::Scale(float initLength, const math::Vector<float, 3>& initScale, bool initRelative): Animator{initLength}, scale{initScale}, relative{initRelative} { } void Scale::play() { Animator::play(); if (targetActor) { startScale = targetActor->getScale(); targetScale = relative ? startScale + scale : scale; diff = targetScale - startScale; } } void Scale::updateProgress() { Animator::updateProgress(); if (targetActor) targetActor->setScale(startScale + (diff * progress)); } Sequence::Sequence(const std::vector<Animator*>& initAnimators): Animator(std::accumulate(initAnimators.begin(), initAnimators.end(), 0.0F, [](float a, Animator* b) noexcept { return a + b->getLength(); })) { for (auto animator : initAnimators) { assert(animator); addAnimator(*animator); } } Sequence::Sequence(const std::vector<std::unique_ptr<Animator>>& initAnimators): Animator(std::accumulate(initAnimators.begin(), initAnimators.end(), 0.0F, [](float a, const std::unique_ptr<Animator>& b) noexcept { return a + b->getLength(); })) { for (const std::unique_ptr<Animator>& animator : initAnimators) { assert(animator.get()); addAnimator(*animator); } } void Sequence::play() { setProgress(0.0F); done = false; running = true; targetActor = actor; if (!targetActor && parent) targetActor = parent->getTargetActor(); if (!animators.empty()) { currentAnimator = animators.front(); currentAnimator->play(); } else currentAnimator = nullptr; } void Sequence::updateProgress() { Animator::updateProgress(); float time = 0.0F; for (auto animator : animators) { if (animator->getLength() <= 0.0F || currentTime > time + animator->getLength()) { if (animator == currentAnimator) animator->setProgress(1.0F); } else if (currentTime <= time) { if (animator == currentAnimator) animator->setProgress(0.0F); } else { if (currentAnimator != animator) { currentAnimator = animator; animator->play(); } animator->setProgress((currentTime - time) / animator->getLength()); } time += animator->getLength(); } } Shake::Shake(float initLength, const math::Vector<float, 3>& initDistance, float initTimeScale): Animator{initLength}, distance{initDistance}, timeScale{initTimeScale} { seedX = std::uniform_int_distribution<std::uint32_t>{0, std::numeric_limits<std::uint32_t>::max()}(core::randomEngine); seedY = std::uniform_int_distribution<std::uint32_t>{0, std::numeric_limits<std::uint32_t>::max()}(core::randomEngine); seedZ = std::uniform_int_distribution<std::uint32_t>{0, std::numeric_limits<std::uint32_t>::max()}(core::randomEngine); } void Shake::play() { Animator::play(); if (targetActor) startPosition = targetActor->getPosition(); } void Shake::updateProgress() { Animator::updateProgress(); if (targetActor) { const float x = length * progress * timeScale; const auto x1 = static_cast<std::uint64_t>(x); const auto x2 = x1 + 1; const auto t = x - static_cast<float>(x1); math::Vector<float, 3> previousPosition{}; math::Vector<float, 3> nextPosition{}; if (x1 != 0) { previousPosition.v[0] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedX | (x1 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[0]; previousPosition.v[1] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedY | (x1 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[1]; previousPosition.v[2] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedZ | (x1 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[2]; } if (x2 != static_cast<std::uint32_t>(timeScale)) { nextPosition.v[0] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedX | (x2 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[0]; nextPosition.v[1] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedY | (x2 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[1]; nextPosition.v[2] = (2.0F * (static_cast<float>(hash::fnv1::hash<std::uint32_t>(seedZ | (x2 << 32))) / std::numeric_limits<std::uint32_t>::max()) - 1.0F) * distance.v[2]; } const math::Vector<float, 3> noise{ math::smoothStep(previousPosition.v[0], nextPosition.v[0], t), math::smoothStep(previousPosition.v[1], nextPosition.v[1], t), math::smoothStep(previousPosition.v[2], nextPosition.v[2], t) }; targetActor->setPosition(startPosition + noise); } } }
30.68169
190
0.56087
[ "vector" ]
5b07ecfee229e928f4f494662d0a1e86f337d2ed
3,226
hpp
C++
src/Library/math/Vector_tfs.hpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
16
2021-12-28T18:30:01.000Z
2022-03-26T12:59:48.000Z
src/Library/math/Vector_tfs.hpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
61
2022-01-04T22:56:36.000Z
2022-03-31T13:19:29.000Z
src/Library/math/Vector_tfs.hpp
ut-issl/s2e-core
900fae6b738eb8765cd98c48acb2b74f05dcc68c
[ "MIT" ]
2
2022-03-03T03:39:25.000Z
2022-03-12T04:50:30.000Z
/*! \file Vector_impl.hpp \author TAKISAWA Jun'ichi. \brief Vector.hppのテンプレート実装 */ #ifndef VECTOR_HPP_TFS_HPP_ #define VECTOR_HPP_TFS_HPP_ #include <cmath> namespace libra { template <size_t N, typename T> Vector<N, T>::Vector(const T& n) { for (size_t i = 0; i < N; ++i) { vector_[i] = n; } } template <size_t N, typename T> Vector<N, T>& Vector<N, T>::operator+=(const Vector<N, T>& v) { for (size_t i = 0; i < N; ++i) { vector_[i] += v.vector_[i]; } return *this; } template <size_t N, typename T> Vector<N, T>& Vector<N, T>::operator-=(const Vector<N, T>& v) { for (size_t i = 0; i < N; ++i) { vector_[i] -= v.vector_[i]; } return *this; } template <size_t N, typename T> Vector<N, T>& Vector<N, T>::operator*=(const T& n) { for (size_t i = 0; i < N; ++i) { vector_[i] *= n; } return *this; } template <size_t N, typename T> Vector<N, T>& Vector<N, T>::operator/=(const T& n) { return operator*=(1.0 / n); } template <size_t N, typename T> Vector<N, T> Vector<N, T>::operator-() const { Vector<N, T> temp = *this; temp *= -1; return temp; } template <size_t N, typename T> void fill_up(Vector<N, T>& v, const T& n) { for (size_t i = 0; i < N; ++i) { v[i] = n; } } template <size_t N, typename T> void print(const Vector<N, T>& v, char delimiter, std::ostream& stream) { stream << v[0]; for (size_t i = 1; i < N; ++i) { stream << delimiter << v[i]; } } template <size_t N, typename T> const Vector<N, T> operator+(const Vector<N, T>& lhs, const Vector<N, T>& rhs) { Vector<N, T> temp; for (size_t i = 0; i < N; ++i) { temp[i] = lhs[i] + rhs[i]; } return temp; } template <size_t N, typename T> const Vector<N, T> operator-(const Vector<N, T>& lhs, const Vector<N, T>& rhs) { Vector<N, T> temp; for (size_t i = 0; i < N; ++i) { temp[i] = lhs[i] - rhs[i]; } return temp; } template <size_t N, typename T> const Vector<N, T> operator*(const T& lhs, const Vector<N, T>& rhs) { Vector<N, T> temp; for (size_t i = 0; i < N; ++i) { temp[i] = lhs * rhs[i]; } return temp; } template <size_t N, typename T> const T inner_product(const Vector<N, T>& lhs, const Vector<N, T>& rhs) { T temp = 0; for (size_t i = 0; i < N; ++i) { temp += lhs[i] * rhs[i]; } return temp; } template <typename T> const Vector<3, T> outer_product(const Vector<3, T>& lhs, const Vector<3, T>& rhs) { Vector<3, T> temp; temp[0] = lhs[1] * rhs[2] - lhs[2] * rhs[1]; temp[1] = lhs[2] * rhs[0] - lhs[0] * rhs[2]; temp[2] = lhs[0] * rhs[1] - lhs[1] * rhs[0]; return temp; } template <size_t N> double norm(const Vector<N, double>& v) { double temp = 0.0; for (size_t i = 0; i < N; ++i) { temp += pow(v[i], 2.0); } return sqrt(temp); } template <size_t N> Vector<N, double>& normalize(Vector<N, double>& v) { double n = norm(v); if (n == 0.0) { return v; } //零ベクトル // 正規化 n = 1.0 / n; for (size_t i = 0; i < N; ++i) { v[i] *= n; } return v; } template <size_t N> double angle(const Vector<N, double>& v1, const Vector<N, double>& v2) { double cos = inner_product(v1, v2) / (norm(v1) * norm(v2)); return acos(cos); } } // namespace libra #endif // VECTOR_HPP_TFS_HPP_
21.506667
84
0.572536
[ "vector" ]