text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::Invoke;
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ConstLog) {
const root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1)
.WillOnce(Invoke([](const record_t& record) {
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
EXPECT_EQ(0, record.severity());
EXPECT_EQ(0, record.attributes().size());
}));
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
} // namespace testing
} // namespace blackhole
<commit_msg>chore(tests): add test to check logger overload<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::Invoke;
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ConstLog) {
const root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1)
.WillOnce(Invoke([](const record_t& record) {
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
EXPECT_EQ(0, record.severity());
EXPECT_EQ(0, record.attributes().size());
}));
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordWithAttributesToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
const view_of<attributes_t>::type attributes{{"key#1", {42}}};
attribute_pack pack{attributes};
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1)
.WillOnce(Invoke([&](const record_t& record) {
EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
EXPECT_EQ(0, record.severity());
ASSERT_EQ(1, record.attributes().size());
EXPECT_EQ(attributes, record.attributes().at(0).get());
}));
}
logger.log(0, "GET /porn.png HTTP/1.1", pack);
}
} // namespace testing
} // namespace blackhole
<|endoftext|>
|
<commit_before>
#pragma once
#include <vector>
#include <unordered_map>
#include <iostream>
#include <limits>
#include <functional>
template <class E>
class PriorityQueue
{
private:
struct Node
{
E elem;
double key;
};
const double MAX = std::numeric_limits<double>::infinity();
std::vector<Node> _elems;
std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > _indexLookUp;
int _size;
void buildMinHeap(void)
{
int startIndex = _size/2;
for(int i = startIndex; i >= 0; i--)
{
minHeapify(i);
}
}
void swap(int ind1,int ind2)
{
Node tmp = _elems[ind1];
_elems[ind1] = _elems[ind2];
_elems[ind2] = tmp;
_indexLookUp[_elems[ind1].elem] = ind1;
_indexLookUp[_elems[ind2].elem] = ind2;
}
void minHeapify(int index)
{
int indexOfMin = 0;
int left = leftChild(index);
int right = rightChild(index);
if(left >= 0 && _elems[index].key > _elems[left].key)
{
indexOfMin = left;
}
else
{
indexOfMin = index;
}
if(right >= 0 && _elems[indexOfMin].key > _elems[right].key)
{
indexOfMin = right;
}
if(indexOfMin != index)
{
swap(indexOfMin,index);
minHeapify(indexOfMin);
}
}
int leftChild(int index)
{
int res = 2*index + 1;
return (res < _size) ? res : -1;
}
int rightChild(int index)
{
int res = 2*index + 2;
return (res < _size) ? res : -1;
}
int parent(int index)
{
return (index <= 0) ? -1 : ((index - 1)/2);
}
public:
PriorityQueue(std::function<size_t(E)> hashFunctor, std::function<bool(E,E)> equalityFunctor)
{
std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > m(0,hashFunctor,equalityFunctor);
_indexLookUp = m;
_size = 0;
}
E peek(void)
{
return _elems[0].elem;
}
E poll(void)
{
E result = _elems[0].elem;
_elems[0] = _elems.back();
auto it = _indexLookUp.find(_elems.back().elem);
_indexLookUp.erase(it);
_elems.pop_back();
_indexLookUp[_elems[0].elem] = 0;
_size -= 1;
minHeapify(0);
return result;
}
void decreaseKey(E elem, double newKey)
{
int index = _indexLookUp[elem];
if(_elems[index].key > newKey)
{
_elems[index].key = newKey;
int current = index;
while(current > 0)
{
if(_elems[current].key < _elems[parent(current)].key)
{
swap(current,parent(current));
current = parent(current);
}
else
{
break;
}
}
}
}
void insert(E e, double k)
{
Node n;
n.elem = e;
n.key = MAX;
_elems.push_back(n);
_indexLookUp[e] = _size;
_size += 1;
decreaseKey(e,k);
}
void update(E e, double k)
{
if(_indexLookUp.find(e) != _indexLookUp.end())
{
decreaseKey(e,k);
}
else
{
insert(e,k);
}
}
void merge(PriorityQueue<E> other)
{
for(unsigned long i = 0; i < other._elems.size(); i++)
{
_elems.push_back(other._elems[i]);
_indexLookUp[_elems.back().elem] = _size + i;
_size += 1;
}
buildMinHeap();
}
void print(void)
{
if(_elems.size() == 0)
{
std::cout << "empty queue" << std::endl;
}
for(auto node : _elems)
{
std::cout << "key: " << node.key << ", ";
}
std::cout << std::endl;
}
};
<commit_msg>added isEmpty() method to queue<commit_after>
#pragma once
#include <vector>
#include <unordered_map>
#include <iostream>
#include <limits>
#include <functional>
template <class E>
class PriorityQueue
{
private:
struct Node
{
E elem;
double key;
};
const double MAX = std::numeric_limits<double>::infinity();
std::vector<Node> _elems;
std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > _indexLookUp;
int _size;
void buildMinHeap(void)
{
int startIndex = _size/2;
for(int i = startIndex; i >= 0; i--)
{
minHeapify(i);
}
}
void swap(int ind1,int ind2)
{
Node tmp = _elems[ind1];
_elems[ind1] = _elems[ind2];
_elems[ind2] = tmp;
_indexLookUp[_elems[ind1].elem] = ind1;
_indexLookUp[_elems[ind2].elem] = ind2;
}
void minHeapify(int index)
{
int indexOfMin = 0;
int left = leftChild(index);
int right = rightChild(index);
if(left >= 0 && _elems[index].key > _elems[left].key)
{
indexOfMin = left;
}
else
{
indexOfMin = index;
}
if(right >= 0 && _elems[indexOfMin].key > _elems[right].key)
{
indexOfMin = right;
}
if(indexOfMin != index)
{
swap(indexOfMin,index);
minHeapify(indexOfMin);
}
}
int leftChild(int index)
{
int res = 2*index + 1;
return (res < _size) ? res : -1;
}
int rightChild(int index)
{
int res = 2*index + 2;
return (res < _size) ? res : -1;
}
int parent(int index)
{
return (index <= 0) ? -1 : ((index - 1)/2);
}
public:
PriorityQueue(std::function<size_t(E)> hashFunctor, std::function<bool(E,E)> equalityFunctor)
{
std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > m(0,hashFunctor,equalityFunctor);
_indexLookUp = m;
_size = 0;
}
bool isEmpty()
{
return (_size == 0);
}
E peek(void)
{
return _elems[0].elem;
}
E poll(void)
{
E result = _elems[0].elem;
_elems[0] = _elems.back();
auto it = _indexLookUp.find(_elems.back().elem);
_indexLookUp.erase(it);
_elems.pop_back();
_indexLookUp[_elems[0].elem] = 0;
_size -= 1;
minHeapify(0);
return result;
}
void decreaseKey(E elem, double newKey)
{
int index = _indexLookUp[elem];
if(_elems[index].key > newKey)
{
_elems[index].key = newKey;
int current = index;
while(current > 0)
{
if(_elems[current].key < _elems[parent(current)].key)
{
swap(current,parent(current));
current = parent(current);
}
else
{
break;
}
}
}
}
void insert(E e, double k)
{
Node n;
n.elem = e;
n.key = MAX;
_elems.push_back(n);
_indexLookUp[e] = _size;
_size += 1;
decreaseKey(e,k);
}
void update(E e, double k)
{
if(_indexLookUp.find(e) != _indexLookUp.end())
{
decreaseKey(e,k);
}
else
{
insert(e,k);
}
}
void merge(PriorityQueue<E> other)
{
for(unsigned long i = 0; i < other._elems.size(); i++)
{
_elems.push_back(other._elems[i]);
_indexLookUp[_elems.back().elem] = _size + i;
_size += 1;
}
buildMinHeap();
}
void print(void)
{
if(_elems.size() == 0)
{
std::cout << "empty queue" << std::endl;
}
for(auto node : _elems)
{
std::cout << "key: " << node.key << ", ";
}
std::cout << std::endl;
}
};
<|endoftext|>
|
<commit_before>#pragma once
#include "../lubee/random.hpp"
#include "../lubee/check_serialization.hpp"
#include <gtest/gtest.h>
#include <cereal/archives/json.hpp>
#include <cereal/archives/binary.hpp>
namespace spi {
namespace test {
class Random : public ::testing::Test {
private:
lubee::RandomMT _mt;
public:
Random(): _mt(lubee::RandomMT::Make<4>()) {}
auto& mt() {
return _mt;
}
};
#define USING(t) using t = typename TestFixture::t
template <class T>
class TestObj {
public:
using value_t = T;
private:
value_t _value;
static int s_counter;
public:
TestObj(TestObj&&) = default;
TestObj(const TestObj&) = delete;
TestObj() {
++s_counter;
}
TestObj(const value_t& v):
_value(v)
{
++s_counter;
}
~TestObj() {
--s_counter;
}
TestObj& operator = (const T& t) {
_value = t;
return *this;
}
bool operator == (const TestObj& m) const {
return _value == m._value;
}
static void InitializeCounter() {
s_counter = 0;
}
static bool CheckCounter(const int c) {
return c == s_counter;
}
};
template <class T>
int TestObj<T>::s_counter;
template <class T>
inline bool operator == (const T& t, const TestObj<T>& o) {
return o == t;
}
// コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化
template <class T, ENABLE_IF(!std::is_trivial<T>{})>
void InitializeCounter() {
T::InitializeCounter();
}
template <class T, ENABLE_IF(std::is_trivial<T>{})>
void InitializeCounter() {}
// コンストラクタ・デストラクタが呼ばれる回数をチェック
template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})>
void CheckCounter(const V& v) {
ASSERT_TRUE(T::CheckCounter(v));
}
template <class T, class V, ENABLE_IF(std::is_trivial<T>{})>
void CheckCounter(const V&) {}
}
}
<commit_msg>TestObj: getValue(), noexceptを付加<commit_after>#pragma once
#include "../lubee/random.hpp"
#include "../lubee/check_serialization.hpp"
#include <gtest/gtest.h>
#include <cereal/archives/json.hpp>
#include <cereal/archives/binary.hpp>
namespace spi {
namespace test {
class Random : public ::testing::Test {
private:
lubee::RandomMT _mt;
public:
Random(): _mt(lubee::RandomMT::Make<4>()) {}
auto& mt() noexcept {
return _mt;
}
};
#define USING(t) using t = typename TestFixture::t
template <class T>
class TestObj {
public:
using value_t = T;
private:
value_t _value;
static int s_counter;
public:
TestObj(TestObj&&) = default;
TestObj(const TestObj&) = delete;
TestObj() noexcept {
++s_counter;
}
TestObj(const value_t& v) noexcept:
_value(v)
{
++s_counter;
}
~TestObj() noexcept {
--s_counter;
}
TestObj& operator = (const T& t) {
_value = t;
return *this;
}
value_t getValue() const noexcept {
return _value;
}
bool operator == (const TestObj& m) const noexcept {
return _value == m._value;
}
static void InitializeCounter() noexcept {
s_counter = 0;
}
static bool CheckCounter(const int c) noexcept {
return c == s_counter;
}
};
template <class T>
int TestObj<T>::s_counter;
template <class T>
inline bool operator == (const T& t, const TestObj<T>& o) noexcept {
return o == t;
}
// コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化
template <class T, ENABLE_IF(!std::is_trivial<T>{})>
void InitializeCounter() {
T::InitializeCounter();
}
template <class T, ENABLE_IF(std::is_trivial<T>{})>
void InitializeCounter() noexcept {}
// コンストラクタ・デストラクタが呼ばれる回数をチェック
template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})>
void CheckCounter(const V& v) {
ASSERT_TRUE(T::CheckCounter(v));
}
template <class T, class V, ENABLE_IF(std::is_trivial<T>{})>
void CheckCounter(const V&) noexcept {}
}
}
<|endoftext|>
|
<commit_before>#include <PresentaBALLSettings.h>
#include <PresentaBALLView.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/SYSTEM/directory.h>
#include <QLineEdit>
#include <QFileDialog>
namespace BALL
{
namespace VIEW
{
PresentaBALLSettings::PresentaBALLSettings(QWidget* parent, const char* name, Qt::WindowFlags fl)
: ConfigDialog(parent, fl),
Ui_PresentaBALLSettingsData()
{
setupUi(this);
setObjectName(name);
setWidgetStackName((String)tr("PresentaBALL"));
setINIFileSectionName("PresentaBALL");
registerWidgets_();
connect(browse_button, SIGNAL(clicked()), this, SLOT(selectIndexHTMLLocation()));
}
PresentaBALLSettings::~PresentaBALLSettings()
{ }
void PresentaBALLSettings::setIndexHTMLLocation(const QString& path)
{
index_html_edit->setText(path);
}
QString PresentaBALLSettings::getIndexHTMLLocation()
{
return index_html_edit->text();
}
void PresentaBALLSettings::selectIndexHTMLLocation()
{
QString new_location = QFileDialog::getOpenFileName(this, "Select a start page for PresentaBALL");
if (new_location != "")
{
setIndexHTMLLocation(new_location);
}
}
void PresentaBALLSettings::restoreDefaultValues(bool all)
{
PreferencesEntry::restoreDefaultValues(all);
//set the webpage language according to the language set in preferences
String home_dir = Directory::getUserHomeDir();
INIFile f(home_dir + FileSystem::PATH_SEPARATOR + ".BALLView");
f.read();
Path p;
String s;
if (f.hasEntry("GENERAL", "language") && f.getValue("GENERAL", "language") == "de_DE")
{
s = p.find("HTMLBasedInterface/html_de");
}
else
{
s = p.find("HTMLBasedInterface/html_eng");
}
if (!s.isEmpty())
{
setIndexHTMLLocation((s + "/index.html").c_str());
}
else
{
Log.error() << "No html directory set!" << std::endl;
}
}
}
}
<commit_msg>[PresentaBALL] Fix: Set default values in settings dialog<commit_after>#include <PresentaBALLSettings.h>
#include <PresentaBALLView.h>
#include <BALL/SYSTEM/path.h>
#include <BALL/SYSTEM/directory.h>
#include <QLineEdit>
#include <QFileDialog>
namespace BALL
{
namespace VIEW
{
PresentaBALLSettings::PresentaBALLSettings(QWidget* parent, const char* name, Qt::WindowFlags fl)
: ConfigDialog(parent, fl),
Ui_PresentaBALLSettingsData()
{
setupUi(this);
setObjectName(name);
setWidgetStackName((String)tr("PresentaBALL"));
setINIFileSectionName("PresentaBALL");
registerWidgets_();
restoreDefaultValues();
connect(browse_button, SIGNAL(clicked()), this, SLOT(selectIndexHTMLLocation()));
}
PresentaBALLSettings::~PresentaBALLSettings()
{ }
void PresentaBALLSettings::setIndexHTMLLocation(const QString& path)
{
index_html_edit->setText(path);
}
QString PresentaBALLSettings::getIndexHTMLLocation()
{
return index_html_edit->text();
}
void PresentaBALLSettings::selectIndexHTMLLocation()
{
QString new_location = QFileDialog::getOpenFileName(this, "Select a start page for PresentaBALL");
if (new_location != "")
{
setIndexHTMLLocation(new_location);
}
}
void PresentaBALLSettings::restoreDefaultValues(bool all)
{
PreferencesEntry::restoreDefaultValues(all);
//set the webpage language according to the language set in preferences
String home_dir = Directory::getUserHomeDir();
INIFile f(home_dir + FileSystem::PATH_SEPARATOR + ".BALLView");
f.read();
Path p;
String s;
if (f.hasEntry("GENERAL", "language") && f.getValue("GENERAL", "language") == "de_DE")
{
s = p.find("HTMLBasedInterface/html_de");
}
else
{
s = p.find("HTMLBasedInterface/html_eng");
}
if (!s.isEmpty())
{
setIndexHTMLLocation((s + "/index.html").c_str());
}
else
{
Log.error() << "No html directory set!" << std::endl;
}
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fwkhelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:57:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include "workwin.hxx"
#include <sfx2/frame.hxx>
void SAL_CALL RefreshToolbars( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( xFrame.is() )
{
SfxFrame* pFrame=0;
for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
{
if ( pFrame->GetFrameInterface() == xFrame )
break;
}
if ( pFrame )
{
SfxWorkWindow* pWrkWin = pFrame->GetWorkWindow_Impl();
if ( pWrkWin )
pWrkWin->UpdateObjectBars_Impl();
}
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.216); FILE MERGED 2008/04/01 15:38:44 thb 1.4.216.3: #i85898# Stripping all external header guards 2008/04/01 12:40:40 thb 1.4.216.2: #i85898# Stripping all external header guards 2008/03/31 13:38:01 rt 1.4.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fwkhelper.cxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/frame/XFrame.hpp>
#include "sal/config.h"
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include "workwin.hxx"
#include <sfx2/frame.hxx>
void SAL_CALL RefreshToolbars( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( xFrame.is() )
{
SfxFrame* pFrame=0;
for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
{
if ( pFrame->GetFrameInterface() == xFrame )
break;
}
if ( pFrame )
{
SfxWorkWindow* pWrkWin = pFrame->GetWorkWindow_Impl();
if ( pWrkWin )
pWrkWin->UpdateObjectBars_Impl();
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>tdf#90994 Sidebar tab bar buttons should should have accessible names<commit_after><|endoftext|>
|
<commit_before>#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime>
#include <assert.h>
#define pi 3.14159
#define mod 1000000007
using namespace std;
long long int a[500000];
int main()
{
long long int n = 0,m = 0,a = 2,total_need = 0;
cin>>n>>m;
total_need = (n*m)/a;
cout<<total_need;
return 0;
}
<commit_msg>Delete Domino_piling.cpp<commit_after><|endoftext|>
|
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef int (Implementation::Model::*IntOneArgMethod) (
const Abstract::Point& coordinates
) const;
typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) (
const Abstract::Point& coordinates
) const;
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*IntThreeArgsMethod) (
int team,
int bacterium_index,
int spec
);
typedef void (Implementation::Model::*ThreeArgsMethod) (
int team,
int bacterium_index,
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
static void checkOneArgMethod(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<IntOneArgMethod>(
Implementation::Model* model,
IntOneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<TwoArgsMethod>(
Implementation::Model* model,
TwoArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates, 0), Exception
);
}
template<>
void checkModelMethodForThrow<MultiArgsMethod>(
Implementation::Model* model,
MultiArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(
coordinates,
DEFAULT_MASS,
0,
0,
0
),
Exception
);
}
// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
Implementation::Model* model,
Func model_method
) {
model->kill(0, 0);
checkModelMethodForThrow(
model,
model_method,
0,
0
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method,
bool dead_test
) {
// Range errors: test all combinations of
// "wrong" (outside of correct range) arguments.
// This solution works for coordinates and non-coordinates
// methods of Model. (< 0, = 0, > MAX)
int wrong_args[] = {-1, 0, MIN_WIDTH};
BOOST_FOREACH (int arg1, wrong_args) {
BOOST_FOREACH (int arg2, wrong_args) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
checkModelMethodForThrow(
model,
model_method,
arg1,
arg2
);
}
}
}
if (dead_test) {
// "dead" error
// (attempt to do something with dead bacterium)
deadTest(model, model_method);
}
}
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
model->createNewByCoordinates(
coordinates,
DEFAULT_MASS,
0,
0,
0
);
return coordinates;
}
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int team = model->getTeamByCoordinates(coordinates);
BOOST_REQUIRE(team == 0);
checkErrorHandling<IntOneArgMethod>(
model,
&Implementation::Model::getTeamByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (is_alive_test) {
Implementation::Model* model = createBaseModel(1, 1);
checkErrorHandling(
model,
&Implementation::Model::isAlive,
false
);
BOOST_REQUIRE(model->isAlive(0, 0) == true);
model->kill(0, 0);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
delete model;
}
BOOST_AUTO_TEST_CASE (get_instruction_test) {
Implementation::Model* model = createBaseModel(1, 1);
int instruction = model->getInstruction(0, 0);
BOOST_REQUIRE(instruction == 0);
checkErrorHandling(
model,
&Implementation::Model::getInstruction,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
BOOST_REQUIRE(derived_coordinates == coordinates);
checkErrorHandling(
model,
&Implementation::Model::getCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_direction_test) {
Implementation::Model* model = createBaseModel();
createInBaseCoordinates(model);
int direction = model->getDirection(0, 0);
BOOST_REQUIRE(direction == Abstract::LEFT);
checkErrorHandling(
model,
&Implementation::Model::getDirection,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(
model,
&Implementation::Model::getMass,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling(
model,
&Implementation::Model::kill,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling<OneArgMethod>(
model,
&Implementation::Model::killByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int test_val = 1;
model->changeMassByCoordinates(coordinates, test_val);
int new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
model->changeMassByCoordinates(coordinates, -test_val);
new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == DEFAULT_MASS);
checkErrorHandling<TwoArgsMethod>(
model,
&Implementation::Model::changeMassByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
checkErrorHandling<MultiArgsMethod>(
model,
&Implementation::Model::createNewByCoordinates,
false
);
delete model;
}
<commit_msg>Implement checkModelMethodForThrow <OneArgMethod2><commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef int (Implementation::Model::*IntOneArgMethod) (
const Abstract::Point& coordinates
) const;
typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) (
const Abstract::Point& coordinates
) const;
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*IntThreeArgsMethod) (
int team,
int bacterium_index,
int spec
);
typedef void (Implementation::Model::*ThreeArgsMethod) (
int team,
int bacterium_index,
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
static void checkOneArgMethod(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<IntOneArgMethod>(
Implementation::Model* model,
IntOneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<OneArgMethod2>(
Implementation::Model* model,
OneArgMethod2 model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<TwoArgsMethod>(
Implementation::Model* model,
TwoArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates, 0), Exception
);
}
template<>
void checkModelMethodForThrow<MultiArgsMethod>(
Implementation::Model* model,
MultiArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(
coordinates,
DEFAULT_MASS,
0,
0,
0
),
Exception
);
}
// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
Implementation::Model* model,
Func model_method
) {
model->kill(0, 0);
checkModelMethodForThrow(
model,
model_method,
0,
0
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method,
bool dead_test
) {
// Range errors: test all combinations of
// "wrong" (outside of correct range) arguments.
// This solution works for coordinates and non-coordinates
// methods of Model. (< 0, = 0, > MAX)
int wrong_args[] = {-1, 0, MIN_WIDTH};
BOOST_FOREACH (int arg1, wrong_args) {
BOOST_FOREACH (int arg2, wrong_args) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
checkModelMethodForThrow(
model,
model_method,
arg1,
arg2
);
}
}
}
if (dead_test) {
// "dead" error
// (attempt to do something with dead bacterium)
deadTest(model, model_method);
}
}
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
model->createNewByCoordinates(
coordinates,
DEFAULT_MASS,
0,
0,
0
);
return coordinates;
}
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int team = model->getTeamByCoordinates(coordinates);
BOOST_REQUIRE(team == 0);
checkErrorHandling<IntOneArgMethod>(
model,
&Implementation::Model::getTeamByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (is_alive_test) {
Implementation::Model* model = createBaseModel(1, 1);
checkErrorHandling(
model,
&Implementation::Model::isAlive,
false
);
BOOST_REQUIRE(model->isAlive(0, 0) == true);
model->kill(0, 0);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
delete model;
}
BOOST_AUTO_TEST_CASE (get_instruction_test) {
Implementation::Model* model = createBaseModel(1, 1);
int instruction = model->getInstruction(0, 0);
BOOST_REQUIRE(instruction == 0);
checkErrorHandling(
model,
&Implementation::Model::getInstruction,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
BOOST_REQUIRE(derived_coordinates == coordinates);
checkErrorHandling(
model,
&Implementation::Model::getCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_direction_test) {
Implementation::Model* model = createBaseModel();
createInBaseCoordinates(model);
int direction = model->getDirection(0, 0);
BOOST_REQUIRE(direction == Abstract::LEFT);
checkErrorHandling(
model,
&Implementation::Model::getDirection,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(
model,
&Implementation::Model::getMass,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling(
model,
&Implementation::Model::kill,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling<OneArgMethod>(
model,
&Implementation::Model::killByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int test_val = 1;
model->changeMassByCoordinates(coordinates, test_val);
int new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
model->changeMassByCoordinates(coordinates, -test_val);
new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == DEFAULT_MASS);
checkErrorHandling<TwoArgsMethod>(
model,
&Implementation::Model::changeMassByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
checkErrorHandling<MultiArgsMethod>(
model,
&Implementation::Model::createNewByCoordinates,
false
);
delete model;
}
<|endoftext|>
|
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef int (Implementation::Model::*IntOneArgMethod) (
const Abstract::Point& coordinates
) const;
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
static void checkOneArgMethod(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<IntOneArgMethod>(
Implementation::Model* model,
IntOneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<TwoArgsMethod>(
Implementation::Model* model,
TwoArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates, 0), Exception
);
}
template<>
void checkModelMethodForThrow<MultiArgsMethod>(
Implementation::Model* model,
MultiArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(
coordinates,
DEFAULT_MASS,
0,
0,
0
),
Exception
);
}
// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
Implementation::Model* model,
Func model_method
) {
model->kill(0, 0);
checkModelMethodForThrow(
model,
model_method,
0,
0
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method,
bool dead_test
) {
// Range errors: test all combinations of
// "wrong" (outside of correct range) arguments.
// This solution works for coordinates and non-coordinates
// methods of Model. (< 0, = 0, > MAX)
int wrong_args[] = {-1, 0, MIN_WIDTH};
BOOST_FOREACH (int arg1, wrong_args) {
BOOST_FOREACH (int arg2, wrong_args) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
checkModelMethodForThrow(
model,
model_method,
arg1,
arg2
);
}
}
}
if (dead_test) {
// "dead" error
// (attempt to do something with dead bacterium)
deadTest(model, model_method);
}
}
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
model->createNewByCoordinates(
coordinates,
DEFAULT_MASS,
0,
0,
0
);
return coordinates;
}
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int team = model->getTeamByCoordinates(coordinates);
BOOST_REQUIRE(team == 0);
checkErrorHandling<IntOneArgMethod>(
model,
&Implementation::Model::getTeamByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (is_alive_test) {
Implementation::Model* model = createBaseModel(1, 1);
checkErrorHandling(
model,
&Implementation::Model::isAlive,
false
);
BOOST_REQUIRE(model->isAlive(0, 0) == true);
model->kill(0, 0);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
delete model;
}
BOOST_AUTO_TEST_CASE (get_instruction_test) {
Implementation::Model* model = createBaseModel(1, 1);
int instruction = model->getInstruction(0, 0);
BOOST_REQUIRE(instruction == 0);
checkErrorHandling(
model,
&Implementation::Model::getInstruction,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
BOOST_REQUIRE(derived_coordinates == coordinates);
checkErrorHandling(
model,
&Implementation::Model::getCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_direction_test) {
Implementation::Model* model = createBaseModel();
createInBaseCoordinates(model);
int direction = model->getDirection(0, 0);
BOOST_REQUIRE(direction == Abstract::LEFT);
checkErrorHandling(
model,
&Implementation::Model::getDirection,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(
model,
&Implementation::Model::getMass,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
// FIXME test doesn't work correctly without this function call.
// The solution is to use set instead of vector in model.
model->clearBeforeMove(0);
checkErrorHandling(
model,
&Implementation::Model::kill,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling<OneArgMethod>(
model,
&Implementation::Model::killByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int test_val = 1;
model->changeMassByCoordinates(coordinates, test_val);
int new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
model->changeMassByCoordinates(coordinates, -test_val);
new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == DEFAULT_MASS);
checkErrorHandling<TwoArgsMethod>(
model,
&Implementation::Model::changeMassByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
checkErrorHandling<MultiArgsMethod>(
model,
&Implementation::Model::createNewByCoordinates,
false
);
delete model;
}
<commit_msg>Model tests: remove FIXME<commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include "Model.hpp"
typedef int (Implementation::Model::*IntOneArgMethod) (
const Abstract::Point& coordinates
) const;
typedef void (Implementation::Model::*OneArgMethod) (
const Abstract::Point& coordinates
);
typedef void (Implementation::Model::*TwoArgsMethod) (
const Abstract::Point& coordinates,
int change
);
typedef void (Implementation::Model::*MultiArgsMethod) (
const Abstract::Point& coordinates,
int mass,
int direction,
int team,
int instruction
);
template<typename Func>
static void checkOneArgMethod(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates), Exception
);
}
template<typename Func>
void checkModelMethodForThrow(
Implementation::Model* model,
Func model_method,
int arg1,
int arg2
) {
BOOST_REQUIRE_THROW(
((*model).*model_method)(arg1, arg2), Exception
);
}
template<>
void checkModelMethodForThrow<IntOneArgMethod>(
Implementation::Model* model,
IntOneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<OneArgMethod>(
Implementation::Model* model,
OneArgMethod model_method,
int arg1,
int arg2
) {
checkOneArgMethod(model, model_method, arg1, arg2);
}
template<>
void checkModelMethodForThrow<TwoArgsMethod>(
Implementation::Model* model,
TwoArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(coordinates, 0), Exception
);
}
template<>
void checkModelMethodForThrow<MultiArgsMethod>(
Implementation::Model* model,
MultiArgsMethod model_method,
int arg1,
int arg2
) {
Abstract::Point coordinates(arg1, arg2);
BOOST_REQUIRE_THROW(
((*model).*model_method)(
coordinates,
DEFAULT_MASS,
0,
0,
0
),
Exception
);
}
// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
Implementation::Model* model,
Func model_method
) {
model->kill(0, 0);
checkModelMethodForThrow(
model,
model_method,
0,
0
);
}
template<typename Func>
static void checkErrorHandling(
Implementation::Model* model,
Func model_method,
bool dead_test
) {
// Range errors: test all combinations of
// "wrong" (outside of correct range) arguments.
// This solution works for coordinates and non-coordinates
// methods of Model. (< 0, = 0, > MAX)
int wrong_args[] = {-1, 0, MIN_WIDTH};
BOOST_FOREACH (int arg1, wrong_args) {
BOOST_FOREACH (int arg2, wrong_args) {
if ((arg1 != 0) || (arg2 != 0)) {
// (0, 0) is correct
checkModelMethodForThrow(
model,
model_method,
arg1,
arg2
);
}
}
}
if (dead_test) {
// "dead" error
// (attempt to do something with dead bacterium)
deadTest(model, model_method);
}
}
static Abstract::Point createInBaseCoordinates(
Implementation::Model* model
) {
Abstract::Point coordinates(0, 0);
model->createNewByCoordinates(
coordinates,
DEFAULT_MASS,
0,
0,
0
);
return coordinates;
}
static Implementation::Model* createBaseModel(
int bacteria = 0,
int teams = 1
) {
Implementation::Model* model =
Abstract::makeModel<Implementation::Model>(
MIN_WIDTH,
MIN_HEIGHT,
bacteria,
teams
);
return model;
}
BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int team = model->getTeamByCoordinates(coordinates);
BOOST_REQUIRE(team == 0);
checkErrorHandling<IntOneArgMethod>(
model,
&Implementation::Model::getTeamByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (width_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
delete model;
}
BOOST_AUTO_TEST_CASE (height_test) {
Implementation::Model* model = createBaseModel();
BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
delete model;
}
BOOST_AUTO_TEST_CASE (bacteria_number_test) {
Implementation::Model* model = createBaseModel();
int bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 0);
createInBaseCoordinates(model);
bacteria_number = model->getBacteriaNumber(0);
BOOST_REQUIRE(bacteria_number == 1);
// range errors
BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
delete model;
}
BOOST_AUTO_TEST_CASE (is_alive_test) {
Implementation::Model* model = createBaseModel(1, 1);
checkErrorHandling(
model,
&Implementation::Model::isAlive,
false
);
BOOST_REQUIRE(model->isAlive(0, 0) == true);
model->kill(0, 0);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
delete model;
}
BOOST_AUTO_TEST_CASE (get_instruction_test) {
Implementation::Model* model = createBaseModel(1, 1);
int instruction = model->getInstruction(0, 0);
BOOST_REQUIRE(instruction == 0);
checkErrorHandling(
model,
&Implementation::Model::getInstruction,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
BOOST_REQUIRE(derived_coordinates == coordinates);
checkErrorHandling(
model,
&Implementation::Model::getCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_direction_test) {
Implementation::Model* model = createBaseModel();
createInBaseCoordinates(model);
int direction = model->getDirection(0, 0);
BOOST_REQUIRE(direction == Abstract::LEFT);
checkErrorHandling(
model,
&Implementation::Model::getDirection,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (get_mass_test) {
Implementation::Model* model = createBaseModel(1, 1);
int mass = model->getMass(0, 0);
BOOST_REQUIRE(mass == DEFAULT_MASS);
checkErrorHandling(
model,
&Implementation::Model::getMass,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->kill(0, 0);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling(
model,
&Implementation::Model::kill,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
model->killByCoordinates(coordinates);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::EMPTY);
BOOST_REQUIRE(model->isAlive(0, 0) == false);
// error handling checks
createInBaseCoordinates(model);
model->clearBeforeMove(0);
checkErrorHandling<OneArgMethod>(
model,
&Implementation::Model::killByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
int test_val = 1;
model->changeMassByCoordinates(coordinates, test_val);
int new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
model->changeMassByCoordinates(coordinates, -test_val);
new_mass = model->getMassByCoordinates(coordinates);
BOOST_REQUIRE(new_mass == DEFAULT_MASS);
checkErrorHandling<TwoArgsMethod>(
model,
&Implementation::Model::changeMassByCoordinates,
true
);
delete model;
}
BOOST_AUTO_TEST_CASE (create_coordinates_test) {
Implementation::Model* model = createBaseModel();
Abstract::Point coordinates = createInBaseCoordinates(model);
Abstract::CellState state = model->cellState(coordinates);
BOOST_REQUIRE(state == Abstract::BACTERIUM);
checkErrorHandling<MultiArgsMethod>(
model,
&Implementation::Model::createNewByCoordinates,
false
);
delete model;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2002 *
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*
* "@(#) $Id: contLogTestImpl.cpp,v 1.8 2008/01/09 10:11:38 eallaert Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* eallaert 2007-11-05 initial version
*
*/
#include <contLogTestImpl.h>
#include <ACSErrTypeCommon.h>
#include <loggingLogLevelDefinition.h>
#include <loggingLogger.h>
#include "loggingGetLogger.h"
#include <iostream>
ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.8 2008/01/09 10:11:38 eallaert Exp $")
/* ----------------------------------------------------------------*/
TestLogLevelsComp::TestLogLevelsComp(
const ACE_CString &name,
maci::ContainerServices * containerServices) :
ACSComponentImpl(name, containerServices)
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp");
}
/* ----------------------------------------------------------------*/
TestLogLevelsComp::~TestLogLevelsComp()
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp");
ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name());
}
/* --------------------- [ CORBA interface ] ----------------------*/
::contLogTest::LongSeq*
TestLogLevelsComp::getLevels ()
throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)
{
Logging::Logger *l = getLogger();
::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);
level->length(5);
// need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++
for (int i = 0; i <5 ; i++)
level[i] = static_cast< CORBA::Long >(i);
level[3] = static_cast< CORBA::Long >(l->getRemoteLevel());
level[4] = static_cast< CORBA::Long >(l->getLocalLevel());
return level._retn();
}
void
TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)
{
ACE_Log_Priority p;
CORBA::ULong t=0;
for (t=0; t<levels.length(); t++){
p = LogLevelDefinition::getACELogPriority(levels[t]);
LogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]);
ACS_SHORT_LOG((p, "dummy log message for core level %d/%s", lld.getValue(), lld.getName().c_str()));
}
// log last message always at highest, non-OFF level (so it should get always through,
// unless the central level is put to OFF).
p = LogLevelDefinition::getACELogPriority(levels[levels.length()-2]);
ACS_SHORT_LOG((p, "===last log messsage==="));
}
/* --------------- [ MACI DLL support functions ] -----------------*/
#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)
/* ----------------------------------------------------------------*/
/*___oOo___*/
<commit_msg>Corrected type in "last log message" within logDummyMessages() method. This lead to this last message not being recognised as such, and a timeout in LogSeriesExpectant.java<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) Associated Universities Inc., 2002 *
* (c) European Southern Observatory, 2002
* Copyright by ESO (in the framework of the ALMA collaboration)
* and Cosylab 2002, All rights reserved
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*
* "@(#) $Id: contLogTestImpl.cpp,v 1.9 2008/01/10 09:32:20 eallaert Exp $"
*
* who when what
* -------- ---------- ----------------------------------------------
* eallaert 2007-11-05 initial version
*
*/
#include <contLogTestImpl.h>
#include <ACSErrTypeCommon.h>
#include <loggingLogLevelDefinition.h>
#include <loggingLogger.h>
#include "loggingGetLogger.h"
#include <iostream>
ACE_RCSID(contLogTest, contLogTestImpl, "$Id: contLogTestImpl.cpp,v 1.9 2008/01/10 09:32:20 eallaert Exp $")
/* ----------------------------------------------------------------*/
TestLogLevelsComp::TestLogLevelsComp(
const ACE_CString &name,
maci::ContainerServices * containerServices) :
ACSComponentImpl(name, containerServices)
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::TestLogLevelsComp");
}
/* ----------------------------------------------------------------*/
TestLogLevelsComp::~TestLogLevelsComp()
{
// ACS_TRACE is used for debugging purposes
ACS_TRACE("::TestLogLevelsComp::~TestLogLevelsComp");
ACS_DEBUG_PARAM("::TestLogLevelsComp::~TestLogLevelsComp", "Destroying %s...", name());
}
/* --------------------- [ CORBA interface ] ----------------------*/
::contLogTest::LongSeq*
TestLogLevelsComp::getLevels ()
throw (CORBA::SystemException, ACSErrTypeCommon::CouldntPerformActionEx)
{
Logging::Logger *l = getLogger();
::contLogTest::LongSeq_var level = new ::contLogTest::LongSeq(5);
level->length(5);
// need the equivalent of Java's logConfig.getMinLogLevel() etc. in C++
for (int i = 0; i <5 ; i++)
level[i] = static_cast< CORBA::Long >(i);
level[3] = static_cast< CORBA::Long >(l->getRemoteLevel());
level[4] = static_cast< CORBA::Long >(l->getLocalLevel());
return level._retn();
}
void
TestLogLevelsComp::logDummyMessages (const ::contLogTest::LongSeq & levels)
{
ACE_Log_Priority p;
CORBA::ULong t=0;
for (t=0; t<levels.length(); t++){
p = LogLevelDefinition::getACELogPriority(levels[t]);
LogLevelDefinition lld = LogLevelDefinition::fromInteger(levels[t]);
ACS_SHORT_LOG((p, "dummy log message for core level %d/%s", lld.getValue(), lld.getName().c_str()));
}
// log last message always at highest, non-OFF level (so it should get always through,
// unless the central level is put to OFF).
p = LogLevelDefinition::getACELogPriority(AcsLogLevels::EMERGENCY_VAL);
ACS_SHORT_LOG((p, "===last log message==="));
}
/* --------------- [ MACI DLL support functions ] -----------------*/
#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(TestLogLevelsComp)
/* ----------------------------------------------------------------*/
/*___oOo___*/
<|endoftext|>
|
<commit_before>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrTesselatedPathRenderer.h"
#include "GrMemory.h"
#include "GrPathUtils.h"
#include <internal_glu.h>
struct PolygonData {
PolygonData(GrTDArray<GrPoint>* vertices, GrTDArray<short>* indices)
: fVertices(vertices)
, fIndices(indices)
{
}
GrTDArray<GrPoint>* fVertices;
GrTDArray<short>* fIndices;
};
static void beginData(GLenum type, void* data)
{
GR_DEBUGASSERT(type == GL_TRIANGLES);
}
static void edgeFlagData(GLboolean flag, void* data)
{
}
static void vertexData(void* vertexData, void* data)
{
short* end = static_cast<PolygonData*>(data)->fIndices->append();
*end = reinterpret_cast<long>(vertexData);
}
static void endData(void* data)
{
}
static void combineData(GLdouble coords[3], void* vertexData[4],
GLfloat weight[4], void **outData, void* data)
{
PolygonData* polygonData = static_cast<PolygonData*>(data);
int index = polygonData->fVertices->count();
*polygonData->fVertices->append() = GrPoint::Make(static_cast<float>(coords[0]),
static_cast<float>(coords[1]));
*outData = reinterpret_cast<void*>(index);
}
typedef void (*TESSCB)();
static unsigned fill_type_to_glu_winding_rule(GrPathFill fill) {
switch (fill) {
case kWinding_PathFill:
return GLU_TESS_WINDING_NONZERO;
case kEvenOdd_PathFill:
return GLU_TESS_WINDING_ODD;
case kInverseWinding_PathFill:
return GLU_TESS_WINDING_POSITIVE;
case kInverseEvenOdd_PathFill:
return GLU_TESS_WINDING_ODD;
case kHairLine_PathFill:
return GLU_TESS_WINDING_NONZERO; // FIXME: handle this
default:
GrAssert(!"Unknown path fill!");
return 0;
}
}
GrTesselatedPathRenderer::GrTesselatedPathRenderer() {
}
class Edge {
public:
Edge() {}
Edge(float x, float y, float z) : fX(x), fY(y), fZ(z) {}
GrPoint intersect(const Edge& other) {
return GrPoint::Make(
(fY * other.fZ - other.fY * fZ) / (fX * other.fY - other.fX * fY),
(fX * other.fZ - other.fX * fZ) / (other.fX * fY - fX * other.fY));
}
float fX, fY, fZ;
};
typedef GrTDArray<Edge> EdgeArray;
bool isCCW(const GrPoint* v)
{
GrVec v1 = v[1] - v[0];
GrVec v2 = v[2] - v[1];
return v1.cross(v2) < 0;
}
static size_t computeEdgesAndOffsetVertices(const GrMatrix& matrix,
const GrMatrix& inverse,
GrPoint* vertices,
size_t numVertices,
EdgeArray* edges)
{
GrPoint p = vertices[numVertices - 1];
matrix.mapPoints(&p, 1);
float sign = isCCW(vertices) ? -1.0f : 1.0f;
for (size_t i = 0; i < numVertices; ++i) {
GrPoint q = vertices[i];
matrix.mapPoints(&q, 1);
if (p == q) continue;
GrVec tangent = GrVec::Make(p.fY - q.fY, q.fX - p.fX);
float scale = sign / tangent.length();
float cross2 = p.fX * q.fY - q.fX * p.fY;
Edge edge(tangent.fX * scale,
tangent.fY * scale,
cross2 * scale + 0.5f);
*edges->append() = edge;
p = q;
}
Edge prev_edge = *edges->back();
for (size_t i = 0; i < edges->count(); ++i) {
Edge edge = edges->at(i);
vertices[i] = prev_edge.intersect(edge);
inverse.mapPoints(&vertices[i], 1);
prev_edge = edge;
}
return edges->count();
}
void GrTesselatedPathRenderer::drawPath(GrDrawTarget* target,
GrDrawTarget::StageBitfield stages,
GrPathIter* path,
GrPathFill fill,
const GrPoint* translate) {
GrDrawTarget::AutoStateRestore asr(target);
bool colorWritesWereDisabled = target->isColorWriteDisabled();
// face culling doesn't make sense here
GrAssert(GrDrawTarget::kBoth_DrawFace == target->getDrawFace());
GrMatrix viewM = target->getViewMatrix();
// In order to tesselate the path we get a bound on how much the matrix can
// stretch when mapping to screen coordinates.
GrScalar stretch = viewM.getMaxStretch();
bool useStretch = stretch > 0;
GrScalar tol = GrPathUtils::gTolerance;
if (!useStretch) {
// TODO: deal with perspective in some better way.
tol /= 10;
} else {
GrScalar sinv = GR_Scalar1 / stretch;
tol = GrMul(tol, sinv);
}
GrScalar tolSqd = GrMul(tol, tol);
path->rewind();
int subpathCnt;
int maxPts = GrPathUtils::worstCasePointCount(path, &subpathCnt, tol);
GrVertexLayout layout = 0;
for (int s = 0; s < GrDrawTarget::kNumStages; ++s) {
if ((1 << s) & stages) {
layout |= GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s);
}
}
bool inverted = IsFillInverted(fill);
if (inverted) {
maxPts += 4;
subpathCnt++;
}
GrPoint* base = new GrPoint[maxPts];
GrPoint* vert = base;
GrPoint* subpathBase = base;
GrAutoSTMalloc<8, uint16_t> subpathVertCount(subpathCnt);
path->rewind();
GrPoint pts[4];
bool first = true;
int subpath = 0;
for (;;) {
GrPathCmd cmd = path->next(pts);
switch (cmd) {
case kMove_PathCmd:
if (!first) {
subpathVertCount[subpath] = vert-subpathBase;
subpathBase = vert;
++subpath;
}
*vert = pts[0];
vert++;
break;
case kLine_PathCmd:
*vert = pts[1];
vert++;
break;
case kQuadratic_PathCmd: {
GrPathUtils::generateQuadraticPoints(pts[0], pts[1], pts[2],
tolSqd, &vert,
GrPathUtils::quadraticPointCount(pts, tol));
break;
}
case kCubic_PathCmd: {
GrPathUtils::generateCubicPoints(pts[0], pts[1], pts[2], pts[3],
tolSqd, &vert,
GrPathUtils::cubicPointCount(pts, tol));
break;
}
case kClose_PathCmd:
break;
case kEnd_PathCmd:
subpathVertCount[subpath] = vert-subpathBase;
++subpath; // this could be only in debug
goto FINISHED;
}
first = false;
}
FINISHED:
if (translate) {
for (int i = 0; i < vert - base; i++) {
base[i].offset(translate->fX, translate->fY);
}
}
if (inverted) {
GrRect bounds;
GrAssert(NULL != target->getRenderTarget());
bounds.setLTRB(0, 0,
GrIntToScalar(target->getRenderTarget()->width()),
GrIntToScalar(target->getRenderTarget()->height()));
GrMatrix vmi;
if (target->getViewInverse(&vmi)) {
vmi.mapRect(&bounds);
}
*vert++ = GrPoint::Make(bounds.fLeft, bounds.fTop);
*vert++ = GrPoint::Make(bounds.fLeft, bounds.fBottom);
*vert++ = GrPoint::Make(bounds.fRight, bounds.fBottom);
*vert++ = GrPoint::Make(bounds.fRight, bounds.fTop);
subpathVertCount[subpath++] = 4;
}
GrAssert(subpath == subpathCnt);
GrAssert((vert - base) <= maxPts);
size_t count = vert - base;
if (count < 3) {
delete[] base;
return;
}
if (subpathCnt == 1 && !inverted && path->convexHint() == kConvex_ConvexHint) {
if (target->isAntialiasState()) {
target->enableState(GrDrawTarget::kEdgeAA_StateBit);
EdgeArray edges;
GrMatrix inverse, matrix = target->getViewMatrix();
target->getViewInverse(&inverse);
count = computeEdgesAndOffsetVertices(matrix, inverse, base, count, &edges);
GrPoint triangle[3];
triangle[0] = base[0];
Edge triangleEdges[6];
triangleEdges[0] = *edges.back();
triangleEdges[1] = edges[0];
for (size_t i = 1; i < count - 1; i++) {
triangle[1] = base[i];
triangle[2] = base[i + 1];
triangleEdges[2] = edges[i - 1];
triangleEdges[3] = edges[i];
triangleEdges[4] = edges[i];
triangleEdges[5] = edges[i + 1];
target->setVertexSourceToArray(layout, triangle, 3);
target->setEdgeAAData(&triangleEdges[0].fX);
target->drawNonIndexed(kTriangles_PrimitiveType, 0, 3);
}
target->disableState(GrDrawTarget::kEdgeAA_StateBit);
} else {
target->setVertexSourceToArray(layout, base, count);
target->drawNonIndexed(kTriangleFan_PrimitiveType, 0, count);
}
delete[] base;
return;
}
// FIXME: This copy could be removed if we had (templated?) versions of
// generate_*_point above that wrote directly into doubles.
double* inVertices = new double[count * 3];
for (size_t i = 0; i < count; ++i) {
inVertices[i * 3] = base[i].fX;
inVertices[i * 3 + 1] = base[i].fY;
inVertices[i * 3 + 2] = 1.0;
}
GLUtesselator* tess = internal_gluNewTess();
unsigned windingRule = fill_type_to_glu_winding_rule(fill);
internal_gluTessProperty(tess, GLU_TESS_WINDING_RULE, windingRule);
internal_gluTessCallback(tess, GLU_TESS_BEGIN_DATA, (TESSCB) &beginData);
internal_gluTessCallback(tess, GLU_TESS_VERTEX_DATA, (TESSCB) &vertexData);
internal_gluTessCallback(tess, GLU_TESS_END_DATA, (TESSCB) &endData);
internal_gluTessCallback(tess, GLU_TESS_EDGE_FLAG_DATA, (TESSCB) &edgeFlagData);
internal_gluTessCallback(tess, GLU_TESS_COMBINE_DATA, (TESSCB) &combineData);
GrTDArray<short> indices;
GrTDArray<GrPoint> vertices;
PolygonData data(&vertices, &indices);
internal_gluTessBeginPolygon(tess, &data);
size_t i = 0;
for (int sp = 0; sp < subpathCnt; ++sp) {
internal_gluTessBeginContour(tess);
int start = i;
int end = start + subpathVertCount[sp];
for (; i < end; ++i) {
double* inVertex = &inVertices[i * 3];
*vertices.append() = GrPoint::Make(inVertex[0], inVertex[1]);
internal_gluTessVertex(tess, inVertex, reinterpret_cast<void*>(i));
}
internal_gluTessEndContour(tess);
}
internal_gluTessEndPolygon(tess);
internal_gluDeleteTess(tess);
if (indices.count() > 0) {
target->setVertexSourceToArray(layout, vertices.begin(), vertices.count());
target->setIndexSourceToArray(indices.begin(), indices.count());
target->drawIndexed(kTriangles_PrimitiveType,
0,
0,
vertices.count(),
indices.count());
}
delete[] inVertices;
delete[] base;
}
bool GrTesselatedPathRenderer::canDrawPath(const GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill) const {
return kHairLine_PathFill != fill;
}
void GrTesselatedPathRenderer::drawPathToStencil(GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill,
const GrPoint* translate) {
GrAlwaysAssert(!"multipass stencil should not be needed");
}
bool GrTesselatedPathRenderer::supportsAA(GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill) {
int subpathCnt = 0;
int tol = GrPathUtils::gTolerance;
GrPathUtils::worstCasePointCount(path, &subpathCnt, tol);
return (subpathCnt == 1 &&
!IsFillInverted(fill) &&
path->convexHint() == kConvex_ConvexHint);
}
<commit_msg>Fix winding order check for negative scale in tesselated path rendering. The isCCW() code in GrTesselatedPathRenderer was using untransformed vertices, which fails for transforms with negative scale. Doing the check after transformation fixes it. This was causing some missing geometry in the PolyToPoly and Shapes tests in SampleApp.<commit_after>/*
Copyright 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "GrTesselatedPathRenderer.h"
#include "GrMemory.h"
#include "GrPathUtils.h"
#include <internal_glu.h>
struct PolygonData {
PolygonData(GrTDArray<GrPoint>* vertices, GrTDArray<short>* indices)
: fVertices(vertices)
, fIndices(indices)
{
}
GrTDArray<GrPoint>* fVertices;
GrTDArray<short>* fIndices;
};
static void beginData(GLenum type, void* data)
{
GR_DEBUGASSERT(type == GL_TRIANGLES);
}
static void edgeFlagData(GLboolean flag, void* data)
{
}
static void vertexData(void* vertexData, void* data)
{
short* end = static_cast<PolygonData*>(data)->fIndices->append();
*end = reinterpret_cast<long>(vertexData);
}
static void endData(void* data)
{
}
static void combineData(GLdouble coords[3], void* vertexData[4],
GLfloat weight[4], void **outData, void* data)
{
PolygonData* polygonData = static_cast<PolygonData*>(data);
int index = polygonData->fVertices->count();
*polygonData->fVertices->append() = GrPoint::Make(static_cast<float>(coords[0]),
static_cast<float>(coords[1]));
*outData = reinterpret_cast<void*>(index);
}
typedef void (*TESSCB)();
static unsigned fill_type_to_glu_winding_rule(GrPathFill fill) {
switch (fill) {
case kWinding_PathFill:
return GLU_TESS_WINDING_NONZERO;
case kEvenOdd_PathFill:
return GLU_TESS_WINDING_ODD;
case kInverseWinding_PathFill:
return GLU_TESS_WINDING_POSITIVE;
case kInverseEvenOdd_PathFill:
return GLU_TESS_WINDING_ODD;
case kHairLine_PathFill:
return GLU_TESS_WINDING_NONZERO; // FIXME: handle this
default:
GrAssert(!"Unknown path fill!");
return 0;
}
}
GrTesselatedPathRenderer::GrTesselatedPathRenderer() {
}
class Edge {
public:
Edge() {}
Edge(float x, float y, float z) : fX(x), fY(y), fZ(z) {}
GrPoint intersect(const Edge& other) {
return GrPoint::Make(
(fY * other.fZ - other.fY * fZ) / (fX * other.fY - other.fX * fY),
(fX * other.fZ - other.fX * fZ) / (other.fX * fY - fX * other.fY));
}
float fX, fY, fZ;
};
typedef GrTDArray<Edge> EdgeArray;
bool isCCW(const GrPoint* pts)
{
GrVec v1 = pts[1] - pts[0];
GrVec v2 = pts[2] - pts[1];
return v1.cross(v2) < 0;
}
static size_t computeEdgesAndOffsetVertices(const GrMatrix& matrix,
const GrMatrix& inverse,
GrPoint* vertices,
size_t numVertices,
EdgeArray* edges)
{
matrix.mapPoints(vertices, numVertices);
GrPoint p = vertices[numVertices - 1];
float sign = isCCW(vertices) ? -1.0f : 1.0f;
for (size_t i = 0; i < numVertices; ++i) {
GrPoint q = vertices[i];
if (p == q) continue;
GrVec tangent = GrVec::Make(p.fY - q.fY, q.fX - p.fX);
float scale = sign / tangent.length();
float cross2 = p.fX * q.fY - q.fX * p.fY;
Edge edge(tangent.fX * scale,
tangent.fY * scale,
cross2 * scale + 0.5f);
*edges->append() = edge;
p = q;
}
Edge prev_edge = *edges->back();
for (size_t i = 0; i < edges->count(); ++i) {
Edge edge = edges->at(i);
vertices[i] = prev_edge.intersect(edge);
inverse.mapPoints(&vertices[i], 1);
prev_edge = edge;
}
return edges->count();
}
void GrTesselatedPathRenderer::drawPath(GrDrawTarget* target,
GrDrawTarget::StageBitfield stages,
GrPathIter* path,
GrPathFill fill,
const GrPoint* translate) {
GrDrawTarget::AutoStateRestore asr(target);
bool colorWritesWereDisabled = target->isColorWriteDisabled();
// face culling doesn't make sense here
GrAssert(GrDrawTarget::kBoth_DrawFace == target->getDrawFace());
GrMatrix viewM = target->getViewMatrix();
// In order to tesselate the path we get a bound on how much the matrix can
// stretch when mapping to screen coordinates.
GrScalar stretch = viewM.getMaxStretch();
bool useStretch = stretch > 0;
GrScalar tol = GrPathUtils::gTolerance;
if (!useStretch) {
// TODO: deal with perspective in some better way.
tol /= 10;
} else {
GrScalar sinv = GR_Scalar1 / stretch;
tol = GrMul(tol, sinv);
}
GrScalar tolSqd = GrMul(tol, tol);
path->rewind();
int subpathCnt;
int maxPts = GrPathUtils::worstCasePointCount(path, &subpathCnt, tol);
GrVertexLayout layout = 0;
for (int s = 0; s < GrDrawTarget::kNumStages; ++s) {
if ((1 << s) & stages) {
layout |= GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s);
}
}
bool inverted = IsFillInverted(fill);
if (inverted) {
maxPts += 4;
subpathCnt++;
}
GrPoint* base = new GrPoint[maxPts];
GrPoint* vert = base;
GrPoint* subpathBase = base;
GrAutoSTMalloc<8, uint16_t> subpathVertCount(subpathCnt);
path->rewind();
GrPoint pts[4];
bool first = true;
int subpath = 0;
for (;;) {
GrPathCmd cmd = path->next(pts);
switch (cmd) {
case kMove_PathCmd:
if (!first) {
subpathVertCount[subpath] = vert-subpathBase;
subpathBase = vert;
++subpath;
}
*vert = pts[0];
vert++;
break;
case kLine_PathCmd:
*vert = pts[1];
vert++;
break;
case kQuadratic_PathCmd: {
GrPathUtils::generateQuadraticPoints(pts[0], pts[1], pts[2],
tolSqd, &vert,
GrPathUtils::quadraticPointCount(pts, tol));
break;
}
case kCubic_PathCmd: {
GrPathUtils::generateCubicPoints(pts[0], pts[1], pts[2], pts[3],
tolSqd, &vert,
GrPathUtils::cubicPointCount(pts, tol));
break;
}
case kClose_PathCmd:
break;
case kEnd_PathCmd:
subpathVertCount[subpath] = vert-subpathBase;
++subpath; // this could be only in debug
goto FINISHED;
}
first = false;
}
FINISHED:
if (translate) {
for (int i = 0; i < vert - base; i++) {
base[i].offset(translate->fX, translate->fY);
}
}
if (inverted) {
GrRect bounds;
GrAssert(NULL != target->getRenderTarget());
bounds.setLTRB(0, 0,
GrIntToScalar(target->getRenderTarget()->width()),
GrIntToScalar(target->getRenderTarget()->height()));
GrMatrix vmi;
if (target->getViewInverse(&vmi)) {
vmi.mapRect(&bounds);
}
*vert++ = GrPoint::Make(bounds.fLeft, bounds.fTop);
*vert++ = GrPoint::Make(bounds.fLeft, bounds.fBottom);
*vert++ = GrPoint::Make(bounds.fRight, bounds.fBottom);
*vert++ = GrPoint::Make(bounds.fRight, bounds.fTop);
subpathVertCount[subpath++] = 4;
}
GrAssert(subpath == subpathCnt);
GrAssert((vert - base) <= maxPts);
size_t count = vert - base;
if (count < 3) {
delete[] base;
return;
}
if (subpathCnt == 1 && !inverted && path->convexHint() == kConvex_ConvexHint) {
if (target->isAntialiasState()) {
target->enableState(GrDrawTarget::kEdgeAA_StateBit);
EdgeArray edges;
GrMatrix inverse, matrix = target->getViewMatrix();
target->getViewInverse(&inverse);
count = computeEdgesAndOffsetVertices(matrix, inverse, base, count, &edges);
GrPoint triangle[3];
triangle[0] = base[0];
Edge triangleEdges[6];
triangleEdges[0] = *edges.back();
triangleEdges[1] = edges[0];
for (size_t i = 1; i < count - 1; i++) {
triangle[1] = base[i];
triangle[2] = base[i + 1];
triangleEdges[2] = edges[i - 1];
triangleEdges[3] = edges[i];
triangleEdges[4] = edges[i];
triangleEdges[5] = edges[i + 1];
target->setVertexSourceToArray(layout, triangle, 3);
target->setEdgeAAData(&triangleEdges[0].fX);
target->drawNonIndexed(kTriangles_PrimitiveType, 0, 3);
}
target->disableState(GrDrawTarget::kEdgeAA_StateBit);
} else {
target->setVertexSourceToArray(layout, base, count);
target->drawNonIndexed(kTriangleFan_PrimitiveType, 0, count);
}
delete[] base;
return;
}
// FIXME: This copy could be removed if we had (templated?) versions of
// generate_*_point above that wrote directly into doubles.
double* inVertices = new double[count * 3];
for (size_t i = 0; i < count; ++i) {
inVertices[i * 3] = base[i].fX;
inVertices[i * 3 + 1] = base[i].fY;
inVertices[i * 3 + 2] = 1.0;
}
GLUtesselator* tess = internal_gluNewTess();
unsigned windingRule = fill_type_to_glu_winding_rule(fill);
internal_gluTessProperty(tess, GLU_TESS_WINDING_RULE, windingRule);
internal_gluTessCallback(tess, GLU_TESS_BEGIN_DATA, (TESSCB) &beginData);
internal_gluTessCallback(tess, GLU_TESS_VERTEX_DATA, (TESSCB) &vertexData);
internal_gluTessCallback(tess, GLU_TESS_END_DATA, (TESSCB) &endData);
internal_gluTessCallback(tess, GLU_TESS_EDGE_FLAG_DATA, (TESSCB) &edgeFlagData);
internal_gluTessCallback(tess, GLU_TESS_COMBINE_DATA, (TESSCB) &combineData);
GrTDArray<short> indices;
GrTDArray<GrPoint> vertices;
PolygonData data(&vertices, &indices);
internal_gluTessBeginPolygon(tess, &data);
size_t i = 0;
for (int sp = 0; sp < subpathCnt; ++sp) {
internal_gluTessBeginContour(tess);
int start = i;
int end = start + subpathVertCount[sp];
for (; i < end; ++i) {
double* inVertex = &inVertices[i * 3];
*vertices.append() = GrPoint::Make(inVertex[0], inVertex[1]);
internal_gluTessVertex(tess, inVertex, reinterpret_cast<void*>(i));
}
internal_gluTessEndContour(tess);
}
internal_gluTessEndPolygon(tess);
internal_gluDeleteTess(tess);
if (indices.count() > 0) {
target->setVertexSourceToArray(layout, vertices.begin(), vertices.count());
target->setIndexSourceToArray(indices.begin(), indices.count());
target->drawIndexed(kTriangles_PrimitiveType,
0,
0,
vertices.count(),
indices.count());
}
delete[] inVertices;
delete[] base;
}
bool GrTesselatedPathRenderer::canDrawPath(const GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill) const {
return kHairLine_PathFill != fill;
}
void GrTesselatedPathRenderer::drawPathToStencil(GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill,
const GrPoint* translate) {
GrAlwaysAssert(!"multipass stencil should not be needed");
}
bool GrTesselatedPathRenderer::supportsAA(GrDrawTarget* target,
GrPathIter* path,
GrPathFill fill) {
int subpathCnt = 0;
int tol = GrPathUtils::gTolerance;
GrPathUtils::worstCasePointCount(path, &subpathCnt, tol);
return (subpathCnt == 1 &&
!IsFillInverted(fill) &&
path->convexHint() == kConvex_ConvexHint);
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local Includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_PERIODIC
#include "libmesh/periodic_boundaries.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/elem.h"
#include "libmesh/periodic_boundary.h"
#include "libmesh/mesh_base.h"
#include "libmesh/boundary_info.h"
namespace libMesh
{
PeriodicBoundaries::~PeriodicBoundaries()
{
for (auto & pr : *this)
delete pr.second;
}
PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id)
{
iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second;
}
const PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id) const
{
const_iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second;
}
const Elem * PeriodicBoundaries::neighbor(boundary_id_type boundary_id,
const PointLocatorBase & point_locator,
const Elem * e,
unsigned int side) const
{
// Find a point on that side (and only that side)
Point p = e->build_side_ptr(side)->centroid();
const PeriodicBoundaryBase * b = this->boundary(boundary_id);
libmesh_assert (b);
p = b->get_corresponding_pos(p);
std::set<const Elem *> candidate_elements;
point_locator.operator()(p, candidate_elements);
// We might have found multiple elements, e.g. if two distinct periodic
// boundaries are overlapping (see systems_of_equations_ex9, for example).
// As a result, we need to search for the element that has boundary_id.
const MeshBase & mesh = point_locator.get_mesh();
for(const Elem * elem_it : candidate_elements)
{
unsigned int s_neigh =
mesh.get_boundary_info().side_with_boundary_id(elem_it, b->pairedboundary);
// If s_neigh is not invalid then we have found an element that contains
// boundary_id, so return this element
if(s_neigh != libMesh::invalid_uint)
{
return elem_it;
}
}
libmesh_error_msg("Periodic boundary neighbor not found");
return nullptr;
}
} // namespace libMesh
#endif // LIBMESH_ENABLE_PERIODIC
<commit_msg>Make overzealous PBC error into careful assertion<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2020 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local Includes
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_PERIODIC
#include "libmesh/periodic_boundaries.h"
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/mesh_base.h"
#include "libmesh/periodic_boundary.h"
#include "libmesh/point_locator_base.h"
#include "libmesh/remote_elem.h"
namespace libMesh
{
PeriodicBoundaries::~PeriodicBoundaries()
{
for (auto & pr : *this)
delete pr.second;
}
PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id)
{
iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second;
}
const PeriodicBoundaryBase * PeriodicBoundaries::boundary(boundary_id_type id) const
{
const_iterator i = this->find(id);
if (i == this->end())
return nullptr;
return i->second;
}
const Elem * PeriodicBoundaries::neighbor(boundary_id_type boundary_id,
const PointLocatorBase & point_locator,
const Elem * e,
unsigned int side) const
{
// Find a point on that side (and only that side)
Point p = e->build_side_ptr(side)->centroid();
const PeriodicBoundaryBase * b = this->boundary(boundary_id);
libmesh_assert (b);
p = b->get_corresponding_pos(p);
std::set<const Elem *> candidate_elements;
point_locator.operator()(p, candidate_elements);
// We might have found multiple elements, e.g. if two distinct periodic
// boundaries are overlapping (see systems_of_equations_ex9, for example).
// As a result, we need to search for the element that has boundary_id.
const MeshBase & mesh = point_locator.get_mesh();
for(const Elem * elem_it : candidate_elements)
{
unsigned int s_neigh =
mesh.get_boundary_info().side_with_boundary_id(elem_it, b->pairedboundary);
// If s_neigh is not invalid then we have found an element that contains
// boundary_id, so return this element
if(s_neigh != libMesh::invalid_uint)
{
return elem_it;
}
}
// If we should have found a periodic neighbor but didn't then
// either we're on a ghosted element with a remote periodic neighbor
// or we're on a mesh with an inconsistent periodic boundary.
libmesh_assert_msg(!mesh.is_serial() &&
(e->processor_id() != mesh.processor_id()),
"Periodic boundary neighbor not found");
return remote_elem;
}
} // namespace libMesh
#endif // LIBMESH_ENABLE_PERIODIC
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPointSetDifferenceStatisticsCalculator.h"
mitk::PointSetDifferenceStatisticsCalculator::PointSetDifferenceStatisticsCalculator() :
m_StatisticsCalculated(false)
{
m_PointSet1 = mitk::PointSet::New();
m_PointSet2 = mitk::PointSet::New();
m_Statistics.Reset();
}
mitk::PointSetDifferenceStatisticsCalculator::PointSetDifferenceStatisticsCalculator(mitk::PointSet::Pointer pSet1, mitk::PointSet::Pointer pSet2)
{
m_PointSet1 = pSet1;
m_PointSet2 = pSet2;
m_StatisticsCalculated = false;
m_Statistics.Reset();
}
mitk::PointSetDifferenceStatisticsCalculator::~PointSetDifferenceStatisticsCalculator()
{
}
void mitk::PointSetDifferenceStatisticsCalculator::SetPointSets(mitk::PointSet::Pointer pSet1, mitk::PointSet::Pointer pSet2)
{
if (pSet1.IsNotNull())
{
m_PointSet1 = pSet1;
}
if (pSet2.IsNotNull())
{
m_PointSet2 = pSet2;
}
m_StatisticsCalculated = false;
m_Statistics.Reset();
}
std::vector<double> mitk::PointSetDifferenceStatisticsCalculator::GetDifferences()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_DifferencesVector;
}
std::vector<double> mitk::PointSetDifferenceStatisticsCalculator::GetSquaredDifferences()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_SquaredDifferencesVector;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMean()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Mean;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetSD()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Sigma;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetVariance()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Variance;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetRMS()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.RMS;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMedian()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Median;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMax()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Max;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMin()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Min;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetNumberOfPoints()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.N;
}
void mitk::PointSetDifferenceStatisticsCalculator::ComputeStatistics()
{
if ((m_PointSet1==NULL)||(m_PointSet2==NULL))
{
itkExceptionMacro("Point sets specified are not valid. Please specify correct Point sets");
}
else if (m_PointSet1->GetSize()!=m_PointSet2->GetSize())
{
itkExceptionMacro("PointSets are not equal. Please make sure that your PointSets have the same size and hold corresponding points.");
}
else if (m_PointSet1->GetSize()==0)
{
itkExceptionMacro("There are no points in the PointSets. Please make sure that the PointSets contain points");
}
else
{
double mean, sd, rms= 0.0;
std::vector<double> differencesVector;
mitk::Point3D point1;
mitk::Point3D point2;
int numberOfPoints = m_PointSet1->GetSize();
for (int i=0; i<numberOfPoints; i++)
{
point1 = m_PointSet1->GetPoint(i);
point2 = m_PointSet2->GetPoint(i);
double squaredDistance = point1.SquaredEuclideanDistanceTo(point2);
mean+=sqrt(squaredDistance);
rms+=squaredDistance;
this->m_SquaredDifferencesVector.push_back(squaredDistance);
differencesVector.push_back(sqrt(squaredDistance));
}
m_DifferencesVector = differencesVector;
mean = mean/numberOfPoints;
rms = sqrt(rms/numberOfPoints);
for (int i=0; i<differencesVector.size(); i++)
{
sd+=(differencesVector.at(i)-mean)*(differencesVector.at(i)-mean);
}
double variance = sd/numberOfPoints;
sd = sqrt(variance);
std::sort(differencesVector.begin(),differencesVector.end());
double min = differencesVector.at(0);
double max = differencesVector.at(numberOfPoints-1);
double median = 0.0;
if (numberOfPoints%2 == 0)
{
median = (differencesVector.at(numberOfPoints/2)+differencesVector.at(numberOfPoints/2-1))/2;
}
else
{
median = differencesVector.at((numberOfPoints-1)/2+1);
}
m_Statistics.Mean = mean;
m_Statistics.Sigma = sd;
m_Statistics.Variance = variance;
m_Statistics.RMS = rms;
m_Statistics.Min = differencesVector.at(0);
m_Statistics.Max = differencesVector.at(numberOfPoints-1);
m_Statistics.Median = median;
m_Statistics.N = numberOfPoints;
m_StatisticsCalculated = true;
}
}
<commit_msg>corrected zero check<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2009-05-12 19:56:03 +0200 (Di, 12 Mai 2009) $
Version: $Revision: 17179 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkPointSetDifferenceStatisticsCalculator.h"
mitk::PointSetDifferenceStatisticsCalculator::PointSetDifferenceStatisticsCalculator() :
m_StatisticsCalculated(false)
{
m_PointSet1 = mitk::PointSet::New();
m_PointSet2 = mitk::PointSet::New();
m_Statistics.Reset();
}
mitk::PointSetDifferenceStatisticsCalculator::PointSetDifferenceStatisticsCalculator(mitk::PointSet::Pointer pSet1, mitk::PointSet::Pointer pSet2)
{
m_PointSet1 = pSet1;
m_PointSet2 = pSet2;
m_StatisticsCalculated = false;
m_Statistics.Reset();
}
mitk::PointSetDifferenceStatisticsCalculator::~PointSetDifferenceStatisticsCalculator()
{
}
void mitk::PointSetDifferenceStatisticsCalculator::SetPointSets(mitk::PointSet::Pointer pSet1, mitk::PointSet::Pointer pSet2)
{
if (pSet1.IsNotNull())
{
m_PointSet1 = pSet1;
}
if (pSet2.IsNotNull())
{
m_PointSet2 = pSet2;
}
m_StatisticsCalculated = false;
m_Statistics.Reset();
}
std::vector<double> mitk::PointSetDifferenceStatisticsCalculator::GetDifferences()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_DifferencesVector;
}
std::vector<double> mitk::PointSetDifferenceStatisticsCalculator::GetSquaredDifferences()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_SquaredDifferencesVector;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMean()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Mean;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetSD()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Sigma;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetVariance()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Variance;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetRMS()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.RMS;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMedian()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Median;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMax()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Max;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetMin()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.Min;
}
double mitk::PointSetDifferenceStatisticsCalculator::GetNumberOfPoints()
{
if (!m_StatisticsCalculated)
{
this->ComputeStatistics();
}
return m_Statistics.N;
}
void mitk::PointSetDifferenceStatisticsCalculator::ComputeStatistics()
{
if ((m_PointSet1.IsNull())||(m_PointSet2.IsNull()))
{
itkExceptionMacro("Point sets specified are not valid. Please specify correct Point sets");
}
else if (m_PointSet1->GetSize()!=m_PointSet2->GetSize())
{
itkExceptionMacro("PointSets are not equal. Please make sure that your PointSets have the same size and hold corresponding points.");
}
else if (m_PointSet1->GetSize()==0)
{
itkExceptionMacro("There are no points in the PointSets. Please make sure that the PointSets contain points");
}
else
{
double mean, sd, rms= 0.0;
std::vector<double> differencesVector;
mitk::Point3D point1;
mitk::Point3D point2;
int numberOfPoints = m_PointSet1->GetSize();
for (int i=0; i<numberOfPoints; i++)
{
point1 = m_PointSet1->GetPoint(i);
point2 = m_PointSet2->GetPoint(i);
double squaredDistance = point1.SquaredEuclideanDistanceTo(point2);
mean+=sqrt(squaredDistance);
rms+=squaredDistance;
this->m_SquaredDifferencesVector.push_back(squaredDistance);
differencesVector.push_back(sqrt(squaredDistance));
}
m_DifferencesVector = differencesVector;
mean = mean/numberOfPoints;
rms = sqrt(rms/numberOfPoints);
for (int i=0; i<differencesVector.size(); i++)
{
sd+=(differencesVector.at(i)-mean)*(differencesVector.at(i)-mean);
}
double variance = sd/numberOfPoints;
sd = sqrt(variance);
std::sort(differencesVector.begin(),differencesVector.end());
double min = differencesVector.at(0);
double max = differencesVector.at(numberOfPoints-1);
double median = 0.0;
if (numberOfPoints%2 == 0)
{
median = (differencesVector.at(numberOfPoints/2)+differencesVector.at(numberOfPoints/2-1))/2;
}
else
{
median = differencesVector.at((numberOfPoints-1)/2+1);
}
m_Statistics.Mean = mean;
m_Statistics.Sigma = sd;
m_Statistics.Variance = variance;
m_Statistics.RMS = rms;
m_Statistics.Min = differencesVector.at(0);
m_Statistics.Max = differencesVector.at(numberOfPoints-1);
m_Statistics.Median = median;
m_Statistics.N = numberOfPoints;
m_StatisticsCalculated = true;
}
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <Eigen/Geometry>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit/robot_state/conversions.h>
#include "cros.hpp"
#include "c_container.h"
#include "moveit_container.hpp"
static void
robot_state_zero( robot_state::RobotState *state )
{
double *x = state->getVariablePositions();
size_t n = state->getVariableNames().size();
memset(x, 0, n * sizeof(x[0]) );
}
struct container *
tms_container_create( cros_node_handle *nh, const char *robot_description )
{
return new container(nh->node_handle, robot_description);
}
void
tms_container_destroy( struct container * c)
{
delete c;
}
size_t
tms_container_variable_count( struct container *c )
{
return c->robot_model->getVariableCount();
}
int
tms_container_merge_group( struct container *c, const char *group,
size_t n_group, const double *q_group,
size_t n_all, double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState state(c->robot_model);
state.setVariablePositions(q_all);
size_t n_all_model = state.getVariableCount();
state.setJointGroupPositions(group, q_group);
memcpy(q_all, state.getVariablePositions(), n_all_model*sizeof(q_all[0]));
return 0;
}
int
tms_container_set_start( struct container * c, size_t n_all, const double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState start_state = c->planning_scene->getCurrentState();
start_state.setVariablePositions(q_all);
start_state.update(true);
// c->req.start_state.joint_state.name = start_state.getVariableNames();
// {
// size_t n = c->req.start_state.joint_state.name.size();
// double *p = start_state.getVariablePositions();
// c->req.start_state.joint_state.position.resize( n );
// std::copy ( p, p+n,
// c->req.start_state.joint_state.position.begin() );
// }
// c->req.start_state.is_diff = true;
c->planning_scene->setCurrentState(start_state);
// // Print stuff
// {
// double r[4],v[3];
// tms_container_group_fk( c, group, n, q, r, v );
// fprintf(stderr,
// "r_start[4] = {%f, %f, %f, %f}\n"
// "v_start[3] = {%f, %f, %f}\n",
// r[0], r[1], r[2], r[3],
// v[0], v[1], v[2] );
// }
return 0;
}
int
tms_container_set_group( struct container * c, const char *group )
{
c->req.group_name = group;
return 0;
}
int
tms_container_goal_clear( struct container *c )
{
c->req.goal_constraints.clear();
return 0;
}
int
tms_container_set_js_goal( struct container * c, const char *group, size_t n_all, double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState goal_state(c->robot_model);
goal_state.setVariablePositions(q_all);
const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup(group);
moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
joint_model_group);
c->req.goal_constraints.push_back(joint_goal);
{
double *x = goal_state.getVariablePositions();
for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
fprintf(stderr, "goal %lu: %f\n", i, x[i] );
}
}
return 0;
}
int
tms_container_set_ws_goal( struct container * c, const char *link, const double quat[4], const double vec[3],
double tol_x, double tol_angle )
{
geometry_msgs::PoseStamped stamped_pose;
stamped_pose.header.frame_id = "base";
geometry_msgs::Pose &pose = stamped_pose.pose;
pose.orientation.x = quat[0];
pose.orientation.y = quat[1];
pose.orientation.z = quat[2];
pose.orientation.w = quat[3];
pose.position.x = vec[0];
pose.position.y = vec[1];
pose.position.z = vec[2];
fprintf(stderr,"constructing pose goal\n");
moveit_msgs::Constraints pose_goal =
kinematic_constraints::constructGoalConstraints(link, stamped_pose, tol_x, tol_angle );
fprintf(stderr,"adding pose goal...\n");
c->req.goal_constraints.push_back(pose_goal);
fprintf(stderr,"...added\n");
return 0;
// robot_state::RobotState goal_state(c->robot_model);
// /* Zero positions because somebody's not inititializing their shit */
// robot_state_zero( &goal_state);
// const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup(group);
// bool got_ik = goal_state.setFromIK(joint_model_group,pose);
// fprintf(stderr, "IK: %s\n", got_ik ? "yes" : "no" );
// if( ! got_ik ) return -1;
// moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
// joint_model_group);
// c->req.goal_constraints.push_back(joint_goal);
// {
// double *x = goal_state.getVariablePositions();
// for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
// fprintf(stderr, "goal %lu: %f\n", i, x[i] );
// }
// }
// {
// double r[4],v[3];
// tms_container_link_fk( c, tms_container_group_endlink( c, group ),
// goal_state.getVariableNames().size(),
// goal_state.getVariablePositions(),
// r, v );
// fprintf(stderr,
// "r_goal[4] = {%f, %f, %f, %f}\n"
// "v_goal[3] = {%f, %f, %f}\n",
// r[0], r[1], r[2], r[3],
// v[0], v[1], v[2] );
// }
}
int
tms_container_plan( struct container * c,
double timeout,
size_t *n_vars, size_t *n_points, double **points)
{
/**********/
/* PLAN */
/**********/
moveit_msgs::MoveItErrorCodes err;
planning_interface::MotionPlanResponse res;
c->req.allowed_planning_time = timeout;
moveit::core::robotStateToRobotStateMsg(c->planning_scene->getCurrentState(), c->req.start_state);
std::cout << c->req << std::endl;
planning_interface::PlanningContextPtr context =
c->planner_instance->getPlanningContext(c->planning_scene, c->req, err);
context->solve(res);
if(res.error_code_.val != res.error_code_.SUCCESS)
{
//TODO: Why is this 0 instead of SUCCESS?
fprintf(stderr, "Planning failed: %d\n", res.error_code_.val );
//return 0;
}
if(res.error_code_.val < 0 ) {
fprintf(stderr, "returning failure\n");
return -1;
}
/************/
/* Result */
/************/
moveit_msgs::MotionPlanResponse res_msg;
res.getMessage(res_msg);
int i = 0;
for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
itr != res_msg.trajectory.joint_trajectory.points.end();
itr++ )
{
printf("waypoint %02d: ", i++);
for( auto j = itr->positions.begin();
j != itr->positions.end();
j++ )
{
printf("%f\t", *j );
}
printf("\n");
}
/* Copy Result */
*n_points = res_msg.trajectory.joint_trajectory.points.size();
if( 0 == n_points ) return 0;
*n_vars = res_msg.trajectory.joint_trajectory.points[0].positions.size();
i = 0;
double *start = (double*)malloc( sizeof(*start) * (*n_points) * (*n_vars) );
*points = start;
for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
itr != res_msg.trajectory.joint_trajectory.points.end();
itr++ )
{
size_t s = itr->positions.size();
if( s != *n_vars ) {
fprintf(stderr, "Bogus variable count\n");
*n_points = 0;
free(points);
return -1;
}
std::copy( itr->positions.begin(), itr->positions.end(), start );
// for( size_t j = 0; j < *n_vars; j ++ ) {
// printf("%f\t", start[j] );
// }
// printf("\n");
start = start + (*n_vars);
}
// printf("%lx\n",*points);
// for(i = 0; i < (*n_vars)*(*n_points); i++ ){
// printf("%f%c", (*points)[i], ( (i+1) % (*n_vars) ) ? '\t' : '\n' );
// }
/***************/
/* Visualize */
/***************/
moveit_msgs::DisplayTrajectory display_trajectory;
ROS_INFO("Visualizing plan 1 (again)");
display_trajectory.trajectory_start = res_msg.trajectory_start;
display_trajectory.trajectory.push_back(res_msg.trajectory);
c->display_publisher.publish(display_trajectory);
return 0;
}
const char *
tms_container_group_endlink( struct container * c, const char *group )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
const std::vector<std::string> &link_names = joint_model_group->getLinkModelNames();
const std::string & end_link = link_names[ link_names.size()-1];
return end_link.c_str();
}
size_t
tms_container_group_joint_count( struct container * c, const char *group )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
return joint_model_group->getVariableCount();
}
const char *
tms_container_group_joint_name( struct container * c, const char *group, size_t i )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
const std::vector< std::string > & names = joint_model_group->getActiveJointModelNames();
if( i < names.size() ) {
return names[i].c_str();
} else {
return NULL;
}
}
int
tms_container_group_fk( struct container * c, const char *group, size_t n, const double *q,
double r[4], double v[3] )
{
/* Find link for end of group */
const char *end_link = tms_container_group_endlink(c, group);
robot_state::RobotState state(c->robot_model);
/* Zero positions because somebody's not inititializing their shit */
robot_state_zero(&state);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
/* Set state */
{
std::vector<double> joint_values(n, 0.0);
std::copy ( q, q+n, joint_values.begin() );
state.setJointGroupPositions(joint_model_group, joint_values);
}
return tms_container_link_fk( c, end_link,
state.getVariableNames().size(),
state.getVariablePositions(),
r, v );
}
int
tms_container_link_fk( struct container * c, const char *link, size_t n, const double *q,
double r[4], double v[3] )
{
robot_state::RobotState state(c->robot_model);
// Make robot state
{
double *x = state.getVariablePositions();
size_t n2 = tms_container_variable_count(c);
if( n2 != n ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
n2, n);
return -1;
}
memcpy( x, q, n*sizeof(x[0]) );
}
// get TF
const Eigen::Affine3d estart_tf = state.getFrameTransform(link);
{
const Eigen::Quaternion<double> equat( estart_tf.rotation() );
r[0] = equat.x();
r[1] = equat.y();
r[2] = equat.z();
r[3] = equat.w();
}
{
const auto e_start = estart_tf.translation();
v[0] = e_start[0];
v[1] = e_start[1];
v[2] = e_start[2];
}
return 0;
}
// int
// tms_container_set_planner( struct container * c, const char *planner )
// {
// c->req.planner_id = planner;
// return 0;
// }
int
tms_container_set_volume( struct container * c,
const double min[3],
const double max[3] )
{
c->req.workspace_parameters.min_corner.x = min[0];
c->req.workspace_parameters.min_corner.y = min[1];
c->req.workspace_parameters.min_corner.z = min[2];
c->req.workspace_parameters.max_corner.x = max[0];
c->req.workspace_parameters.max_corner.y = max[1];
c->req.workspace_parameters.max_corner.z = max[2];
return 0;
}
<commit_msg>Omit moveit printing<commit_after>#include <cstdlib>
#include <Eigen/Geometry>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit/robot_state/conversions.h>
#include "cros.hpp"
#include "c_container.h"
#include "moveit_container.hpp"
static void
robot_state_zero( robot_state::RobotState *state )
{
double *x = state->getVariablePositions();
size_t n = state->getVariableNames().size();
memset(x, 0, n * sizeof(x[0]) );
}
struct container *
tms_container_create( cros_node_handle *nh, const char *robot_description )
{
return new container(nh->node_handle, robot_description);
}
void
tms_container_destroy( struct container * c)
{
delete c;
}
size_t
tms_container_variable_count( struct container *c )
{
return c->robot_model->getVariableCount();
}
int
tms_container_merge_group( struct container *c, const char *group,
size_t n_group, const double *q_group,
size_t n_all, double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState state(c->robot_model);
state.setVariablePositions(q_all);
size_t n_all_model = state.getVariableCount();
state.setJointGroupPositions(group, q_group);
memcpy(q_all, state.getVariablePositions(), n_all_model*sizeof(q_all[0]));
return 0;
}
int
tms_container_set_start( struct container * c, size_t n_all, const double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState start_state = c->planning_scene->getCurrentState();
start_state.setVariablePositions(q_all);
start_state.update(true);
// c->req.start_state.joint_state.name = start_state.getVariableNames();
// {
// size_t n = c->req.start_state.joint_state.name.size();
// double *p = start_state.getVariablePositions();
// c->req.start_state.joint_state.position.resize( n );
// std::copy ( p, p+n,
// c->req.start_state.joint_state.position.begin() );
// }
// c->req.start_state.is_diff = true;
c->planning_scene->setCurrentState(start_state);
// // Print stuff
// {
// double r[4],v[3];
// tms_container_group_fk( c, group, n, q, r, v );
// fprintf(stderr,
// "r_start[4] = {%f, %f, %f, %f}\n"
// "v_start[3] = {%f, %f, %f}\n",
// r[0], r[1], r[2], r[3],
// v[0], v[1], v[2] );
// }
return 0;
}
int
tms_container_set_group( struct container * c, const char *group )
{
c->req.group_name = group;
return 0;
}
int
tms_container_goal_clear( struct container *c )
{
c->req.goal_constraints.clear();
return 0;
}
int
tms_container_set_js_goal( struct container * c, const char *group, size_t n_all, double *q_all )
{
if( n_all != tms_container_variable_count(c) ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
tms_container_variable_count(c), n_all);
return -1;
}
robot_state::RobotState goal_state(c->robot_model);
goal_state.setVariablePositions(q_all);
const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup(group);
moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
joint_model_group);
c->req.goal_constraints.push_back(joint_goal);
{
double *x = goal_state.getVariablePositions();
for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
fprintf(stderr, "goal %lu: %f\n", i, x[i] );
}
}
return 0;
}
int
tms_container_set_ws_goal( struct container * c, const char *link, const double quat[4], const double vec[3],
double tol_x, double tol_angle )
{
geometry_msgs::PoseStamped stamped_pose;
stamped_pose.header.frame_id = "base";
geometry_msgs::Pose &pose = stamped_pose.pose;
pose.orientation.x = quat[0];
pose.orientation.y = quat[1];
pose.orientation.z = quat[2];
pose.orientation.w = quat[3];
pose.position.x = vec[0];
pose.position.y = vec[1];
pose.position.z = vec[2];
fprintf(stderr,"constructing pose goal\n");
moveit_msgs::Constraints pose_goal =
kinematic_constraints::constructGoalConstraints(link, stamped_pose, tol_x, tol_angle );
fprintf(stderr,"adding pose goal...\n");
c->req.goal_constraints.push_back(pose_goal);
fprintf(stderr,"...added\n");
return 0;
// robot_state::RobotState goal_state(c->robot_model);
// /* Zero positions because somebody's not inititializing their shit */
// robot_state_zero( &goal_state);
// const robot_state::JointModelGroup* joint_model_group = goal_state.getJointModelGroup(group);
// bool got_ik = goal_state.setFromIK(joint_model_group,pose);
// fprintf(stderr, "IK: %s\n", got_ik ? "yes" : "no" );
// if( ! got_ik ) return -1;
// moveit_msgs::Constraints joint_goal = kinematic_constraints::constructGoalConstraints(goal_state,
// joint_model_group);
// c->req.goal_constraints.push_back(joint_goal);
// {
// double *x = goal_state.getVariablePositions();
// for( size_t i = 0; i < goal_state.getVariableNames().size(); i++ ) {
// fprintf(stderr, "goal %lu: %f\n", i, x[i] );
// }
// }
// {
// double r[4],v[3];
// tms_container_link_fk( c, tms_container_group_endlink( c, group ),
// goal_state.getVariableNames().size(),
// goal_state.getVariablePositions(),
// r, v );
// fprintf(stderr,
// "r_goal[4] = {%f, %f, %f, %f}\n"
// "v_goal[3] = {%f, %f, %f}\n",
// r[0], r[1], r[2], r[3],
// v[0], v[1], v[2] );
// }
}
int
tms_container_plan( struct container * c,
double timeout,
size_t *n_vars, size_t *n_points, double **points)
{
/**********/
/* PLAN */
/**********/
moveit_msgs::MoveItErrorCodes err;
planning_interface::MotionPlanResponse res;
c->req.allowed_planning_time = timeout;
moveit::core::robotStateToRobotStateMsg(c->planning_scene->getCurrentState(), c->req.start_state);
//std::cout << c->req << std::endl;
planning_interface::PlanningContextPtr context =
c->planner_instance->getPlanningContext(c->planning_scene, c->req, err);
context->solve(res);
if(res.error_code_.val != res.error_code_.SUCCESS)
{
//TODO: Why is this 0 instead of SUCCESS?
fprintf(stderr, "Planning failed: %d\n", res.error_code_.val );
//return 0;
}
if(res.error_code_.val < 0 ) {
fprintf(stderr, "returning failure\n");
return -1;
}
/************/
/* Result */
/************/
moveit_msgs::MotionPlanResponse res_msg;
res.getMessage(res_msg);
int i = 0;
// for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
// itr != res_msg.trajectory.joint_trajectory.points.end();
// itr++ )
// {
// printf("waypoint %02d: ", i++);
// for( auto j = itr->positions.begin();
// j != itr->positions.end();
// j++ )
// {
// printf("%f\t", *j );
// }
// printf("\n");
// }
/* Copy Result */
*n_points = res_msg.trajectory.joint_trajectory.points.size();
if( 0 == n_points ) return 0;
*n_vars = res_msg.trajectory.joint_trajectory.points[0].positions.size();
i = 0;
double *start = (double*)malloc( sizeof(*start) * (*n_points) * (*n_vars) );
*points = start;
for( auto itr = res_msg.trajectory.joint_trajectory.points.begin();
itr != res_msg.trajectory.joint_trajectory.points.end();
itr++ )
{
size_t s = itr->positions.size();
if( s != *n_vars ) {
fprintf(stderr, "Bogus variable count\n");
*n_points = 0;
free(points);
return -1;
}
std::copy( itr->positions.begin(), itr->positions.end(), start );
// for( size_t j = 0; j < *n_vars; j ++ ) {
// printf("%f\t", start[j] );
// }
// printf("\n");
start = start + (*n_vars);
}
// printf("%lx\n",*points);
// for(i = 0; i < (*n_vars)*(*n_points); i++ ){
// printf("%f%c", (*points)[i], ( (i+1) % (*n_vars) ) ? '\t' : '\n' );
// }
/***************/
/* Visualize */
/***************/
moveit_msgs::DisplayTrajectory display_trajectory;
ROS_INFO("Visualizing plan 1 (again)");
display_trajectory.trajectory_start = res_msg.trajectory_start;
display_trajectory.trajectory.push_back(res_msg.trajectory);
c->display_publisher.publish(display_trajectory);
return 0;
}
const char *
tms_container_group_endlink( struct container * c, const char *group )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
const std::vector<std::string> &link_names = joint_model_group->getLinkModelNames();
const std::string & end_link = link_names[ link_names.size()-1];
return end_link.c_str();
}
size_t
tms_container_group_joint_count( struct container * c, const char *group )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
return joint_model_group->getVariableCount();
}
const char *
tms_container_group_joint_name( struct container * c, const char *group, size_t i )
{
robot_state::RobotState state(c->robot_model);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
const std::vector< std::string > & names = joint_model_group->getActiveJointModelNames();
if( i < names.size() ) {
return names[i].c_str();
} else {
return NULL;
}
}
int
tms_container_group_fk( struct container * c, const char *group, size_t n, const double *q,
double r[4], double v[3] )
{
/* Find link for end of group */
const char *end_link = tms_container_group_endlink(c, group);
robot_state::RobotState state(c->robot_model);
/* Zero positions because somebody's not inititializing their shit */
robot_state_zero(&state);
const robot_state::JointModelGroup* joint_model_group
= state.getJointModelGroup(group);
/* Set state */
{
std::vector<double> joint_values(n, 0.0);
std::copy ( q, q+n, joint_values.begin() );
state.setJointGroupPositions(joint_model_group, joint_values);
}
return tms_container_link_fk( c, end_link,
state.getVariableNames().size(),
state.getVariablePositions(),
r, v );
}
int
tms_container_link_fk( struct container * c, const char *link, size_t n, const double *q,
double r[4], double v[3] )
{
robot_state::RobotState state(c->robot_model);
// Make robot state
{
double *x = state.getVariablePositions();
size_t n2 = tms_container_variable_count(c);
if( n2 != n ) {
fprintf(stderr, "error: Size mismatch between robot model (%lu) and provided array (%lu)\n",
n2, n);
return -1;
}
memcpy( x, q, n*sizeof(x[0]) );
}
// get TF
const Eigen::Affine3d estart_tf = state.getFrameTransform(link);
{
const Eigen::Quaternion<double> equat( estart_tf.rotation() );
r[0] = equat.x();
r[1] = equat.y();
r[2] = equat.z();
r[3] = equat.w();
}
{
const auto e_start = estart_tf.translation();
v[0] = e_start[0];
v[1] = e_start[1];
v[2] = e_start[2];
}
return 0;
}
// int
// tms_container_set_planner( struct container * c, const char *planner )
// {
// c->req.planner_id = planner;
// return 0;
// }
int
tms_container_set_volume( struct container * c,
const double min[3],
const double max[3] )
{
c->req.workspace_parameters.min_corner.x = min[0];
c->req.workspace_parameters.min_corner.y = min[1];
c->req.workspace_parameters.min_corner.z = min[2];
c->req.workspace_parameters.max_corner.x = max[0];
c->req.workspace_parameters.max_corner.y = max[1];
c->req.workspace_parameters.max_corner.z = max[2];
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "ctvm.h"
#include "ctvm_util.h"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <Magick++.h>
int main(int argc, char **argv)
{
/* Test CTVM.dylib Link */
std::cout << std::endl;
std::cout << "Testing libctvm Link." << std::endl;
BoostDoubleMatrix DummySinogram(0, 0);
BoostDoubleVector DummyAngles(0);
// BoostDoubleMatrix DummyReconstruction = tval3_reconstruction(DummySinogram,DummyAngles);
std::cout << " " << "Passed." << std::endl;
/* Test CTVM_util.dylib Link */
std::cout << std::endl;
std::cout << "Allocating tiny(3x3) random matrix..." << std::endl;
BoostDoubleMatrix RandomMatrix = CreateRandomMatrix(3, 3);
std::cout << " " << RandomMatrix << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Rasterized Version..." << std::endl;
std::cout << " " << MatrixToVector(RandomMatrix) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Back to Matrix..." << std::endl;
std::cout << " " << VectorToMatrix(MatrixToVector(RandomMatrix), 3, 3) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Allocating large(1000x1000) random matrix..." << std::endl;
BoostDoubleMatrix RandomMatrixLarge = CreateRandomMatrix(1000, 1000);
std::cout << " " << "Passed." << std::endl;
std::cout << "Testing Normalization" << std::endl;
BoostDoubleMatrix TestMatrix(3, 3);
TestMatrix(0, 0) = 1; TestMatrix(0, 1) = 5; TestMatrix(0, 2) = 3;
TestMatrix(1, 0) = 2; TestMatrix(1, 1) = 11; TestMatrix(1, 2) = 5;
TestMatrix(2, 0) = 1; TestMatrix(2, 1) = 10; TestMatrix(2, 2) = 6;
std::cout << "Original Matrix: " << TestMatrix << std::endl;
std::cout << "Normalized: " << NormalizeMatrix(TestMatrix) << std::endl;
/* Test ImageMagick */
std::cout << std::endl;
using namespace Magick;
InitializeMagick("");
std::cout << "Testing ImageMagick Link." << std::endl;
Image someImage;
someImage.read("C:\\data\\peppers.jpg");
std::cout << " " << "Passed." << std::endl;
std::cout << "Creating Novel Image" << std::endl;
Image anotherImage;
anotherImage.size(Geometry(32, 32)); // Specify the dimensionality
Pixels anotherImageView(anotherImage); // Get a view of the image
PixelPacket aPixel;
aPixel.red = ColorGray::scaleDoubleToQuantum(0.5);
aPixel.green = ColorGray::scaleDoubleToQuantum(0.5);
aPixel.blue = ColorGray::scaleDoubleToQuantum(0.5);
*(anotherImageView.get(16, 16, 1, 1)) = aPixel;
anotherImage.type(GrayscaleType); // Specify the color type
anotherImageView.sync();
anotherImage.write("C:\\data\\testoutimage.png");
std::cout << " " << "Passed." << std::endl;
/* Test CTVM Image Load */
std::cout << std::endl;
std::cout << "Testing CTVM Image Load." << std::endl;
BoostDoubleMatrix ImageMatrix = LoadImage("C:\\data\\peppers.jpg");
std::cout << "Image Data:" << std::endl;
std::cout << ImageMatrix(0, 0) << " " << ImageMatrix(0, 1) << " " << ImageMatrix(0, 3) << std::endl;
std::cout << ImageMatrix(1, 0) << " " << ImageMatrix(1, 1) << " " << ImageMatrix(1, 3) << std::endl;
std::cout << ImageMatrix(2, 0) << " " << ImageMatrix(2, 1) << " " << ImageMatrix(2, 3) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Testing CTVM Image Write." << std::endl;
WriteImage(ImageMatrix, "C:\\data\\test_peppers.jpg");
std::cout << " " << "Passed." << std::endl;
/* Initialisation */
BoostDoubleMatrix A(2, 4), W(4, 2), NU(4, 2);
BoostDoubleVector U(4), U1(9), B(2), LAMBDA(2);
A(0, 0) = 1; A(0, 1) = 0; A(0, 2) = 1; A(0, 3) = 0;
A(1, 0) = 0; A(1, 1) = 1; A(1, 2) = 1; A(1, 3) = 1;
W(0, 0) = -1; W(0, 1) = 1;
W(1, 0) = 0; W(1, 1) = 1;
W(2, 0) = -1; W(2, 1) = 0;
W(3, 0) = 0; W(3, 1) = 1;
NU(0, 0) = 2; NU(0, 1) = 1;
NU(1, 0) = 1; NU(1, 1) = 0;
NU(2, 0) = 0; NU(2, 1) = 2;
NU(3, 0) = 1; NU(3, 1) = 3;
U(0) = 1;
U(1) = 2;
U(2) = 0;
U(3) = 1;
U1(0) = 1;
U1(1) = 2;
U1(2) = 0;
U1(3) = 1;
U1(4) = 3;
U1(5) = -2;
U1(6) = 0;
U1(7) = -1;
U1(8) = 0;
B(0) = 1;
B(1) = 2;
LAMBDA(0) = 2;
LAMBDA(1) = 1;
double beta = sqrt(2);
double mu = 3;
/* Test Gradient2DMatrix */
std::cout << std::endl;
std::cout << "Testing CTVM 2D Gradient for all i." << std::endl;
BoostDoubleMatrix X = VectorToMatrix(U, 2, 2);
BoostDoubleMatrix GradientMatrix = Gradient2DMatrix(U);
BoostDoubleMatrix Di = Norm_Gradient2DMatrix(U1, 4);
std::cout << "Original Matrix: " << X << std::endl;
std::cout << "Gradients DiU (right gradient, down gradient): " << GradientMatrix << std::endl;
std::cout << "Original Vector: " << U1 << std::endl;
std::cout << " D(4) times U: " << prod(Di,U1) << std::endl;
std::cout << " " << "Passed." << std::endl;
/*Test Lagrangian function*/
std::cout << std::endl;
double L = Lagrangian(A, U, B, W, NU, LAMBDA, beta, mu);
std::cout << "Lagrangian: " << L << std::endl; // expected result L = 8.6213
std::cout << " " << "Passed." << std::endl;
/*Test Shrinke function*/
std::cout << std::endl;
int ii = 1;
BoostDoubleVector DiUk = Gradient2D(U, ii);
BoostDoubleVector NUi (2);
for (int jj = 0; jj < 2; ++jj) { NUi(jj) = NU(ii, jj); }
BoostDoubleVector SHRIKE = Shrike(DiUk, NUi, beta);
std::cout << "W(i,l+1): " << SHRIKE << std::endl; // expected result SHRIKE = ( -0.2988585, -0.42265)
std::cout << " " << "Passed." << std::endl;
return 0;
}<commit_msg>correct<commit_after>#include <iostream>
#include "ctvm.h"
#include "ctvm_util.h"
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <Magick++.h>
int main(int argc, char **argv)
{
/* Test CTVM.dylib Link */
std::cout << std::endl;
std::cout << "Testing libctvm Link." << std::endl;
BoostDoubleMatrix DummySinogram(0, 0);
BoostDoubleVector DummyAngles(0);
// BoostDoubleMatrix DummyReconstruction = tval3_reconstruction(DummySinogram,DummyAngles);
std::cout << " " << "Passed." << std::endl;
/* Test CTVM_util.dylib Link */
std::cout << std::endl;
std::cout << "Allocating tiny(3x3) random matrix..." << std::endl;
BoostDoubleMatrix RandomMatrix = CreateRandomMatrix(3, 3);
std::cout << " " << RandomMatrix << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Rasterized Version..." << std::endl;
std::cout << " " << MatrixToVector(RandomMatrix) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Back to Matrix..." << std::endl;
std::cout << " " << VectorToMatrix(MatrixToVector(RandomMatrix), 3, 3) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Allocating large(1000x1000) random matrix..." << std::endl;
BoostDoubleMatrix RandomMatrixLarge = CreateRandomMatrix(1000, 1000);
std::cout << " " << "Passed." << std::endl;
std::cout << "Testing Normalization" << std::endl;
BoostDoubleMatrix TestMatrix(3, 3);
TestMatrix(0, 0) = 1; TestMatrix(0, 1) = 5; TestMatrix(0, 2) = 3;
TestMatrix(1, 0) = 2; TestMatrix(1, 1) = 11; TestMatrix(1, 2) = 5;
TestMatrix(2, 0) = 1; TestMatrix(2, 1) = 10; TestMatrix(2, 2) = 6;
std::cout << "Original Matrix: " << TestMatrix << std::endl;
std::cout << "Normalized: " << NormalizeMatrix(TestMatrix) << std::endl;
/* Test ImageMagick */
std::cout << std::endl;
using namespace Magick;
InitializeMagick("");
std::cout << "Testing ImageMagick Link." << std::endl;
Image someImage;
someImage.read("C:\\data\\peppers.jpg");
std::cout << " " << "Passed." << std::endl;
std::cout << "Creating Novel Image" << std::endl;
Image anotherImage;
anotherImage.size(Geometry(32, 32)); // Specify the dimensionality
Pixels anotherImageView(anotherImage); // Get a view of the image
PixelPacket aPixel;
aPixel.red = ColorGray::scaleDoubleToQuantum(0.5);
aPixel.green = ColorGray::scaleDoubleToQuantum(0.5);
aPixel.blue = ColorGray::scaleDoubleToQuantum(0.5);
*(anotherImageView.get(16, 16, 1, 1)) = aPixel;
anotherImage.type(GrayscaleType); // Specify the color type
anotherImageView.sync();
anotherImage.write("C:\\data\\testoutimage.png");
std::cout << " " << "Passed." << std::endl;
/* Test CTVM Image Load */
std::cout << std::endl;
std::cout << "Testing CTVM Image Load." << std::endl;
BoostDoubleMatrix ImageMatrix = LoadImage("C:\\data\\peppers.jpg");
std::cout << "Image Data:" << std::endl;
std::cout << ImageMatrix(0, 0) << " " << ImageMatrix(0, 1) << " " << ImageMatrix(0, 3) << std::endl;
std::cout << ImageMatrix(1, 0) << " " << ImageMatrix(1, 1) << " " << ImageMatrix(1, 3) << std::endl;
std::cout << ImageMatrix(2, 0) << " " << ImageMatrix(2, 1) << " " << ImageMatrix(2, 3) << std::endl;
std::cout << " " << "Passed." << std::endl;
std::cout << "Testing CTVM Image Write." << std::endl;
WriteImage(ImageMatrix, "C:\\data\\test_peppers.jpg");
std::cout << " " << "Passed." << std::endl;
/* Initialisation */
BoostDoubleMatrix A(2, 4), W(4, 2), NU(4, 2);
BoostDoubleVector U(4), U1(9), B(2), LAMBDA(2);
A(0, 0) = 1; A(0, 1) = 0; A(0, 2) = 1; A(0, 3) = 0;
A(1, 0) = 0; A(1, 1) = 1; A(1, 2) = 1; A(1, 3) = 1;
W(0, 0) = -1; W(0, 1) = 1;
W(1, 0) = 0; W(1, 1) = 1;
W(2, 0) = -1; W(2, 1) = 0;
W(3, 0) = 0; W(3, 1) = 1;
NU(0, 0) = 2; NU(0, 1) = 1;
NU(1, 0) = 1; NU(1, 1) = 0;
NU(2, 0) = 0; NU(2, 1) = 2;
NU(3, 0) = 1; NU(3, 1) = 3;
U(0) = 1;
U(1) = 2;
U(2) = 0;
U(3) = 1;
U1(0) = 1;
U1(1) = 2;
U1(2) = 0;
U1(3) = 1;
U1(4) = 3;
U1(5) = -2;
U1(6) = 0;
U1(7) = -1;
U1(8) = 0;
B(0) = 1;
B(1) = 2;
LAMBDA(0) = 2;
LAMBDA(1) = 1;
double beta = sqrt(2);
double mu = 3;
/* Test Gradient2DMatrix */
std::cout << std::endl;
std::cout << "Testing CTVM 2D Gradient for all i." << std::endl;
BoostDoubleMatrix X = VectorToMatrix(U, 2, 2);
BoostDoubleMatrix GradientMatrix = Gradient2DMatrix(U);
BoostDoubleMatrix Di = Unit_Gradient2DMatrix(U1, 4);
std::cout << "Original Matrix: " << X << std::endl;
std::cout << "Gradients DiU (right gradient, down gradient): " << GradientMatrix << std::endl;
std::cout << "Original Vector: " << U1 << std::endl;
std::cout << " D(4) times U: " << prod(Di,U1) << std::endl;
std::cout << " " << "Passed." << std::endl;
/*Test Lagrangian function*/
std::cout << std::endl;
double L = Lagrangian(A, U, B, W, NU, LAMBDA, beta, mu);
std::cout << "Lagrangian: " << L << std::endl; // expected result L = 8.6213
std::cout << " " << "Passed." << std::endl;
/*Test Shrinke function*/
std::cout << std::endl;
int ii = 1;
BoostDoubleVector DiUk = Gradient2D(U, ii);
BoostDoubleVector NUi (2);
for (int jj = 0; jj < 2; ++jj) { NUi(jj) = NU(ii, jj); }
BoostDoubleVector SHRIKE = Shrike(DiUk, NUi, beta);
std::cout << "W(i,l+1): " << SHRIKE << std::endl; // expected result SHRIKE = ( -0.2988585, -0.42265)
std::cout << " " << "Passed." << std::endl;
return 0;
}<|endoftext|>
|
<commit_before>// This file is for a basic string library so I do not have to use <cstring>
int getStringLength(char *str)
{
int result= 0;
for(int index = 0; str[index]; index++)
{
++result;
}
return result;
}
// Utliity function
void clearTempStringsToNull(char *str)
{
for(int index = 0; str[index] ; index++)
{
str[index] = 0;
}
}
//TODO: make another compreString that is case insensitive
bool compareString(char *fString, char *sString) // first/second String
{
int index = 0;
bool result = false;
while(fString[index])
{
if(fString[index] != sString[index])
{ break;}
index++;
}
if (!sString[index])
{
result = true;
}
return result;
}
//NOTE(Dustin): You will have to free this memory if you use this function
char* CopyString(char *strToCopy)
{
char *result = (char*)calloc(getStringLength(strToCopy)+1, sizeof(char));
for (int index = 0; strToCopy[index]; index++)
{
result[index] = strToCopy[index];
}
return result;
}
//NOTE(Dustin): Overloaded function, the calle defines were the copy gets placed
void CopyString(char *strToCopy, char *placeToPutCopiedString)
{
for (int index = 0; strToCopy[index]; index++)
{
placeToPutCopiedString[index] = strToCopy[index];
}
}
//NOTE(Dustin): Enduser needs to free the resultstring
char* CatString(char *originString, char *strToCat)
{
int originLength = getStringLength(originString);
int catStrLength = getStringLength(strToCat);
int outstringLength = (originLength + catStrLength);
int catStrIndex = 0;
char *result = ((char*)calloc(outstringLength+1, sizeof(char)));
for(int index = 0; index < outstringLength; index++)
{
if(index < originLength)
{
result[index] = originString[index];
}
else
{
result[index] = strToCat[catStrIndex];
catStrIndex++;
}
}
return result;
}
//Overloaded function to let calle tell where to put the result
void CatString(char *originString, char *strToCat, char *outputString)
{
int originLength = getStringLength(originString);
int catStrLength = getStringLength(strToCat);
int outstringLength = (originLength + catStrLength);
int catStrIndex = 0;
for(int index = 0; index < outstringLength; index++)
{
if(index < originLength)
{
outputString[index] = originString[index];
}
else
{
outputString[index] =strToCat[catStrIndex];
catStrLength++;
}
}
}
// if no outputstring then calle has to free | if you don't give me a valid savePlace you get nothing back about where you were in the string/array
char* SplitString(char *inputString, char strDelim, char *savePlace, char *outputString=NULL)
{
bool isParsingStringToDelim = true;
int index = 0;
int resultIndex = 0;
if(inputString)
{
while (isParsingStringToDelim)
{
//TODO: make this take multiple possible delim characters
if(inputString[index] == strDelim)
{
clearTempStringsToNull(savePlace);
isParsingStringToDelim = false;
index++;
if (savePlace)
{
for(int localIndex = 0; inputString[index]; localIndex++)
{
savePlace[localIndex] = inputString[index];
index++;
}
}
}
else
{
if (inputString[index])
{
resultIndex++;
index++;
}
else
{
break;
}
}
}
if(resultIndex)
{
if(!outputString)
{
char *result = ((char*)calloc(resultIndex+1, sizeof(char)));
for(int localIndex = 0; localIndex < resultIndex; localIndex++)
{
result[localIndex] = inputString[localIndex];
}
return result;
}
else
{
for(int localIndex = 0; localIndex < resultIndex; localIndex++)
{
outputString[localIndex] = inputString[localIndex];
}
return outputString; // make sure if this is in a if that it doesnt fail all the time
}
}
}
return NULL;
}
<commit_msg>continued refining of spechtStringLub<commit_after>// This file is for a basic string library so I do not have to use <cstring>
int getStringLength(char *str)
{
int result= 0;
for(int index = 0; str[index]; index++)
{
++result;
}
return result;
}
// Utliity function
void clearTempStringsToNull(char *str)
{
for(int index = 0; str[index] ; index++)
{
str[index] = 0;
}
}
//TODO: make another compreString that is case insensitive
bool compareString(char *fString, char *sString) // first/second String
{
int index = 0;
bool result = false;
while(fString[index])
{
if(fString[index] != sString[index])
{ break;}
index++;
}
if (!sString[index])
{
result = true;
}
return result;
}
//NOTE(dustin): if you don't pass a placetoputcopiedstring then you will have to free the result
char* CopyString(char *strToCopy, char *placeToPutCopiedString=NULL)
{
if(!placeToPutCopiedString)
{
char *result = (char*)calloc(getStringLength(strToCopy)+1, sizeof(char));
for (int index = 0; strToCopy[index]; index++)
{
result[index] = strToCopy[index];
}
return result;
}
else
{
for (int index = 0; strToCopy[index]; index++)
{
placeToPutCopiedString[index] = strToCopy[index];
}
return placeToPutCopiedString; // if you check for a return, this make it not fail everytime
}
}
//NOTE(Dustin): Enduser needs to free the resultstring
char* CatString(char *originString, char *strToCat, char *outputString=NULL)
{
int originLength = getStringLength(originString);
int catStrLength = getStringLength(strToCat);
int outstringLength = (originLength + catStrLength);
int catStrIndex = 0;
if(!outputString)
{
char *result = ((char*)calloc(outstringLength+1, sizeof(char)));
for(int index = 0; index < outstringLength; index++)
{
if(index < originLength)
{
result[index] = originString[index];
}
else
{
result[index] = strToCat[catStrIndex];
catStrIndex++;
}
}
return result;
}
else
{
for(int index = 0; index < outstringLength; index++)
{
if(index < originLength)
{
outputString[index] = originString[index];
}
else
{
outputString[index] =strToCat[catStrIndex];
catStrLength++;
}
}
return outputString; // if you check for a return, this makes it not just fail
}
}
// if no outputstring then calle has to free | if you don't give me a valid savePlace you get nothing back about where you were in the string/array
char* SplitString(char *inputString, char strDelim, char *savePlace, char *outputString=NULL)
{
bool isParsingStringToDelim = true;
int index = 0;
int resultIndex = 0;
if(inputString)
{
while (isParsingStringToDelim)
{
//TODO: make this take multiple possible delim characters
if(inputString[index] == strDelim)
{
clearTempStringsToNull(savePlace);
isParsingStringToDelim = false;
index++;
if (savePlace)
{
for(int localIndex = 0; inputString[index]; localIndex++)
{
savePlace[localIndex] = inputString[index];
index++;
}
}
}
else
{
if (inputString[index])
{
resultIndex++;
index++;
}
else
{
break;
}
}
}
if(resultIndex)
{
if(!outputString)
{
char *result = ((char*)calloc(resultIndex+1, sizeof(char)));
for(int localIndex = 0; localIndex < resultIndex; localIndex++)
{
result[localIndex] = inputString[localIndex];
}
return result;
}
else
{
for(int localIndex = 0; localIndex < resultIndex; localIndex++)
{
outputString[localIndex] = inputString[localIndex];
}
return outputString; // make sure if this is in a if that it doesnt fail all the time
}
}
}
return NULL;
}
<|endoftext|>
|
<commit_before>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
:field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
if (! pIndexer_->isRealTime())
{
std::string sorterName = field_+".tmp";
bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
sorterFullPath_= path.string();
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 130000000);
}
else
alloc_ = new boost::scoped_alloc(recycle_);
}
FieldIndexer::~FieldIndexer()
{
/*
InMemoryPostingMap::iterator iter = postingMap_.begin()
for(; iter !=postingMap_.end(); ++iter)
{
delete iter->second;
}
*/
if (alloc_) delete alloc_;
pMemCache_ = NULL;
if (sorter_) delete sorter_;
}
void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
char* pData = data;
memcpy(pData, &(termId), sizeof(termId));
pData += sizeof(termId);
memcpy(pData, &(docId), sizeof(docId));
pData += sizeof(docId);
memcpy(pData, &(offset), sizeof(offset));
pData += sizeof(offset);
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
if (pIndexer_->isRealTime())
{
InMemoryPosting* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
if (postingIter == postingMap_.end())
{
//curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->termId_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->offset_);
}
}
else
{
if (!sorter_)
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 130000000);
char data[12];
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
convert(data,iter->termId_,docid,iter->offset_);
sorter_->add_data(12, data);
}
}
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
InMemoryPosting* curPosting;
for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
if (postingIter == postingMap_.end())
{
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->first] = curPosting;
}
else
curPosting = postingIter->second;
ForwardIndexOffset::iterator endit = iter->second->end();
for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
curPosting->add(docid, *it);
}
}
void FieldIndexer::reset()
{
InMemoryPosting* pPosting;
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->hasNoChunk())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
}
void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
InMemoryPosting* pPosting;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->hasNoChunk())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
postingMap_.clear();
delete alloc_;
alloc_ = new boost::scoped_alloc(recycle_);
}
else
{
sorter_->sort();
FILE* f = fopen(sorterFullPath_.c_str(),"r");
fseek(f, 0, SEEK_SET);
uint64_t count;
fread(&count, sizeof(uint64_t), 1, f);
pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
uint8_t len;
fread(&len, sizeof(uint8_t), 1, f);
uint32_t docId,offset;
fread(&tid, sizeof(uint32_t), 1, f);
fread(&docId, sizeof(uint32_t), 1, f);
fread(&offset, sizeof(uint32_t), 1, f);
if(tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(docId, offset);
lastTerm = tid;
}
}catch(std::exception& e)
{
cout<<e.what()<<endl;
}
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
sorter_->clear_files();
delete sorter_;
sorter_ = NULL;
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new InMemoryTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<commit_msg>recover<commit_after>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
FieldIndexer::FieldIndexer(const char* field, MemCache* pCache, Indexer* pIndexer)
:field_(field),pMemCache_(pCache),pIndexer_(pIndexer),vocFilePointer_(0),alloc_(0),sorter_(0),termCount_(0)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
if (! pIndexer_->isRealTime())
{
std::string sorterName = field_+".tmp";
bfs::path path(bfs::path(pIndexer->pConfigurationManager_->indexStrategy_.indexLocation_) /bfs::path(sorterName));
sorterFullPath_= path.string();
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);
}
else
alloc_ = new boost::scoped_alloc(recycle_);
}
FieldIndexer::~FieldIndexer()
{
/*
InMemoryPostingMap::iterator iter = postingMap_.begin()
for(; iter !=postingMap_.end(); ++iter)
{
delete iter->second;
}
*/
if (alloc_) delete alloc_;
pMemCache_ = NULL;
if (sorter_) delete sorter_;
}
void convert(char* data, uint32_t termId, uint32_t docId, uint32_t offset)
{
char* pData = data;
memcpy(pData, &(termId), sizeof(termId));
pData += sizeof(termId);
memcpy(pData, &(docId), sizeof(docId));
pData += sizeof(docId);
memcpy(pData, &(offset), sizeof(offset));
pData += sizeof(offset);
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<LAInput> laInput)
{
if (pIndexer_->isRealTime())
{
InMemoryPosting* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termId_);
if (postingIter == postingMap_.end())
{
//curPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->termId_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->offset_);
}
}
else
{
if (!sorter_)
sorter_=new izenelib::am::IzeneSort<uint32_t, uint8_t, true>(sorterFullPath_.c_str(), 100000000);
char data[12];
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
convert(data,iter->termId_,docid,iter->offset_);
sorter_->add_data(12, data);
}
}
}
void FieldIndexer::addField(docid_t docid, boost::shared_ptr<ForwardIndex> forwardindex)
{
InMemoryPosting* curPosting;
for (ForwardIndex::iterator iter = forwardindex->begin(); iter != forwardindex->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->first);
if (postingIter == postingMap_.end())
{
curPosting = BOOST_NEW(*alloc_, InMemoryPosting)(pMemCache_, skipInterval_, maxSkipLevel_);
postingMap_[iter->first] = curPosting;
}
else
curPosting = postingIter->second;
ForwardIndexOffset::iterator endit = iter->second->end();
for (ForwardIndexOffset::iterator it = iter->second->begin(); it != endit; ++it)
curPosting->add(docid, *it);
}
}
void FieldIndexer::reset()
{
InMemoryPosting* pPosting;
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->hasNoChunk())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
}
void writeTermInfo(IndexOutput* pVocWriter, termid_t tid, const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
InMemoryPosting* pPosting;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
for (InMemoryPostingMap::iterator iter = postingMap_.begin(); iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->hasNoChunk())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
postingMap_.clear();
delete alloc_;
alloc_ = new boost::scoped_alloc(recycle_);
}
else
{
sorter_->sort();
FILE* f = fopen(sorterFullPath_.c_str(),"r");
fseek(f, 0, SEEK_SET);
uint64_t count;
fread(&count, sizeof(uint64_t), 1, f);
pPosting = new InMemoryPosting(pMemCache_, skipInterval_, maxSkipLevel_);
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
uint8_t len;
fread(&len, sizeof(uint8_t), 1, f);
uint32_t docId,offset;
fread(&tid, sizeof(uint32_t), 1, f);
fread(&docId, sizeof(uint32_t), 1, f);
fread(&offset, sizeof(uint32_t), 1, f);
if(tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(docId, offset);
lastTerm = tid;
}
}catch(std::exception& e)
{
cout<<e.what()<<endl;
}
if (!pPosting->hasNoChunk())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
sorter_->clear_files();
delete sorter_;
sorter_ = NULL;
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new InMemoryTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<|endoftext|>
|
<commit_before>#include "Swampert.h"
#include "j1App.h"
#include "j1Pathfinding.h"
#include "j1Audio.h"
Swampert::Swampert()
{
}
Swampert::~Swampert()
{
}
bool Swampert::Awake(pugi::xml_node &conf)
{
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("attack").as_int(0);
speed = conf.attribute("speed").as_int(0);
name = conf.attribute("name").as_string("");
position.x = conf.attribute("pos_x").as_int(0);
position.y = conf.attribute("pos_y").as_int(0);
active = conf.attribute("active").as_bool(false);
return true;
}
bool Swampert::Start()
{
pokemon_player = true;
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 17;
gamestate = TIMETOPLAY;
timetoplay = SDL_GetTicks();
movable = true;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 15, 15 }, COLLIDER_PLAYER, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
return true;
}
bool Swampert::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
if (pokemon_player)
{
//pokemon controlled by player
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
/*
case SPECIALATTACK:
{
SpecialAttack();
break;
}
*/
default:
{
break;
}
}
}
else
{
//Pokemon IA
switch (state)
{
case IDLE:
{
Idle_IA();
break;
}
case WALKING:
{
Walking_IA();
break;
}
case ATTACKING:
{
Attack_IA();
break;
}
/*
case SPECIALATTACK:
{
SpecialAttack();
break;
}
*/
default:
{
break;
}
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Swampert::Draw()
{
App->anim_manager->Drawing_Manager(state, direction, position, 7);
}
bool Swampert::CleanUp()
{
return true;
}
void Swampert::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
{
}
}
}
bool Swampert::Idle()
{
//IDLE SCEPTYLE
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
state = WALKING;
CheckOrientation();
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 7); //this number may need to be changed?
current_animation->Reset();
}
else
{
state = IDLE;
}
return true;
}
bool Swampert::Walking()
{
walking = false;
Move();
if (walking == false)
{
state = IDLE;
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 7); //This number may need to be changed?
current_animation->Reset();
}
else
{
state = WALKING;
}
return false;
}
bool Swampert::Move()
{
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT);
int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
if (temp == 0)
{
position.x -= speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
if (temp == 0)
{
position.y += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
if (temp == 0)
{
position.x += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
if (temp == 0)
{
position.y -= speed;
}
walking = true;
}
return walking;
}
bool Swampert::Attack()
{
if (attacker)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(collision_attack);
attacker = false;
current_animation->Reset();
current_animation = nullptr;
state = IDLE;
}
}
else
{
attacker = true;
if (direction == UP)
{
collision_attack = App->collision->AddCollider({ position.x, position.y, 8, 20 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == RIGHT)
{
collision_attack = App->collision->AddCollider({ position.x, position.y, 20, 8 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == DOWN)
{
collision_attack = App->collision->AddCollider({ position.x, position.y, 8, 20 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == LEFT)
{
collision_attack = App->collision->AddCollider({ position.x, position.y, 20, 8 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
}
return true;
}
bool Swampert::Idle_IA()
{
if (movable)
{
if (reset_run)
{
timetorun = SDL_GetTicks();
reset_run = false;
}
else
{
if (SDL_GetTicks() - timetorun > 200)
{
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
state = WALKING;
reset_distance = true;
}
}
}
return true;
}
bool Swampert::Walking_IA()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move_IA();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}
bool Swampert::Move_IA()
{
//App->pathfinding->CreatePath(position, target->Getposition());
return true;
}
bool Swampert::Attack_IA()
{
return true;
}
bool Swampert::CheckOrientation()
{
return true;
}
void Swampert::OnInputCallback(INPUTEVENT, EVENTSTATE)
{
}<commit_msg>Swampert attack colliders modified<commit_after>#include "Swampert.h"
#include "j1App.h"
#include "j1Pathfinding.h"
#include "j1Audio.h"
Swampert::Swampert()
{
}
Swampert::~Swampert()
{
}
bool Swampert::Awake(pugi::xml_node &conf)
{
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("attack").as_int(0);
speed = conf.attribute("speed").as_int(0);
name = conf.attribute("name").as_string("");
position.x = conf.attribute("pos_x").as_int(0);
position.y = conf.attribute("pos_y").as_int(0);
active = conf.attribute("active").as_bool(false);
return true;
}
bool Swampert::Start()
{
pokemon_player = true;
state = IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 17;
gamestate = TIMETOPLAY;
timetoplay = SDL_GetTicks();
movable = true;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 15, 15 }, COLLIDER_PLAYER, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
reset_run = true;
return true;
}
bool Swampert::Update()
{
// STATE MACHINE ------------------
if (gamestate == INGAME)
{
if (pokemon_player)
{
//pokemon controlled by player
switch (state)
{
case IDLE:
{
Idle();
break;
}
case WALKING:
{
Walking();
break;
}
case ATTACKING:
{
Attack();
break;
}
/*
case SPECIALATTACK:
{
SpecialAttack();
break;
}
*/
default:
{
break;
}
}
}
else
{
//Pokemon IA
switch (state)
{
case IDLE:
{
Idle_IA();
break;
}
case WALKING:
{
Walking_IA();
break;
}
case ATTACKING:
{
Attack_IA();
break;
}
/*
case SPECIALATTACK:
{
SpecialAttack();
break;
}
*/
default:
{
break;
}
}
}
}
else if (gamestate == INMENU)
{
}
else if (gamestate == TIMETOPLAY)
{
if (SDL_GetTicks() - timetoplay > 1000)
{
gamestate = INGAME;
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Swampert::Draw()
{
App->anim_manager->Drawing_Manager(state, direction, position, 7);
}
bool Swampert::CleanUp()
{
return true;
}
void Swampert::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
if (c1 == collision_feet && c2->type == COLLIDER_ENEMY)
{
}
}
}
bool Swampert::Idle()
{
//IDLE SCEPTYLE
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
state = WALKING;
CheckOrientation();
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 7); //this number may need to be changed?
current_animation->Reset();
}
else
{
state = IDLE;
}
return true;
}
bool Swampert::Walking()
{
walking = false;
Move();
if (walking == false)
{
state = IDLE;
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN)
{
state = ATTACKING;
current_animation = App->anim_manager->GetAnimation(state, direction, 7); //This number may need to be changed?
current_animation->Reset();
}
else
{
state = WALKING;
}
return false;
}
bool Swampert::Move()
{
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
//int temp = App->map->MovementCost(position.x - speed, position.y, LEFT);
int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
if (temp == 0)
{
position.x -= speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
//int temp = App->map->MovementCost(position.x, position.y + (speed + height), DOWN);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
if (temp == 0)
{
position.y += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
//int temp = App->map->MovementCost(position.x + (speed + width), position.y, RIGHT);
int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
if (temp == 0)
{
position.x += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
if (temp == 0)
{
position.y -= speed;
}
walking = true;
}
return walking;
}
bool Swampert::Attack()
{
if (attacker)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(collision_attack);
attacker = false;
current_animation->Reset();
current_animation = nullptr;
state = IDLE;
}
}
else
{
attacker = true;
if (direction == UP)
{
collision_attack = App->collision->AddCollider({ position.x - 11, position.y - 35, 22, 8 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == RIGHT)
{
collision_attack = App->collision->AddCollider({ position.x + 12, position.y - 26, 8, 22 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == DOWN)
{
collision_attack = App->collision->AddCollider({ position.x - 10, position.y - 4, 22, 8 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
else if (direction == LEFT)
{
collision_attack = App->collision->AddCollider({ position.x - 20, position.y - 26, 8, 22 }, COLLIDER_PLAYER, this);
App->audio->PlayFx(10);
}
}
return true;
}
bool Swampert::Idle_IA()
{
if (movable)
{
if (reset_run)
{
timetorun = SDL_GetTicks();
reset_run = false;
}
else
{
if (SDL_GetTicks() - timetorun > 200)
{
int direc_select = rand() % 4 + 1;
if (direc_select == 1)
{
direction = UP;
}
else if (direc_select == 2)
{
direction = DOWN;
}
else if (direc_select == 3)
{
direction = LEFT;
}
else if (direc_select == 4)
{
direction = RIGHT;
}
state = WALKING;
reset_distance = true;
}
}
}
return true;
}
bool Swampert::Walking_IA()
{
walking = false;
if (reset_distance)
{
distance = rand() % 60 + 20;
dis_moved = 0;
reset_distance = false;
}
Move_IA();
if (dis_moved >= distance)
{
walking = false;
reset_run = true;
}
if (walking == false)
{
state = IDLE;
}
else
{
state = WALKING;
}
return true;
}
bool Swampert::Move_IA()
{
//App->pathfinding->CreatePath(position, target->Getposition());
return true;
}
bool Swampert::Attack_IA()
{
return true;
}
bool Swampert::CheckOrientation()
{
return true;
}
void Swampert::OnInputCallback(INPUTEVENT, EVENTSTATE)
{
}<|endoftext|>
|
<commit_before>// [WriteFile Name=StatisticalQuery, Category=Analysis]
// [Legal]
// Copyright 2017 Esri.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]
#include "StatisticalQuery.h"
#include "Map.h"
#include "MapQuickView.h"
#include "ArcGISVectorTiledLayer.h"
#include "FeatureLayer.h"
#include "ServiceFeatureTable.h"
#include "StatisticalQuery.h"
#include "StatisticsQueryParameters.h"
#include "StatisticDefinition.h"
#include "StatisticRecord.h"
#include "StatisticRecordIterator.h"
#include "Viewpoint.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
StatisticalQuery::StatisticalQuery(QQuickItem* parent /* = nullptr */):
QQuickItem(parent)
{
}
void StatisticalQuery::init()
{
// Register the map view for QML
qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
qmlRegisterType<StatisticalQuery>("Esri.Samples", 1, 0, "StatisticalQuerySample");
}
void StatisticalQuery::componentComplete()
{
QQuickItem::componentComplete();
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// Create a new Map with the world streets vector basemap
m_map = new Map(Basemap::streetsVector(this), this);
// Create feature table using the world cities URL
m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0"), this);
// Create a new feature layer to display features in the world cities table
FeatureLayer* featureLayer = new FeatureLayer(m_featureTable, this);
m_map->operationalLayers()->append(featureLayer);
// Set map to map view
m_mapView->setMap(m_map);
connect(m_featureTable, &ServiceFeatureTable::errorOccurred, [this](Error e)
{
if (e.isEmpty())
return;
emit showStatistics(e.message());
});
// connect to queryStatisticsCompleted
connect(m_featureTable, &ServiceFeatureTable::queryStatisticsCompleted, this, [this](QUuid, StatisticsQueryResult* rawResult)
{
if (!rawResult)
return;
// Delete rawResult when we leave local scope.
QScopedPointer<StatisticsQueryResult> result(rawResult);
// Iterate through the results
QObject parent;
QString resultText;
StatisticRecordIterator iter = result->iterator();
while (iter.hasNext())
{
StatisticRecord* record = iter.next(&parent);
const QVariantMap& statsMap = record->statistics();
for (const auto& it : statsMap.toStdMap())
{
resultText += QString("%1: %2\n").arg(it.first, it.second.toString());
}
}
// Display the Results
emit showStatistics(resultText);
});
}
void StatisticalQuery::queryStatistics(bool extentOnly, bool bigCitiesOnly)
{
// create the parameters
StatisticsQueryParameters queryParameters;
// Add the Statistic Definitions
QList<StatisticDefinition> definitions
{
StatisticDefinition("POP", StatisticType::Average, ""),
StatisticDefinition("POP", StatisticType::Minimum, ""),
StatisticDefinition("POP", StatisticType::Maximum, ""),
StatisticDefinition("POP", StatisticType::Sum, ""),
StatisticDefinition("POP", StatisticType::StandardDeviation, ""),
StatisticDefinition("POP", StatisticType::Variance, ""),
StatisticDefinition("POP", StatisticType::Count, "CityCount")
};
queryParameters.setStatisticDefinitions(definitions);
// If only using features in the current extent, set up the spatial filter for the statistics query parameters
if (extentOnly)
{
// Set the statistics query parameters geometry with the envelope
queryParameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());
// Set the spatial relationship to Intersects (which is the default)
queryParameters.setSpatialRelationship(SpatialRelationship::Intersects);
}
// If only evaluating the largest cities (over 5 million in population), set up an attribute filter
if (bigCitiesOnly)
queryParameters.setWhereClause("POP_RANK = 1");
// Execute the statistical query with these parameters
m_featureTable->queryStatistics(queryParameters);
}
<commit_msg>Reverting back to QVariantMap iterator.<commit_after>// [WriteFile Name=StatisticalQuery, Category=Analysis]
// [Legal]
// Copyright 2017 Esri.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]
#include "StatisticalQuery.h"
#include "Map.h"
#include "MapQuickView.h"
#include "ArcGISVectorTiledLayer.h"
#include "FeatureLayer.h"
#include "ServiceFeatureTable.h"
#include "StatisticalQuery.h"
#include "StatisticsQueryParameters.h"
#include "StatisticDefinition.h"
#include "StatisticRecord.h"
#include "StatisticRecordIterator.h"
#include "Viewpoint.h"
#include <QUrl>
using namespace Esri::ArcGISRuntime;
StatisticalQuery::StatisticalQuery(QQuickItem* parent /* = nullptr */):
QQuickItem(parent)
{
}
void StatisticalQuery::init()
{
// Register the map view for QML
qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
qmlRegisterType<StatisticalQuery>("Esri.Samples", 1, 0, "StatisticalQuerySample");
}
void StatisticalQuery::componentComplete()
{
QQuickItem::componentComplete();
// find QML MapView component
m_mapView = findChild<MapQuickView*>("mapView");
// Create a new Map with the world streets vector basemap
m_map = new Map(Basemap::streetsVector(this), this);
// Create feature table using the world cities URL
m_featureTable = new ServiceFeatureTable(QUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/SampleWorldCities/MapServer/0"), this);
// Create a new feature layer to display features in the world cities table
FeatureLayer* featureLayer = new FeatureLayer(m_featureTable, this);
m_map->operationalLayers()->append(featureLayer);
// Set map to map view
m_mapView->setMap(m_map);
connect(m_featureTable, &ServiceFeatureTable::errorOccurred, [this](Error e)
{
if (e.isEmpty())
return;
emit showStatistics(e.message());
});
// connect to queryStatisticsCompleted
connect(m_featureTable, &ServiceFeatureTable::queryStatisticsCompleted, this, [this](QUuid, StatisticsQueryResult* rawResult)
{
if (!rawResult)
return;
// Delete rawResult when we leave local scope.
QScopedPointer<StatisticsQueryResult> result(rawResult);
// Iterate through the results
QObject parent;
QString resultText;
StatisticRecordIterator iter = result->iterator();
while (iter.hasNext())
{
StatisticRecord* record = iter.next(&parent);
const QVariantMap& statsMap = record->statistics();
for (auto it = statsMap.cbegin(); it != statsMap.cend(); ++it)
{
resultText += QString("%1: %2\n").arg(it.key(), it.value().toString());
}
}
// Display the Results
emit showStatistics(resultText);
});
}
void StatisticalQuery::queryStatistics(bool extentOnly, bool bigCitiesOnly)
{
// create the parameters
StatisticsQueryParameters queryParameters;
// Add the Statistic Definitions
QList<StatisticDefinition> definitions
{
StatisticDefinition("POP", StatisticType::Average, ""),
StatisticDefinition("POP", StatisticType::Minimum, ""),
StatisticDefinition("POP", StatisticType::Maximum, ""),
StatisticDefinition("POP", StatisticType::Sum, ""),
StatisticDefinition("POP", StatisticType::StandardDeviation, ""),
StatisticDefinition("POP", StatisticType::Variance, ""),
StatisticDefinition("POP", StatisticType::Count, "CityCount")
};
queryParameters.setStatisticDefinitions(definitions);
// If only using features in the current extent, set up the spatial filter for the statistics query parameters
if (extentOnly)
{
// Set the statistics query parameters geometry with the envelope
queryParameters.setGeometry(m_mapView->currentViewpoint(ViewpointType::BoundingGeometry).targetGeometry());
// Set the spatial relationship to Intersects (which is the default)
queryParameters.setSpatialRelationship(SpatialRelationship::Intersects);
}
// If only evaluating the largest cities (over 5 million in population), set up an attribute filter
if (bigCitiesOnly)
queryParameters.setWhereClause("POP_RANK = 1");
// Execute the statistical query with these parameters
m_featureTable->queryStatistics(queryParameters);
}
<|endoftext|>
|
<commit_before><commit_msg>Fix memory leak<commit_after><|endoftext|>
|
<commit_before>/*!
\file barrier.cpp
\brief Barrier synchronization primitive implementation
\author Ivan Shynkarenka
\date 16.03.2016
\copyright MIT License
*/
#include "threads/barrier.h"
#include "errors/exceptions.h"
#include <cassert>
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "errors/fatal.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
namespace CppCommon {
//! @cond INTERNALS
class Barrier::Impl
{
public:
Impl(int threads) : _threads(threads)
{
assert((threads > 0) && "Barrier threads counter must be greater than zero!");
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_init(&_barrier, nullptr, threads);
if (result != 0)
throwex SystemException("Failed to initialize a synchronization barrier!", result);
#elif defined(_WIN32) || defined(_WIN64)
if (!InitializeSynchronizationBarrier(&_barrier, threads, -1))
throwex SystemException("Failed to initialize a synchronization barrier!");
#endif
}
~Impl()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_destroy(&_barrier);
if (result != 0)
fatality(SystemException("Failed to destroy a synchronization barrier!", result));
#elif defined(_WIN32) || defined(_WIN64)
DeleteSynchronizationBarrier(&_barrier);
#endif
}
int threads() const noexcept
{
return _threads;
}
bool Wait()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_wait(&_barrier);
if ((result != PTHREAD_BARRIER_SERIAL_THREAD) && (result != 0))
throwex SystemException("Failed to wait at a synchronization barrier!", result);
return (result == PTHREAD_BARRIER_SERIAL_THREAD);
#elif defined(_WIN32) || defined(_WIN64)
return (EnterSynchronizationBarrier(&_barrier, 0) == TRUE);
#endif
}
private:
int _threads;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
pthread_barrier_t _barrier;
#elif defined(_WIN32) || defined(_WIN64)
SYNCHRONIZATION_BARRIER _barrier;
#endif
};
//! @endcond
Barrier::Barrier(int threads) : _pimpl(std::make_unique<Impl>(threads))
{
}
Barrier::Barrier(Barrier&& barrier) noexcept : _pimpl(std::move(barrier._pimpl))
{
}
Barrier::~Barrier()
{
}
Barrier& Barrier::operator=(Barrier&& barrier) noexcept
{
_pimpl = std::move(barrier._pimpl);
return *this;
}
int Barrier::threads() const noexcept
{
return _pimpl->threads();
}
bool Barrier::Wait()
{
return _pimpl->Wait();
}
} // namespace CppCommon
<commit_msg>Fix MinGW build<commit_after>/*!
\file barrier.cpp
\brief Barrier synchronization primitive implementation
\author Ivan Shynkarenka
\date 16.03.2016
\copyright MIT License
*/
#include "threads/barrier.h"
#include "errors/exceptions.h"
#include <cassert>
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
#include "errors/fatal.h"
#include <pthread.h>
#elif defined(__MINGW32__) || defined(__MINGW64__)
#include <condition_variable>
#include <mutex>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif
namespace CppCommon {
//! @cond INTERNALS
class Barrier::Impl
{
public:
Impl(int threads) : _threads(threads)
{
assert((threads > 0) && "Barrier threads counter must be greater than zero!");
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_init(&_barrier, nullptr, threads);
if (result != 0)
throwex SystemException("Failed to initialize a synchronization barrier!", result);
#elif defined(__MINGW32__) || defined(__MINGW64__)
_counter = threads;
_generation = 0;
#elif defined(_WIN32) || defined(_WIN64)
if (!InitializeSynchronizationBarrier(&_barrier, threads, -1))
throwex SystemException("Failed to initialize a synchronization barrier!");
#endif
}
~Impl()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_destroy(&_barrier);
if (result != 0)
fatality(SystemException("Failed to destroy a synchronization barrier!", result));
#elif defined(__MINGW32__) || defined(__MINGW64__)
// Do nothing here...
#elif defined(_WIN32) || defined(_WIN64)
DeleteSynchronizationBarrier(&_barrier);
#endif
}
int threads() const noexcept
{
return _threads;
}
bool Wait()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
int result = pthread_barrier_wait(&_barrier);
if ((result != PTHREAD_BARRIER_SERIAL_THREAD) && (result != 0))
throwex SystemException("Failed to wait at a synchronization barrier!", result);
return (result == PTHREAD_BARRIER_SERIAL_THREAD);
#elif defined(__MINGW32__) || defined(__MINGW64__)
std::unique_lock<std::mutex> lock(_mutex);
// Remember the current barrier generation
int generation = _generation;
// Decrease the count of waiting threads
if (--_counter == 0)
{
// Increase the current barrier generation
++_generation;
// Reset waiting threads counter
_counter = _threads;
// Notify all waiting threads
_cond.notify_all();
// Notify the last thread that reached the barrier
return true;
}
// Wait for the next barrier generation
_cond.wait(lock, [&, this]() { return generation != _generation; });
// Notify each of remaining threads
return false;
#elif defined(_WIN32) || defined(_WIN64)
return (EnterSynchronizationBarrier(&_barrier, 0) == TRUE);
#endif
}
private:
int _threads;
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
pthread_barrier_t _barrier;
#elif defined(__MINGW32__) || defined(__MINGW64__)
std::mutex _mutex;
std::condition_variable _cond;
int _counter;
int _generation;
#elif defined(_WIN32) || defined(_WIN64)
SYNCHRONIZATION_BARRIER _barrier;
#endif
};
//! @endcond
Barrier::Barrier(int threads) : _pimpl(std::make_unique<Impl>(threads))
{
}
Barrier::Barrier(Barrier&& barrier) noexcept : _pimpl(std::move(barrier._pimpl))
{
}
Barrier::~Barrier()
{
}
Barrier& Barrier::operator=(Barrier&& barrier) noexcept
{
_pimpl = std::move(barrier._pimpl);
return *this;
}
int Barrier::threads() const noexcept
{
return _pimpl->threads();
}
bool Barrier::Wait()
{
return _pimpl->Wait();
}
} // namespace CppCommon
<|endoftext|>
|
<commit_before>#include "OverloadRunValidationAlgorithm.h"
#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/WorkStop.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Operation.h>
bool Scheduler::OverloadRunValidationAlgorithm::isValid(const Run * run) const
{
if (run->getVehicle() == nullptr) return true; // Have no vehicle to check with
const auto& stops = run->getWorkStops();
const Capacity vehicle_capacity = run->getVehicle()->getCapacity();
bool overflow = false;
Capacity run_demand;
for (auto stop_it = stops.begin(); stop_it != stops.end() && !overflow; ++stop_it) {
run_demand += (*stop_it)->getOperation()->getDemand();
overflow = (run_demand > vehicle_capacity);
}
return overflow;
}
<commit_msg>[#45] Bugfix in overload checker<commit_after>#include "OverloadRunValidationAlgorithm.h"
#include <Engine/SceneManager/Run.h>
#include <Engine/SceneManager/WorkStop.h>
#include <Engine/SceneManager/Vehicle.h>
#include <Engine/SceneManager/Operation.h>
bool Scheduler::OverloadRunValidationAlgorithm::isValid(const Run * run) const
{
if (run->getVehicle() == nullptr) return true; // Have no vehicle to check with
const auto& stops = run->getWorkStops();
const Capacity vehicle_capacity = run->getVehicle()->getCapacity();
bool overload = false;
Capacity run_demand;
for (auto stop_it = stops.begin(); stop_it != stops.end() && !overload; ++stop_it) {
run_demand += (*stop_it)->getOperation()->getDemand();
overload = (run_demand > vehicle_capacity);
}
return !overload;
}
<|endoftext|>
|
<commit_before>#include "vvvsourcegraph.hpp"
#include <memory>
using namespace clang;
using namespace std;
shared_ptr<SemanticVertex>
getSemanticVertexFromStmt(const Stmt* stmt, Graph& graph, const clang::ASTContext& context)
{
SemanticVertex* ret = 0;
if(stmt) switch(stmt->getStmtClass()){
case Stmt::CompoundStmtClass: ret = new BlockCompound(graph, stmt, context); break;
case Stmt::IfStmtClass: ret = new BlockIf( graph, stmt, context); break;
case Stmt::SwitchStmtClass: ret = new BlockSwitch( graph, stmt, context); break;
case Stmt::CaseStmtClass: ret = new BlockCase( graph, stmt, context); break;
case Stmt::DefaultStmtClass: ret = new BlockDefault( graph, stmt, context); break;
case Stmt::ForStmtClass: ret = new BlockFor( graph, stmt, context); break;
case Stmt::WhileStmtClass: ret = new BlockWhile( graph, stmt, context); break;
case Stmt::DoStmtClass: ret = new BlockDoWhile( graph, stmt, context); break;
case Stmt::CallExprClass: ret = new BlockCall( graph, stmt, context); break;
case Stmt::ReturnStmtClass: ret = new BlockReturn( graph, stmt, context); break;
case Stmt::BreakStmtClass: ret = new BlockBreak( graph ); break;
case Stmt::ContinueStmtClass: ret = new BlockContinue( graph ); break;
default: ret = new BlockSimple( graph, stmt, context); break; }
return shared_ptr<SemanticVertex>(ret);
}
void BlockIf::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto thenStmt = getSemanticVertexFromStmt( stmt->getThen(), graph, context );
auto elseStmt = getSemanticVertexFromStmt( stmt->getElse(), graph, context );
thenStmt->expand( vertex, end, onReturn, onBreak, onContinue);
if( elseStmt )
elseStmt->expand( vertex, end, onReturn, onBreak, onContinue);
else {
edge_t e = boost::add_edge( vertex, end, graph).first;
graph[e].text = "false"; }
auto outedges = boost::out_edges( vertex, graph );
auto i = outedges.first;
edge_t trueBranch = *(i++);
edge_t falseBranch = *i;
graph[ trueBranch ].text = "true";
graph[ falseBranch ].text = "false";
}
void BlockCall::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, decl2str( stmt, context ) );
boost::add_edge( begin, vertex, graph );
boost::add_edge( vertex, end, graph );
}
void BlockReturn::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, std::string("return ") + decl2str( stmt->getRetValue(), context ) );
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, onReturn, graph);
}
void BlockSimple::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, decl2str( stmt, context ) );
boost::add_edge( begin, vertex, graph );
boost::add_edge( vertex, end, graph );
}
static std::vector<std::shared_ptr<SemanticVertex>>
groupChildren(const std::vector<const Stmt*>& stmts,
Graph& graph, const ASTContext& context)
{
using namespace std;
using uptrSemVert = shared_ptr<SemanticVertex>;
std::vector<uptrSemVert> ret;
std::vector<uptrSemVert> oneBlock;
auto addOneBlock = [&oneBlock, &ret, &graph, &context]() {
if(oneBlock.size()) {
ret.push_back( uptrSemVert(new BlockSimpleCompound(graph, oneBlock, context) ) );
oneBlock.clear();} };
for( auto& stmt : stmts ) {
auto sv = getSemanticVertexFromStmt( stmt, graph, context);
if (sv->getType() != SEMANTIC_BLOCK_TYPE::SIMPLE) {
addOneBlock();
ret.push_back( std::move(sv) );}
else oneBlock.push_back( std::move(sv) ); }
addOneBlock();
return ret;
}
void BlockCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
auto children = getCompoundStmtChildren( stmt );
const auto groupedChildren = groupChildren(children, graph, context);
const auto numChildren = groupedChildren.size();
switch(numChildren){
case 0: boost::add_edge(begin,end,graph); break;
case 1: groupedChildren[0]->expand(begin,end,onReturn, onBreak, onContinue); break;
default:
{
size_t i = numChildren-1;
groupedChildren[i]->expand(begin,end,onReturn,onBreak,onContinue);
boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
do
{
--i;
groupedChildren[i]->expand(begin,groupedChildren[i+1]->getVertex(),onReturn,onBreak,onContinue);
boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
}while(i!=0);
boost::add_edge( begin, groupedChildren[0]->getVertex(), graph);
}
break;};
vertex = groupedChildren[0]->getVertex();
}
void BlockSimpleCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
std::string caption;
for(const auto& stmt: stmts)
caption += "\n" + stmt->toString();
vertex = addProcessVertex( graph, caption );
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, end, graph);
}
void BlockFor::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex(graph, decl2str(stmt->getInc(),context) );
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex(graph, "");
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockDoWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, "" );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex( graph, decl2str( stmt->getCond(), context));
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockSwitch::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, decl2str(stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto children = getCompoundStmtChildren( stmt->getBody() );
const auto groupedChildren = groupChildren(children, graph, context);
const auto numChildren = groupedChildren.size();
switch(numChildren){
case 0: boost::add_edge(vertex,end,graph); break;
case 1: groupedChildren[0]->expand(vertex,end,onReturn, end, onContinue); break;
default: { size_t i = numChildren-1;
if(groupedChildren[i]->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
groupedChildren[i]->expand(vertex,end,onReturn,end,onContinue);
do {
--i;
auto& currentChild = groupedChildren[i];
auto& nextChild = groupedChildren[i+1];
const auto localend = (nextChild->getType() == SEMANTIC_BLOCK_TYPE::BREAK) ? end :
nextChild->getVertex();
if(currentChild->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
currentChild->expand(vertex, localend, onReturn, end, onContinue); // TODO: connect children to each other, not to vertex
}while(i!=0);
}
break;};
}
static std::pair<vector<string>,const Stmt*> getConditions(const CaseStmt* stmt, const ASTContext& context)
{
std::pair<vector<string>, const Stmt*> ret;
auto currentStmt = stmt;
for(;;){
ret.first.push_back( decl2str(currentStmt->getLHS(), context) );
auto subStmt = currentStmt->getSubStmt();
if( subStmt->getStmtClass() == Stmt::CaseStmtClass )
currentStmt = static_cast<const CaseStmt*>(subStmt);
else {
currentStmt = nullptr;
ret.second = subStmt;
break;} }
return ret;
}
static
string joinStringsWith( const vector<string>& v, const string& delimiter)
{
string ret;
const auto numStrings = v.size();
const auto numStrings_1 = numStrings-1;
for(size_t i = 0; i < numStrings; ++i) {
ret += v[i];
if( i!= numStrings_1) ret += delimiter; }
return ret;
}
void BlockCase::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
auto condition = getConditions( stmt, context );
auto statements = getSemanticVertexFromStmt( condition.second, graph, context);
statements->expand( begin, end, onReturn, onBreak, onContinue );
vertex = statements->getVertex();
boost::remove_edge( begin, vertex, graph );
auto beginvertex = boost::add_edge( begin, vertex, graph).first;
graph[beginvertex].text = joinStringsWith( condition.first, ", " );
/*
vertex = addConditionVertex( graph, "CASE");
auto beginvertex = boost::add_edge( begin, vertex, graph).first;
boost::add_edge( vertex, end, graph);
graph[beginvertex].text = joinStringsWith( condition.first, ", " );
*/
}
void BlockDefault::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, "default: ");
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, end, graph);
}
void BlockBreak::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
boost::add_edge( begin, onBreak, graph);
}
void BlockContinue::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
boost::add_edge( begin, onContinue, graph);
}
<commit_msg>fix case bug<commit_after>#include "vvvsourcegraph.hpp"
#include <memory>
using namespace clang;
using namespace std;
shared_ptr<SemanticVertex>
getSemanticVertexFromStmt(const Stmt* stmt, Graph& graph, const clang::ASTContext& context)
{
SemanticVertex* ret = 0;
if(stmt) switch(stmt->getStmtClass()){
case Stmt::CompoundStmtClass: ret = new BlockCompound(graph, stmt, context); break;
case Stmt::IfStmtClass: ret = new BlockIf( graph, stmt, context); break;
case Stmt::SwitchStmtClass: ret = new BlockSwitch( graph, stmt, context); break;
case Stmt::CaseStmtClass: ret = new BlockCase( graph, stmt, context); break;
case Stmt::DefaultStmtClass: ret = new BlockDefault( graph, stmt, context); break;
case Stmt::ForStmtClass: ret = new BlockFor( graph, stmt, context); break;
case Stmt::WhileStmtClass: ret = new BlockWhile( graph, stmt, context); break;
case Stmt::DoStmtClass: ret = new BlockDoWhile( graph, stmt, context); break;
case Stmt::CallExprClass: ret = new BlockCall( graph, stmt, context); break;
case Stmt::ReturnStmtClass: ret = new BlockReturn( graph, stmt, context); break;
case Stmt::BreakStmtClass: ret = new BlockBreak( graph ); break;
case Stmt::ContinueStmtClass: ret = new BlockContinue( graph ); break;
default: ret = new BlockSimple( graph, stmt, context); break; }
return shared_ptr<SemanticVertex>(ret);
}
void BlockIf::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto thenStmt = getSemanticVertexFromStmt( stmt->getThen(), graph, context );
auto elseStmt = getSemanticVertexFromStmt( stmt->getElse(), graph, context );
thenStmt->expand( vertex, end, onReturn, onBreak, onContinue);
if( elseStmt )
elseStmt->expand( vertex, end, onReturn, onBreak, onContinue);
else {
edge_t e = boost::add_edge( vertex, end, graph).first;
graph[e].text = "false"; }
auto outedges = boost::out_edges( vertex, graph );
auto i = outedges.first;
edge_t trueBranch = *(i++);
edge_t falseBranch = *i;
graph[ trueBranch ].text = "true";
graph[ falseBranch ].text = "false";
}
void BlockCall::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, decl2str( stmt, context ) );
boost::add_edge( begin, vertex, graph );
boost::add_edge( vertex, end, graph );
}
void BlockReturn::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, std::string("return ") + decl2str( stmt->getRetValue(), context ) );
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, onReturn, graph);
}
void BlockSimple::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addProcessVertex( graph, decl2str( stmt, context ) );
boost::add_edge( begin, vertex, graph );
boost::add_edge( vertex, end, graph );
}
static std::vector<std::shared_ptr<SemanticVertex>>
groupChildren(const std::vector<const Stmt*>& stmts,
Graph& graph, const ASTContext& context)
{
using namespace std;
using uptrSemVert = shared_ptr<SemanticVertex>;
std::vector<uptrSemVert> ret;
std::vector<uptrSemVert> oneBlock;
auto addOneBlock = [&oneBlock, &ret, &graph, &context]() {
if(oneBlock.size()) {
ret.push_back( uptrSemVert(new BlockSimpleCompound(graph, oneBlock, context) ) );
oneBlock.clear();} };
for( auto& stmt : stmts ) {
auto sv = getSemanticVertexFromStmt( stmt, graph, context);
if (sv->getType() != SEMANTIC_BLOCK_TYPE::SIMPLE) {
addOneBlock();
ret.push_back( std::move(sv) );}
else oneBlock.push_back( std::move(sv) ); }
addOneBlock();
return ret;
}
void BlockCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
auto children = getCompoundStmtChildren( stmt );
const auto groupedChildren = groupChildren(children, graph, context);
const auto numChildren = groupedChildren.size();
switch(numChildren){
case 0: boost::add_edge(begin,end,graph); break;
case 1: groupedChildren[0]->expand(begin,end,onReturn, onBreak, onContinue); break;
default:
{
size_t i = numChildren-1;
groupedChildren[i]->expand(begin,end,onReturn,onBreak,onContinue);
boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
do
{
--i;
groupedChildren[i]->expand(begin,groupedChildren[i+1]->getVertex(),onReturn,onBreak,onContinue);
boost::remove_edge( begin, groupedChildren[i]->getVertex(), graph);
}while(i!=0);
boost::add_edge( begin, groupedChildren[0]->getVertex(), graph);
}
break;};
vertex = groupedChildren[0]->getVertex();
}
void BlockSimpleCompound::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
std::string caption;
for(const auto& stmt: stmts)
caption += "\n" + stmt->toString();
vertex = addProcessVertex( graph, caption );
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, end, graph);
}
void BlockFor::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex(graph, decl2str(stmt->getInc(),context) );
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, decl2str( stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex(graph, "");
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockDoWhile::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addLoopOpenVertex( graph, "" );
boost::add_edge( begin, vertex, graph);
auto endLoopVertex = addLoopCloseVertex( graph, decl2str( stmt->getCond(), context));
boost::add_edge( endLoopVertex, end, graph);
auto body = getSemanticVertexFromStmt( stmt->getBody(), graph, context);
body->expand( vertex, endLoopVertex, onReturn, end, endLoopVertex );
}
void BlockSwitch::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, decl2str(stmt->getCond(), context) );
boost::add_edge( begin, vertex, graph);
auto children = getCompoundStmtChildren( stmt->getBody() );
const auto groupedChildren = groupChildren(children, graph, context);
const auto numChildren = groupedChildren.size();
switch(numChildren){
case 0: boost::add_edge(vertex,end,graph); break;
case 1: groupedChildren[0]->expand(vertex,end,onReturn, end, onContinue); break;
default: { size_t i = numChildren-1;
if(groupedChildren[i]->getType() != SEMANTIC_BLOCK_TYPE::BREAK)
{
groupedChildren[i]->expand(vertex,end,onReturn,end,onContinue);
boost::remove_edge(vertex,groupedChildren[i]->getVertex(), graph);
}
do {
--i;
auto& currentChild = groupedChildren[i];
auto& nextChild = groupedChildren[i+1];
const auto localend = (nextChild->getType() == SEMANTIC_BLOCK_TYPE::BREAK) ? end :
nextChild->getVertex();
const auto currentChildType = currentChild->getType();
if(currentChildType != SEMANTIC_BLOCK_TYPE::BREAK){
currentChild->expand(vertex, localend, onReturn, end, onContinue); // TODO: connect children to each other, not to vertex
if( currentChildType != SEMANTIC_BLOCK_TYPE::CASE
&& currentChildType != SEMANTIC_BLOCK_TYPE::DEFAULT)
boost::remove_edge(vertex, currentChild->getVertex(), graph); }
}while(i!=0);
}
break;};
}
static std::pair<vector<string>,const Stmt*> getConditions(const CaseStmt* stmt, const ASTContext& context)
{
std::pair<vector<string>, const Stmt*> ret;
auto currentStmt = stmt;
for(;;){
ret.first.push_back( decl2str(currentStmt->getLHS(), context) );
auto subStmt = currentStmt->getSubStmt();
if( subStmt->getStmtClass() == Stmt::CaseStmtClass )
currentStmt = static_cast<const CaseStmt*>(subStmt);
else {
currentStmt = nullptr;
ret.second = subStmt;
break;} }
return ret;
}
static
string joinStringsWith( const vector<string>& v, const string& delimiter)
{
string ret;
const auto numStrings = v.size();
const auto numStrings_1 = numStrings-1;
for(size_t i = 0; i < numStrings; ++i) {
ret += v[i];
if( i!= numStrings_1) ret += delimiter; }
return ret;
}
void BlockCase::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
auto condition = getConditions( stmt, context );
auto statements = getSemanticVertexFromStmt( condition.second, graph, context);
statements->expand( begin, end, onReturn, onBreak, onContinue );
vertex = statements->getVertex();
boost::remove_edge( begin, vertex, graph );
auto beginvertex = boost::add_edge( begin, vertex, graph).first;
graph[beginvertex].text = joinStringsWith( condition.first, ", " );
/*
vertex = addConditionVertex( graph, "CASE");
auto beginvertex = boost::add_edge( begin, vertex, graph).first;
boost::add_edge( vertex, end, graph);
graph[beginvertex].text = joinStringsWith( condition.first, ", " );
*/
}
void BlockDefault::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
vertex = addConditionVertex( graph, "default: ");
boost::add_edge( begin, vertex, graph);
boost::add_edge( vertex, end, graph);
}
void BlockBreak::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
boost::add_edge( begin, onBreak, graph);
}
void BlockContinue::expand(vertex_t begin, vertex_t end, vertex_t onReturn, vertex_t onBreak, vertex_t onContinue)
{
boost::add_edge( begin, onContinue, graph);
}
<|endoftext|>
|
<commit_before>#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <libmesh/libmesh.h>
int main( int argc, char **argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and Petsc)
// that require initialization before use.
libMesh::LibMeshInit init(argc, argv);
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() );
runner.run();
return 0;
}
<commit_msg>If we see unit test failure, don't ignore it!<commit_after>#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <libmesh/libmesh.h>
int main( int argc, char **argv)
{
// Initialize the library. This is necessary because the library
// may depend on a number of other libraries (i.e. MPI and Petsc)
// that require initialization before use.
libMesh::LibMeshInit init(argc, argv);
CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() );
// If the tests all succeed, report success
if (runner.run())
return 0;
// If any test fails report failure
return 1;
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 (RX64M) メイン @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"
#include "chip/LTC2348_16.hpp"
#include "sample.hpp"
namespace seeda {
static const int seeda_version_ = 100;
static const uint32_t build_id_ = B_ID;
typedef utils::command<256> CMD;
#ifdef SEEDA
typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif
// Soft SDC 用 SPI 定義(SPI)
#ifdef SEEDA
typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
typedef device::spi_io<MISO, MOSI, SPCK> SPI;
typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< カード選択信号
typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON)
typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< カード検出
#else
// SDC 用 SPI 定義(RSPI)
typedef device::rspi_io<device::RSPI> SPI;
typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< カード選択信号
typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON)
typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< カード検出
#endif
typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;
#ifdef SEEDA
// LTC2348-16 A/D 制御ポート定義
typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141)
typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61)
typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126)
typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53)
typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50)
typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41)
typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39)
typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37)
typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36)
typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35)
typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34)
typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif
typedef device::flash_io FLASH_IO;
typedef utils::flash_man<FLASH_IO> FLASH_MAN;
//-----------------------------------------------------------------//
/*!
@brief SDC_IO クラスへの参照
@return SDC_IO クラス
*/
//-----------------------------------------------------------------//
SDC& at_sdc();
#ifdef SEEDA
//-----------------------------------------------------------------//
/*!
@brief EADC クラスへの参照
@return EADC クラス
*/
//-----------------------------------------------------------------//
EADC& at_eadc();
#endif
//-----------------------------------------------------------------//
/*!
@brief EADC サーバー
*/
//-----------------------------------------------------------------//
void eadc_server();
//-----------------------------------------------------------------//
/*!
@brief EADC サーバー許可
@param[in] ena 「false」の場合不許可
*/
//-----------------------------------------------------------------//
void enable_eadc_server(bool ena = true);
//-----------------------------------------------------------------//
/*!
@brief 時間の作成
@param[in] date 日付
@param[in] time 時間
*/
//-----------------------------------------------------------------//
size_t make_time(const char* date, const char* time);
//-----------------------------------------------------------------//
/*!
@brief GMT 時間の設定
@param[in] t GMT 時間
*/
//-----------------------------------------------------------------//
void set_time(time_t t);
//-----------------------------------------------------------------//
/*!
@brief 時間の表示
@param[in] t 時間
@param[in] dst 出力文字列
@param[in] size 文字列の大きさ
@return 生成された文字列の長さ
*/
//-----------------------------------------------------------------//
int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);
//-----------------------------------------------------------------//
/*!
@brief 設定スイッチの状態を取得
@return 設定スイッチの状態
*/
//-----------------------------------------------------------------//
uint8_t get_switch()
{
#ifdef SEEDA
return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
return 0; // for only develope mode
#endif
}
//-----------------------------------------------------------------//
/*!
@brief A/D サンプルの参照
@param[in] ch チャネル(0~7)
@return A/D サンプル
*/
//-----------------------------------------------------------------//
sample_t& at_sample(uint8_t ch);
//-----------------------------------------------------------------//
/*!
@brief A/D サンプルの取得
@param[in] ch チャネル(0~7)
@return A/D サンプル
*/
//-----------------------------------------------------------------//
const sample_t& get_sample(uint8_t ch);
//-----------------------------------------------------------------//
/*!
@brief 内臓 A/D 変換値の取得
@param[in] ch チャネル(5、6、7)
@return A/D 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_adc(uint32_t ch);
}
extern "C" {
//-----------------------------------------------------------------//
/*!
@brief GMT 時間の取得
@return GMT 時間
*/
//-----------------------------------------------------------------//
time_t get_time();
};
<commit_msg>update version number<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief SEEDA03 (RX64M) メイン @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"
#include "chip/LTC2348_16.hpp"
#include "sample.hpp"
namespace seeda {
static const int seeda_version_ = 110;
static const uint32_t build_id_ = B_ID;
typedef utils::command<256> CMD;
#ifdef SEEDA
typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif
// Soft SDC 用 SPI 定義(SPI)
#ifdef SEEDA
typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
typedef device::spi_io<MISO, MOSI, SPCK> SPI;
typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT; ///< カード選択信号
typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON)
typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT; ///< カード検出
#else
// SDC 用 SPI 定義(RSPI)
typedef device::rspi_io<device::RSPI> SPI;
typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT; ///< カード選択信号
typedef device::NULL_PORT SDC_POWER; ///< カード電源制御(常に電源ON)
typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT; ///< カード検出
#endif
typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;
#ifdef SEEDA
// LTC2348-16 A/D 制御ポート定義
typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN; // P40(141)
typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV; // PC6(61)
typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY; // PD0/IRQ0(126)
typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD; // P53(53)
typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI; // P56(50)
typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO; // P86(41)
typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI; // P87(39)
typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0; // P20(37)
typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2; // P21(36)
typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4; // P22(35)
typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6; // P23(34)
typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif
typedef device::flash_io FLASH_IO;
typedef utils::flash_man<FLASH_IO> FLASH_MAN;
//-----------------------------------------------------------------//
/*!
@brief SDC_IO クラスへの参照
@return SDC_IO クラス
*/
//-----------------------------------------------------------------//
SDC& at_sdc();
#ifdef SEEDA
//-----------------------------------------------------------------//
/*!
@brief EADC クラスへの参照
@return EADC クラス
*/
//-----------------------------------------------------------------//
EADC& at_eadc();
#endif
//-----------------------------------------------------------------//
/*!
@brief EADC サーバー
*/
//-----------------------------------------------------------------//
void eadc_server();
//-----------------------------------------------------------------//
/*!
@brief EADC サーバー許可
@param[in] ena 「false」の場合不許可
*/
//-----------------------------------------------------------------//
void enable_eadc_server(bool ena = true);
//-----------------------------------------------------------------//
/*!
@brief 時間の作成
@param[in] date 日付
@param[in] time 時間
*/
//-----------------------------------------------------------------//
size_t make_time(const char* date, const char* time);
//-----------------------------------------------------------------//
/*!
@brief GMT 時間の設定
@param[in] t GMT 時間
*/
//-----------------------------------------------------------------//
void set_time(time_t t);
//-----------------------------------------------------------------//
/*!
@brief 時間の表示
@param[in] t 時間
@param[in] dst 出力文字列
@param[in] size 文字列の大きさ
@return 生成された文字列の長さ
*/
//-----------------------------------------------------------------//
int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);
//-----------------------------------------------------------------//
/*!
@brief 設定スイッチの状態を取得
@return 設定スイッチの状態
*/
//-----------------------------------------------------------------//
uint8_t get_switch()
{
#ifdef SEEDA
return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
return 0; // for only develope mode
#endif
}
//-----------------------------------------------------------------//
/*!
@brief A/D サンプルの参照
@param[in] ch チャネル(0~7)
@return A/D サンプル
*/
//-----------------------------------------------------------------//
sample_t& at_sample(uint8_t ch);
//-----------------------------------------------------------------//
/*!
@brief A/D サンプルの取得
@param[in] ch チャネル(0~7)
@return A/D サンプル
*/
//-----------------------------------------------------------------//
const sample_t& get_sample(uint8_t ch);
//-----------------------------------------------------------------//
/*!
@brief 内臓 A/D 変換値の取得
@param[in] ch チャネル(5、6、7)
@return A/D 変換値
*/
//-----------------------------------------------------------------//
uint16_t get_adc(uint32_t ch);
}
extern "C" {
//-----------------------------------------------------------------//
/*!
@brief GMT 時間の取得
@return GMT 時間
*/
//-----------------------------------------------------------------//
time_t get_time();
};
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <thread>
#include <utility>
#include <vector>
#include <CLI11/CLI11.hpp>
#define PROFILE_CSV_LINE_LENGTH 9
struct profile_data{
double time_total;
double forward_time;
double reverse_time;
size_t chain_stack_total;
size_t nochain_stack_total;
size_t no_autodiff_passes;
size_t autodiff_passes;
size_t n_threads;
};
using profile_data_map = std::map<std::string, profile_data>;
profile_data_map profile_map;
/**
* Compute the summary of profiling data
* from CSV files with Stan profiling data.
* Command line options handled by CLI11 lib.
*
* @param argc Number of arguments
* @param argv Arguments
*
* @return 0 for success,
* non-zero otherwise
*/
int main(int argc, const char *argv[]) {
std::string usage = R"(Usage: profilesummary [OPTIONS] stan_profiling_csv_file(s)
Report summaries of the profiling data CSV files with Stan profiling data.
Example: profilesummary profiling_chain_1.csv profiling_chain_2.csv
Options:
-h, --help Produce help message, then exit.
-s, --sig_figs [n] Significant figures reported. Default is 2.
Must be an integer from (1, 18), inclusive.
)";
if (argc < 2) {
std::cout << usage << std::endl;
return -1;
}
// Command-line arguments
int sig_figs = 4;
std::string csv_filename;
std::vector<std::string> filenames;
CLI::App app{"Allowed options"};
app.add_option("--sig_figs,-s", sig_figs, "Significant figures, default 4.",
true)
->check(CLI::Range(1, 18));
app.add_option("input_files", filenames, "Stan profiling CSV files.", true)
->required()
->check(CLI::ExistingFile);
try {
CLI11_PARSE(app, argc, argv);
} catch (const CLI::ParseError &e) {
std::cout << e.get_exit_code();
return app.exit(e);
}
for (int i = 0; i < filenames.size(); ++i) {
std::ifstream infile;
infile.open(filenames[i].c_str());
if (infile.good()) {
infile.close();
} else {
std::cout << "Cannot read input csv file: " << filenames[i] << "."
<< std::endl;
return -1;
}
}
std::string delimiter = ",";
try {
for (int i = 0; i < filenames.size(); ++i) {
std::string line;
std::ifstream infile;
infile.open(filenames[i].c_str());
std::getline(infile, line); // ignore header
while(std::getline(infile, line, '\n'))
{
std::stringstream line_stream(line);
std::vector<std::string> line_cells;
std::string cell;
while(std::getline(line_stream,cell, ','))
{
line_cells.push_back(cell);
}
if(line_cells.size() != PROFILE_CSV_LINE_LENGTH) {
std::cerr << "Expected " << PROFILE_CSV_LINE_LENGTH << " but found "
<< line_cells.size() << " columns!" << "!" << std::endl;
return -1;
}
std::string name = line_cells[0];
profile_data_map::iterator it = profile_map.find(name);
if (it == profile_map.end()) {
profile_map[name] = {};
}
profile_data& p = profile_map[name];
p.time_total += std::stod(line_cells[2]);
p.time_total += std::stod(line_cells[2]);
p.forward_time += std::stod(line_cells[3]);
p.reverse_time += std::stod(line_cells[4]);
p.chain_stack_total += std::stoi(line_cells[5]);
p.nochain_stack_total += std::stoi(line_cells[6]);
p.no_autodiff_passes += std::stoi(line_cells[7]);
p.autodiff_passes += std::stoi(line_cells[8]);
p.n_threads += 1;
}
infile.close();
}
size_t n_files = filenames.size();
// TODO: Iterate over all profiles and if n_threads > n_files do sum*n_files/threads
std::cout << std::setprecision(sig_figs)
<< "Profile information combined from " << n_files << " file(s)"
<< std::endl << std::endl
<< "Timing information: " << std::endl << std::endl
// TODO: These tabs are obviously useless
<< "\t\t" << "Total" << "\t\t" << "Forward pass" << "\t\t" << "Reverse pass" << std::endl;
profile_data_map::iterator it;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.time_total
<< "\t\t"<< it->second.forward_time
<< "\t\t"<< it->second.reverse_time << std::endl;
}
std::cout << "Memory information: " << std::endl << std::endl
<< "\t\t" << "ChainStack" << "\t\t" << "NoChainStack" << std::endl;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.chain_stack_total
<< "\t\t"<< it->second.nochain_stack_total
<< std::endl;
}
std::cout << "Autodiff information: " << std::endl << std::endl
<< "\t\t" << "NoADPasses" << "\t\t" << "AdPasses" << std::endl;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.no_autodiff_passes
<< "\t\t"<< it->second.autodiff_passes
<< std::endl;
}
} catch (const std::invalid_argument &e) {
std::cerr << "Error during processing. " << e.what() << std::endl;
return -1;
}
return 0;
}
<commit_msg>extra newlines<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <thread>
#include <utility>
#include <vector>
#include <CLI11/CLI11.hpp>
#define PROFILE_CSV_LINE_LENGTH 9
struct profile_data{
double time_total;
double forward_time;
double reverse_time;
size_t chain_stack_total;
size_t nochain_stack_total;
size_t no_autodiff_passes;
size_t autodiff_passes;
size_t n_threads;
};
using profile_data_map = std::map<std::string, profile_data>;
profile_data_map profile_map;
/**
* Compute the summary of profiling data
* from CSV files with Stan profiling data.
* Command line options handled by CLI11 lib.
*
* @param argc Number of arguments
* @param argv Arguments
*
* @return 0 for success,
* non-zero otherwise
*/
int main(int argc, const char *argv[]) {
std::string usage = R"(Usage: profilesummary [OPTIONS] stan_profiling_csv_file(s)
Report summaries of the profiling data CSV files with Stan profiling data.
Example: profilesummary profiling_chain_1.csv profiling_chain_2.csv
Options:
-h, --help Produce help message, then exit.
-s, --sig_figs [n] Significant figures reported. Default is 2.
Must be an integer from (1, 18), inclusive.
)";
if (argc < 2) {
std::cout << usage << std::endl;
return -1;
}
// Command-line arguments
int sig_figs = 4;
std::string csv_filename;
std::vector<std::string> filenames;
CLI::App app{"Allowed options"};
app.add_option("--sig_figs,-s", sig_figs, "Significant figures, default 4.",
true)
->check(CLI::Range(1, 18));
app.add_option("input_files", filenames, "Stan profiling CSV files.", true)
->required()
->check(CLI::ExistingFile);
try {
CLI11_PARSE(app, argc, argv);
} catch (const CLI::ParseError &e) {
std::cout << e.get_exit_code();
return app.exit(e);
}
for (int i = 0; i < filenames.size(); ++i) {
std::ifstream infile;
infile.open(filenames[i].c_str());
if (infile.good()) {
infile.close();
} else {
std::cout << "Cannot read input csv file: " << filenames[i] << "."
<< std::endl;
return -1;
}
}
std::string delimiter = ",";
try {
for (int i = 0; i < filenames.size(); ++i) {
std::string line;
std::ifstream infile;
infile.open(filenames[i].c_str());
std::getline(infile, line); // ignore header
while(std::getline(infile, line, '\n'))
{
std::stringstream line_stream(line);
std::vector<std::string> line_cells;
std::string cell;
while(std::getline(line_stream,cell, ','))
{
line_cells.push_back(cell);
}
if(line_cells.size() != PROFILE_CSV_LINE_LENGTH) {
std::cerr << "Expected " << PROFILE_CSV_LINE_LENGTH << " but found "
<< line_cells.size() << " columns!" << "!" << std::endl;
return -1;
}
std::string name = line_cells[0];
profile_data_map::iterator it = profile_map.find(name);
if (it == profile_map.end()) {
profile_map[name] = {};
}
profile_data& p = profile_map[name];
p.time_total += std::stod(line_cells[2]);
p.time_total += std::stod(line_cells[2]);
p.forward_time += std::stod(line_cells[3]);
p.reverse_time += std::stod(line_cells[4]);
p.chain_stack_total += std::stoi(line_cells[5]);
p.nochain_stack_total += std::stoi(line_cells[6]);
p.no_autodiff_passes += std::stoi(line_cells[7]);
p.autodiff_passes += std::stoi(line_cells[8]);
p.n_threads += 1;
}
infile.close();
}
size_t n_files = filenames.size();
// TODO: Iterate over all profiles and if n_threads > n_files do sum*n_files/threads
std::cout << std::setprecision(sig_figs)
<< "Profile information combined from " << n_files << " file(s)"
<< std::endl << std::endl
<< "Timing information: " << std::endl << std::endl
// TODO: These tabs are obviously useless
<< "\t\t" << "Total" << "\t\t" << "Forward pass" << "\t\t" << "Reverse pass" << std::endl;
profile_data_map::iterator it;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.time_total
<< "\t\t"<< it->second.forward_time
<< "\t\t"<< it->second.reverse_time << std::endl;
}
std::cout << std::endl << "Memory information: " << std::endl << std::endl
<< "\t\t" << "ChainStack" << "\t\t" << "NoChainStack" << std::endl;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.chain_stack_total
<< "\t\t"<< it->second.nochain_stack_total
<< std::endl;
}
std::cout << std::endl << "Autodiff information: " << std::endl << std::endl
<< "\t\t" << "NoADPasses" << "\t\t" << "AdPasses" << std::endl;
for (it = profile_map.begin(); it != profile_map.end(); it++)
{
std::cout << it->first
<< "\t\t" << it->second.no_autodiff_passes
<< "\t\t"<< it->second.autodiff_passes
<< std::endl;
}
} catch (const std::invalid_argument &e) {
std::cerr << "Error during processing. " << e.what() << std::endl;
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <binary_search_tree.hpp>
#include <catch.hpp>
SCENARIO("default constructor")
{
BinarySearchTree<int> bst;
REQUIRE(bst.root() == nullptr);
}
SCENARIO("insertElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE(bst.value_() == 7);
REQUIRE(bst.leftNode_() == nullptr);
REQUIRE(bst.rightNode_() == nullptr);
}
SCENARIO("findElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE( bst.isFound(7) == 1);
}
SCENARIO("infile")
{
BinarySearchTree<int> bst;
bst.infile("file.txt");
REQUIRE( bst.count() == 0);
}
SCENARIO("_count")
{
BinarySearchTree<int> bst;
int count = 0;
bst.insert(7);
count = bst.count(bst.root());
REQUIRE( count == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>
#include <catch.hpp>
SCENARIO("default constructor")
{
BinarySearchTree<int> bst;
REQUIRE(bst.root() == nullptr);
}
SCENARIO("insertElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE(bst.value_() == 7);
REQUIRE(bst.leftNode_() == nullptr);
REQUIRE(bst.rightNode_() == nullptr);
}
SCENARIO("findElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE( bst.isFound(7) == 1);
}
SCENARIO("infile")
{
BinarySearchTree<int> bst;
bst.infile("file.txt");
REQUIRE( bst.count() == 0);
}
SCENARIO("_count")
{
BinarySearchTree<int> bst;
int count = 0;
bst.insert(7);
count = bst.count();
REQUIRE( count == 1);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#define INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <comphelper/comphelperdllapi.h>
// forward declaration
namespace com { namespace sun { namespace star { namespace accessibility {
class XAccessible;
class XAccessibleContext;
}}}}
namespace comphelper
{
//= OAccessibleImplementationAccess
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XUnoTunnel
> OAccImpl_Base;
struct OAccImpl_Impl;
/** This is a helper class which allows accessing several aspects of the implementation
of an AccessibleContext.
<p>For instance, when you want to implement a context which can be re-parented, you:
<ul><li>derive your class from OAccessibleImplementationAccess</li>
<li>use <code>setAccessibleParent( <em>component</em>, <em>new_parent</em> )</code>
</ul>
</p>
<p>Another aspect which can be controlled from the outside are states. If you have a class which
has only partial control over it's states, you may consider deriving from OAccessibleImplementationAccess.<br/>
For instance, say you have an implementation (say component A) which is <em>unable</em> to know or to
determine if the represented object is selected, but another component (say B) which uses A (and integrates
it into a tree of accessibility components) is.<br/>
In this case, if A is derived from OAccessibleImplementationAccess, B can manipulate this
foreign-controlled state flag "SELECTED" by using the static helper methods on this class.</p>
<p>Please note that the support for foreign controlled states is rather restrictive: You can't have states
which <em>may be</em> controlled by a foreign instances. This is implied by the fact that a derived
class can ask for states which are <em>set</em> only, not for the ones which are <em>reset</em> currently.
</p>
*/
class COMPHELPER_DLLPUBLIC OAccessibleImplementationAccess : public OAccImpl_Base
{
private:
OAccImpl_Impl* m_pImpl;
protected:
/// retrieves the parent previously set via <method>setAccessibleParent</method>
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
implGetForeignControlledParent( ) const;
/** retrieves the set of currently set states which are controlled by a foreign instance
@return
a bit mask, where a set bit 2^n means that the AccessibleStateType n has been set
*/
sal_Int64 implGetForeignControlledStates( ) const;
/// sets the accessible parent component
virtual void setAccessibleParent(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxAccParent );
/// sets or resets a bit of the foreign controlled states
virtual void setStateBit( const sal_Int16 _nState, const sal_Bool _bSet );
protected:
OAccessibleImplementationAccess( );
virtual ~OAccessibleImplementationAccess( );
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rIdentifier ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
public:
/** tries to access the implementation of an OAccessibleImplementationAccess derivee which is known as
interface only.
@param _rxComponent
is the component which should be examined.
@return
the pointer to the implementation, if successful. The only known error condition so far
is an invalid context (which means it is <NULL/>, or the implementation is not derived
from OAccessibleImplementationAccess, or retrieving the implementation failed).
*/
static OAccessibleImplementationAccess* getImplementation(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent
);
/** sets the parent for a derived implementation
@param _rxComponent
is the component which's new parent should be set
@param _rxNewParent
is the new parent of the component
@return
<TRUE/> in case of success, <FALSE/> otherwise. For error condition please look at
<method>getImplementation</method>.
*/
static bool setAccessibleParent(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxNewParent
);
private:
COMPHELPER_DLLPRIVATE static const ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
};
} // namespace comphelper
#endif // INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>No need for these functions to be virtual<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#define INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <comphelper/comphelperdllapi.h>
// forward declaration
namespace com { namespace sun { namespace star { namespace accessibility {
class XAccessible;
class XAccessibleContext;
}}}}
namespace comphelper
{
//= OAccessibleImplementationAccess
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XUnoTunnel
> OAccImpl_Base;
struct OAccImpl_Impl;
/** This is a helper class which allows accessing several aspects of the implementation
of an AccessibleContext.
<p>For instance, when you want to implement a context which can be re-parented, you:
<ul><li>derive your class from OAccessibleImplementationAccess</li>
<li>use <code>setAccessibleParent( <em>component</em>, <em>new_parent</em> )</code>
</ul>
</p>
<p>Another aspect which can be controlled from the outside are states. If you have a class which
has only partial control over it's states, you may consider deriving from OAccessibleImplementationAccess.<br/>
For instance, say you have an implementation (say component A) which is <em>unable</em> to know or to
determine if the represented object is selected, but another component (say B) which uses A (and integrates
it into a tree of accessibility components) is.<br/>
In this case, if A is derived from OAccessibleImplementationAccess, B can manipulate this
foreign-controlled state flag "SELECTED" by using the static helper methods on this class.</p>
<p>Please note that the support for foreign controlled states is rather restrictive: You can't have states
which <em>may be</em> controlled by a foreign instances. This is implied by the fact that a derived
class can ask for states which are <em>set</em> only, not for the ones which are <em>reset</em> currently.
</p>
*/
class COMPHELPER_DLLPUBLIC OAccessibleImplementationAccess : public OAccImpl_Base
{
private:
OAccImpl_Impl* m_pImpl;
protected:
/// retrieves the parent previously set via <method>setAccessibleParent</method>
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
implGetForeignControlledParent( ) const;
/** retrieves the set of currently set states which are controlled by a foreign instance
@return
a bit mask, where a set bit 2^n means that the AccessibleStateType n has been set
*/
sal_Int64 implGetForeignControlledStates( ) const;
/// sets the accessible parent component
void setAccessibleParent(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxAccParent );
/// sets or resets a bit of the foreign controlled states
void setStateBit( const sal_Int16 _nState, const sal_Bool _bSet );
protected:
OAccessibleImplementationAccess( );
virtual ~OAccessibleImplementationAccess( );
// XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rIdentifier ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
public:
/** tries to access the implementation of an OAccessibleImplementationAccess derivee which is known as
interface only.
@param _rxComponent
is the component which should be examined.
@return
the pointer to the implementation, if successful. The only known error condition so far
is an invalid context (which means it is <NULL/>, or the implementation is not derived
from OAccessibleImplementationAccess, or retrieving the implementation failed).
*/
static OAccessibleImplementationAccess* getImplementation(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent
);
/** sets the parent for a derived implementation
@param _rxComponent
is the component which's new parent should be set
@param _rxNewParent
is the new parent of the component
@return
<TRUE/> in case of success, <FALSE/> otherwise. For error condition please look at
<method>getImplementation</method>.
*/
static bool setAccessibleParent(
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent,
const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxNewParent
);
private:
COMPHELPER_DLLPRIVATE static const ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
};
} // namespace comphelper
#endif // INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-explorer.
*
* libbitcoin-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/explorer/commands/ek-to-address.hpp>
#include <iostream>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/address.hpp>
using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
using namespace bc::wallet;
console_result ek_to_address::invoke(std::ostream& output, std::ostream& error)
{
#ifdef WITH_ICU
const auto& passphrase = get_passphrase_argument();
const auto& key = get_ek_private_key_argument();
bool compressed;
uint8_t version;
ec_private secret;
if (!decrypt(secret.data(), version, compressed, key, passphrase))
{
error << BX_EK_TO_ADDRESS_INVALID_PASSPHRASE << std::endl;
return console_result::failure;
}
const auto point = secret_to_public_key(secret, compressed);
const address payment_address(version, point);
output << secret << std::endl;
return console_result::okay;
#else
error << BX_EK_TO_ADDRESS_REQUIRES_ICU << std::endl;
return console_result::failure;
#endif
}
<commit_msg>fix: ek-to-address was returning the ec private key instead of the address.<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin-explorer.
*
* libbitcoin-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <bitcoin/explorer/commands/ek-to-address.hpp>
#include <iostream>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/address.hpp>
using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
using namespace bc::wallet;
console_result ek_to_address::invoke(std::ostream& output, std::ostream& error)
{
#ifdef WITH_ICU
const auto& passphrase = get_passphrase_argument();
const auto& key = get_ek_private_key_argument();
bool compressed;
uint8_t version;
ec_private secret;
if (!decrypt(secret.data(), version, compressed, key, passphrase))
{
error << BX_EK_TO_ADDRESS_INVALID_PASSPHRASE << std::endl;
return console_result::failure;
}
const auto point = secret_to_public_key(secret, compressed);
const address payment_address(version, point);
output << payment_address << std::endl;
return console_result::okay;
#else
error << BX_EK_TO_ADDRESS_REQUIRES_ICU << std::endl;
return console_result::failure;
#endif
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <chrono> // NOLINT(build/c++11)
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "absl/time/time.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_api_delegate.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/testing/tflite_model_reader.h"
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/register.h"
namespace {
void FillInputTensor(tflite::Interpreter* interpreter) {
for (int k = 0; k < interpreter->inputs().size(); ++k) {
TfLiteTensor* tensor_ptr = interpreter->tensor(interpreter->inputs()[k]);
const auto tensor_elements_count = tflite::NumElements(tensor_ptr);
if (tensor_ptr->type == kTfLiteFloat32) {
float* p = interpreter->typed_input_tensor<float>(k);
for (int i = 0; i < tensor_elements_count; ++i) {
p[i] = std::sin(i);
}
}
if (tensor_ptr->type == kTfLiteInt32) {
int* p = interpreter->typed_input_tensor<int>(k);
for (int i = 0; i < tensor_elements_count; ++i) {
p[i] = i % 2;
}
}
}
}
void CompareCPUGPUResults(tflite::Interpreter* cpu, tflite::Interpreter* gpu,
float eps) {
for (int i = 0; i < cpu->outputs().size(); ++i) {
const float* cpu_out = cpu->typed_output_tensor<float>(i);
const float* gpu_out = gpu->typed_output_tensor<float>(i);
auto out_n = tflite::NumElements(cpu->tensor(cpu->outputs()[i]));
const int kMaxPrint = 10;
int printed = 0;
int total_different = 0;
for (int k = 0; k < out_n; ++k) {
const float abs_diff = fabs(cpu_out[k] - gpu_out[k]);
if (abs_diff > eps) {
total_different++;
if (printed < kMaxPrint) {
std::cout << "Output #" << i << ": element #" << k << ": CPU value - "
<< cpu_out[k] << ", GPU value - " << gpu_out[k]
<< ", abs diff - " << abs_diff << std::endl;
printed++;
}
if (printed == kMaxPrint) {
std::cout << "Printed " << kMaxPrint
<< " different elements, threshhold - " << eps
<< ", next different elements skipped" << std::endl;
printed++;
}
}
}
std::cout << "Total " << total_different
<< " different elements, for output #" << i << ", threshhold - "
<< eps << std::endl;
}
}
} // namespace
int main(int argc, char** argv) {
if (argc <= 1) {
std::cerr << "Expected model path as second argument." << std::endl;
return -1;
}
auto model = tflite::FlatBufferModel::BuildFromFile(argv[1]);
if (!model) {
std::cerr << "FlatBufferModel::BuildFromFile failed, model path - "
<< argv[1] << std::endl;
return -1;
}
tflite::ops::builtin::BuiltinOpResolver op_resolver;
tflite::InterpreterBuilder builder(*model, op_resolver);
// CPU.
std::unique_ptr<tflite::Interpreter> cpu_inference;
builder(&cpu_inference);
if (!cpu_inference) {
std::cerr << "Failed to build CPU inference." << std::endl;
return -1;
}
auto status = cpu_inference->AllocateTensors();
if (status != kTfLiteOk) {
std::cerr << "Failed to AllocateTensors for CPU inference." << std::endl;
return -1;
}
FillInputTensor(cpu_inference.get());
status = cpu_inference->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Failed to Invoke CPU inference." << std::endl;
return -1;
}
// GPU.
std::unique_ptr<tflite::Interpreter> gpu_inference;
builder(&gpu_inference);
if (!gpu_inference) {
std::cerr << "Failed to build GPU inference." << std::endl;
return -1;
}
TfLiteGpuDelegateOptionsV2 options;
options.is_precision_loss_allowed = -1;
options.inference_preference =
TFLITE_GPU_INFERENCE_PREFERENCE_FAST_SINGLE_ANSWER;
options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
options.inference_priority2 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_MEMORY_USAGE;
options.inference_priority3 = TFLITE_GPU_INFERENCE_PRIORITY_MAX_PRECISION;
options.max_delegated_partitions = 1;
auto* gpu_delegate = TfLiteGpuDelegateV2Create(&options);
status = gpu_inference->ModifyGraphWithDelegate(gpu_delegate);
if (status != kTfLiteOk) {
std::cerr << "ModifyGraphWithDelegate failed." << std::endl;
return -1;
}
FillInputTensor(gpu_inference.get());
status = gpu_inference->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Failed to Invoke GPU inference." << std::endl;
return -1;
}
CompareCPUGPUResults(cpu_inference.get(), gpu_inference.get(), 1e-4f);
// CPU inference latency.
auto start = std::chrono::high_resolution_clock::now();
cpu_inference->Invoke();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "CPU time - " << (end - start).count() * 1e-6f << "ms"
<< std::endl;
// GPU inference latency.
start = std::chrono::high_resolution_clock::now();
gpu_inference->Invoke();
end = std::chrono::high_resolution_clock::now();
std::cout << "GPU time(CPU->GPU->CPU) - " << (end - start).count() * 1e-6f
<< "ms" << std::endl;
TfLiteGpuDelegateV2Delete(gpu_delegate);
return EXIT_SUCCESS;
}
<commit_msg>Added initialization of new field.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <chrono> // NOLINT(build/c++11)
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "absl/time/time.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_api_delegate.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/testing/tflite_model_reader.h"
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/register.h"
namespace {
void FillInputTensor(tflite::Interpreter* interpreter) {
for (int k = 0; k < interpreter->inputs().size(); ++k) {
TfLiteTensor* tensor_ptr = interpreter->tensor(interpreter->inputs()[k]);
const auto tensor_elements_count = tflite::NumElements(tensor_ptr);
if (tensor_ptr->type == kTfLiteFloat32) {
float* p = interpreter->typed_input_tensor<float>(k);
for (int i = 0; i < tensor_elements_count; ++i) {
p[i] = std::sin(i);
}
}
if (tensor_ptr->type == kTfLiteInt32) {
int* p = interpreter->typed_input_tensor<int>(k);
for (int i = 0; i < tensor_elements_count; ++i) {
p[i] = i % 2;
}
}
}
}
void CompareCPUGPUResults(tflite::Interpreter* cpu, tflite::Interpreter* gpu,
float eps) {
for (int i = 0; i < cpu->outputs().size(); ++i) {
const float* cpu_out = cpu->typed_output_tensor<float>(i);
const float* gpu_out = gpu->typed_output_tensor<float>(i);
auto out_n = tflite::NumElements(cpu->tensor(cpu->outputs()[i]));
const int kMaxPrint = 10;
int printed = 0;
int total_different = 0;
for (int k = 0; k < out_n; ++k) {
const float abs_diff = fabs(cpu_out[k] - gpu_out[k]);
if (abs_diff > eps) {
total_different++;
if (printed < kMaxPrint) {
std::cout << "Output #" << i << ": element #" << k << ": CPU value - "
<< cpu_out[k] << ", GPU value - " << gpu_out[k]
<< ", abs diff - " << abs_diff << std::endl;
printed++;
}
if (printed == kMaxPrint) {
std::cout << "Printed " << kMaxPrint
<< " different elements, threshhold - " << eps
<< ", next different elements skipped" << std::endl;
printed++;
}
}
}
std::cout << "Total " << total_different
<< " different elements, for output #" << i << ", threshhold - "
<< eps << std::endl;
}
}
} // namespace
int main(int argc, char** argv) {
if (argc <= 1) {
std::cerr << "Expected model path as second argument." << std::endl;
return -1;
}
auto model = tflite::FlatBufferModel::BuildFromFile(argv[1]);
if (!model) {
std::cerr << "FlatBufferModel::BuildFromFile failed, model path - "
<< argv[1] << std::endl;
return -1;
}
tflite::ops::builtin::BuiltinOpResolver op_resolver;
tflite::InterpreterBuilder builder(*model, op_resolver);
// CPU.
std::unique_ptr<tflite::Interpreter> cpu_inference;
builder(&cpu_inference);
if (!cpu_inference) {
std::cerr << "Failed to build CPU inference." << std::endl;
return -1;
}
auto status = cpu_inference->AllocateTensors();
if (status != kTfLiteOk) {
std::cerr << "Failed to AllocateTensors for CPU inference." << std::endl;
return -1;
}
FillInputTensor(cpu_inference.get());
status = cpu_inference->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Failed to Invoke CPU inference." << std::endl;
return -1;
}
// GPU.
std::unique_ptr<tflite::Interpreter> gpu_inference;
builder(&gpu_inference);
if (!gpu_inference) {
std::cerr << "Failed to build GPU inference." << std::endl;
return -1;
}
TfLiteGpuDelegateOptionsV2 options;
options.is_precision_loss_allowed = -1;
options.inference_preference =
TFLITE_GPU_INFERENCE_PREFERENCE_FAST_SINGLE_ANSWER;
options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
options.inference_priority2 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_MEMORY_USAGE;
options.inference_priority3 = TFLITE_GPU_INFERENCE_PRIORITY_MAX_PRECISION;
options.experimental_flags = TFLITE_GPU_EXPERIMENTAL_FLAGS_NONE;
options.max_delegated_partitions = 1;
auto* gpu_delegate = TfLiteGpuDelegateV2Create(&options);
status = gpu_inference->ModifyGraphWithDelegate(gpu_delegate);
if (status != kTfLiteOk) {
std::cerr << "ModifyGraphWithDelegate failed." << std::endl;
return -1;
}
FillInputTensor(gpu_inference.get());
status = gpu_inference->Invoke();
if (status != kTfLiteOk) {
std::cerr << "Failed to Invoke GPU inference." << std::endl;
return -1;
}
CompareCPUGPUResults(cpu_inference.get(), gpu_inference.get(), 1e-4f);
// CPU inference latency.
auto start = std::chrono::high_resolution_clock::now();
cpu_inference->Invoke();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "CPU time - " << (end - start).count() * 1e-6f << "ms"
<< std::endl;
// GPU inference latency.
start = std::chrono::high_resolution_clock::now();
gpu_inference->Invoke();
end = std::chrono::high_resolution_clock::now();
std::cout << "GPU time(CPU->GPU->CPU) - " << (end - start).count() * 1e-6f
<< "ms" << std::endl;
TfLiteGpuDelegateV2Delete(gpu_delegate);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 <vtkObjectFactory.h>
// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"
// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>
// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
return refNode->IsA("vtkMRMLSpatialObjectsNode");
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjectsNode =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
if(Superclass::ReadDataInternal(refNode) != 0)
{
return 0;
}
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("ReadData: File name not specified");
return 0;
}
// compute file prefix
std::string name(fullName);
std::string::size_type loc = name.find_last_of(".");
if( loc == std::string::npos )
{
vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
return 0;
}
std::string extension = name.substr(loc);
vtkDebugMacro("ReadData: extension = " << extension.c_str());
int result = 1;
try
{
if(extension == std::string(".tre"))
{
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(fullName);
reader->Update();
// WARNING : Should we check if the tube contains less than 2 points...
char childName[] = "Tube";
TubeNetType::ChildrenListType* tubeList =
reader->GetGroup()->GetChildren(tubeList->GetMaximumDepth(), childName);
// -----------------------------------------------------------------------
// Copy skeleton points from vessels into polydata structure
// -----------------------------------------------------------------------
// Initialize the SpatialObject
// Count number of points && remove dupplicate
int totalNumberOfPoints = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end();
++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
if(currTube->GetNumberOfPoints() < 2)
continue;
totalNumberOfPoints += currTube->GetNumberOfPoints();
}
// Create the points
vtkNew<vtkPoints> vesselsPoints;
vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);
// Create the Lines
vtkNew<vtkCellArray> vesselLinesCA;
// Create scalar array that indicates the radius at each
// centerline point.
vtkNew<vtkDoubleArray> tubeRadius;
tubeRadius->SetName("TubeRadius");
tubeRadius->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates TubeID.
vtkNew<vtkDoubleArray> tubeIDs;
tubeIDs->SetName("TubeIDs");
tubeIDs->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates both tangeantes at each
// centerline point.
vtkNew<vtkDoubleArray> tan1;
tan1->SetName("Tan1");
tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
tan1->SetNumberOfComponents(3);
vtkNew<vtkDoubleArray> tan2;
tan2->SetName("Tan2");
tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
tan2->SetNumberOfComponents(3);
// Create scalar array that indicates Ridgness and medialness at each
// centerline point.
bool containsMidialnessInfo = false;
vtkNew<vtkDoubleArray> medialness;
medialness->SetName("Medialness");
medialness->SetNumberOfTuples(totalNumberOfPoints);
bool containsRidgnessInfo = false;
vtkNew<vtkDoubleArray> ridgeness;
ridgeness->SetName("Ridgeness");
ridgeness->SetNumberOfTuples(totalNumberOfPoints);
int pointID = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end(); ++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
int tubeSize = currTube->GetNumberOfPoints();
if(tubeSize < 2)
continue;
currTube->ComputeTangentAndNormals();
// Create a pointID list [linear for a polyline]
vtkIdType* pointIDs = new vtkIdType[tubeSize];
vtkNew<vtkPolyLine> vesselLine;
// Get the tube element spacing information.
const double* axesRatio = currTube->GetSpacing();
int index = 0;
std::vector<TubePointType>::iterator tubePointIterator;
for(tubePointIterator = currTube->GetPoints().begin();
tubePointIterator != currTube->GetPoints().end();
++tubePointIterator, ++pointID, ++index)
{
PointType inputPoint = tubePointIterator->GetPosition();
pointIDs[index] = pointID;
// Insert points using the element spacing information.
vesselsPoints->SetPoint(pointID,
inputPoint[0],
inputPoint[1] * axesRatio[1] / axesRatio[0],
inputPoint[2] * axesRatio[2] / axesRatio[0]);
// TubeID
tubeIDs->SetTuple1(pointID, currTube->GetId());
// Radius
tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());
// Tangeantes
tan1->SetTuple3(pointID,
(*tubePointIterator).GetNormal1()[0],
(*tubePointIterator).GetNormal1()[1],
(*tubePointIterator).GetNormal1()[2]);
tan2->SetTuple3(pointID,
(*tubePointIterator).GetNormal2()[0],
(*tubePointIterator).GetNormal2()[1],
(*tubePointIterator).GetNormal2()[2]);
// Medialness & Ridgness
if(tubePointIterator->GetMedialness() != 0)
{
containsMidialnessInfo = true;
}
medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());
if(tubePointIterator->GetRidgeness() != 0)
{
containsRidgnessInfo = true;
}
ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
}
vesselLine->Initialize(tubeSize,
pointIDs,
vesselsPoints.GetPointer());
vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
delete [] pointIDs;
}
// Convert spatial objects to a PolyData
vtkNew<vtkPolyData> vesselsPD;
vesselsPD->SetLines(vesselLinesCA.GetPointer());
vesselsPD->SetPoints(vesselsPoints.GetPointer());
// Add the Radius information
vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");
// Add the TudeID information
vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());
// Add Tangeantes information
vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
vesselsPD->GetPointData()->AddArray(tan2.GetPointer());
// Add Medialness & Ridgness if contains information
if(containsMidialnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
}
if(containsRidgnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
}
// Remove any duplicate points from polydata.
// The tubes generation will fails if any duplicates points are present.
// Cleaned before, could create degeneration problems with the cells
//vtkNew<vtkCleanPolyData> cleanedVesselPD;
//cleanedVesselPD->SetInput(vesselsPD.GetPointer());
vtkDebugMacro("Points: " << totalNumberOfPoints);
spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
spatialObjectsNode->SetSpatialObject(reader->GetGroup());
delete tubeList;
}
}
catch(...)
{
result = 0;
}
if(spatialObjectsNode->GetPolyData() != NULL)
{
// is there an active scalar array?
if(spatialObjectsNode->GetDisplayNode())
{
double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
if(scalarRange)
{
vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
<< ", " << scalarRange[1]);
spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
}
}
spatialObjectsNode->GetPolyData()->Modified();
}
return result;
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjects =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("vtkMRMLModelNode: File name not specified");
return 0;
}
std::string extension =
itksys::SystemTools::GetFilenameLastExtension(fullName);
int result = 1;
if(extension == ".tre")
{
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(fullName.c_str());
writer->SetInput(spatialObjects->GetSpatialObject());
writer->Update();
}
catch(...)
{
result = 0;
vtkErrorMacro("Error occured writing Spatial Objects: "
<< fullName.c_str());
}
}
else
{
result = 0;
vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
}
return result;
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
return "tre";
}
<commit_msg>PATCH: Maximum depth of group<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 <vtkObjectFactory.h>
// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"
// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>
// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>
//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
}
//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
return refNode->IsA("vtkMRMLSpatialObjectsNode");
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjectsNode =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
if(Superclass::ReadDataInternal(refNode) != 0)
{
return 0;
}
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("ReadData: File name not specified");
return 0;
}
// compute file prefix
std::string name(fullName);
std::string::size_type loc = name.find_last_of(".");
if( loc == std::string::npos )
{
vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
return 0;
}
std::string extension = name.substr(loc);
vtkDebugMacro("ReadData: extension = " << extension.c_str());
int result = 1;
try
{
if(extension == std::string(".tre"))
{
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(fullName);
reader->Update();
// WARNING : Should we check if the tube contains less than 2 points...
char childName[] = "Tube";
TubeNetType::ChildrenListType* tubeList =
reader->GetGroup()->GetChildren(reader->GetGroup()->GetMaximumDepth(), childName);
// -----------------------------------------------------------------------
// Copy skeleton points from vessels into polydata structure
// -----------------------------------------------------------------------
// Initialize the SpatialObject
// Count number of points && remove dupplicate
int totalNumberOfPoints = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end();
++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
if(currTube->GetNumberOfPoints() < 2)
continue;
totalNumberOfPoints += currTube->GetNumberOfPoints();
}
// Create the points
vtkNew<vtkPoints> vesselsPoints;
vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);
// Create the Lines
vtkNew<vtkCellArray> vesselLinesCA;
// Create scalar array that indicates the radius at each
// centerline point.
vtkNew<vtkDoubleArray> tubeRadius;
tubeRadius->SetName("TubeRadius");
tubeRadius->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates TubeID.
vtkNew<vtkDoubleArray> tubeIDs;
tubeIDs->SetName("TubeIDs");
tubeIDs->SetNumberOfTuples(totalNumberOfPoints);
// Create scalar array that indicates both tangeantes at each
// centerline point.
vtkNew<vtkDoubleArray> tan1;
tan1->SetName("Tan1");
tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
tan1->SetNumberOfComponents(3);
vtkNew<vtkDoubleArray> tan2;
tan2->SetName("Tan2");
tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
tan2->SetNumberOfComponents(3);
// Create scalar array that indicates Ridgness and medialness at each
// centerline point.
bool containsMidialnessInfo = false;
vtkNew<vtkDoubleArray> medialness;
medialness->SetName("Medialness");
medialness->SetNumberOfTuples(totalNumberOfPoints);
bool containsRidgnessInfo = false;
vtkNew<vtkDoubleArray> ridgeness;
ridgeness->SetName("Ridgeness");
ridgeness->SetNumberOfTuples(totalNumberOfPoints);
int pointID = 0;
for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
tubeIT != tubeList->end(); ++tubeIT )
{
TubeType* currTube =
static_cast<TubeType*>((*tubeIT).GetPointer());
currTube->RemoveDuplicatePoints();
int tubeSize = currTube->GetNumberOfPoints();
if(tubeSize < 2)
continue;
currTube->ComputeTangentAndNormals();
// Create a pointID list [linear for a polyline]
vtkIdType* pointIDs = new vtkIdType[tubeSize];
vtkNew<vtkPolyLine> vesselLine;
// Get the tube element spacing information.
const double* axesRatio = currTube->GetSpacing();
int index = 0;
std::vector<TubePointType>::iterator tubePointIterator;
for(tubePointIterator = currTube->GetPoints().begin();
tubePointIterator != currTube->GetPoints().end();
++tubePointIterator, ++pointID, ++index)
{
PointType inputPoint = tubePointIterator->GetPosition();
pointIDs[index] = pointID;
// Insert points using the element spacing information.
vesselsPoints->SetPoint(pointID,
inputPoint[0],
inputPoint[1] * axesRatio[1] / axesRatio[0],
inputPoint[2] * axesRatio[2] / axesRatio[0]);
// TubeID
tubeIDs->SetTuple1(pointID, currTube->GetId());
// Radius
tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());
// Tangeantes
tan1->SetTuple3(pointID,
(*tubePointIterator).GetNormal1()[0],
(*tubePointIterator).GetNormal1()[1],
(*tubePointIterator).GetNormal1()[2]);
tan2->SetTuple3(pointID,
(*tubePointIterator).GetNormal2()[0],
(*tubePointIterator).GetNormal2()[1],
(*tubePointIterator).GetNormal2()[2]);
// Medialness & Ridgness
if(tubePointIterator->GetMedialness() != 0)
{
containsMidialnessInfo = true;
}
medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());
if(tubePointIterator->GetRidgeness() != 0)
{
containsRidgnessInfo = true;
}
ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
}
vesselLine->Initialize(tubeSize,
pointIDs,
vesselsPoints.GetPointer());
vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
delete [] pointIDs;
}
// Convert spatial objects to a PolyData
vtkNew<vtkPolyData> vesselsPD;
vesselsPD->SetLines(vesselLinesCA.GetPointer());
vesselsPD->SetPoints(vesselsPoints.GetPointer());
// Add the Radius information
vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");
// Add the TudeID information
vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());
// Add Tangeantes information
vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
vesselsPD->GetPointData()->AddArray(tan2.GetPointer());
// Add Medialness & Ridgness if contains information
if(containsMidialnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
}
if(containsRidgnessInfo == true)
{
vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
}
// Remove any duplicate points from polydata.
// The tubes generation will fails if any duplicates points are present.
// Cleaned before, could create degeneration problems with the cells
//vtkNew<vtkCleanPolyData> cleanedVesselPD;
//cleanedVesselPD->SetInput(vesselsPD.GetPointer());
vtkDebugMacro("Points: " << totalNumberOfPoints);
spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
spatialObjectsNode->SetSpatialObject(reader->GetGroup());
delete tubeList;
}
}
catch(...)
{
result = 0;
}
if(spatialObjectsNode->GetPolyData() != NULL)
{
// is there an active scalar array?
if(spatialObjectsNode->GetDisplayNode())
{
double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
if(scalarRange)
{
vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
<< ", " << scalarRange[1]);
spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
}
}
spatialObjectsNode->GetPolyData()->Modified();
}
return result;
}
//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
vtkMRMLSpatialObjectsNode* spatialObjects =
vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);
std::string fullName = this->GetFullNameFromFileName();
if(fullName == std::string(""))
{
vtkErrorMacro("vtkMRMLModelNode: File name not specified");
return 0;
}
std::string extension =
itksys::SystemTools::GetFilenameLastExtension(fullName);
int result = 1;
if(extension == ".tre")
{
try
{
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(fullName.c_str());
writer->SetInput(spatialObjects->GetSpatialObject());
writer->Update();
}
catch(...)
{
result = 0;
vtkErrorMacro("Error occured writing Spatial Objects: "
<< fullName.c_str());
}
}
else
{
result = 0;
vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
}
return result;
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}
//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
return "tre";
}
<|endoftext|>
|
<commit_before>#include <QGraphicsView>
#include "fish_annotator/common/annotation_scene.h"
namespace fish_annotator {
AnnotationScene::AnnotationScene(QObject *parent)
: QGraphicsScene(parent)
, mode_(kDoNothing)
, type_(kBox)
, start_pos_()
, rect_item_(nullptr)
, line_item_(nullptr)
, dot_item_(nullptr) {
}
void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
QObject::connect(widget, &AnnotationWidget::setAnnotation,
this, &AnnotationScene::setAnnotationType);
}
void AnnotationScene::setMode(Mode mode) {
mode_ = mode;
QGraphicsView::DragMode drag;
if(mode == kDraw) {
makeItemsControllable(false);
drag = QGraphicsView::NoDrag;
}
else if(mode == kSelect) {
makeItemsControllable(true);
drag = QGraphicsView::RubberBandDrag;
}
auto view = views().at(0);
if(view != nullptr) view->setDragMode(drag);
}
void AnnotationScene::setAnnotationType(AnnotationType type) {
type_ = type;
}
namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}
void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw && sceneRect().contains(event->scenePos()) == true) {
start_pos_ = event->scenePos();
switch(type_) {
case kBox:
rect_item_ = new QGraphicsRectItem(
start_pos_.x(), start_pos_.y(), 0, 0);
rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(rect_item_);
break;
case kLine:
line_item_ = new QGraphicsLineItem(QLineF(
start_pos_, start_pos_));
line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(line_item_);
break;
case kDot:
dot_item_ = new QGraphicsEllipseItem(
start_pos_.x() - pen_width,
start_pos_.y() - pen_width,
2 * pen_width, 2 * pen_width);
dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(dot_item_);
break;
}
}
QGraphicsScene::mousePressEvent(event);
}
void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
auto update_pos = event->scenePos();
qreal margin;
switch(type_) {
case kBox:
margin = pen_width / 2.0;
break;
case kLine:
margin = pen_width;
break;
case kDot:
margin = 2.0 * pen_width;
break;
}
update_pos.setX(qMin(update_pos.x(), sceneRect().right() - margin));
update_pos.setX(qMax(update_pos.x(), sceneRect().left() + margin));
update_pos.setY(qMin(update_pos.y(), sceneRect().bottom() - margin));
update_pos.setY(qMax(update_pos.y(), sceneRect().top() + margin));
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
auto left = qMin(start_pos_.x(), update_pos.x());
auto top = qMin(start_pos_.y(), update_pos.y());
auto width = qAbs(start_pos_.x() - update_pos.x());
auto height = qAbs(start_pos_.y() - update_pos.y());
rect_item_->setRect(QRectF(left, top, width, height));
}
break;
case kLine:
if(line_item_ != nullptr) {
line_item_->setLine(QLineF(start_pos_, update_pos));
}
break;
case kDot:
if(dot_item_ != nullptr) {
dot_item_->setRect(QRectF(
update_pos.x() - pen_width,
update_pos.y() - pen_width,
2 * pen_width, 2 * pen_width));
}
break;
}
}
QGraphicsScene::mouseMoveEvent(event);
}
void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
emit boxFinished(rect_item_->rect());
removeItem(rect_item_);
rect_item_ = nullptr;
}
break;
case kLine:
if(line_item_ != nullptr) {
emit lineFinished(line_item_->line());
removeItem(line_item_);
line_item_ = nullptr;
}
break;
case kDot:
if(dot_item_ != nullptr) {
emit dotFinished(QPointF(
dot_item_->rect().topLeft().x() + pen_width,
dot_item_->rect().topLeft().y() + pen_width));
removeItem(dot_item_);
dot_item_ = nullptr;
}
break;
}
mode_ = kSelect;
}
QGraphicsScene::mouseReleaseEvent(event);
}
void AnnotationScene::makeItemsControllable(bool controllable) {
foreach(QGraphicsItem *item, items()) {
item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
}
}
#include "../../include/fish_annotator/common/moc_annotation_scene.cpp"
} // namespace fish_annotator
<commit_msg>Change to cursor when drawing is enabled. This closes #25.<commit_after>#include <QGraphicsView>
#include "fish_annotator/common/annotation_scene.h"
namespace fish_annotator {
AnnotationScene::AnnotationScene(QObject *parent)
: QGraphicsScene(parent)
, mode_(kDoNothing)
, type_(kBox)
, start_pos_()
, rect_item_(nullptr)
, line_item_(nullptr)
, dot_item_(nullptr) {
}
void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
QObject::connect(widget, &AnnotationWidget::setAnnotation,
this, &AnnotationScene::setAnnotationType);
}
void AnnotationScene::setMode(Mode mode) {
mode_ = mode;
QGraphicsView::DragMode drag;
if(mode == kDraw) {
QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
makeItemsControllable(false);
drag = QGraphicsView::NoDrag;
}
else if(mode == kSelect) {
makeItemsControllable(true);
drag = QGraphicsView::RubberBandDrag;
}
auto view = views().at(0);
if(view != nullptr) view->setDragMode(drag);
}
void AnnotationScene::setAnnotationType(AnnotationType type) {
type_ = type;
}
namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}
void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw && sceneRect().contains(event->scenePos()) == true) {
start_pos_ = event->scenePos();
switch(type_) {
case kBox:
rect_item_ = new QGraphicsRectItem(
start_pos_.x(), start_pos_.y(), 0, 0);
rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(rect_item_);
break;
case kLine:
line_item_ = new QGraphicsLineItem(QLineF(
start_pos_, start_pos_));
line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(line_item_);
break;
case kDot:
dot_item_ = new QGraphicsEllipseItem(
start_pos_.x() - pen_width,
start_pos_.y() - pen_width,
2 * pen_width, 2 * pen_width);
dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(dot_item_);
break;
}
}
QGraphicsScene::mousePressEvent(event);
}
void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
auto update_pos = event->scenePos();
qreal margin;
switch(type_) {
case kBox:
margin = pen_width / 2.0;
break;
case kLine:
margin = pen_width;
break;
case kDot:
margin = 2.0 * pen_width;
break;
}
update_pos.setX(qMin(update_pos.x(), sceneRect().right() - margin));
update_pos.setX(qMax(update_pos.x(), sceneRect().left() + margin));
update_pos.setY(qMin(update_pos.y(), sceneRect().bottom() - margin));
update_pos.setY(qMax(update_pos.y(), sceneRect().top() + margin));
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
auto left = qMin(start_pos_.x(), update_pos.x());
auto top = qMin(start_pos_.y(), update_pos.y());
auto width = qAbs(start_pos_.x() - update_pos.x());
auto height = qAbs(start_pos_.y() - update_pos.y());
rect_item_->setRect(QRectF(left, top, width, height));
}
break;
case kLine:
if(line_item_ != nullptr) {
line_item_->setLine(QLineF(start_pos_, update_pos));
}
break;
case kDot:
if(dot_item_ != nullptr) {
dot_item_->setRect(QRectF(
update_pos.x() - pen_width,
update_pos.y() - pen_width,
2 * pen_width, 2 * pen_width));
}
break;
}
}
QGraphicsScene::mouseMoveEvent(event);
}
void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
emit boxFinished(rect_item_->rect());
removeItem(rect_item_);
rect_item_ = nullptr;
}
break;
case kLine:
if(line_item_ != nullptr) {
emit lineFinished(line_item_->line());
removeItem(line_item_);
line_item_ = nullptr;
}
break;
case kDot:
if(dot_item_ != nullptr) {
emit dotFinished(QPointF(
dot_item_->rect().topLeft().x() + pen_width,
dot_item_->rect().topLeft().y() + pen_width));
removeItem(dot_item_);
dot_item_ = nullptr;
}
break;
}
mode_ = kSelect;
QApplication::restoreOverrideCursor();
}
QGraphicsScene::mouseReleaseEvent(event);
}
void AnnotationScene::makeItemsControllable(bool controllable) {
foreach(QGraphicsItem *item, items()) {
item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
}
}
#include "../../include/fish_annotator/common/moc_annotation_scene.cpp"
} // namespace fish_annotator
<|endoftext|>
|
<commit_before>#include "log.h"
#include "InstructionQueue.h"
#include "SegmentAccessor.h"
#include "JobReport.h"
#include "Assembler.h"
#define DEFAULT_INST_TIMEOUT_MS (100000)
using namespace liber;
using namespace liber::rsync;
//-----------------------------------------------------------------------------
Assembler::Assembler( SegmentAccessor& segment_accessor )
: assembler_state_ ( segment_accessor )
, instruction_timeout_ms_ ( DEFAULT_INST_TIMEOUT_MS )
{
}
//-----------------------------------------------------------------------------
Assembler::~Assembler()
{
}
//-----------------------------------------------------------------------------
bool Assembler::process(
JobDescriptor& job_descriptor,
InstructionQueue& instruction_queue,
AssemblyReport& report
)
{
assembler_state_.reset();
assembler_state_.jobDescriptor() = job_descriptor;
while ( ( assembler_state_.done() == false ) &&
( assembler_state_.failed() == false ) )
{
Instruction* instruction_ptr = instruction_queue.pop(
instruction_timeout_ms_
);
if ( instruction_ptr )
{
switch ( instruction_ptr->type() )
{
case BeginInstruction::Type:
report.begin.sample();
break;
case SegmentInstruction::Type:
report.segmentCount++;
break;
case ChunkInstruction::Type:
report.chunkCount++;
break;
case EndInstruction::Type:
report.end.sample();
break;
default:
log::error("Assembler - Invalid instruction type %d\n",
instruction_ptr->type());
break;
}
instruction_ptr->execute(
assembler_state_
);
if ( assembler_state_.failed() )
{
log::error(
"Assembler::process - "
"Instruction (type=%d) failed with status %d\n",
instruction_ptr->type(),
assembler_state_.status_
);
}
delete instruction_ptr;
}
else
{
log::error("Assembler - NULL instruction.\n");
}
}
report.status = assembler_state_.status_;
return ( assembler_state_.failed() == false );
}
//-----------------------------------------------------------------------------
std::ofstream& Assembler::outputStream()
{
return assembler_state_.stream();
}
<commit_msg>Fixed bad spelling in include.<commit_after>#include "Log.h"
#include "InstructionQueue.h"
#include "SegmentAccessor.h"
#include "JobReport.h"
#include "Assembler.h"
#define DEFAULT_INST_TIMEOUT_MS (100000)
using namespace liber;
using namespace liber::rsync;
//-----------------------------------------------------------------------------
Assembler::Assembler( SegmentAccessor& segment_accessor )
: assembler_state_ ( segment_accessor )
, instruction_timeout_ms_ ( DEFAULT_INST_TIMEOUT_MS )
{
}
//-----------------------------------------------------------------------------
Assembler::~Assembler()
{
}
//-----------------------------------------------------------------------------
bool Assembler::process(
JobDescriptor& job_descriptor,
InstructionQueue& instruction_queue,
AssemblyReport& report
)
{
assembler_state_.reset();
assembler_state_.jobDescriptor() = job_descriptor;
while ( ( assembler_state_.done() == false ) &&
( assembler_state_.failed() == false ) )
{
Instruction* instruction_ptr = instruction_queue.pop(
instruction_timeout_ms_
);
if ( instruction_ptr )
{
switch ( instruction_ptr->type() )
{
case BeginInstruction::Type:
report.begin.sample();
break;
case SegmentInstruction::Type:
report.segmentCount++;
break;
case ChunkInstruction::Type:
report.chunkCount++;
break;
case EndInstruction::Type:
report.end.sample();
break;
default:
log::error("Assembler - Invalid instruction type %d\n",
instruction_ptr->type());
break;
}
instruction_ptr->execute(
assembler_state_
);
if ( assembler_state_.failed() )
{
log::error(
"Assembler::process - "
"Instruction (type=%d) failed with status %d\n",
instruction_ptr->type(),
assembler_state_.status_
);
}
delete instruction_ptr;
}
else
{
log::error("Assembler - NULL instruction.\n");
}
}
report.status = assembler_state_.status_;
return ( assembler_state_.failed() == false );
}
//-----------------------------------------------------------------------------
std::ofstream& Assembler::outputStream()
{
return assembler_state_.stream();
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief memory_slice_view expression implementation
*/
#pragma once
namespace etl {
/*!
* \brief View that shows a slice of an expression
* \tparam T The type of expression on which the view is made
*/
template <typename T, bool Aligned>
struct memory_slice_view {
using sub_type = T; ///< The sub type
using value_type = value_t<sub_type>; ///< The value contained in the expression
using memory_type = value_type*; ///< The memory acess type
using const_memory_type = const value_type*; ///< The const memory access type
using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; ///< The type returned by the view
using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; ///< The const type return by the view
private:
T sub; ///< The Sub expression
const size_t first; ///< The index
const size_t last; ///< The last index
friend struct etl_traits<memory_slice_view>;
public:
/*!
* \brief The vectorization type for V
*/
template<typename V = default_vec>
using vec_type = typename V::template vec_type<value_type>;
/*!
* \brief Construct a new memory_slice_view over the given sub expression
* \param sub The sub expression
* \param first The first index
* \param last The last index
*/
memory_slice_view(sub_type sub, size_t first, size_t last)
: sub(sub), first(first), last(last) {}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
const_return_type operator[](size_t j) const {
return sub[first + j];
}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
return_type operator[](size_t j) {
return sub[first + j];
}
/*!
* \brief Returns the value at the given index
* This function never has side effects.
* \param j The index
* \return the value at the given index.
*/
value_type read_flat(size_t j) const noexcept {
return sub[first + j];
}
//Note(CPP17): Use if constexpr for alignment
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec, bool A = Aligned, cpp_enable_if(A)>
auto load(size_t x) const noexcept {
return sub.template load<V>(x + first );
}
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec, bool A = Aligned, cpp_disable_if(A)>
auto load(size_t x) const noexcept {
return sub.template loadu<V>(x + first );
}
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec>
auto loadu(size_t x) const noexcept {
return sub.template loadu<V>(x + first );
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_enable_if(A)>
void store(vec_type<V> in, size_t i) noexcept {
sub.template store<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_disable_if(A)>
void store(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void storeu(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal store
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void stream(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Test if this expression aliases with the given expression
* \param rhs The other expression to test
* \return true if the two expressions aliases, false otherwise
*/
template <typename E>
bool alias(const E& rhs) const noexcept {
return sub.alias(rhs);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
memory_type memory_start() noexcept {
return sub.memory_start() + first ;
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
const_memory_type memory_start() const noexcept {
return sub.memory_start() + first ;
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
memory_type memory_end() noexcept {
return sub.memory_start() + last ;
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
const_memory_type memory_end() const noexcept {
return sub.memory_start() + last;
}
// Assignment functions
/*!
* \brief Assign to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
std_assign_evaluate(*this, lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
// Internals
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::back_propagate_visitor& visitor) const {
sub.visit(visitor);
}
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::temporary_allocator_visitor& visitor) const {
sub.visit(visitor);
}
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(detail::evaluator_visitor& visitor) const {
bool old_need_value = visitor.need_value;
visitor.need_value = true;
sub.visit(visitor);
visitor.need_value = old_need_value;
}
};
/*!
* \brief Specialization for memory_slice_view
*/
template <typename T, bool Aligned>
struct etl_traits<etl::memory_slice_view<T, Aligned>> {
using expr_t = etl::memory_slice_view<T, Aligned>; ///< The expression type
using sub_expr_t = std::decay_t<T>; ///< The sub expression type
using value_type = typename etl_traits<sub_expr_t>::value_type; ///< The value type
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = true; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = false; ///< Indicates if the expression is fast
static constexpr bool is_linear = etl_traits<sub_expr_t>::is_linear; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = Aligned; ///< Indicates if the expression is padded
static constexpr bool needs_evaluator = etl_traits<sub_expr_t>::needs_evaluator; ///< Indicates if the exxpression needs a evaluator visitor
static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = cpp::bool_constant<decay_traits<sub_expr_t>::template vectorizable<V>::value>;
/*!
* \brief Returns the size of the given expression
* \param v The expression to get the size for
* \returns the size of the given expression
*/
static size_t size(const expr_t& v) {
return v.last - v.first;
}
/*!
* \brief Returns the dth dimension of the given expression
* \param v The expression
* \param d The dimension to get
* \return The dth dimension of the given expression
*/
static size_t dim(const expr_t& v, size_t d) {
cpp_unused(d);
return v.last - v.first;
}
/*!
* \brief Returns the number of expressions for this type
* \return the number of dimensions of this type
*/
static constexpr size_t dimensions() {
return 1;
}
};
/*!
* \brief Returns view representing a memory slice view of the given expression.
* \param value The ETL expression
* \param first The first index
* \param last The last index
* \return a view expression representing a sub dimensional view of the given expression
*/
template <bool Aligned = false, typename E>
auto memory_slice(E&& value, size_t first, size_t last) -> detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>> {
static_assert(is_etl_expr<E>::value, "etl::memory_slice can only be used on ETL expressions");
return detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>>{{value, first, last}};
}
} //end of namespace etl
<commit_msg>Allow non-temporal stores in aligned memory slices<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief memory_slice_view expression implementation
*/
#pragma once
namespace etl {
/*!
* \brief View that shows a slice of an expression
* \tparam T The type of expression on which the view is made
*/
template <typename T, bool Aligned>
struct memory_slice_view {
using sub_type = T; ///< The sub type
using value_type = value_t<sub_type>; ///< The value contained in the expression
using memory_type = value_type*; ///< The memory acess type
using const_memory_type = const value_type*; ///< The const memory access type
using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; ///< The type returned by the view
using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()[0])>; ///< The const type return by the view
private:
T sub; ///< The Sub expression
const size_t first; ///< The index
const size_t last; ///< The last index
friend struct etl_traits<memory_slice_view>;
public:
/*!
* \brief The vectorization type for V
*/
template<typename V = default_vec>
using vec_type = typename V::template vec_type<value_type>;
/*!
* \brief Construct a new memory_slice_view over the given sub expression
* \param sub The sub expression
* \param first The first index
* \param last The last index
*/
memory_slice_view(sub_type sub, size_t first, size_t last)
: sub(sub), first(first), last(last) {}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
const_return_type operator[](size_t j) const {
return sub[first + j];
}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
return_type operator[](size_t j) {
return sub[first + j];
}
/*!
* \brief Returns the value at the given index
* This function never has side effects.
* \param j The index
* \return the value at the given index.
*/
value_type read_flat(size_t j) const noexcept {
return sub[first + j];
}
//Note(CPP17): Use if constexpr for alignment
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec, bool A = Aligned, cpp_enable_if(A)>
auto load(size_t x) const noexcept {
return sub.template load<V>(x + first );
}
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec, bool A = Aligned, cpp_disable_if(A)>
auto load(size_t x) const noexcept {
return sub.template loadu<V>(x + first );
}
/*!
* \brief Load several elements of the expression at once
* \param x The position at which to start.
* \tparam V The vectorization mode to use
* \return a vector containing several elements of the expression
*/
template <typename V = default_vec>
auto loadu(size_t x) const noexcept {
return sub.template loadu<V>(x + first );
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_enable_if(A)>
void store(vec_type<V> in, size_t i) noexcept {
sub.template store<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_disable_if(A)>
void store(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec>
void storeu(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal store
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_enable_if(A)>
void stream(vec_type<V> in, size_t i) noexcept {
sub.template stream<V>(in, first + i);
}
/*!
* \brief Store several elements in the matrix at once, using non-temporal store
* \param in The several elements to store
* \param i The position at which to start. This will be aligned from the beginning (multiple of the vector size).
* \tparam V The vectorization mode to use
*/
template <typename V = default_vec, bool A = Aligned, cpp_disable_if(A)>
void stream(vec_type<V> in, size_t i) noexcept {
sub.template storeu<V>(in, first + i);
}
/*!
* \brief Test if this expression aliases with the given expression
* \param rhs The other expression to test
* \return true if the two expressions aliases, false otherwise
*/
template <typename E>
bool alias(const E& rhs) const noexcept {
return sub.alias(rhs);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
memory_type memory_start() noexcept {
return sub.memory_start() + first ;
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
const_memory_type memory_start() const noexcept {
return sub.memory_start() + first ;
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
memory_type memory_end() noexcept {
return sub.memory_start() + last ;
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
const_memory_type memory_end() const noexcept {
return sub.memory_start() + last;
}
// Assignment functions
/*!
* \brief Assign to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_to(L&& lhs) const {
std_assign_evaluate(*this, lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template<typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
// Internals
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::back_propagate_visitor& visitor) const {
sub.visit(visitor);
}
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(const detail::temporary_allocator_visitor& visitor) const {
sub.visit(visitor);
}
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(detail::evaluator_visitor& visitor) const {
bool old_need_value = visitor.need_value;
visitor.need_value = true;
sub.visit(visitor);
visitor.need_value = old_need_value;
}
};
/*!
* \brief Specialization for memory_slice_view
*/
template <typename T, bool Aligned>
struct etl_traits<etl::memory_slice_view<T, Aligned>> {
using expr_t = etl::memory_slice_view<T, Aligned>; ///< The expression type
using sub_expr_t = std::decay_t<T>; ///< The sub expression type
using value_type = typename etl_traits<sub_expr_t>::value_type; ///< The value type
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = true; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = false; ///< Indicates if the expression is fast
static constexpr bool is_linear = etl_traits<sub_expr_t>::is_linear; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = Aligned; ///< Indicates if the expression is padded
static constexpr bool needs_evaluator = etl_traits<sub_expr_t>::needs_evaluator; ///< Indicates if the exxpression needs a evaluator visitor
static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
using vectorizable = cpp::bool_constant<decay_traits<sub_expr_t>::template vectorizable<V>::value>;
/*!
* \brief Returns the size of the given expression
* \param v The expression to get the size for
* \returns the size of the given expression
*/
static size_t size(const expr_t& v) {
return v.last - v.first;
}
/*!
* \brief Returns the dth dimension of the given expression
* \param v The expression
* \param d The dimension to get
* \return The dth dimension of the given expression
*/
static size_t dim(const expr_t& v, size_t d) {
cpp_unused(d);
return v.last - v.first;
}
/*!
* \brief Returns the number of expressions for this type
* \return the number of dimensions of this type
*/
static constexpr size_t dimensions() {
return 1;
}
};
/*!
* \brief Returns view representing a memory slice view of the given expression.
* \param value The ETL expression
* \param first The first index
* \param last The last index
* \return a view expression representing a sub dimensional view of the given expression
*/
template <bool Aligned = false, typename E>
auto memory_slice(E&& value, size_t first, size_t last) -> detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>> {
static_assert(is_etl_expr<E>::value, "etl::memory_slice can only be used on ETL expressions");
return detail::identity_helper<E, memory_slice_view<detail::build_identity_type<E>, Aligned>>{{value, first, last}};
}
} //end of namespace etl
<|endoftext|>
|
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include <stdarg.h>
#include "user_log.c++.h"
#include <time.h>
#include "condor_uid.h"
static char *_FileName_ = __FILE__;
static const char SynchDelimiter[] = "...\n";
static void display_ids();
extern "C" char *find_env (const char *, const char *);
extern "C" char *get_env_val (const char *);
UserLog::UserLog (const char *owner, const char *file, int c, int p, int s)
{
UserLog();
initialize (owner, file, c, p, s);
}
/* --- The following two functions are taken from the shadow's ulog.c --- */
/*
Find the value of an environment value, given the condor style envrionment
string which may contain several variable definitions separated by
semi-colons.
*/
char *
find_env( const char * name, const char * env )
{
const char *ptr;
for( ptr=env; *ptr; ptr++ ) {
if( strncmp(name,ptr,strlen(name)) == 0 ) {
return get_env_val( ptr );
}
}
return NULL;
}
/*
Given a pointer to the a particular environment substring string
containing the desired value, pick out the value and return a
pointer to it. N.B. this is copied into a static data area to
avoid introducing NULL's into the original environment string,
and a pointer into the static area is returned.
*/
char *
get_env_val( const char *str )
{
const char *src;
char *dst;
static char answer[512];
/* Find the '=' */
for( src=str; *src && *src != '='; src++ )
;
if( *src != '=' ) {
return NULL;
}
/* Skip over any white space */
src += 1;
while( *src && isspace(*src) ) {
src++;
}
/* Now we are at beginning of result */
dst = answer;
while( *src && !isspace(*src) && *src != ';' ) {
*dst++ = *src++;
}
*dst = '\0';
return answer;
}
void UserLog::
initialize( const char *file, int c, int p, int s )
{
int fd;
// Save parameter info
path = new char[ strlen(file) + 1 ];
strcpy( path, file );
in_block = FALSE;
if (fp) fclose(fp);
#ifndef WIN32
if( (fd = open( path, O_CREAT | O_WRONLY, 0664 )) < 0 ) {
dprintf( D_ALWAYS,
"UserLog::initialize: open(%s) failed - errno %d", path, errno );
return;
}
// attach it to stdio stream
if( (fp = fdopen(fd,"a")) == NULL ) {
dprintf( D_ALWAYS,
"UserLog::initialize: fdopen() failed - errno %d", path, errno );
}
#else
if( (fp = fopen(path,"a+t")) == NULL ) {
dprintf( D_ALWAYS,
"UserLog::initialize: fopen failed - errno %d", path, errno );
}
fd = _fileno(fp);
#endif
// set the stdio stream for line buffering
if( setvbuf(fp,NULL,_IOLBF,BUFSIZ) < 0 ) {
dprintf( D_ALWAYS, "setvbuf failed in UserLog::initialize" );
}
// prepare to lock the file
lock = new FileLock( fd );
initialize(c, p, s);
}
void UserLog::
initialize( const char *owner, const char *file, int c, int p, int s )
{
priv_state priv;
init_user_ids(owner);
// switch to user priv, saving the current user
priv = set_user_priv();
// initialize log file
initialize(file,c,p,s);
// get back to whatever UID and GID we started with
set_priv(priv);
}
void UserLog::
initialize( int c, int p, int s )
{
cluster = c;
proc = p;
subproc = s;
}
UserLog::~UserLog()
{
delete [] path;
delete lock;
if (fp != 0) fclose( fp );
}
void
UserLog::display()
{
dprintf( D_ALWAYS, "Path = \"%s\"\n", path );
dprintf( D_ALWAYS, "Job = %d.%d.%d\n", proc, cluster, subproc );
dprintf( D_ALWAYS, "fp = 0x%x\n", fp );
lock->display();
dprintf( D_ALWAYS, "in_block = %s\n", in_block ? "TRUE" : "FALSE" );
}
int UserLog::
writeEvent (ULogEvent *event)
{
// the the log is not initialized, don't bother --- just return OK
if (!fp) return 1;
if (!lock) return 0;
if (!event) return 0;
int retval;
priv_state priv = set_user_priv();
// fill in event context
event->cluster = cluster;
event->proc = proc;
event->subproc = subproc;
lock->obtain (WRITE_LOCK);
fseek (fp, 0, SEEK_END);
retval = event->putEvent (fp);
if (!retval) fputc ('\n', fp);
if (fprintf (fp, SynchDelimiter) < 0) retval = 0;
lock->release ();
set_priv( priv );
return retval;
}
void
UserLog::put( const char *fmt, ... )
{
va_list ap;
va_start( ap, fmt );
if( !fp ) {
return;
}
if( !in_block ) {
lock->obtain( WRITE_LOCK );
fseek( fp, 0, SEEK_END );
}
output_header();
vfprintf( fp, fmt, ap );
if( !in_block ) {
lock->release();
}
}
void
UserLog::begin_block()
{
struct tm *tm;
time_t clock;
if( !fp ) {
return;
}
lock->obtain( WRITE_LOCK );
fseek( fp, 0, SEEK_END );
(void)time( (time_t *)&clock );
tm = localtime( (time_t *)&clock );
fprintf( fp, "(%d.%d.%d) %d/%d %02d:%02d:%02d\n",
cluster, proc, subproc,
tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec
);
in_block = TRUE;
}
void
UserLog::end_block()
{
if( !fp ) {
return;
}
in_block = FALSE;
lock->release();
}
void
UserLog::output_header()
{
struct tm *tm;
time_t clock;
if( !fp ) {
return;
}
if( in_block ) {
fprintf( fp, "(%d.%d.%d) ", cluster, proc, subproc );
} else {
(void)time( (time_t *)&clock );
tm = localtime( (time_t *)&clock );
fprintf( fp, "(%d.%d.%d) %d/%d %02d:%02d:%02d ",
cluster, proc, subproc,
tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec
);
}
}
extern "C" LP *
InitUserLog( const char *own, const char *file, int c, int p, int s )
{
UserLog *answer;
answer = new UserLog( own, file, c, p, s );
return (LP *)answer;
}
extern "C" void
CloseUserLog( LP *lp )
{
delete lp;
}
extern "C" void
PutUserLog( LP *lp, const char *fmt, ... )
{
va_list ap;
char buf[1024];
if( !lp ) {
return;
}
va_start( ap, fmt );
vsprintf( buf, fmt, ap );
((UserLog *)lp) -> put( buf );
}
extern "C" void
BeginUserLogBlock( LP *lp )
{
if( !lp ) {
return;
}
((UserLog *)lp) -> begin_block();
}
extern "C" void
EndUserLogBlock( LP *lp )
{
if( !lp ) {
return;
}
((UserLog *)lp) -> end_block();
}
// ReadUserLog class
ReadUserLog::
ReadUserLog (const char * filename)
{
if (!initialize(filename))
dprintf(D_ALWAYS, "Failed to open %s", filename);
}
bool ReadUserLog::
initialize (const char *filename)
{
if ((_fd = open (filename, O_RDONLY, 0)) == -1) return false;
if ((_fp = fdopen (_fd, "r")) == NULL) return false;
return true;
}
ULogEventOutcome ReadUserLog::
readEvent (ULogEvent *& event)
{
long filepos;
int eventnumber;
int retval1, retval2;
// store file position so that if we are unable to read the event, we can
// rewind to this location
if (!_fp || ((filepos = ftell(_fp)) == -1L))
return ULOG_UNK_ERROR;
retval1 = fscanf (_fp, "%d", &eventnumber);
// so we don't dump core if the above fscanf failed
if (retval1 != 1) eventnumber = 1;
// allocate event object; check if allocated successfully
event = instantiateEvent ((ULogEventNumber) eventnumber);
if (!event)
{
return ULOG_UNK_ERROR;
}
// read event from file; check for result
retval2 = event->getEvent (_fp);
// check if error in reading event
if (!retval1 || !retval2)
{
// try to synchronize the log
if (synchronize())
{
// if synchronization was successful, reset file position and ...
if (fseek (_fp, filepos, SEEK_SET))
{
dprintf(D_ALWAYS, "fseek() failed in ReadUserLog::readEvent");
return ULOG_UNK_ERROR;
}
// ... attempt to read the event again
clearerr (_fp);
retval1 = fscanf (_fp, "%d", &eventnumber);
retval2 = event->getEvent (_fp);
// if failed again, we have a parse error
if (!retval1 || !retval2)
{
delete event;
event = NULL; // To prevent FMR: Free memory read
synchronize ();
return ULOG_RD_ERROR;
}
else
{
return ULOG_OK;
}
}
else
{
// if we could not synchronize the log, we don't have the full
// event in the stream yet; restore file position and return
if (fseek (_fp, filepos, SEEK_SET))
{
dprintf(D_ALWAYS, "fseek() failed in ReadUserLog::readEvent");
return ULOG_UNK_ERROR;
}
clearerr (_fp);
delete event;
event = NULL; // To prevent FMR: Free memory read
return ULOG_NO_EVENT;
}
}
else
{
// got the event successfully -- synchronize the log
if (synchronize ())
{
return ULOG_OK;
}
else
{
// got the event, but could not synchronize!! treat as incomplete
// event
delete event;
event = NULL; // To prevent FMR: Free memory read
clearerr (_fp);
return ULOG_NO_EVENT;
}
}
// will not reach here
return ULOG_UNK_ERROR;
}
bool ReadUserLog::
synchronize ()
{
char buffer[32];
while (1) {
if (fgets (buffer, 32, _fp) == NULL) return false;
if (strcmp (buffer, SynchDelimiter) == 0) return true;
}
return false;
}
<commit_msg>+ fixed bug: now we actually flush the user log after writing each event via fflush().<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
* CONDOR Copyright Notice
*
* See LICENSE.TXT for additional notices and disclaimers.
*
* Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
* University of Wisconsin-Madison, Madison, WI. All Rights Reserved.
* No use of the CONDOR Software Program Source Code is authorized
* without the express consent of the CONDOR Team. For more information
* contact: CONDOR Team, Attention: Professor Miron Livny,
* 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
* (608) 262-0856 or miron@cs.wisc.edu.
*
* U.S. Government Rights Restrictions: Use, duplication, or disclosure
* by the U.S. Government is subject to restrictions as set forth in
* subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
* Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
* (2) of Commercial Computer Software-Restricted Rights at 48 CFR
* 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
* Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
* WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#include "condor_common.h"
#include "condor_debug.h"
#include <stdarg.h>
#include "user_log.c++.h"
#include <time.h>
#include "condor_uid.h"
static char *_FileName_ = __FILE__;
static const char SynchDelimiter[] = "...\n";
static void display_ids();
extern "C" char *find_env (const char *, const char *);
extern "C" char *get_env_val (const char *);
UserLog::UserLog (const char *owner, const char *file, int c, int p, int s)
{
UserLog();
initialize (owner, file, c, p, s);
}
/* --- The following two functions are taken from the shadow's ulog.c --- */
/*
Find the value of an environment value, given the condor style envrionment
string which may contain several variable definitions separated by
semi-colons.
*/
char *
find_env( const char * name, const char * env )
{
const char *ptr;
for( ptr=env; *ptr; ptr++ ) {
if( strncmp(name,ptr,strlen(name)) == 0 ) {
return get_env_val( ptr );
}
}
return NULL;
}
/*
Given a pointer to the a particular environment substring string
containing the desired value, pick out the value and return a
pointer to it. N.B. this is copied into a static data area to
avoid introducing NULL's into the original environment string,
and a pointer into the static area is returned.
*/
char *
get_env_val( const char *str )
{
const char *src;
char *dst;
static char answer[512];
/* Find the '=' */
for( src=str; *src && *src != '='; src++ )
;
if( *src != '=' ) {
return NULL;
}
/* Skip over any white space */
src += 1;
while( *src && isspace(*src) ) {
src++;
}
/* Now we are at beginning of result */
dst = answer;
while( *src && !isspace(*src) && *src != ';' ) {
*dst++ = *src++;
}
*dst = '\0';
return answer;
}
void UserLog::
initialize( const char *file, int c, int p, int s )
{
int fd;
// Save parameter info
path = new char[ strlen(file) + 1 ];
strcpy( path, file );
in_block = FALSE;
if (fp) fclose(fp);
#ifndef WIN32
// Unix
if( (fd = open( path, O_CREAT | O_WRONLY, 0664 )) < 0 ) {
dprintf( D_ALWAYS,
"UserLog::initialize: open(%s) failed - errno %d", path, errno );
return;
}
// attach it to stdio stream
if( (fp = fdopen(fd,"a")) == NULL ) {
dprintf( D_ALWAYS,
"UserLog::initialize: fdopen() failed - errno %d", path, errno );
}
#else
// Windows (Visual C++)
if( (fp = fopen(path,"a+tc")) == NULL ) {
dprintf( D_ALWAYS,
"UserLog::initialize: fopen failed - errno %d", path, errno );
}
fd = _fileno(fp);
#endif
// set the stdio stream for line buffering
if( setvbuf(fp,NULL,_IOLBF,BUFSIZ) < 0 ) {
dprintf( D_ALWAYS, "setvbuf failed in UserLog::initialize" );
}
// prepare to lock the file
lock = new FileLock( fd );
initialize(c, p, s);
}
void UserLog::
initialize( const char *owner, const char *file, int c, int p, int s )
{
priv_state priv;
init_user_ids(owner);
// switch to user priv, saving the current user
priv = set_user_priv();
// initialize log file
initialize(file,c,p,s);
// get back to whatever UID and GID we started with
set_priv(priv);
}
void UserLog::
initialize( int c, int p, int s )
{
cluster = c;
proc = p;
subproc = s;
}
UserLog::~UserLog()
{
delete [] path;
delete lock;
if (fp != 0) fclose( fp );
}
void
UserLog::display()
{
dprintf( D_ALWAYS, "Path = \"%s\"\n", path );
dprintf( D_ALWAYS, "Job = %d.%d.%d\n", proc, cluster, subproc );
dprintf( D_ALWAYS, "fp = 0x%x\n", fp );
lock->display();
dprintf( D_ALWAYS, "in_block = %s\n", in_block ? "TRUE" : "FALSE" );
}
int UserLog::
writeEvent (ULogEvent *event)
{
// the the log is not initialized, don't bother --- just return OK
if (!fp) return 1;
if (!lock) return 0;
if (!event) return 0;
int retval;
priv_state priv = set_user_priv();
// fill in event context
event->cluster = cluster;
event->proc = proc;
event->subproc = subproc;
lock->obtain (WRITE_LOCK);
fseek (fp, 0, SEEK_END);
retval = event->putEvent (fp);
if (!retval) fputc ('\n', fp);
if (fprintf (fp, SynchDelimiter) < 0) retval = 0;
fflush(fp);
lock->release ();
set_priv( priv );
return retval;
}
void
UserLog::put( const char *fmt, ... )
{
va_list ap;
va_start( ap, fmt );
if( !fp ) {
return;
}
if( !in_block ) {
lock->obtain( WRITE_LOCK );
fseek( fp, 0, SEEK_END );
}
output_header();
vfprintf( fp, fmt, ap );
if( !in_block ) {
lock->release();
}
}
void
UserLog::begin_block()
{
struct tm *tm;
time_t clock;
if( !fp ) {
return;
}
lock->obtain( WRITE_LOCK );
fseek( fp, 0, SEEK_END );
(void)time( (time_t *)&clock );
tm = localtime( (time_t *)&clock );
fprintf( fp, "(%d.%d.%d) %d/%d %02d:%02d:%02d\n",
cluster, proc, subproc,
tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec
);
in_block = TRUE;
}
void
UserLog::end_block()
{
if( !fp ) {
return;
}
in_block = FALSE;
lock->release();
}
void
UserLog::output_header()
{
struct tm *tm;
time_t clock;
if( !fp ) {
return;
}
if( in_block ) {
fprintf( fp, "(%d.%d.%d) ", cluster, proc, subproc );
} else {
(void)time( (time_t *)&clock );
tm = localtime( (time_t *)&clock );
fprintf( fp, "(%d.%d.%d) %d/%d %02d:%02d:%02d ",
cluster, proc, subproc,
tm->tm_mon + 1, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec
);
}
}
extern "C" LP *
InitUserLog( const char *own, const char *file, int c, int p, int s )
{
UserLog *answer;
answer = new UserLog( own, file, c, p, s );
return (LP *)answer;
}
extern "C" void
CloseUserLog( LP *lp )
{
delete lp;
}
extern "C" void
PutUserLog( LP *lp, const char *fmt, ... )
{
va_list ap;
char buf[1024];
if( !lp ) {
return;
}
va_start( ap, fmt );
vsprintf( buf, fmt, ap );
((UserLog *)lp) -> put( buf );
}
extern "C" void
BeginUserLogBlock( LP *lp )
{
if( !lp ) {
return;
}
((UserLog *)lp) -> begin_block();
}
extern "C" void
EndUserLogBlock( LP *lp )
{
if( !lp ) {
return;
}
((UserLog *)lp) -> end_block();
}
// ReadUserLog class
ReadUserLog::
ReadUserLog (const char * filename)
{
if (!initialize(filename))
dprintf(D_ALWAYS, "Failed to open %s", filename);
}
bool ReadUserLog::
initialize (const char *filename)
{
if ((_fd = open (filename, O_RDONLY, 0)) == -1) return false;
if ((_fp = fdopen (_fd, "r")) == NULL) return false;
return true;
}
ULogEventOutcome ReadUserLog::
readEvent (ULogEvent *& event)
{
long filepos;
int eventnumber;
int retval1, retval2;
// store file position so that if we are unable to read the event, we can
// rewind to this location
if (!_fp || ((filepos = ftell(_fp)) == -1L))
return ULOG_UNK_ERROR;
retval1 = fscanf (_fp, "%d", &eventnumber);
// so we don't dump core if the above fscanf failed
if (retval1 != 1) eventnumber = 1;
// allocate event object; check if allocated successfully
event = instantiateEvent ((ULogEventNumber) eventnumber);
if (!event)
{
return ULOG_UNK_ERROR;
}
// read event from file; check for result
retval2 = event->getEvent (_fp);
// check if error in reading event
if (!retval1 || !retval2)
{
// try to synchronize the log
if (synchronize())
{
// if synchronization was successful, reset file position and ...
if (fseek (_fp, filepos, SEEK_SET))
{
dprintf(D_ALWAYS, "fseek() failed in ReadUserLog::readEvent");
return ULOG_UNK_ERROR;
}
// ... attempt to read the event again
clearerr (_fp);
retval1 = fscanf (_fp, "%d", &eventnumber);
retval2 = event->getEvent (_fp);
// if failed again, we have a parse error
if (!retval1 || !retval2)
{
delete event;
event = NULL; // To prevent FMR: Free memory read
synchronize ();
return ULOG_RD_ERROR;
}
else
{
return ULOG_OK;
}
}
else
{
// if we could not synchronize the log, we don't have the full
// event in the stream yet; restore file position and return
if (fseek (_fp, filepos, SEEK_SET))
{
dprintf(D_ALWAYS, "fseek() failed in ReadUserLog::readEvent");
return ULOG_UNK_ERROR;
}
clearerr (_fp);
delete event;
event = NULL; // To prevent FMR: Free memory read
return ULOG_NO_EVENT;
}
}
else
{
// got the event successfully -- synchronize the log
if (synchronize ())
{
return ULOG_OK;
}
else
{
// got the event, but could not synchronize!! treat as incomplete
// event
delete event;
event = NULL; // To prevent FMR: Free memory read
clearerr (_fp);
return ULOG_NO_EVENT;
}
}
// will not reach here
return ULOG_UNK_ERROR;
}
bool ReadUserLog::
synchronize ()
{
char buffer[32];
while (1) {
if (fgets (buffer, 32, _fp) == NULL) return false;
if (strcmp (buffer, SynchDelimiter) == 0) return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#ifndef MOS_RENDER_TARGET_HPP
#define MOS_RENDER_TARGET_HPP
#include <memory>
#include <atomic>
#include <optional.hpp>
#include <glm/glm.hpp>
#include <mos/render/texture_2d.hpp>
#include <mos/render/texture_cube.hpp>
namespace mos {
class RenderTarget;
using OptTarget = std::experimental::optional<RenderTarget>;
/**
* @brief The RenderTarget class
*
* Represents a rendertarget, with asociated texture. For off screen rendering.
*/
class RenderTarget {
public:
/**
* @brief Target
* @param resolution
*/
explicit RenderTarget(const SharedTexture2D & texture,
const SharedTexture2D & depth_texture,
const SharedTextureCube texture_cube);
/**
* @brief The texture that is rendered to.
*/
const SharedTexture2D texture;
/**
* @brief The depth texture that is rendered to.
*/
const SharedTexture2D depth_texture;
/**
* @brief Cube texture that can be rendered to.
*/
const SharedTextureCube texture_cube;
int width() const;
int height() const;
/**
* @brief unique id
* @return id
*/
unsigned int id() const;
private:
unsigned int id_;
static std::atomic_uint current_id_;
};
}
#endif // MOS_RENDER_TARGET_HPP
<commit_msg>Working.<commit_after>#ifndef MOS_RENDER_TARGET_HPP
#define MOS_RENDER_TARGET_HPP
#include <memory>
#include <atomic>
#include <optional.hpp>
#include <glm/glm.hpp>
#include <mos/render/texture_2d.hpp>
#include <mos/render/texture_cube.hpp>
namespace mos {
class RenderTarget;
using OptTarget = std::experimental::optional<RenderTarget>;
/**
* @brief The RenderTarget class
*
* Represents a rendertarget, with asociated texture. For off screen rendering.
*/
class RenderTarget {
public:
/**
* @brief Target
* @param resolution
*/
explicit RenderTarget(const SharedTexture2D & texture = nullptr,
const SharedTexture2D & depth_texture = nullptr,
const SharedTextureCube texture_cube = nullptr);
/**
* @brief The texture that is rendered to.
*/
const SharedTexture2D texture;
/**
* @brief The depth texture that is rendered to.
*/
const SharedTexture2D depth_texture;
/**
* @brief Cube texture that can be rendered to.
*/
const SharedTextureCube texture_cube;
int width() const;
int height() const;
/**
* @brief unique id
* @return id
*/
unsigned int id() const;
private:
unsigned int id_;
static std::atomic_uint current_id_;
};
}
#endif // MOS_RENDER_TARGET_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dpsdbtab.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_DPSDBTAB_HXX
#define SC_DPSDBTAB_HXX
#include <com/sun/star/uno/Reference.hxx>
namespace com { namespace sun { namespace star {
namespace lang {
class XMultiServiceFactory;
}
}}}
#include "dptabdat.hxx"
// --------------------------------------------------------------------
//
// implementation of ScDPTableData with database data
//
struct ScImportSourceDesc
{
String aDBName;
String aObject;
USHORT nType; // enum DataImportMode
BOOL bNative;
BOOL operator== ( const ScImportSourceDesc& rOther ) const
{ return aDBName == rOther.aDBName &&
aObject == rOther.aObject &&
nType == rOther.nType &&
bNative == rOther.bNative; }
};
class ScDatabaseDPData_Impl;
class ScDatabaseDPData : public ScDPTableData
{
private:
ScDatabaseDPData_Impl* pImpl;
BOOL OpenDatabase();
void InitAllColumnEntries();
public:
ScDatabaseDPData(
::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > xSMgr,
const ScImportSourceDesc& rImport );
virtual ~ScDatabaseDPData();
virtual long GetColumnCount();
virtual const TypedStrCollection& GetColumnEntries(long nColumn);
virtual String getDimensionName(long nColumn);
virtual BOOL getIsDataLayoutDimension(long nColumn);
virtual BOOL IsDateDimension(long nDim);
virtual void DisposeData();
virtual void SetEmptyFlags( BOOL bIgnoreEmptyRows, BOOL bRepeatIfEmpty );
virtual void ResetIterator();
virtual BOOL GetNextRow( const ScDPTableIteratorParam& rParam );
};
#endif
<commit_msg>INTEGRATION: CWS koheidatapilot01 (1.3.570); FILE MERGED 2008/04/25 20:59:10 kohei 1.3.570.5: RESYNC: (1.3-1.4); FILE MERGED 2008/04/24 23:26:38 kohei 1.3.570.4: * fixed a regression on page field filtering by the empty string value. * fixed an incorrect drill-down table with number groups (i88531). * moved the shared string storage out of ScDPCacheTable to make it more generic. 2008/04/17 13:10:39 kohei 1.3.570.3: Used ScDPItemData to store cell values to allow numerical comparison where appropriate. Also fixed the regression involving drill-down on group names. 2007/12/06 07:06:15 kohei 1.3.570.2: removed all previously invisible code. 2007/10/29 17:44:39 kohei 1.3.570.1: initial checkin<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dpsdbtab.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SC_DPSDBTAB_HXX
#define SC_DPSDBTAB_HXX
#include <com/sun/star/uno/Reference.hxx>
namespace com { namespace sun { namespace star {
namespace lang {
class XMultiServiceFactory;
}
}}}
#include "dptabdat.hxx"
#include <vector>
#include <set>
class ScDPCacheTable;
// --------------------------------------------------------------------
//
// implementation of ScDPTableData with database data
//
struct ScImportSourceDesc
{
String aDBName;
String aObject;
USHORT nType; // enum DataImportMode
BOOL bNative;
BOOL operator== ( const ScImportSourceDesc& rOther ) const
{ return aDBName == rOther.aDBName &&
aObject == rOther.aObject &&
nType == rOther.nType &&
bNative == rOther.bNative; }
};
class ScDatabaseDPData_Impl;
class ScDatabaseDPData : public ScDPTableData
{
private:
ScDatabaseDPData_Impl* pImpl;
BOOL OpenDatabase();
public:
ScDatabaseDPData(
::com::sun::star::uno::Reference<
::com::sun::star::lang::XMultiServiceFactory > xSMgr,
const ScImportSourceDesc& rImport );
virtual ~ScDatabaseDPData();
virtual long GetColumnCount();
virtual const TypedStrCollection& GetColumnEntries(long nColumn);
virtual String getDimensionName(long nColumn);
virtual BOOL getIsDataLayoutDimension(long nColumn);
virtual BOOL IsDateDimension(long nDim);
virtual void DisposeData();
virtual void SetEmptyFlags( BOOL bIgnoreEmptyRows, BOOL bRepeatIfEmpty );
virtual void CreateCacheTable();
virtual void FilterCacheTable(const ::std::vector<ScDPDimension*>& rPageDims);
virtual void GetDrillDownData(const ::std::vector<ScDPCacheTable::Criterion>& rCriteria,
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > >& rData);
virtual void CalcResults(CalcInfo& rInfo, bool bAutoShow);
virtual const ScDPCacheTable& GetCacheTable() const;
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
namespace rc {
template<typename T>
class Arbitrary : public gen::Generator<T>
{
public:
static_assert(std::is_integral<T>::value,
"No specialization of Arbitrary for type");
T generate() const override
{
using namespace detail;
int size = std::min(gen::currentSize(), gen::kNominalSize);
RandomEngine::Atom r;
// TODO this switching shouldn't be done here. pickAtom?
ImplicitParam<param::CurrentNode> currentNode;
if (*currentNode != nullptr) {
r = currentNode->atom();
} else {
ImplicitParam<param::RandomEngine> randomEngine;
r = randomEngine->nextAtom();
}
// We vary the size by using different number of bits. This way, we can be
// that the max value can also be generated.
int nBits = (size * std::numeric_limits<T>::digits) / gen::kNominalSize;
if (nBits == 0)
return 0;
constexpr RandomEngine::Atom randIntMax =
std::numeric_limits<RandomEngine::Atom>::max();
RandomEngine::Atom mask = ~((randIntMax - 1) << (nBits - 1));
T x = static_cast<T>(r & mask);
if (std::numeric_limits<T>::is_signed)
{
// Use the topmost bit as the signed bit. Even in the case of a signed
// 64-bit integer, it won't be used since it actually IS the sign bit.
constexpr int basicBits =
std::numeric_limits<RandomEngine::Atom>::digits;
x *= ((r >> (basicBits - 1)) == 0) ? 1 : -1;
}
return x;
}
shrink::IteratorUP<T> shrink(T value) const override
{
std::vector<T> constants;
if (value < 0)
constants.push_back(-value);
return shrink::sequentially(
shrink::constant(constants),
shrink::towards(value, static_cast<T>(0)));
}
};
// Base for float and double arbitrary instances
template<typename T>
class ArbitraryReal : public gen::Generator<T>
{
public:
T generate() const override
{
int64_t i = *gen::arbitrary<int64_t>();
T x = static_cast<T>(i) / std::numeric_limits<int64_t>::max();
return std::pow<T>(1.2, gen::currentSize()) * x;
}
shrink::IteratorUP<T> shrink(T value) const override
{
std::vector<T> constants;
if (value < 0)
constants.push_back(-value);
T truncated = std::trunc(value);
if (std::abs(truncated) < std::abs(value))
constants.push_back(truncated);
return shrink::constant(constants);
}
};
template<>
class Arbitrary<float> : public ArbitraryReal<float> {};
template<>
class Arbitrary<double> : public ArbitraryReal<double> {};
template<>
class Arbitrary<bool> : public gen::Generator<bool>
{
public:
bool generate() const override
{
return (*gen::resize(gen::kNominalSize,
gen::arbitrary<uint8_t>()) & 0x1) == 0;
}
shrink::IteratorUP<bool> shrink(bool value)
{
if (value)
return shrink::constant<bool>({false});
else
return shrink::nothing<bool>();
}
};
template<typename ...Types>
class Arbitrary<std::tuple<Types...>>
: public gen::TupleOf<Arbitrary<Types>...>
{
public:
Arbitrary() : gen::TupleOf<Arbitrary<Types>...>(
gen::arbitrary<Types>()...) {}
};
template<typename T1, typename T2>
class Arbitrary<std::pair<T1, T2>>
: public gen::PairOf<Arbitrary<detail::DecayT<T1>>,
Arbitrary<detail::DecayT<T2>>>
{
public:
Arbitrary()
: gen::PairOf<Arbitrary<detail::DecayT<T1>>,
Arbitrary<detail::DecayT<T2>>>(
gen::arbitrary<detail::DecayT<T1>>(),
gen::arbitrary<detail::DecayT<T2>>()) {}
};
// Base template class for collection types
template<typename Coll, typename ValueType>
class ArbitraryCollection : public gen::Collection<Coll, Arbitrary<ValueType>>
{
public:
typedef gen::Collection<Coll, Arbitrary<ValueType>> CollectionGen;
ArbitraryCollection() : CollectionGen(gen::arbitrary<ValueType>()) {}
};
// std::vector
template<typename T, typename Allocator>
class Arbitrary<std::vector<T, Allocator>>
: public ArbitraryCollection<std::vector<T, Allocator>, T> {};
// std::deque
template<typename T, typename Allocator>
class Arbitrary<std::deque<T, Allocator>>
: public ArbitraryCollection<std::deque<T, Allocator>, T> {};
// std::forward_list
template<typename T, typename Allocator>
class Arbitrary<std::forward_list<T, Allocator>>
: public ArbitraryCollection<std::forward_list<T, Allocator>, T> {};
// std::list
template<typename T, typename Allocator>
class Arbitrary<std::list<T, Allocator>>
: public ArbitraryCollection<std::list<T, Allocator>, T> {};
// std::set
template<typename Key, typename Compare, typename Allocator>
class Arbitrary<std::set<Key, Compare, Allocator>>
: public ArbitraryCollection<std::set<Key, Compare, Allocator>, Key> {};
// std::map
template<typename Key, typename T, typename Compare, typename Allocator>
class Arbitrary<std::map<Key, T, Compare, Allocator>>
: public ArbitraryCollection<std::map<Key, T, Compare, Allocator>,
std::pair<Key, T>> {};
// std::multiset
template<typename Key, typename Compare, typename Allocator>
class Arbitrary<std::multiset<Key, Compare, Allocator>>
: public ArbitraryCollection<std::multiset<Key, Compare, Allocator>, Key> {};
// std::multimap
template<typename Key, typename T, typename Compare, typename Allocator>
class Arbitrary<std::multimap<Key, T, Compare, Allocator>>
: public ArbitraryCollection<std::multimap<Key, T, Compare, Allocator>,
std::pair<Key, T>> {};
// std::unordered_set
template<typename Key, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_set<Key, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_set<Key, Hash, KeyEqual, Allocator>,
Key> {};
// std::unordered_map
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_map<Key, T, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_map<Key, T, Hash, KeyEqual, Allocator>,
std::pair<Key, T>> {};
// std::unordered_multiset
template<typename Key, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_multiset<Key, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_multiset<Key, Hash, KeyEqual, Allocator>,
Key> {};
// std::unordered_multimap
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator>,
std::pair<Key, T>> {};
// std::basic_string
template<typename T, typename Traits, typename Allocator>
class Arbitrary<std::basic_string<T, Traits, Allocator>>
: public gen::Collection<std::basic_string<T, Traits, Allocator>, gen::Character<T>>
{
public:
typedef std::basic_string<T, Traits, Allocator> StringType;
Arbitrary() : gen::Collection<StringType, gen::Character<T>>(
gen::character<T>()) {}
};
// std::array
template<typename T, std::size_t N>
class Arbitrary<std::array<T, N>>
: public ArbitraryCollection<std::array<T, N>, T> {};
} // namespace rc
<commit_msg>Fix a test which broke because of new RandomEngine<commit_after>#pragma once
namespace rc {
template<typename T>
class Arbitrary : public gen::Generator<T>
{
public:
static_assert(std::is_integral<T>::value,
"No specialization of Arbitrary for type");
T generate() const override
{
using namespace detail;
int size = std::min(gen::currentSize(), gen::kNominalSize);
RandomEngine::Atom r;
// TODO this switching shouldn't be done here. pickAtom?
ImplicitParam<param::CurrentNode> currentNode;
if (*currentNode != nullptr) {
r = currentNode->atom();
} else {
ImplicitParam<param::RandomEngine> randomEngine;
r = randomEngine->nextAtom();
}
// We vary the size by using different number of bits. This way, we can be
// that the max value can also be generated.
int nBits = (size * std::numeric_limits<T>::digits) / gen::kNominalSize;
if (nBits == 0)
return 0;
constexpr RandomEngine::Atom randIntMax =
std::numeric_limits<RandomEngine::Atom>::max();
RandomEngine::Atom mask = ~((randIntMax - 1) << (nBits - 1));
T x = static_cast<T>(r & mask);
if (std::numeric_limits<T>::is_signed)
{
// Use the topmost bit as the signed bit. Even in the case of a signed
// 64-bit integer, it won't be used since it actually IS the sign bit.
constexpr int basicBits =
std::numeric_limits<RandomEngine::Atom>::digits;
x *= ((r >> (basicBits - 1)) == 0) ? 1 : -1;
}
return x;
}
shrink::IteratorUP<T> shrink(T value) const override
{
std::vector<T> constants;
if (value < 0)
constants.push_back(-value);
return shrink::sequentially(
shrink::constant(constants),
shrink::towards(value, static_cast<T>(0)));
}
};
// Base for float and double arbitrary instances
template<typename T>
class ArbitraryReal : public gen::Generator<T>
{
public:
T generate() const override
{
int64_t i = *gen::arbitrary<int64_t>();
T x = static_cast<T>(i) / std::numeric_limits<int64_t>::max();
return std::pow<T>(1.1, gen::currentSize()) * x;
}
shrink::IteratorUP<T> shrink(T value) const override
{
std::vector<T> constants;
if (value < 0)
constants.push_back(-value);
T truncated = std::trunc(value);
if (std::abs(truncated) < std::abs(value))
constants.push_back(truncated);
return shrink::constant(constants);
}
};
template<>
class Arbitrary<float> : public ArbitraryReal<float> {};
template<>
class Arbitrary<double> : public ArbitraryReal<double> {};
template<>
class Arbitrary<bool> : public gen::Generator<bool>
{
public:
bool generate() const override
{
return (*gen::resize(gen::kNominalSize,
gen::arbitrary<uint8_t>()) & 0x1) == 0;
}
shrink::IteratorUP<bool> shrink(bool value)
{
if (value)
return shrink::constant<bool>({false});
else
return shrink::nothing<bool>();
}
};
template<typename ...Types>
class Arbitrary<std::tuple<Types...>>
: public gen::TupleOf<Arbitrary<Types>...>
{
public:
Arbitrary() : gen::TupleOf<Arbitrary<Types>...>(
gen::arbitrary<Types>()...) {}
};
template<typename T1, typename T2>
class Arbitrary<std::pair<T1, T2>>
: public gen::PairOf<Arbitrary<detail::DecayT<T1>>,
Arbitrary<detail::DecayT<T2>>>
{
public:
Arbitrary()
: gen::PairOf<Arbitrary<detail::DecayT<T1>>,
Arbitrary<detail::DecayT<T2>>>(
gen::arbitrary<detail::DecayT<T1>>(),
gen::arbitrary<detail::DecayT<T2>>()) {}
};
// Base template class for collection types
template<typename Coll, typename ValueType>
class ArbitraryCollection : public gen::Collection<Coll, Arbitrary<ValueType>>
{
public:
typedef gen::Collection<Coll, Arbitrary<ValueType>> CollectionGen;
ArbitraryCollection() : CollectionGen(gen::arbitrary<ValueType>()) {}
};
// std::vector
template<typename T, typename Allocator>
class Arbitrary<std::vector<T, Allocator>>
: public ArbitraryCollection<std::vector<T, Allocator>, T> {};
// std::deque
template<typename T, typename Allocator>
class Arbitrary<std::deque<T, Allocator>>
: public ArbitraryCollection<std::deque<T, Allocator>, T> {};
// std::forward_list
template<typename T, typename Allocator>
class Arbitrary<std::forward_list<T, Allocator>>
: public ArbitraryCollection<std::forward_list<T, Allocator>, T> {};
// std::list
template<typename T, typename Allocator>
class Arbitrary<std::list<T, Allocator>>
: public ArbitraryCollection<std::list<T, Allocator>, T> {};
// std::set
template<typename Key, typename Compare, typename Allocator>
class Arbitrary<std::set<Key, Compare, Allocator>>
: public ArbitraryCollection<std::set<Key, Compare, Allocator>, Key> {};
// std::map
template<typename Key, typename T, typename Compare, typename Allocator>
class Arbitrary<std::map<Key, T, Compare, Allocator>>
: public ArbitraryCollection<std::map<Key, T, Compare, Allocator>,
std::pair<Key, T>> {};
// std::multiset
template<typename Key, typename Compare, typename Allocator>
class Arbitrary<std::multiset<Key, Compare, Allocator>>
: public ArbitraryCollection<std::multiset<Key, Compare, Allocator>, Key> {};
// std::multimap
template<typename Key, typename T, typename Compare, typename Allocator>
class Arbitrary<std::multimap<Key, T, Compare, Allocator>>
: public ArbitraryCollection<std::multimap<Key, T, Compare, Allocator>,
std::pair<Key, T>> {};
// std::unordered_set
template<typename Key, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_set<Key, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_set<Key, Hash, KeyEqual, Allocator>,
Key> {};
// std::unordered_map
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_map<Key, T, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_map<Key, T, Hash, KeyEqual, Allocator>,
std::pair<Key, T>> {};
// std::unordered_multiset
template<typename Key, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_multiset<Key, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_multiset<Key, Hash, KeyEqual, Allocator>,
Key> {};
// std::unordered_multimap
template<typename Key, typename T, typename Hash, typename KeyEqual, typename Allocator>
class Arbitrary<std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator>>
: public ArbitraryCollection<std::unordered_multimap<Key, T, Hash, KeyEqual, Allocator>,
std::pair<Key, T>> {};
// std::basic_string
template<typename T, typename Traits, typename Allocator>
class Arbitrary<std::basic_string<T, Traits, Allocator>>
: public gen::Collection<std::basic_string<T, Traits, Allocator>, gen::Character<T>>
{
public:
typedef std::basic_string<T, Traits, Allocator> StringType;
Arbitrary() : gen::Collection<StringType, gen::Character<T>>(
gen::character<T>()) {}
};
// std::array
template<typename T, std::size_t N>
class Arbitrary<std::array<T, N>>
: public ArbitraryCollection<std::array<T, N>, T> {};
} // namespace rc
<|endoftext|>
|
<commit_before>#include <Engine/Renderer/Texture/TextureManager.hpp>
#include <cstdio>
#include <FreeImage.h>
#include <Engine/Renderer/Texture/Texture.hpp>
namespace Ra
{
namespace Engine
{
TextureManager::TextureManager()
: m_verbose( false )
{
}
TextureManager::~TextureManager()
{
for ( auto& tex : m_textures )
{
delete tex.second;
}
m_textures.clear();
}
void TextureManager::addTexture( const std::string& name, int width, int height, void* data )
{
TextureData texData;
texData.name = name;
texData.width = width;
texData.height = height;
texData.data = data;
m_pendingTextures[name] = texData;
}
Texture* TextureManager::addTexture( const std::string& filename )
{
Texture* ret = nullptr;
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
FIBITMAP* dib = nullptr; // TODO This name is nonsense, change it
// Find format from file signature
fif = FreeImage_GetFileType( filename.c_str(), 0 );
if ( FIF_UNKNOWN == fif )
{
// Find format from file extension
fif = FreeImage_GetFIFFromFilename( filename.c_str() );
}
if ( FIF_UNKNOWN == fif )
{
// Still unknown
std::string error = "Cannot determine " + filename + " image format.";
LOG( logERROR ) << error;
return nullptr;
}
if ( FreeImage_FIFSupportsReading( fif ) )
{
dib = FreeImage_Load( fif, filename.c_str() );
}
std::string error = "Something went wrong while trying to load " + filename + ".";
if ( nullptr == dib )
{
LOG( logERROR ) << error;
return nullptr;
}
ret = new Texture( filename, GL_TEXTURE_2D );
unsigned char* data = FreeImage_GetBits( dib );
int bpp = FreeImage_GetBPP( dib );
int format = 0, internal = 0;
switch ( bpp )
{
case 8:
{
// FIXME(Charly): Debug this
format = GL_RED;
internal = GL_RED;
} break;
case 24:
{
format = GL_BGR;
internal = GL_RGB;
} break;
case 32:
{
format = GL_BGRA;
internal = GL_RGBA;
} break;
default:
{
LOG( logERROR ) << "Unknow bytes per pixel format : " << bpp;
}
}
int w = FreeImage_GetWidth( dib );
int h = FreeImage_GetHeight( dib );
if ( m_verbose )
{
LOG( logINFO ) << "Image stats (" << filename << ") :\n"
<< "\tBPP : 0x" << std::hex << bpp << std::dec << std::endl
<< "\tFormat : 0x" << std::hex << format << std::dec << std::endl
<< "\tSize : " << w << ", " << h;
}
CORE_ASSERT( data, "Data is null" );
ret->initGL( internal, w, h, format, GL_UNSIGNED_BYTE, data );
ret->genMipmap( GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR );
m_textures.insert( TexturePair( filename, ret ) );
FreeImage_Unload( dib );
return ret;
}
Texture* TextureManager::getOrLoadTexture( const std::string& filename )
{
Texture* ret = nullptr;
auto it = m_textures.find( filename );
if ( it != m_textures.end() )
{
ret = it->second;
}
else
{
auto pending = m_pendingTextures.find( filename );
if ( pending != m_pendingTextures.end() )
{
ret = new Texture( filename, GL_TEXTURE_2D );
ret->initGL( GL_RGBA, pending->second.width, pending->second.height,
GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, pending->second.data );
ret->genMipmap( GL_LINEAR, GL_LINEAR );
ret->setClamp( GL_CLAMP, GL_CLAMP );
m_pendingTextures.erase( filename );
m_textures[filename] = ret;
}
else
{
ret = addTexture( filename );
}
}
return ret;
}
void TextureManager::deleteTexture( const std::string& filename )
{
auto it = m_textures.find( filename );
if ( it != m_textures.end() )
{
delete it->second;
m_textures.erase( it );
}
}
void TextureManager::deleteTexture( Texture* texture )
{
deleteTexture( texture->getName() );
}
void TextureManager::updateTexture( const std::string& texture, void* data )
{
CORE_ASSERT( m_textures.find( texture ) != m_textures.end(),
"Trying to update non existing texture" );
m_pendingData[texture] = data;
}
void TextureManager::updateTextures()
{
if ( m_pendingData.empty() )
{
return;
}
for ( auto& data : m_pendingData )
{
m_textures[data.first]->updateData( data.second );
}
m_pendingData.clear();
}
RA_SINGLETON_IMPLEMENTATION(TextureManager);
}
} // namespace Ra
<commit_msg>Set the clamping to clamp by default on loading textures<commit_after>#include <Engine/Renderer/Texture/TextureManager.hpp>
#include <cstdio>
#include <FreeImage.h>
#include <Engine/Renderer/Texture/Texture.hpp>
namespace Ra
{
namespace Engine
{
TextureManager::TextureManager()
: m_verbose( false )
{
}
TextureManager::~TextureManager()
{
for ( auto& tex : m_textures )
{
delete tex.second;
}
m_textures.clear();
}
void TextureManager::addTexture( const std::string& name, int width, int height, void* data )
{
TextureData texData;
texData.name = name;
texData.width = width;
texData.height = height;
texData.data = data;
m_pendingTextures[name] = texData;
}
Texture* TextureManager::addTexture( const std::string& filename )
{
Texture* ret = nullptr;
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
FIBITMAP* dib = nullptr; // TODO This name is nonsense, change it
// Find format from file signature
fif = FreeImage_GetFileType( filename.c_str(), 0 );
if ( FIF_UNKNOWN == fif )
{
// Find format from file extension
fif = FreeImage_GetFIFFromFilename( filename.c_str() );
}
if ( FIF_UNKNOWN == fif )
{
// Still unknown
std::string error = "Cannot determine " + filename + " image format.";
LOG( logERROR ) << error;
return nullptr;
}
if ( FreeImage_FIFSupportsReading( fif ) )
{
dib = FreeImage_Load( fif, filename.c_str() );
}
std::string error = "Something went wrong while trying to load " + filename + ".";
if ( nullptr == dib )
{
LOG( logERROR ) << error;
return nullptr;
}
ret = new Texture( filename, GL_TEXTURE_2D );
unsigned char* data = FreeImage_GetBits( dib );
int bpp = FreeImage_GetBPP( dib );
int format = 0, internal = 0;
switch ( bpp )
{
case 8:
{
// FIXME(Charly): Debug this
format = GL_RED;
internal = GL_RED;
} break;
case 24:
{
format = GL_BGR;
internal = GL_RGB;
} break;
case 32:
{
format = GL_BGRA;
internal = GL_RGBA;
} break;
default:
{
LOG( logERROR ) << "Unknow bytes per pixel format : " << bpp;
}
}
int w = FreeImage_GetWidth( dib );
int h = FreeImage_GetHeight( dib );
if ( m_verbose )
{
LOG( logINFO ) << "Image stats (" << filename << ") :\n"
<< "\tBPP : 0x" << std::hex << bpp << std::dec << std::endl
<< "\tFormat : 0x" << std::hex << format << std::dec << std::endl
<< "\tSize : " << w << ", " << h;
}
CORE_ASSERT( data, "Data is null" );
ret->initGL( internal, w, h, format, GL_UNSIGNED_BYTE, data );
ret->genMipmap( GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR );
m_textures.insert( TexturePair( filename, ret ) );
FreeImage_Unload( dib );
return ret;
}
Texture* TextureManager::getOrLoadTexture( const std::string& filename )
{
Texture* ret = nullptr;
auto it = m_textures.find( filename );
if ( it != m_textures.end() )
{
ret = it->second;
}
else
{
auto pending = m_pendingTextures.find( filename );
if ( pending != m_pendingTextures.end() )
{
ret = new Texture( filename, GL_TEXTURE_2D );
ret->initGL( GL_RGBA, pending->second.width, pending->second.height,
GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, pending->second.data );
ret->genMipmap( GL_LINEAR, GL_LINEAR );
ret->setClamp( GL_CLAMP, GL_CLAMP );
m_pendingTextures.erase( filename );
m_textures[filename] = ret;
}
else
{
ret = addTexture( filename );
ret->setClamp( GL_CLAMP, GL_CLAMP );
}
}
return ret;
}
void TextureManager::deleteTexture( const std::string& filename )
{
auto it = m_textures.find( filename );
if ( it != m_textures.end() )
{
delete it->second;
m_textures.erase( it );
}
}
void TextureManager::deleteTexture( Texture* texture )
{
deleteTexture( texture->getName() );
}
void TextureManager::updateTexture( const std::string& texture, void* data )
{
CORE_ASSERT( m_textures.find( texture ) != m_textures.end(),
"Trying to update non existing texture" );
m_pendingData[texture] = data;
}
void TextureManager::updateTextures()
{
if ( m_pendingData.empty() )
{
return;
}
for ( auto& data : m_pendingData )
{
m_textures[data.first]->updateData( data.second );
}
m_pendingData.clear();
}
RA_SINGLETON_IMPLEMENTATION(TextureManager);
}
} // namespace Ra
<|endoftext|>
|
<commit_before>/**
* @file llpanelpeoplemenus.h
* @brief Menus used by the side tray "People" panel
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
// libs
#include "llmenugl.h"
#include "lluictrlfactory.h"
#include "llpanelpeoplemenus.h"
// newview
#include "llagent.h"
#include "llagentdata.h" // for gAgentID
#include "llavataractions.h"
#include "llcallingcard.h" // for LLAvatarTracker
#include "llviewermenu.h" // for gMenuHolder
#include "llfloatersidepanelcontainer.h"
#include "llpanelpeople.h"
namespace LLPanelPeopleMenus
{
NearbyMenu gNearbyMenu;
//== NearbyMenu ===============================================================
LLContextMenu* NearbyMenu::createMenu()
{
// set up the callbacks for all of the avatar menu items
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
if ( mUUIDs.size() == 1 )
{
// Set up for one person selected menu
const LLUUID& id = mUUIDs.front();
registrar.add("Avatar.Profile", boost::bind(&LLAvatarActions::showProfile, id));
registrar.add("Avatar.AddFriend", boost::bind(&LLAvatarActions::requestFriendshipDialog, id));
registrar.add("Avatar.RemoveFriend", boost::bind(&LLAvatarActions::removeFriendDialog, id));
registrar.add("Avatar.IM", boost::bind(&LLAvatarActions::startIM, id));
registrar.add("Avatar.Call", boost::bind(&LLAvatarActions::startCall, id));
registrar.add("Avatar.OfferTeleport", boost::bind(&NearbyMenu::offerTeleport, this));
registrar.add("Avatar.GroupInvite", boost::bind(&LLAvatarActions::inviteToGroup, id));
registrar.add("Avatar.getScriptInfo", boost::bind(&LLAvatarActions::getScriptInfo, id));
registrar.add("Avatar.ShowOnMap", boost::bind(&LLAvatarActions::showOnMap, id));
registrar.add("Avatar.Share", boost::bind(&LLAvatarActions::share, id));
registrar.add("Avatar.Pay", boost::bind(&LLAvatarActions::pay, id));
registrar.add("Avatar.BlockUnblock", boost::bind(&LLAvatarActions::toggleBlock, id));
// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-12-03 (Catznip-2.4.0g) | Modified: Catznip-2.4.0g
registrar.add("Avatar.ZoomIn", boost::bind(&LLAvatarActions::zoomIn, id));
enable_registrar.add("Avatar.VisibleZoomIn", boost::bind(&LLAvatarActions::canZoomIn, id));
registrar.add("Avatar.Report", boost::bind(&LLAvatarActions::report, id));
registrar.add("Avatar.Eject", boost::bind(&LLAvatarActions::landEject, id));
registrar.add("Avatar.Freeze", boost::bind(&LLAvatarActions::landFreeze, id));
enable_registrar.add("Avatar.VisibleFreezeEject", boost::bind(&LLAvatarActions::canLandFreezeOrEject, id));
registrar.add("Avatar.Kick", boost::bind(&LLAvatarActions::estateKick, id));
registrar.add("Avatar.TeleportHome", boost::bind(&LLAvatarActions::estateTeleportHome, id));
enable_registrar.add("Avatar.VisibleKickTeleportHome", boost::bind(&LLAvatarActions::canEstateKickOrTeleportHome, id));
// [/SL:KB]
registrar.add("Nearby.People.TeleportToAvatar", boost::bind(&NearbyMenu::teleportToAvatar, this));
registrar.add("Nearby.People.TrackAvatar", boost::bind(&NearbyMenu::onTrackAvatarMenuItemClick, this));
registrar.add("Avatar.ZoomIn", boost::bind(&LLAvatarActions::zoomIn, id));
enable_registrar.add("Avatar.VisibleZoomIn", boost::bind(&LLAvatarActions::canZoomIn, id));
enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem, this, _2));
enable_registrar.add("Avatar.CheckItem", boost::bind(&NearbyMenu::checkContextMenuItem, this, _2));
// create the context menu from the XUI
return createFromFile("menu_people_nearby.xml");
}
else
{
// Set up for multi-selected People
// registrar.add("Avatar.AddFriend", boost::bind(&LLAvatarActions::requestFriendshipDialog, mUUIDs)); // *TODO: unimplemented
registrar.add("Avatar.IM", boost::bind(&LLAvatarActions::startConference, mUUIDs));
registrar.add("Avatar.Call", boost::bind(&LLAvatarActions::startAdhocCall, mUUIDs));
registrar.add("Avatar.OfferTeleport", boost::bind(&NearbyMenu::offerTeleport, this));
registrar.add("Avatar.RemoveFriend",boost::bind(&LLAvatarActions::removeFriendsDialog, mUUIDs));
// registrar.add("Avatar.Share", boost::bind(&LLAvatarActions::startIM, mUUIDs)); // *TODO: unimplemented
// registrar.add("Avatar.Pay", boost::bind(&LLAvatarActions::pay, mUUIDs)); // *TODO: unimplemented
enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem, this, _2));
// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-11-05 (Catznip-2.4.0g) | Added: Catznip-2.4.0g
registrar.add("Avatar.Eject", boost::bind(&LLAvatarActions::landEjectMultiple, mUUIDs));
registrar.add("Avatar.Freeze", boost::bind(&LLAvatarActions::landFreezeMultiple, mUUIDs));
enable_registrar.add("Avatar.VisibleFreezeEject", boost::bind(&LLAvatarActions::canLandFreezeOrEjectMultiple, mUUIDs, false));
registrar.add("Avatar.Kick", boost::bind(&LLAvatarActions::estateKickMultiple, mUUIDs));
registrar.add("Avatar.TeleportHome", boost::bind(&LLAvatarActions::estateTeleportHomeMultiple, mUUIDs));
enable_registrar.add("Avatar.VisibleKickTeleportHome", boost::bind(&LLAvatarActions::canEstateKickOrTeleportHomeMultiple, mUUIDs, false));
// [/SL:KB]
// create the context menu from the XUI
return createFromFile("menu_people_nearby_multiselect.xml");
}
}
bool NearbyMenu::enableContextMenuItem(const LLSD& userdata)
{
std::string item = userdata.asString();
// Note: can_block and can_delete is used only for one person selected menu
// so we don't need to go over all uuids.
if (item == std::string("can_block"))
{
const LLUUID& id = mUUIDs.front();
return LLAvatarActions::canBlock(id);
}
else if (item == std::string("can_add"))
{
// We can add friends if:
// - there are selected people
// - and there are no friends among selection yet.
//EXT-7389 - disable for more than 1
if(mUUIDs.size() > 1)
{
return false;
}
bool result = (mUUIDs.size() > 0);
uuid_vec_t::const_iterator
id = mUUIDs.begin(),
uuids_end = mUUIDs.end();
for (;id != uuids_end; ++id)
{
if ( LLAvatarActions::isFriend(*id) )
{
result = false;
break;
}
}
return result;
}
else if (item == std::string("can_delete"))
{
// We can remove friends if:
// - there are selected people
// - and there are only friends among selection.
bool result = (mUUIDs.size() > 0);
uuid_vec_t::const_iterator
id = mUUIDs.begin(),
uuids_end = mUUIDs.end();
for (;id != uuids_end; ++id)
{
if ( !LLAvatarActions::isFriend(*id) )
{
result = false;
break;
}
}
return result;
}
else if (item == std::string("can_call"))
{
return LLAvatarActions::canCall();
}
else if (item == std::string("can_show_on_map"))
{
const LLUUID& id = mUUIDs.front();
return (LLAvatarTracker::instance().isBuddyOnline(id) && is_agent_mappable(id))
|| gAgent.isGodlike();
}
// else if(item == std::string("can_offer_teleport")) ND_MERGE this lines had been missing from FS, intentional?
// {
// return LLAvatarActions::canOfferTeleport(mUUIDs);
// }
return false;
}
bool NearbyMenu::checkContextMenuItem(const LLSD& userdata)
{
std::string item = userdata.asString();
const LLUUID& id = mUUIDs.front();
if (item == std::string("is_blocked"))
{
return LLAvatarActions::isBlocked(id);
}
return false;
}
void NearbyMenu::offerTeleport()
{
// boost::bind cannot recognize overloaded method LLAvatarActions::offerTeleport(),
// so we have to use a wrapper.
LLAvatarActions::offerTeleport(mUUIDs);
}
void NearbyMenu::teleportToAvatar()
// AO: wrapper for functionality managed by LLPanelPeople, because it manages the nearby avatar list.
// Will only work for avatars within radar range.
{
LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
peoplePanel->teleportToAvatar(mUUIDs.front());
}
// Ansariel: Avatar tracking feature
void NearbyMenu::onTrackAvatarMenuItemClick()
{
LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
peoplePanel->startTracking(mUUIDs.front());
}
} // namespace LLPanelPeopleMenus
<commit_msg>Cleared merge issue in llpanelpeoplemenus.cpp<commit_after>/**
* @file llpanelpeoplemenus.h
* @brief Menus used by the side tray "People" panel
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* 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;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
// libs
#include "llmenugl.h"
#include "lluictrlfactory.h"
#include "llpanelpeoplemenus.h"
// newview
#include "llagent.h"
#include "llagentdata.h" // for gAgentID
#include "llavataractions.h"
#include "llcallingcard.h" // for LLAvatarTracker
#include "llviewermenu.h" // for gMenuHolder
#include "llfloatersidepanelcontainer.h"
#include "llpanelpeople.h"
namespace LLPanelPeopleMenus
{
NearbyMenu gNearbyMenu;
//== NearbyMenu ===============================================================
LLContextMenu* NearbyMenu::createMenu()
{
// set up the callbacks for all of the avatar menu items
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
if ( mUUIDs.size() == 1 )
{
// Set up for one person selected menu
const LLUUID& id = mUUIDs.front();
registrar.add("Avatar.Profile", boost::bind(&LLAvatarActions::showProfile, id));
registrar.add("Avatar.AddFriend", boost::bind(&LLAvatarActions::requestFriendshipDialog, id));
registrar.add("Avatar.RemoveFriend", boost::bind(&LLAvatarActions::removeFriendDialog, id));
registrar.add("Avatar.IM", boost::bind(&LLAvatarActions::startIM, id));
registrar.add("Avatar.Call", boost::bind(&LLAvatarActions::startCall, id));
registrar.add("Avatar.OfferTeleport", boost::bind(&NearbyMenu::offerTeleport, this));
registrar.add("Avatar.GroupInvite", boost::bind(&LLAvatarActions::inviteToGroup, id));
registrar.add("Avatar.getScriptInfo", boost::bind(&LLAvatarActions::getScriptInfo, id));
registrar.add("Avatar.ShowOnMap", boost::bind(&LLAvatarActions::showOnMap, id));
registrar.add("Avatar.Share", boost::bind(&LLAvatarActions::share, id));
registrar.add("Avatar.Pay", boost::bind(&LLAvatarActions::pay, id));
registrar.add("Avatar.BlockUnblock", boost::bind(&LLAvatarActions::toggleBlock, id));
// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-12-03 (Catznip-2.4.0g) | Modified: Catznip-2.4.0g
registrar.add("Avatar.ZoomIn", boost::bind(&LLAvatarActions::zoomIn, id));
enable_registrar.add("Avatar.VisibleZoomIn", boost::bind(&LLAvatarActions::canZoomIn, id));
registrar.add("Avatar.Report", boost::bind(&LLAvatarActions::report, id));
registrar.add("Avatar.Eject", boost::bind(&LLAvatarActions::landEject, id));
registrar.add("Avatar.Freeze", boost::bind(&LLAvatarActions::landFreeze, id));
enable_registrar.add("Avatar.VisibleFreezeEject", boost::bind(&LLAvatarActions::canLandFreezeOrEject, id));
registrar.add("Avatar.Kick", boost::bind(&LLAvatarActions::estateKick, id));
registrar.add("Avatar.TeleportHome", boost::bind(&LLAvatarActions::estateTeleportHome, id));
enable_registrar.add("Avatar.VisibleKickTeleportHome", boost::bind(&LLAvatarActions::canEstateKickOrTeleportHome, id));
// [/SL:KB]
registrar.add("Nearby.People.TeleportToAvatar", boost::bind(&NearbyMenu::teleportToAvatar, this));
registrar.add("Nearby.People.TrackAvatar", boost::bind(&NearbyMenu::onTrackAvatarMenuItemClick, this));
registrar.add("Avatar.ZoomIn", boost::bind(&LLAvatarActions::zoomIn, id));
enable_registrar.add("Avatar.VisibleZoomIn", boost::bind(&LLAvatarActions::canZoomIn, id));
enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem, this, _2));
enable_registrar.add("Avatar.CheckItem", boost::bind(&NearbyMenu::checkContextMenuItem, this, _2));
// create the context menu from the XUI
return createFromFile("menu_people_nearby.xml");
}
else
{
// Set up for multi-selected People
// registrar.add("Avatar.AddFriend", boost::bind(&LLAvatarActions::requestFriendshipDialog, mUUIDs)); // *TODO: unimplemented
registrar.add("Avatar.IM", boost::bind(&LLAvatarActions::startConference, mUUIDs));
registrar.add("Avatar.Call", boost::bind(&LLAvatarActions::startAdhocCall, mUUIDs));
registrar.add("Avatar.OfferTeleport", boost::bind(&NearbyMenu::offerTeleport, this));
registrar.add("Avatar.RemoveFriend",boost::bind(&LLAvatarActions::removeFriendsDialog, mUUIDs));
// registrar.add("Avatar.Share", boost::bind(&LLAvatarActions::startIM, mUUIDs)); // *TODO: unimplemented
// registrar.add("Avatar.Pay", boost::bind(&LLAvatarActions::pay, mUUIDs)); // *TODO: unimplemented
enable_registrar.add("Avatar.EnableItem", boost::bind(&NearbyMenu::enableContextMenuItem, this, _2));
// [SL:KB] - Patch: UI-SidepanelPeople | Checked: 2010-11-05 (Catznip-2.4.0g) | Added: Catznip-2.4.0g
registrar.add("Avatar.Eject", boost::bind(&LLAvatarActions::landEjectMultiple, mUUIDs));
registrar.add("Avatar.Freeze", boost::bind(&LLAvatarActions::landFreezeMultiple, mUUIDs));
enable_registrar.add("Avatar.VisibleFreezeEject", boost::bind(&LLAvatarActions::canLandFreezeOrEjectMultiple, mUUIDs, false));
registrar.add("Avatar.Kick", boost::bind(&LLAvatarActions::estateKickMultiple, mUUIDs));
registrar.add("Avatar.TeleportHome", boost::bind(&LLAvatarActions::estateTeleportHomeMultiple, mUUIDs));
enable_registrar.add("Avatar.VisibleKickTeleportHome", boost::bind(&LLAvatarActions::canEstateKickOrTeleportHomeMultiple, mUUIDs, false));
// [/SL:KB]
// create the context menu from the XUI
return createFromFile("menu_people_nearby_multiselect.xml");
}
}
bool NearbyMenu::enableContextMenuItem(const LLSD& userdata)
{
std::string item = userdata.asString();
// Note: can_block and can_delete is used only for one person selected menu
// so we don't need to go over all uuids.
if (item == std::string("can_block"))
{
const LLUUID& id = mUUIDs.front();
return LLAvatarActions::canBlock(id);
}
else if (item == std::string("can_add"))
{
// We can add friends if:
// - there are selected people
// - and there are no friends among selection yet.
//EXT-7389 - disable for more than 1
if(mUUIDs.size() > 1)
{
return false;
}
bool result = (mUUIDs.size() > 0);
uuid_vec_t::const_iterator
id = mUUIDs.begin(),
uuids_end = mUUIDs.end();
for (;id != uuids_end; ++id)
{
if ( LLAvatarActions::isFriend(*id) )
{
result = false;
break;
}
}
return result;
}
else if (item == std::string("can_delete"))
{
// We can remove friends if:
// - there are selected people
// - and there are only friends among selection.
bool result = (mUUIDs.size() > 0);
uuid_vec_t::const_iterator
id = mUUIDs.begin(),
uuids_end = mUUIDs.end();
for (;id != uuids_end; ++id)
{
if ( !LLAvatarActions::isFriend(*id) )
{
result = false;
break;
}
}
return result;
}
else if (item == std::string("can_call"))
{
return LLAvatarActions::canCall();
}
else if (item == std::string("can_show_on_map"))
{
const LLUUID& id = mUUIDs.front();
return (LLAvatarTracker::instance().isBuddyOnline(id) && is_agent_mappable(id))
|| gAgent.isGodlike();
}
// <FS> Prevent teleport button from being disabled when someone on your
// friends list logs out but is still in the region and you have
// multiple people selected.
//else if(item == std::string("can_offer_teleport"))
//{
// return LLAvatarActions::canOfferTeleport(mUUIDs);
//}
// </FS>
return false;
}
bool NearbyMenu::checkContextMenuItem(const LLSD& userdata)
{
std::string item = userdata.asString();
const LLUUID& id = mUUIDs.front();
if (item == std::string("is_blocked"))
{
return LLAvatarActions::isBlocked(id);
}
return false;
}
void NearbyMenu::offerTeleport()
{
// boost::bind cannot recognize overloaded method LLAvatarActions::offerTeleport(),
// so we have to use a wrapper.
LLAvatarActions::offerTeleport(mUUIDs);
}
void NearbyMenu::teleportToAvatar()
// AO: wrapper for functionality managed by LLPanelPeople, because it manages the nearby avatar list.
// Will only work for avatars within radar range.
{
LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
peoplePanel->teleportToAvatar(mUUIDs.front());
}
// Ansariel: Avatar tracking feature
void NearbyMenu::onTrackAvatarMenuItemClick()
{
LLPanelPeople* peoplePanel = dynamic_cast<LLPanelPeople*>(LLFloaterSidePanelContainer::getPanel("people", "panel_people"));
peoplePanel->startTracking(mUUIDs.front());
}
} // namespace LLPanelPeopleMenus
<|endoftext|>
|
<commit_before>#include "RolesProvider.h"
<commit_msg>removed unnecessary file<commit_after><|endoftext|>
|
<commit_before>//
// AnimatedMultiSinus.cpp
// LaserAnimTool
//
// Created by pach on 07/08/14.
// Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//
#include "AnimatedMultiSinus.h"
AnimatedMultiSinus::AnimatedMultiSinus(){
}
AnimatedMultiSinus::~AnimatedMultiSinus(){
AnimatedStuff::~AnimatedStuff();
}
void AnimatedMultiSinus::setup(string name) {
AnimatedStuff::setup(name);
type = "AnimatedMultiSinus";
sin1.freq = 1.;
sin1.speed = 0.;
sin1.height = 1.;
sin2.freq = 1.;
sin2.speed = 0.;
sin2.height = 1.;
sin3.freq = 1.;
sin3.speed = 0.;
sin3.height = 1.;
sinI1.freq = 1.;
sinI1.speed = 0.;
sinI1.height = 1.;
sinI2.freq = 1.;
sinI2.speed = 0.;
sinI2.height = 1.;
sinI3.freq = 1.;
sinI3.speed = 0.;
sinI3.height = 1.;
gui->addSpacer();
gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
gui->addSlider("/posY", -1., 1., &posY);
gui->addSpacer();
gui->addSlider("/1/freq", 0., 50., &sin1.freq);
gui->addSlider("/1/speed", -10., 10., &sin1.speed);
gui->addSlider("/1/height", 0., 1., &sin1.height);
gui->addSpacer();
gui->addSlider("/2/freq", 0., 50., &sin2.freq);
gui->addSlider("/2/speed", -10., 10., &sin2.speed);
gui->addSlider("/2/height", 0., 1., &sin2.height);
gui->addSpacer();
gui->addSlider("/3/freq", 0., 50., &sin3.freq);
gui->addSlider("/3/speed", -10., 10., &sin3.speed);
gui->addSlider("/3/height", 0., 1., &sin3.height);
gui->addSpacer();
gui->addSlider("tan/1/freq", 0., 50., &sinI1.freq);
gui->addSlider("tan/1/speed", -10., 10., &sinI1.speed);
gui->addSlider("tan/1/height", 0., 1., &sinI1.height);
gui->addSpacer();
gui->addSlider("tan/2/freq", 0., 50., &sinI2.freq);
gui->addSlider("tan/2/speed", -10., 10., &sinI2.speed);
gui->addSlider("tan/2/height", 0., 1., &sinI2.height);
gui->addSpacer();
gui->addSlider("tan/3/freq", 0., 50., &sinI3.freq);
gui->addSlider("tan/3/speed", -10., 10., &sinI3.speed);
gui->addSlider("tan/3/height", 0., 1., &sinI3.height);
ofPolyline p;
polylines.push_back(p);
load();
}
void AnimatedMultiSinus::update() {
polylines[0].clear();
float x1, x2, x3, y1, y2, y3;
for (int i=0 ; i<nbPoint ; i++){
y1 = sin((float)i*sin1.freq/nbPoint+ofGetElapsedTimef()*sin1.speed)*sin1.height;
y2 = sin((float)i*sin2.freq/nbPoint+ofGetElapsedTimef()*sin2.speed)*sin2.height;
y3 = sin((float)i*sin3.freq/nbPoint+ofGetElapsedTimef()*sin3.speed)*sin3.height;
x1 = sin((float)i*sinI1.freq/nbPoint+ofGetElapsedTimef()*sinI1.speed)*sinI1.height;
x2 = sin((float)i*sinI2.freq/nbPoint+ofGetElapsedTimef()*sinI2.speed)*sinI2.height;
x3 = sin((float)i*sinI3.freq/nbPoint+ofGetElapsedTimef()*sinI3.speed)*sinI3.height;
polylines[0].addVertex((float)i/(float)nbPoint+x1+x2+x3, y1+y2+y3-posY);
}
}
void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
// string msg = m.getAddress();
// string cmd ;
//
// int ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
vector<string> osc = getOSCcmd(m.getAddress());
string cmd = osc[0];
string msg = osc[1];
if (cmd == "nbPoint"){
nbPoint = m.getArgAsInt32(0);
}
else if (cmd == "posY"){
posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
}
else if (cmd == "1"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin1.height = m.getArgAsFloat(0);
}
}
else if (cmd == "2"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin2.height = m.getArgAsFloat(0);
}
}
else if (cmd == "3"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin3.height = m.getArgAsFloat(0);
}
}
// else if (cmd == "1/freq"){
// sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "1/speed"){
// sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "1/height"){
// sin1.height = m.getArgAsFloat(0);
// }
// else if (cmd == "2/freq"){
// sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "2/speed"){
// sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "2/height"){
// sin2.height = m.getArgAsFloat(0);
// }
// else if (cmd == "3/freq"){
// sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "3/speed"){
// sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "3/height"){
// sin3.height = m.getArgAsFloat(0);
// }
}<commit_msg>small mods<commit_after>//
// AnimatedMultiSinus.cpp
// LaserAnimTool
//
// Created by pach on 07/08/14.
// Copyright (c) 2014 __MyCompanyName__. All rights reserved.
//
#include "AnimatedMultiSinus.h"
AnimatedMultiSinus::AnimatedMultiSinus(){
}
AnimatedMultiSinus::~AnimatedMultiSinus(){
AnimatedStuff::~AnimatedStuff();
}
void AnimatedMultiSinus::setup(string name) {
AnimatedStuff::setup(name);
type = "AnimatedMultiSinus";
sin1.freq = 1.;
sin1.speed = 0.;
sin1.height = 1.;
sin2.freq = 1.;
sin2.speed = 0.;
sin2.height = 1.;
sin3.freq = 1.;
sin3.speed = 0.;
sin3.height = 1.;
sinI1.freq = 1.;
sinI1.speed = 0.;
sinI1.height = 1.;
sinI2.freq = 1.;
sinI2.speed = 0.;
sinI2.height = 1.;
sinI3.freq = 1.;
sinI3.speed = 0.;
sinI3.height = 1.;
gui->addSpacer();
gui->addIntSlider("/nbPoint", 10, 1000, &nbPoint);
gui->addSlider("/posY", -1., 1., &posY);
gui->addSpacer();
gui->addSlider("/1/freq", 0., 200., &sin1.freq);
gui->addSlider("/1/speed", -10., 10., &sin1.speed);
gui->addSlider("/1/height", 0., 1., &sin1.height);
gui->addSpacer();
gui->addSlider("/2/freq", 0., 200., &sin2.freq);
gui->addSlider("/2/speed", -10., 10., &sin2.speed);
gui->addSlider("/2/height", 0., 1., &sin2.height);
gui->addSpacer();
gui->addSlider("/3/freq", 0., 200., &sin3.freq);
gui->addSlider("/3/speed", -10., 10., &sin3.speed);
gui->addSlider("/3/height", 0., 1., &sin3.height);
gui->addSpacer();
gui->addSlider("tan/1/freq", 0., 50., &sinI1.freq);
gui->addSlider("tan/1/speed", -10., 10., &sinI1.speed);
gui->addSlider("tan/1/height", 0., 1., &sinI1.height);
gui->addSpacer();
gui->addSlider("tan/2/freq", 0., 50., &sinI2.freq);
gui->addSlider("tan/2/speed", -10., 10., &sinI2.speed);
gui->addSlider("tan/2/height", 0., 1., &sinI2.height);
gui->addSpacer();
gui->addSlider("tan/3/freq", 0., 50., &sinI3.freq);
gui->addSlider("tan/3/speed", -10., 10., &sinI3.speed);
gui->addSlider("tan/3/height", 0., 1., &sinI3.height);
ofPolyline p;
polylines.push_back(p);
load();
}
void AnimatedMultiSinus::update() {
polylines[0].clear();
float x1, x2, x3, y1, y2, y3;
for (int i=0 ; i<nbPoint ; i++){
y1 = sin((float)i*sin1.freq/nbPoint+ofGetElapsedTimef()*sin1.speed)*sin1.height;
y2 = sin((float)i*sin2.freq/nbPoint+ofGetElapsedTimef()*sin2.speed)*sin2.height;
y3 = sin((float)i*sin3.freq/nbPoint+ofGetElapsedTimef()*sin3.speed)*sin3.height;
x1 = sin((float)i*sinI1.freq/nbPoint+ofGetElapsedTimef()*sinI1.speed)*sinI1.height;
x2 = sin((float)i*sinI2.freq/nbPoint+ofGetElapsedTimef()*sinI2.speed)*sinI2.height;
x3 = sin((float)i*sinI3.freq/nbPoint+ofGetElapsedTimef()*sinI3.speed)*sinI3.height;
polylines[0].addVertex((float)i/(float)nbPoint+x1+x2+x3, y1+y2+y3-posY);
}
}
void AnimatedMultiSinus::parseOSC(ofxOscMessage &m){
// string msg = m.getAddress();
// string cmd ;
//
// int ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
vector<string> osc = getOSCcmd(m.getAddress());
string cmd = osc[0];
string msg = osc[1];
if (cmd == "nbPoint"){
nbPoint = m.getArgAsInt32(0);
}
else if (cmd == "posY"){
posY = ofMap(m.getArgAsFloat(0), 0., 1., -1., 1.);
}
else if (cmd == "1"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin1.height = m.getArgAsFloat(0);
}
}
else if (cmd == "2"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin2.height = m.getArgAsFloat(0);
}
}
else if (cmd == "3"){
// ces = msg.find_first_of("/");
//
// if (ces != -1) {
// if (ces == 0){
// msg = msg.substr(ces+1);
// cmd = msg;
// ces = msg.find_first_of("/");
// if (ces != -1) {
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
// else{
// cmd = msg.substr(0, ces);
// msg = msg.substr(ces);
// }
// }
osc = getOSCcmd(msg);
cmd = osc[0];
msg = osc[1];
if (cmd == "freq"){
sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
}
else if (cmd == "speed"){
sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
}
else if (cmd == "height"){
sin3.height = m.getArgAsFloat(0);
}
}
// else if (cmd == "1/freq"){
// sin1.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "1/speed"){
// sin1.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "1/height"){
// sin1.height = m.getArgAsFloat(0);
// }
// else if (cmd == "2/freq"){
// sin2.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "2/speed"){
// sin2.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "2/height"){
// sin2.height = m.getArgAsFloat(0);
// }
// else if (cmd == "3/freq"){
// sin3.freq = ofMap(m.getArgAsFloat(0), 0., 1., 0., 500.);
// }
// else if (cmd == "3/speed"){
// sin3.speed = ofMap(m.getArgAsFloat(0), 0., 1., 0., 50.);
// }
// else if (cmd == "3/height"){
// sin3.height = m.getArgAsFloat(0);
// }
}<|endoftext|>
|
<commit_before>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"
class Sk2DPathEffectBlitter : public SkBlitter {
public:
Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
: fPE(pe), fDst(dst)
{}
virtual void blitH(int x, int y, int count)
{
fPE->nextSpan(x, y, count, fDst);
}
private:
Sk2DPathEffect* fPE;
SkPath* fDst;
};
////////////////////////////////////////////////////////////////////////////////////
Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat)
{
mat.invert(&fInverse);
}
bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width)
{
Sk2DPathEffectBlitter blitter(this, dst);
SkPath tmp;
SkIRect ir;
src.transform(fInverse, &tmp);
tmp.getBounds().round(&ir);
if (!ir.isEmpty()) {
// need to pass a clip to fillpath, required for inverse filltypes,
// even though those do not make sense for this patheffect
SkRegion clip(ir);
this->begin(ir, dst);
SkScan::FillPath(tmp, clip, &blitter);
this->end(dst);
}
return true;
}
void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path)
{
const SkMatrix& mat = this->getMatrix();
SkPoint src, dst;
src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
do {
mat.mapPoints(&dst, &src, 1);
this->next(dst, x++, y, path);
src.fX += SK_Scalar1;
} while (--count > 0);
}
void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}
////////////////////////////////////////////////////////////////////////////////
void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer)
{
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = fMatrix.flatten(storage);
buffer.write32(size);
buffer.write(storage, size);
}
Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer)
{
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = buffer.readS32();
SkASSERT(size <= sizeof(storage));
buffer.read(storage, size);
fMatrix.unflatten(storage);
fMatrix.invert(&fInverse);
}
SkFlattenable::Factory Sk2DPathEffect::getFactory()
{
return CreateProc;
}
SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer)
{
return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
: INHERITED(m), fPath(p) {
}
SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fPath.unflatten(buffer);
}
SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}
void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fPath.flatten(buffer);
}
SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
return CreateProc;
}
void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
dst->addPath(fPath, loc.fX, loc.fY);
}
static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
SkPath2DPathEffect::CreateProc);
<commit_msg>style cleanup<commit_after>
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Sk2DPathEffect.h"
#include "SkBlitter.h"
#include "SkPath.h"
#include "SkScan.h"
class Sk2DPathEffectBlitter : public SkBlitter {
public:
Sk2DPathEffectBlitter(Sk2DPathEffect* pe, SkPath* dst)
: fPE(pe), fDst(dst) {}
virtual void blitH(int x, int y, int count) {
fPE->nextSpan(x, y, count, fDst);
}
private:
Sk2DPathEffect* fPE;
SkPath* fDst;
};
///////////////////////////////////////////////////////////////////////////////
Sk2DPathEffect::Sk2DPathEffect(const SkMatrix& mat) : fMatrix(mat) {
mat.invert(&fInverse);
}
bool Sk2DPathEffect::filterPath(SkPath* dst, const SkPath& src, SkScalar* width) {
Sk2DPathEffectBlitter blitter(this, dst);
SkPath tmp;
SkIRect ir;
src.transform(fInverse, &tmp);
tmp.getBounds().round(&ir);
if (!ir.isEmpty()) {
// need to pass a clip to fillpath, required for inverse filltypes,
// even though those do not make sense for this patheffect
SkRegion clip(ir);
this->begin(ir, dst);
SkScan::FillPath(tmp, clip, &blitter);
this->end(dst);
}
return true;
}
void Sk2DPathEffect::nextSpan(int x, int y, int count, SkPath* path) {
const SkMatrix& mat = this->getMatrix();
SkPoint src, dst;
src.set(SkIntToScalar(x) + SK_ScalarHalf, SkIntToScalar(y) + SK_ScalarHalf);
do {
mat.mapPoints(&dst, &src, 1);
this->next(dst, x++, y, path);
src.fX += SK_Scalar1;
} while (--count > 0);
}
void Sk2DPathEffect::begin(const SkIRect& uvBounds, SkPath* dst) {}
void Sk2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {}
void Sk2DPathEffect::end(SkPath* dst) {}
///////////////////////////////////////////////////////////////////////////////
void Sk2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = fMatrix.flatten(storage);
buffer.write32(size);
buffer.write(storage, size);
}
Sk2DPathEffect::Sk2DPathEffect(SkFlattenableReadBuffer& buffer) {
char storage[SkMatrix::kMaxFlattenSize];
uint32_t size = buffer.readS32();
SkASSERT(size <= sizeof(storage));
buffer.read(storage, size);
fMatrix.unflatten(storage);
fMatrix.invert(&fInverse);
}
SkFlattenable::Factory Sk2DPathEffect::getFactory() {
return CreateProc;
}
SkFlattenable* Sk2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(Sk2DPathEffect, (buffer));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkPath2DPathEffect::SkPath2DPathEffect(const SkMatrix& m, const SkPath& p)
: INHERITED(m), fPath(p) {
}
SkPath2DPathEffect::SkPath2DPathEffect(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fPath.unflatten(buffer);
}
SkFlattenable* SkPath2DPathEffect::CreateProc(SkFlattenableReadBuffer& buffer) {
return SkNEW_ARGS(SkPath2DPathEffect, (buffer));
}
void SkPath2DPathEffect::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
fPath.flatten(buffer);
}
SkFlattenable::Factory SkPath2DPathEffect::getFactory() {
return CreateProc;
}
void SkPath2DPathEffect::next(const SkPoint& loc, int u, int v, SkPath* dst) {
dst->addPath(fPath, loc.fX, loc.fY);
}
static SkFlattenable::Registrar gReg("SkPath2DPathEffect",
SkPath2DPathEffect::CreateProc);
<|endoftext|>
|
<commit_before>#pragma once
#include "../utilmacro.hpp"
#include <iosfwd>
#include <string>
#include <vector>
namespace nip::error {
enum _Error_Type : uint8_t { NOTE, WARNING, ERROR, FATAL_ERROR };
struct _Error {
_Error(_Error_Type type_i, const char* msg_i, size_t ll = 0, size_t lc = 0, bool hl = false)
: msg(msg_i), loc_line(ll), loc_char(lc), has_location(hl), type(type_i) {}
std::string msg;
size_t loc_line;
size_t loc_char;
bool has_location;
_Error_Type type;
};
class Error_Handler {
public:
ALWAYS_INLINE void add_error(_Error_Type type, const char* msg, size_t ll = 0,
size_t lc = 0, bool hl = false);
void print_errors(std::ostream&);
Error_Handler(){};
Error_Handler(std::vector<std::string>&& source) : source_file(source){};
void set_source(std::vector<std::string>&& source) {
source_file = source;
};
private:
void sort();
std::vector<_Error> error_list;
std::vector<std::string> source_file;
bool has_note = false;
bool has_warning = false;
bool has_error = false;
bool has_fatal = false;
bool sorted = false;
};
}
ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, const char* msg,
size_t ll, size_t lc, bool hl) {
error_list.emplace_back(type, msg, ll, lc, hl);
switch (type) {
case NOTE:
has_note = true;
break;
case WARNING:
has_warning = true;
break;
case ERROR:
has_error = true;
break;
case FATAL_ERROR:
has_fatal = true;
break;
}
}<commit_msg>Add wrapper function to add an error with a string<commit_after>#pragma once
#include "../utilmacro.hpp"
#include <iosfwd>
#include <string>
#include <vector>
namespace nip::error {
enum _Error_Type : uint8_t { NOTE, WARNING, ERROR, FATAL_ERROR };
struct _Error {
_Error(_Error_Type type_i, const char* msg_i, size_t ll = 0, size_t lc = 0, bool hl = false)
: msg(msg_i), loc_line(ll), loc_char(lc), has_location(hl), type(type_i) {}
std::string msg;
size_t loc_line;
size_t loc_char;
bool has_location;
_Error_Type type;
};
class Error_Handler {
public:
ALWAYS_INLINE void add_error(_Error_Type type, std::string& msg, size_t ll = 0,
size_t lc = 0, bool hl = false);
ALWAYS_INLINE void add_error(_Error_Type type, const char* msg, size_t ll = 0,
size_t lc = 0, bool hl = false);
void print_errors(std::ostream&);
Error_Handler(){};
Error_Handler(std::vector<std::string>&& source) : source_file(source){};
void set_source(std::vector<std::string>&& source) {
source_file = source;
};
private:
void sort();
std::vector<_Error> error_list;
std::vector<std::string> source_file;
bool has_note = false;
bool has_warning = false;
bool has_error = false;
bool has_fatal = false;
bool sorted = false;
};
}
ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, std::string& msg,
size_t ll, size_t lc, bool hl) {
add_error(type, msg.data(), ll, lc, hl);
}
ALWAYS_INLINE void nip::error::Error_Handler::add_error(_Error_Type type, const char* msg,
size_t ll, size_t lc, bool hl) {
error_list.emplace_back(type, msg, ll, lc, hl);
switch (type) {
case NOTE:
has_note = true;
break;
case WARNING:
has_warning = true;
break;
case ERROR:
has_error = true;
break;
case FATAL_ERROR:
has_fatal = true;
break;
}
}<|endoftext|>
|
<commit_before>#ifndef PLATE2D_HPP
#define PLATE2D_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/datetime.h>
#include <vector>
#include <functional>
#include "Plater.hpp"
#include "ColorScheme.hpp"
#include "Settings.hpp"
#include "Plater/PlaterObject.hpp"
#include "misc_ui.hpp"
#include "Log.hpp"
namespace Slic3r { namespace GUI {
// Setup for an Easter Egg with the canvas text.
const wxDateTime today_date {wxDateTime().GetDateOnly()};
const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};
const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};
enum class MoveDirection {
Up, Down, Left, Right
};
/// simple POD to make referencing this pair of identifiers easy
struct InstanceIdx {
long obj;
long inst;
};
class Plate2D : public wxPanel {
public:
Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);
/// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.
void update_bed_size();
std::function<void (const unsigned int obj_idx)> on_select_object {};
std::function<void ()> on_double_click {};
/// Do something on right-clicks.
std::function<void (const wxPoint& pos)> on_right_click {};
std::function<void ()> on_instances_moved {};
void set_selected (long obj, long inst) { this->selected_instance = {obj, inst}; }
private:
std::vector<PlaterObject>& objects; //< reference to parent vector
std::shared_ptr<Slic3r::Model> model;
std::shared_ptr<Slic3r::Config> config;
std::shared_ptr<Settings> settings;
// Different brushes to draw with, initialized from settings->Color during the constructor
wxBrush objects_brush {};
wxBrush instance_brush {};
wxBrush selected_brush {};
wxBrush bed_brush {};
wxBrush dragged_brush {};
wxBrush transparent_brush {};
wxPen grid_pen {};
wxPen print_center_pen {};
wxPen clearance_pen {};
wxPen skirt_pen {};
wxPen dark_pen {};
bool user_drawn_background {(the_os == OS::Mac ? false : true)};
/// The object id and selected
InstanceIdx selected_instance {-1, -1};
InstanceIdx drag_object {-1, -1};
/// Handle mouse-move events
void mouse_drag(wxMouseEvent& e);
void mouse_down(wxMouseEvent& e);
void mouse_up(wxMouseEvent& e);
void mouse_dclick(wxMouseEvent& e);
wxPoint drag_start_pos {wxPoint(-1, -1)};
/// Handle repaint events
void repaint(wxPaintEvent& e);
void nudge_key(wxKeyEvent& e);
void nudge(MoveDirection dir);
/// Set/Update all of the colors used by the various brushes in the panel.
void set_colors();
/// Convert a scale point array to a pixel polygon suitable for DrawPolygon
std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);
std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);
/// For a specific point, unscale it relative to the origin
wxPoint unscaled_point_to_pixel(const wxPoint& in);
/// Displacement needed to center bed.
wxPoint bed_origin {};
/// private class variables to stash bits for drawing the print bed area.
wxRealPoint print_center {};
Slic3r::Polygon bed_polygon {};
std::vector<wxPoint> grid {};
/// Set up the 2D canvas blank canvas text.
/// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.
const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") };
/// How much to scale the points to fit in the draw bounding box area.
/// Expressed as pixel / mm
double scaling_factor {1.0};
const std::string LogChannel {"GUI_2D"};
Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {
const auto& zero {this->bed_origin};
return Slic3r::Point(
scale_(x - zero.x) / this->scaling_factor,
scale_(zero.y - y) / this->scaling_factor
);
}
Slic3r::Point point_to_model_units(const wxPoint& pt) {
return this->point_to_model_units(pt.x, pt.y);
}
Slic3r::Point point_to_model_units(const Pointf& pt) {
return this->point_to_model_units(pt.x, pt.y);
}
/// Remove all instance thumbnails.
void clean_instance_thumbnails();
};
} } // Namespace Slic3r::GUI
#endif // PLATE2D_HPP
<commit_msg>Use wxDateTime::Now() to initialze current date instead of default constructor (avoid runtime errors)<commit_after>#ifndef PLATE2D_HPP
#define PLATE2D_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/datetime.h>
#include <vector>
#include <functional>
#include "Plater.hpp"
#include "ColorScheme.hpp"
#include "Settings.hpp"
#include "Plater/PlaterObject.hpp"
#include "misc_ui.hpp"
#include "Log.hpp"
namespace Slic3r { namespace GUI {
// Setup for an Easter Egg with the canvas text.
const wxDateTime today_date {wxDateTime::Now()};
const wxDateTime special_date {13, wxDateTime::Month::Sep, 2006, 0, 0, 0, 0};
const bool today_is_special = {today_date.GetDay() == special_date.GetDay() && today_date.GetMonth() == special_date.GetMonth()};
enum class MoveDirection {
Up, Down, Left, Right
};
/// simple POD to make referencing this pair of identifiers easy
struct InstanceIdx {
long obj;
long inst;
};
class Plate2D : public wxPanel {
public:
Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings);
/// Read print bed size from config and calculate the scaled rendition of the bed given the draw canvas.
void update_bed_size();
std::function<void (const unsigned int obj_idx)> on_select_object {};
std::function<void ()> on_double_click {};
/// Do something on right-clicks.
std::function<void (const wxPoint& pos)> on_right_click {};
std::function<void ()> on_instances_moved {};
void set_selected (long obj, long inst) { this->selected_instance = {obj, inst}; }
private:
std::vector<PlaterObject>& objects; //< reference to parent vector
std::shared_ptr<Slic3r::Model> model;
std::shared_ptr<Slic3r::Config> config;
std::shared_ptr<Settings> settings;
// Different brushes to draw with, initialized from settings->Color during the constructor
wxBrush objects_brush {};
wxBrush instance_brush {};
wxBrush selected_brush {};
wxBrush bed_brush {};
wxBrush dragged_brush {};
wxBrush transparent_brush {};
wxPen grid_pen {};
wxPen print_center_pen {};
wxPen clearance_pen {};
wxPen skirt_pen {};
wxPen dark_pen {};
bool user_drawn_background {(the_os == OS::Mac ? false : true)};
/// The object id and selected
InstanceIdx selected_instance {-1, -1};
InstanceIdx drag_object {-1, -1};
/// Handle mouse-move events
void mouse_drag(wxMouseEvent& e);
void mouse_down(wxMouseEvent& e);
void mouse_up(wxMouseEvent& e);
void mouse_dclick(wxMouseEvent& e);
wxPoint drag_start_pos {wxPoint(-1, -1)};
/// Handle repaint events
void repaint(wxPaintEvent& e);
void nudge_key(wxKeyEvent& e);
void nudge(MoveDirection dir);
/// Set/Update all of the colors used by the various brushes in the panel.
void set_colors();
/// Convert a scale point array to a pixel polygon suitable for DrawPolygon
std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);
std::vector<wxPoint> scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale);
/// For a specific point, unscale it relative to the origin
wxPoint unscaled_point_to_pixel(const wxPoint& in);
/// Displacement needed to center bed.
wxPoint bed_origin {};
/// private class variables to stash bits for drawing the print bed area.
wxRealPoint print_center {};
Slic3r::Polygon bed_polygon {};
std::vector<wxPoint> grid {};
/// Set up the 2D canvas blank canvas text.
/// Easter egg: Sept. 13, 2006. The first part ever printed by a RepRap to make another RepRap.
const wxString CANVAS_TEXT { today_is_special ? _(L"What do you want to print today?™") : _("Drag your objects here") };
/// How much to scale the points to fit in the draw bounding box area.
/// Expressed as pixel / mm
double scaling_factor {1.0};
const std::string LogChannel {"GUI_2D"};
Slic3r::Point point_to_model_units(coordf_t x, coordf_t y) {
const auto& zero {this->bed_origin};
return Slic3r::Point(
scale_(x - zero.x) / this->scaling_factor,
scale_(zero.y - y) / this->scaling_factor
);
}
Slic3r::Point point_to_model_units(const wxPoint& pt) {
return this->point_to_model_units(pt.x, pt.y);
}
Slic3r::Point point_to_model_units(const Pointf& pt) {
return this->point_to_model_units(pt.x, pt.y);
}
/// Remove all instance thumbnails.
void clean_instance_thumbnails();
};
} } // Namespace Slic3r::GUI
#endif // PLATE2D_HPP
<|endoftext|>
|
<commit_before>/*
This file is part of KContactManager.
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "contacteditordialog.h"
#include "kabc/kabcitemeditor.h"
#include "collectioncombobox.h"
#include <akonadi/item.h>
#include <klocale.h>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
ContactEditorDialog::ContactEditorDialog( Mode mode, QAbstractItemModel *collectionModel, QWidget *parent )
: KDialog( parent )
{
setCaption( mode == CreateMode ? i18n( "New Contact" ) : i18n( "Edit Contact" ) );
setButtons( Ok | Cancel );
QWidget *mainWidget = new QWidget( this );
setMainWidget( mainWidget );
QGridLayout *layout = new QGridLayout( mainWidget );
mEditor = new Akonadi::KABCItemEditor( mode == CreateMode ? Akonadi::KABCItemEditor::CreateMode : Akonadi::KABCItemEditor::EditMode, this );
if ( mode == CreateMode ) {
QLabel *label = new QLabel( i18n( "Add to:" ), mainWidget );
KABC::CollectionComboBox *box = new KABC::CollectionComboBox( mainWidget );
if ( collectionModel )
box->setModel( collectionModel );
layout->addWidget( label, 0, 0 );
layout->addWidget( box, 0, 1 );
connect( box, SIGNAL( selectionChanged( const Akonadi::Collection& ) ),
mEditor, SLOT( setDefaultCollection( const Akonadi::Collection& ) ) );
}
layout->addWidget( mEditor, 1, 0, 1, 2 );
layout->setColumnStretch( 1, 1 );
connect( mEditor, SIGNAL( contactStored( const Akonadi::Item& ) ),
this, SIGNAL( contactStored( const Akonadi::Item& ) ) );
connect( this, SIGNAL( okClicked() ), this, SLOT( slotOkClicked() ) );
connect( this, SIGNAL( cancelClicked() ), this, SLOT( slotCancelClicked() ) );
}
ContactEditorDialog::~ContactEditorDialog()
{
}
void ContactEditorDialog::setContact( const Akonadi::Item &contact )
{
mEditor->loadContact( contact );
}
void ContactEditorDialog::slotOkClicked()
{
mEditor->saveContact();
accept();
}
void ContactEditorDialog::slotCancelClicked()
{
reject();
}
#include "contacteditordialog.moc"
<commit_msg>Sets the initial collection<commit_after>/*
This file is part of KContactManager.
Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "contacteditordialog.h"
#include "kabc/kabcitemeditor.h"
#include "collectioncombobox.h"
#include <akonadi/item.h>
#include <klocale.h>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
ContactEditorDialog::ContactEditorDialog( Mode mode, QAbstractItemModel *collectionModel, QWidget *parent )
: KDialog( parent )
{
setCaption( mode == CreateMode ? i18n( "New Contact" ) : i18n( "Edit Contact" ) );
setButtons( Ok | Cancel );
QWidget *mainWidget = new QWidget( this );
setMainWidget( mainWidget );
QGridLayout *layout = new QGridLayout( mainWidget );
mEditor = new Akonadi::KABCItemEditor( mode == CreateMode ? Akonadi::KABCItemEditor::CreateMode : Akonadi::KABCItemEditor::EditMode, this );
if ( mode == CreateMode ) {
QLabel *label = new QLabel( i18n( "Add to:" ), mainWidget );
KABC::CollectionComboBox *box = new KABC::CollectionComboBox( mainWidget );
if ( collectionModel )
box->setModel( collectionModel );
layout->addWidget( label, 0, 0 );
layout->addWidget( box, 0, 1 );
connect( box, SIGNAL( selectionChanged( const Akonadi::Collection& ) ),
mEditor, SLOT( setDefaultCollection( const Akonadi::Collection& ) ) );
mEditor->setDefaultCollection( box->selectedCollection() );
}
layout->addWidget( mEditor, 1, 0, 1, 2 );
layout->setColumnStretch( 1, 1 );
connect( mEditor, SIGNAL( contactStored( const Akonadi::Item& ) ),
this, SIGNAL( contactStored( const Akonadi::Item& ) ) );
connect( this, SIGNAL( okClicked() ), this, SLOT( slotOkClicked() ) );
connect( this, SIGNAL( cancelClicked() ), this, SLOT( slotCancelClicked() ) );
}
ContactEditorDialog::~ContactEditorDialog()
{
}
void ContactEditorDialog::setContact( const Akonadi::Item &contact )
{
mEditor->loadContact( contact );
}
void ContactEditorDialog::slotOkClicked()
{
mEditor->saveContact();
accept();
}
void ContactEditorDialog::slotCancelClicked()
{
reject();
}
#include "contacteditordialog.moc"
<|endoftext|>
|
<commit_before>#include "Input/InputHandler.hpp"
#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
InputHandler::InputHandler(sf::RenderWindow *window)
: m_window{window}
, m_lastMousePos{ 0, 0 }
, m_rightMouseClickState{ 0 }
{
}
void InputHandler::handleInput(QueueHelper<Input> &inputQueue)
{
handleEvents(inputQueue);
handleRealTimeInput(inputQueue);
}
void InputHandler::handleEvents(QueueHelper<Input> &inputQueue)
{
sf::Event event;
while (m_window->pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
m_window->close();
}
else if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
m_window->setView(sf::View(visibleArea));
}
else if (event.type == sf::Event::LostFocus)
{
// Do nothing at the moment
}
else if (event.type == sf::Event::GainedFocus)
{
// Do nothing at the moment
}
else if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::F1)
{
inputQueue.push({ InputTypes::D1 });
}
else if (event.key.code == sf::Keyboard::F2)
{
inputQueue.push({ InputTypes::D2 });
}
else if (event.key.code == sf::Keyboard::F3)
{
inputQueue.push({ InputTypes::D3 });
}
else if (event.key.code == sf::Keyboard::F4)
{
inputQueue.push({ InputTypes::D4 });
}
}
else if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
inputQueue.push({ InputTypes::LEFT_CLICK });
}
}
}
}
void InputHandler::handleRealTimeInput(QueueHelper<Input> &inputQueue)
{
const sf::Vector2i CurrentMousePos = { sf::Mouse::getPosition(*m_window) };
inputQueue.push({ InputTypes::CURSOR_POS, static_cast<sf::Vector2f>(CurrentMousePos) });
/*
if (CurrentMousePos != m_lastMousePos)
{
const sf::Vector2i WindowCenter(static_cast<int>(m_window->getSize().x / 2), static_cast<int>(m_window->getSize().y / 2));
const sf::Vector2i TranslatedMousePos = { CurrentMousePos - WindowCenter };
const sf::Vector2f TranslatedMousePosF(static_cast<sf::Vector2f>(TranslatedMousePos));
inputQueue.push({ InputTypes::TRANSLATED_CURSOR_POS, TranslatedMousePosF });
}
*/
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::UP_LEFT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::UP_RIGHT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::DOWN_LEFT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::DOWN_RIGHT });
}
// Dont handle W A S D separately, when there are pairs like W+A or W+D or S+A or S+D
else
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
inputQueue.push({ InputTypes::UP });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
inputQueue.push({ InputTypes::DOWN });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::LEFT });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::RIGHT });
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
inputQueue.push({ InputTypes::UP_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
inputQueue.push({ InputTypes::DOWN_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
inputQueue.push({ InputTypes::LEFT_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
inputQueue.push({ InputTypes::RIGHT_A });
}
handleRealTimeRightClick(inputQueue);
m_lastMousePos.x = CurrentMousePos.x;
m_lastMousePos.y = CurrentMousePos.y;
}
void InputHandler::handleRealTimeRightClick(QueueHelper<Input> &inputQueue)
{
bool isPressed = { sf::Mouse::isButtonPressed(sf::Mouse::Right) };
// Left mouse key was not pressed and is not pressed (start pressing)
if (isPressed && m_rightMouseClickState == 0)
{
m_rightMouseClickState = 1;
inputQueue.push({ InputTypes::RIGHT_CLICK_START });
}
// Left mouse key was pressed and is still pressed (still pressing)
else if (isPressed && m_rightMouseClickState == 1)
{
m_rightMouseClickState = 2;
inputQueue.push({ InputTypes::RIGHT_CLICK_STILL });
}
// Left mouse key was pressed and is not pressed anymore(stop pressing)
else if (!isPressed && m_rightMouseClickState == 2)
{
m_rightMouseClickState = 3;
inputQueue.push({ InputTypes::RIGHT_CLICK_STOPED });
}
// Left mouse key was not pressed and is not pressed at the moment
else if (!isPressed && m_rightMouseClickState == 3)
{
m_rightMouseClickState = 0;
}
}
<commit_msg>Add window resize functionality<commit_after>#include "Input/InputHandler.hpp"
#include <SFML/Graphics.hpp>
#include <cmath>
#include <iostream>
InputHandler::InputHandler(sf::RenderWindow *window)
: m_window{window}
, m_lastMousePos{ 0, 0 }
, m_rightMouseClickState{ 0 }
{
}
void InputHandler::handleInput(QueueHelper<Input> &inputQueue)
{
handleEvents(inputQueue);
handleRealTimeInput(inputQueue);
}
void InputHandler::handleEvents(QueueHelper<Input> &inputQueue)
{
sf::Event event;
while (m_window->pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
m_window->close();
}
else if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
sf::View view(visibleArea);
//view.zoom(0.5f);
m_window->setView(view);
}
else if (event.type == sf::Event::LostFocus)
{
// Do nothing at the moment
}
else if (event.type == sf::Event::GainedFocus)
{
// Do nothing at the moment
}
else if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::F1)
{
inputQueue.push({ InputTypes::D1 });
}
else if (event.key.code == sf::Keyboard::F2)
{
inputQueue.push({ InputTypes::D2 });
}
else if (event.key.code == sf::Keyboard::F3)
{
inputQueue.push({ InputTypes::D3 });
}
else if (event.key.code == sf::Keyboard::F4)
{
inputQueue.push({ InputTypes::D4 });
}
}
else if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
inputQueue.push({ InputTypes::LEFT_CLICK });
}
}
}
}
void InputHandler::handleRealTimeInput(QueueHelper<Input> &inputQueue)
{
const sf::Vector2i CurrentMousePos = { sf::Mouse::getPosition(*m_window) };
inputQueue.push({ InputTypes::CURSOR_POS, static_cast<sf::Vector2f>(CurrentMousePos) });
/*
if (CurrentMousePos != m_lastMousePos)
{
const sf::Vector2i WindowCenter(static_cast<int>(m_window->getSize().x / 2), static_cast<int>(m_window->getSize().y / 2));
const sf::Vector2i TranslatedMousePos = { CurrentMousePos - WindowCenter };
const sf::Vector2f TranslatedMousePosF(static_cast<sf::Vector2f>(TranslatedMousePos));
inputQueue.push({ InputTypes::TRANSLATED_CURSOR_POS, TranslatedMousePosF });
}
*/
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::UP_LEFT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::W) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::UP_RIGHT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::DOWN_LEFT });
}
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::DOWN_RIGHT });
}
// Dont handle W A S D separately, when there are pairs like W+A or W+D or S+A or S+D
else
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
inputQueue.push({ InputTypes::UP });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
inputQueue.push({ InputTypes::DOWN });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
inputQueue.push({ InputTypes::LEFT });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
inputQueue.push({ InputTypes::RIGHT });
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
inputQueue.push({ InputTypes::UP_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
inputQueue.push({ InputTypes::DOWN_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
inputQueue.push({ InputTypes::LEFT_A });
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
inputQueue.push({ InputTypes::RIGHT_A });
}
handleRealTimeRightClick(inputQueue);
m_lastMousePos.x = CurrentMousePos.x;
m_lastMousePos.y = CurrentMousePos.y;
}
void InputHandler::handleRealTimeRightClick(QueueHelper<Input> &inputQueue)
{
bool isPressed = { sf::Mouse::isButtonPressed(sf::Mouse::Right) };
// Left mouse key was not pressed and is not pressed (start pressing)
if (isPressed && m_rightMouseClickState == 0)
{
m_rightMouseClickState = 1;
inputQueue.push({ InputTypes::RIGHT_CLICK_START });
}
// Left mouse key was pressed and is still pressed (still pressing)
else if (isPressed && m_rightMouseClickState == 1)
{
m_rightMouseClickState = 2;
inputQueue.push({ InputTypes::RIGHT_CLICK_STILL });
}
// Left mouse key was pressed and is not pressed anymore(stop pressing)
else if (!isPressed && m_rightMouseClickState == 2)
{
m_rightMouseClickState = 3;
inputQueue.push({ InputTypes::RIGHT_CLICK_STOPED });
}
// Left mouse key was not pressed and is not pressed at the moment
else if (!isPressed && m_rightMouseClickState == 3)
{
m_rightMouseClickState = 0;
}
}
<|endoftext|>
|
<commit_before>// GradMinimizer: test RooGradMinimizer class
//
// call from command line like, for instance:
// root -l 'GradMinimizer.cpp()'
// R__LOAD_LIBRARY(libRooFit)
#include <iostream>
// #include <exception>
using namespace RooFit;
void GradMinimizer() {
// produce the same random stuff every time
gRandom->SetSeed(1);
RooWorkspace w = RooWorkspace();
w.factory("Gaussian::g(x[-5,5],mu[-3,3],sigma[1])");
auto x = w.var("x");
RooAbsPdf * pdf = w.pdf("g");
RooRealVar * mu = w.var("mu");
RooDataSet * data = pdf->generate(RooArgSet(*x), 10000);
mu->setVal(-2.9);
auto nll = pdf->createNLL(*data);
// save initial values for the start of all minimizations
RooArgSet values = RooArgSet(*mu, *pdf, *nll);
RooArgSet* savedValues = dynamic_cast<RooArgSet*>(values.snapshot());
if (savedValues == nullptr) {
throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!");
}
// --------
RooWallTimer wtimer;
// RooCPUTimer ctimer
// --------
std::cout << "trying nominal calculation" << std::endl;
RooMinimizer m0(*nll);
m0.setMinimizerType("Minuit2");
m0.setStrategy(0);
// m0.setVerbose();
m0.setPrintLevel(0);
wtimer.start();
m0.migrad();
wtimer.stop();
std::cout << " -- nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// m0.hesse();
// m0.minos();
// --------
std::cout << "\n === reset initial values === \n" << std::endl;
values = *savedValues;
// --------
std::cout << "trying GradMinimizer" << std::endl;
RooGradMinimizer m1(*nll);
m1.setStrategy(0);
// m1.setVerbose();
m1.setPrintLevel(0);
wtimer.start();
m1.migrad();
wtimer.stop();
std::cout << " -- GradMinimizer calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// std::cout << "run hesse" << std::endl;
// m1.hesse();
// std::cout << "hesse done" << std::endl;
// m1.minos();
// std::cout << "minos done" << std::endl;
// std::cout << std::endl << std::endl;
// values.Print("v");
// mu->Print("v");
// std::cout << std::endl << std::endl;
// --------
std::cout << "\n === reset initial values === \n" << std::endl;
values = *savedValues;
// --------
std::cout << "trying nominal calculation AGAIN" << std::endl;
RooMinimizer m2(*nll);
m2.setMinimizerType("Minuit2");
m2.setStrategy(0);
// m2.setVerbose();
m2.setPrintLevel(0);
wtimer.start();
m2.migrad();
wtimer.stop();
std::cout << " -- second nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// m2.hesse();
// m2.minos();
}
<commit_msg>Small modifications<commit_after>// GradMinimizer: test RooGradMinimizer class
//
// call from command line like, for instance:
// root -l 'GradMinimizer.cpp()'
// R__LOAD_LIBRARY(libRooFit)
#pragma cling load("libRooFit")
#include <iostream>
// #include <exception>
using namespace RooFit;
void GradMinimizer() {
// produce the same random stuff every time
gRandom->SetSeed(1);
RooWorkspace w = RooWorkspace();
w.factory("Gaussian::g(x[-5,5],mu[0,-3,3],sigma[1])");
auto x = w.var("x");
RooAbsPdf * pdf = w.pdf("g");
RooRealVar * mu = w.var("mu");
RooDataSet * data = pdf->generate(RooArgSet(*x), 10000);
mu->setVal(-2.9);
// mu->setError(0.1);
auto nll = pdf->createNLL(*data);
// save initial values for the start of all minimizations
RooArgSet values = RooArgSet(*mu, *pdf, *nll);
RooArgSet* savedValues = dynamic_cast<RooArgSet*>(values.snapshot());
if (savedValues == nullptr) {
throw std::runtime_error("params->snapshot() cannot be casted to RooArgSet!");
}
// --------
RooWallTimer wtimer;
// RooCPUTimer ctimer
// --------
std::cout << "trying nominal calculation" << std::endl;
RooMinimizer m0(*nll);
m0.setMinimizerType("Minuit2");
m0.setStrategy(0);
// m0.setVerbose();
m0.setPrintLevel(0);
wtimer.start();
m0.migrad();
wtimer.stop();
std::cout << " -- nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// m0.hesse();
// m0.minos();
std::cout << " ====================================== " << std::endl;
// --------
std::cout << " ======== reset initial values ======== " << std::endl;
values = *savedValues;
// --------
std::cout << " ====================================== " << std::endl;
std::cout << "trying GradMinimizer" << std::endl;
RooGradMinimizer m1(*nll);
m1.setStrategy(0);
// m1.setVerbose();
m1.setPrintLevel(0);
wtimer.start();
m1.migrad();
wtimer.stop();
std::cout << " -- GradMinimizer calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// std::cout << "run hesse" << std::endl;
// m1.hesse();
// std::cout << "hesse done" << std::endl;
// m1.minos();
// std::cout << "minos done" << std::endl;
// std::cout << std::endl << std::endl;
// values.Print("v");
// mu->Print("v");
// std::cout << std::endl << std::endl;
// --------
// std::cout << "\n === reset initial values === \n" << std::endl;
// values = *savedValues;
// // --------
// std::cout << "trying nominal calculation AGAIN" << std::endl;
// RooMinimizer m2(*nll);
// m2.setMinimizerType("Minuit2");
// m2.setStrategy(0);
// // m2.setVerbose();
// m2.setPrintLevel(0);
// wtimer.start();
// m2.migrad();
// wtimer.stop();
// std::cout << " -- second nominal calculation wall clock time: " << wtimer.timing_s() << "s" << std::endl;
// m2.hesse();
// m2.minos();
}
<|endoftext|>
|
<commit_before>/*
The MIT License
Copyright (c) 2010 Department Image Processing,
Fraunhofer ITWM.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file IASSConverter.cpp
\author Andre Liebscher
Department Image Processing
Fraunhofer ITWM
\date March 2010
*/
#include <cctype>
#include <cstring>
#include <fstream>
#include <sstream>
#include "boost/cstdint.hpp"
#include "3rdParty/zlib/zlib.h"
#include "IASSConverter.h"
#include <Basics/EndianConvert.h>
#include <Controller/Controller.h>
using namespace std;
using namespace tuvok;
IASSConverter::IASSConverter()
{
m_vConverterDesc = "Fraunhofer MAVI Volume";
m_vSupportedExt.push_back("IASS");
m_vSupportedExt.push_back("IASS.GZ");
}
bool
IASSConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string& strTempDir,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert IASS dataset %s", strSourceFilename.c_str());
// Find out machine endianess
bConvertEndianess = EndianConvert::IsBigEndian();
// Check whether file is compressed and uncompress if necessary
string strInputFile;
if (IsZipped(strSourceFilename)) {
MESSAGE("IASS data is GZIP compressed.");
strInputFile = strTempDir + SysTools::GetFilename(strSourceFilename) +
".uncompressed";
if (!ExtractGZIPDataset(strSourceFilename, strInputFile, 0)) {
WARNING("Error while decompressing %s", strSourceFilename.c_str());
return false;
}
} else {
strInputFile = strSourceFilename;
}
// Read header and check for "magic" values of the IASS file
stHeader header;
ifstream fileData(strInputFile.c_str());
if (fileData.is_open()) {
if(!ReadHeader(header,fileData)) {
WARNING("The file %s is not a IASS file (missing magic)",
strInputFile.c_str());
return false;
}
} else {
WARNING("Could not open IASS file %s", strInputFile.c_str());
return false;
}
fileData.close();
// Init data
strTitle = "Fraunhofer MAVI Volume";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
iComponentCount = 1;
vVolumeSize[0] = header.size.x;
vVolumeSize[1] = header.size.y;
vVolumeSize[2] = header.size.z;
iComponentSize = header.bpp*8;
iHeaderSkip = 0;
bDeleteIntermediateFile = true;
if (header.type >= MONO && header.type <= GREY_32) {
bSigned = false;
bIsFloat = false;
} else if (header.type == GREY_F) {
bSigned = true;
bIsFloat = true;
} else if (header.type == COLOR) {
bSigned = false;
bIsFloat = false;
iComponentCount = 3;
} else {
T_ERROR("Unsupported image type in file %s", strInputFile.c_str());
return false;
}
// Convert raw data to x-locality and decode MONO files
LargeRAWFile zLocalData(strInputFile, header.skip);
zLocalData.Open(false);
if (!zLocalData.IsOpen()) {
T_ERROR("Unable to open source file %s", strInputFile.c_str());
return false;
}
strIntermediateFile = strTempDir + SysTools::GetFilename(strSourceFilename)
+ ".x-local";
LargeRAWFile xLocalData(strIntermediateFile);
xLocalData.Create();
if (!xLocalData.IsOpen()) {
T_ERROR("Unable to open temp file %s for locality conversion",
strIntermediateFile.c_str());
xLocalData.Close();
return false;
}
UINT64 strideZ = header.size.x*header.size.y*header.bpp-header.bpp;
UINT64 sliceSize = header.size.y * header.size.z * header.bpp;
unsigned char* sliceBuffer = new unsigned char[static_cast<size_t>(sliceSize)];
if (header.type == MONO) {
unsigned char* rleBuffer = new unsigned char[static_cast<size_t>(header.rleLength)];
zLocalData.ReadRAW(rleBuffer,header.rleLength);
UINT64 posRLEStream = 0;
UINT64 posOutStream = 0;
UINT64 currLength = *rleBuffer;
UINT64 sliceIndex = 0;
UINT64 currValue = 1;
do {
// This loop is entered if another pixel run would exceed the size of
// the slice buffer
while (posOutStream + currLength >= sliceSize) {
// How many pixels are left to fill up buffer
UINT64 restLength = sliceSize - posOutStream;
// Set these remaining pixels
memset(&sliceBuffer[posOutStream],
static_cast<unsigned char>((currValue%2)*0xff), static_cast<size_t>(restLength));
for (UINT64 y = 0; y < header.size.y; y++) {
xLocalData.SeekPos(y*header.size.x+sliceIndex);
for (UINT64 z = 0; z < header.size.z; z++) {
xLocalData.WriteRAW(&sliceBuffer[y*header.size.z+z],1);
xLocalData.SeekPos(xLocalData.GetPos()+strideZ);
}
}
currLength -= restLength;
posOutStream = 0;
sliceIndex++;
}
// Set pixels of required length
if (currLength > 0) {
memset(&sliceBuffer[posOutStream],
static_cast<unsigned char>((currValue%2)*0xff), static_cast<size_t>(currLength));
posOutStream += currLength;
}
currValue++;
posRLEStream++;
currLength = *(rleBuffer + posRLEStream);
} while (posRLEStream < header.rleLength);
delete[] rleBuffer;
} else {
for (UINT64 x = 0; x < header.size.x; x++) {
zLocalData.ReadRAW(sliceBuffer,sliceSize);
for (UINT64 y = 0; y < header.size.y; y++) {
xLocalData.SeekPos((y*header.size.x+x)*header.bpp);
for (UINT64 z = 0; z < header.size.z; z++) {
xLocalData.WriteRAW(&sliceBuffer[(y*header.size.z+z)*header.bpp],
header.bpp);
xLocalData.SeekPos(xLocalData.GetPos()+strideZ);
}
}
}
}
delete[] sliceBuffer;
if ( strInputFile != strSourceFilename )
Remove(strInputFile, Controller::Debug::Out());
return true;
}
// unimplemented!
bool
IASSConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINT64VECTOR3,
FLOATVECTOR3,
bool,
bool)
{
return false;
}
bool
IASSConverter::CanRead(const std::string& fn,
const std::vector<int8_t>&) const
{
std::string ext = SysTools::GetExt(fn);
std::transform(ext.begin(), ext.end(), ext.begin(),
(int(*)(int))std::toupper);
if (ext != "IASS") {
std::string extPt1 = SysTools::GetExt(SysTools::RemoveExt(fn));
std::transform(extPt1.begin(), extPt1.end(), extPt1.begin(),
(int(*)(int))std::toupper);
ext = extPt1 + "." + ext;
}
return SupportedExtension(ext);
}
bool
IASSConverter::IsZipped(const std::string& strFile)
{
gzFile file = gzopen(strFile.c_str(), "rb");
if (file==0)
return false;
int rt = gzdirect(file);
gzclose(file);
return rt == 1 ? false : true;
}
IASSConverter::stHeader::stHeader()
: type(INVALID), bpp(0), skip(0), rleLength(0), size(), spacing(),
creator(""), history("") {}
void
IASSConverter::stHeader::Reset()
{
type = INVALID;
bpp = 0;
skip = 0;
rleLength = 0;
size.x = 0;
size.y = 0;
size.z = 0;
spacing.x = 0.0;
spacing.y = 0.0;
spacing.z = 0.0;
creator = "";
history = "";
}
bool
IASSConverter::ReadHeader(stHeader& header, std::istream& inputStream)
{
header.Reset();
if(!inputStream.good())
return false;
std::string strLine;
// read magic
getline(inputStream, strLine);
if (!(strLine.substr(0, 9) == "SVstatmat" ||
strLine.substr(0, 4) == "a4iL") ||
inputStream.fail()) {
return false;
}
// read header
do {
getline(inputStream, strLine);
if (inputStream.fail())
return false;
if (strLine.substr(0, 11) == "# SPACING: ") {
std::istringstream in(strLine.substr(11, strLine.length()));
in >> header.spacing.x >> header.spacing.y >> header.spacing.z;
}
else if (strLine.substr(0, 11) == "# CREATOR: ")
header.creator = strLine.substr(11, strLine.length());
else if (strLine.substr(0, 11) == "# HISTORY: ")
header.history = strLine.substr(11, strLine.length());
else if (strLine.substr(0, 8) == "# TYPE: ") {
if (isdigit(strLine[8])) {
std::string tmp = strLine.substr(8, strLine.length());
std::istringstream input_helper(tmp);
unsigned int type;
input_helper >> type;
header.type = static_cast<ePixelType>(type);
if (header.type < 0 || header.type >= INVALID)
return false;
} else {
if (strLine.substr(8, strLine.length()) == "MONO") {
header.type = MONO;
} else if (strLine.substr(8, strLine.length()) == "GREY_8") {
header.type = GREY_8;
} else if (strLine.substr(8, strLine.length()) == "GREY_16") {
header.type = GREY_16;
} else if (strLine.substr(8, strLine.length()) == "GREY_32") {
header.type = GREY_32;
} else if (strLine.substr(8, strLine.length()) == "GREY_F") {
header.type = GREY_F;
} else if (strLine.substr(8, strLine.length()) == "COLOR" ||
strLine.substr(8, strLine.length()) == "RGB_8") {
header.type = COLOR;
} else if (strLine.substr(8, strLine.length()) == "COMPLEX_F") {
header.type = COMPLEX_F;
} else {
return false;
}
}
}
} while (strLine[0] == '#');
if (inputStream.fail() || inputStream.eof()) {
return false;
} else {
std::istringstream input_helper(strLine);
input_helper >> header.size.x >> header.size.y >> header.size.z;
if (inputStream.fail()) {
return false;
}
}
if (header.type == MONO) {
getline(inputStream, strLine);
if (inputStream.fail() || inputStream.eof()) {
return false;
}
std::istringstream input_helper(strLine);
input_helper >> header.rleLength;
}
header.skip = inputStream.tellg();
switch(header.type) {
case(MONO):
header.bpp = 1;
break;
case(GREY_8):
header.bpp = 1;
break;
case(GREY_16):
header.bpp = 2;
break;
case(GREY_32):
header.bpp = 4;
break;
case(GREY_F):
header.bpp = 4;
break;
case(COLOR):
header.bpp = 3;
break;
case(COMPLEX_F):
header.bpp = 8;
break;
case(INVALID):
return false;
};
return true;
}
<commit_msg>Add define to get rid of zlib.<commit_after>/*
The MIT License
Copyright (c) 2010 Department Image Processing,
Fraunhofer ITWM.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/**
\file IASSConverter.cpp
\author Andre Liebscher
Department Image Processing
Fraunhofer ITWM
\date March 2010
*/
#include <cctype>
#include <cstring>
#include <fstream>
#include <sstream>
#include "boost/cstdint.hpp"
#ifndef TUVOK_NO_ZLIB
# include "3rdParty/zlib/zlib.h"
#endif
#include "IASSConverter.h"
#include <Basics/EndianConvert.h>
#include <Controller/Controller.h>
using namespace std;
using namespace tuvok;
IASSConverter::IASSConverter()
{
m_vConverterDesc = "Fraunhofer MAVI Volume";
m_vSupportedExt.push_back("IASS");
m_vSupportedExt.push_back("IASS.GZ");
}
bool
IASSConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string& strTempDir,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert IASS dataset %s", strSourceFilename.c_str());
// Find out machine endianess
bConvertEndianess = EndianConvert::IsBigEndian();
// Check whether file is compressed and uncompress if necessary
string strInputFile;
if (IsZipped(strSourceFilename)) {
MESSAGE("IASS data is GZIP compressed.");
strInputFile = strTempDir + SysTools::GetFilename(strSourceFilename) +
".uncompressed";
if (!ExtractGZIPDataset(strSourceFilename, strInputFile, 0)) {
WARNING("Error while decompressing %s", strSourceFilename.c_str());
return false;
}
} else {
strInputFile = strSourceFilename;
}
// Read header and check for "magic" values of the IASS file
stHeader header;
ifstream fileData(strInputFile.c_str());
if (fileData.is_open()) {
if(!ReadHeader(header,fileData)) {
WARNING("The file %s is not a IASS file (missing magic)",
strInputFile.c_str());
return false;
}
} else {
WARNING("Could not open IASS file %s", strInputFile.c_str());
return false;
}
fileData.close();
// Init data
strTitle = "Fraunhofer MAVI Volume";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
iComponentCount = 1;
vVolumeSize[0] = header.size.x;
vVolumeSize[1] = header.size.y;
vVolumeSize[2] = header.size.z;
iComponentSize = header.bpp*8;
iHeaderSkip = 0;
bDeleteIntermediateFile = true;
if (header.type >= MONO && header.type <= GREY_32) {
bSigned = false;
bIsFloat = false;
} else if (header.type == GREY_F) {
bSigned = true;
bIsFloat = true;
} else if (header.type == COLOR) {
bSigned = false;
bIsFloat = false;
iComponentCount = 3;
} else {
T_ERROR("Unsupported image type in file %s", strInputFile.c_str());
return false;
}
// Convert raw data to x-locality and decode MONO files
LargeRAWFile zLocalData(strInputFile, header.skip);
zLocalData.Open(false);
if (!zLocalData.IsOpen()) {
T_ERROR("Unable to open source file %s", strInputFile.c_str());
return false;
}
strIntermediateFile = strTempDir + SysTools::GetFilename(strSourceFilename)
+ ".x-local";
LargeRAWFile xLocalData(strIntermediateFile);
xLocalData.Create();
if (!xLocalData.IsOpen()) {
T_ERROR("Unable to open temp file %s for locality conversion",
strIntermediateFile.c_str());
xLocalData.Close();
return false;
}
UINT64 strideZ = header.size.x*header.size.y*header.bpp-header.bpp;
UINT64 sliceSize = header.size.y * header.size.z * header.bpp;
unsigned char* sliceBuffer = new unsigned char[static_cast<size_t>(sliceSize)];
if (header.type == MONO) {
unsigned char* rleBuffer = new unsigned char[static_cast<size_t>(header.rleLength)];
zLocalData.ReadRAW(rleBuffer,header.rleLength);
UINT64 posRLEStream = 0;
UINT64 posOutStream = 0;
UINT64 currLength = *rleBuffer;
UINT64 sliceIndex = 0;
UINT64 currValue = 1;
do {
// This loop is entered if another pixel run would exceed the size of
// the slice buffer
while (posOutStream + currLength >= sliceSize) {
// How many pixels are left to fill up buffer
UINT64 restLength = sliceSize - posOutStream;
// Set these remaining pixels
memset(&sliceBuffer[posOutStream],
static_cast<unsigned char>((currValue%2)*0xff), static_cast<size_t>(restLength));
for (UINT64 y = 0; y < header.size.y; y++) {
xLocalData.SeekPos(y*header.size.x+sliceIndex);
for (UINT64 z = 0; z < header.size.z; z++) {
xLocalData.WriteRAW(&sliceBuffer[y*header.size.z+z],1);
xLocalData.SeekPos(xLocalData.GetPos()+strideZ);
}
}
currLength -= restLength;
posOutStream = 0;
sliceIndex++;
}
// Set pixels of required length
if (currLength > 0) {
memset(&sliceBuffer[posOutStream],
static_cast<unsigned char>((currValue%2)*0xff), static_cast<size_t>(currLength));
posOutStream += currLength;
}
currValue++;
posRLEStream++;
currLength = *(rleBuffer + posRLEStream);
} while (posRLEStream < header.rleLength);
delete[] rleBuffer;
} else {
for (UINT64 x = 0; x < header.size.x; x++) {
zLocalData.ReadRAW(sliceBuffer,sliceSize);
for (UINT64 y = 0; y < header.size.y; y++) {
xLocalData.SeekPos((y*header.size.x+x)*header.bpp);
for (UINT64 z = 0; z < header.size.z; z++) {
xLocalData.WriteRAW(&sliceBuffer[(y*header.size.z+z)*header.bpp],
header.bpp);
xLocalData.SeekPos(xLocalData.GetPos()+strideZ);
}
}
}
}
delete[] sliceBuffer;
if ( strInputFile != strSourceFilename )
Remove(strInputFile, Controller::Debug::Out());
return true;
}
// unimplemented!
bool
IASSConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINT64VECTOR3,
FLOATVECTOR3,
bool,
bool)
{
return false;
}
bool
IASSConverter::CanRead(const std::string& fn,
const std::vector<int8_t>&) const
{
std::string ext = SysTools::GetExt(fn);
std::transform(ext.begin(), ext.end(), ext.begin(),
(int(*)(int))std::toupper);
if (ext != "IASS") {
std::string extPt1 = SysTools::GetExt(SysTools::RemoveExt(fn));
std::transform(extPt1.begin(), extPt1.end(), extPt1.begin(),
(int(*)(int))std::toupper);
ext = extPt1 + "." + ext;
}
return SupportedExtension(ext);
}
bool
IASSConverter::IsZipped(const std::string& strFile)
{
#ifdef TUVOK_NO_ZLIB
T_ERROR("No zlib support! Faking this...");
return false;
#else
gzFile file = gzopen(strFile.c_str(), "rb");
if (file==0)
return false;
int rt = gzdirect(file);
gzclose(file);
return rt == 1 ? false : true;
#endif
}
IASSConverter::stHeader::stHeader()
: type(INVALID), bpp(0), skip(0), rleLength(0), size(), spacing(),
creator(""), history("") {}
void
IASSConverter::stHeader::Reset()
{
type = INVALID;
bpp = 0;
skip = 0;
rleLength = 0;
size.x = 0;
size.y = 0;
size.z = 0;
spacing.x = 0.0;
spacing.y = 0.0;
spacing.z = 0.0;
creator = "";
history = "";
}
bool
IASSConverter::ReadHeader(stHeader& header, std::istream& inputStream)
{
header.Reset();
if(!inputStream.good())
return false;
std::string strLine;
// read magic
getline(inputStream, strLine);
if (!(strLine.substr(0, 9) == "SVstatmat" ||
strLine.substr(0, 4) == "a4iL") ||
inputStream.fail()) {
return false;
}
// read header
do {
getline(inputStream, strLine);
if (inputStream.fail())
return false;
if (strLine.substr(0, 11) == "# SPACING: ") {
std::istringstream in(strLine.substr(11, strLine.length()));
in >> header.spacing.x >> header.spacing.y >> header.spacing.z;
}
else if (strLine.substr(0, 11) == "# CREATOR: ")
header.creator = strLine.substr(11, strLine.length());
else if (strLine.substr(0, 11) == "# HISTORY: ")
header.history = strLine.substr(11, strLine.length());
else if (strLine.substr(0, 8) == "# TYPE: ") {
if (isdigit(strLine[8])) {
std::string tmp = strLine.substr(8, strLine.length());
std::istringstream input_helper(tmp);
unsigned int type;
input_helper >> type;
header.type = static_cast<ePixelType>(type);
if (header.type < 0 || header.type >= INVALID)
return false;
} else {
if (strLine.substr(8, strLine.length()) == "MONO") {
header.type = MONO;
} else if (strLine.substr(8, strLine.length()) == "GREY_8") {
header.type = GREY_8;
} else if (strLine.substr(8, strLine.length()) == "GREY_16") {
header.type = GREY_16;
} else if (strLine.substr(8, strLine.length()) == "GREY_32") {
header.type = GREY_32;
} else if (strLine.substr(8, strLine.length()) == "GREY_F") {
header.type = GREY_F;
} else if (strLine.substr(8, strLine.length()) == "COLOR" ||
strLine.substr(8, strLine.length()) == "RGB_8") {
header.type = COLOR;
} else if (strLine.substr(8, strLine.length()) == "COMPLEX_F") {
header.type = COMPLEX_F;
} else {
return false;
}
}
}
} while (strLine[0] == '#');
if (inputStream.fail() || inputStream.eof()) {
return false;
} else {
std::istringstream input_helper(strLine);
input_helper >> header.size.x >> header.size.y >> header.size.z;
if (inputStream.fail()) {
return false;
}
}
if (header.type == MONO) {
getline(inputStream, strLine);
if (inputStream.fail() || inputStream.eof()) {
return false;
}
std::istringstream input_helper(strLine);
input_helper >> header.rleLength;
}
header.skip = inputStream.tellg();
switch(header.type) {
case(MONO):
header.bpp = 1;
break;
case(GREY_8):
header.bpp = 1;
break;
case(GREY_16):
header.bpp = 2;
break;
case(GREY_32):
header.bpp = 4;
break;
case(GREY_F):
header.bpp = 4;
break;
case(COLOR):
header.bpp = 3;
break;
case(COMPLEX_F):
header.bpp = 8;
break;
case(INVALID):
return false;
};
return true;
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <vector>
#include "urdf_parser.h"
const bool debug = true;
namespace urdf{
bool parseMaterial(Material &material, TiXmlElement *config);
bool parseLink(Link &link, TiXmlElement *config);
bool parseJoint(Joint &joint, TiXmlElement *config);
// Added by achq on 2012/10/13 *******************//
/**
* @function isObjectURDF
*/
bool isObjectURDF( const std::string &_xml_string ) {
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *test_xml = xml_doc.FirstChildElement("object");
if ( !test_xml ) { return false; }
else { return true; }
}
/**
* @function isRobotURDF
*/
bool isRobotURDF( const std::string &_xml_string ) {
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *test_xml = xml_doc.FirstChildElement("robot");
if ( !test_xml ) { return false; }
else { return true; }
}
// *************************************************//
boost::shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
boost::shared_ptr<ModelInterface> model(new ModelInterface);
model->clear();
TiXmlDocument xml_doc;
xml_doc.LoadFile(xml_string.c_str());
xml_doc.Parse(xml_string.c_str());
TiXmlElement *robot_xml = xml_doc.FirstChildElement("robot");
if (!robot_xml)
{
// Added the object if by achq for DART - GRIP (2012/10/13
// all the rest is the same as original
robot_xml = xml_doc.FirstChildElement("object");
if( !robot_xml ) {
if(debug) printf ( "Could find neither a robot nor an object element in the xml file \n" );
model.reset();
return model;
}
else {
if(debug) printf ("Found an object file in the xml file! \n");
}
}
else {
if(debug) printf (" Found a robot object in urdf file! \n");
}
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
if(debug) printf ("No name given for the robot. \n");
model.reset();
return model;
}
model->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
try {
parseMaterial(*material, material_xml);
if (model->getMaterial(material->name))
{
if(debug) printf ("material '%s' is not unique. \n", material->name.c_str());
material.reset();
model.reset();
return model;
}
else
{
model->materials_.insert(make_pair(material->name,material));
if(debug) printf ("successfully added a new material '%s' \n", material->name.c_str());
}
}
catch (ParseError &e) {
if(debug) printf ("material xml is not initialized correctly \n");
material.reset();
model.reset();
return model;
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
try {
parseLink(*link, link_xml);
if (model->getLink(link->name))
{
if(debug) printf ("link '%s' is not unique. \n", link->name.c_str());
model.reset();
return model;
}
else
{
// set link visual material
if(debug) printf ("setting link '%s' material \n", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (model->getMaterial(link->visual->material_name))
{
if(debug) printf ("setting link '%s' material to '%s' \n", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = model->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
if(debug) printf ("link '%s' material '%s' defined in Visual. \n", link->name.c_str(),link->visual->material_name.c_str());
model->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
if(debug) printf ("link '%s' material '%s' undefined. \n", link->name.c_str(),link->visual->material_name.c_str());
model.reset();
return model;
}
}
}
}
model->links_.insert(make_pair(link->name,link));
if(debug) printf ("successfully added a new link '%s' \n", link->name.c_str());
}
}
catch (ParseError &e) {
if(debug) printf ("link xml is not initialized correctly \n");
model.reset();
return model;
}
}
if (model->links_.empty()){
if(debug) printf ("No link elements found in urdf file \n");
model.reset();
return model;
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (parseJoint(*joint, joint_xml))
{
if (model->getJoint(joint->name))
{
if(debug) printf ("joint '%s' is not unique. \n", joint->name.c_str());
model.reset();
return model;
}
else
{
model->joints_.insert(make_pair(joint->name,joint));
if(debug) printf ("successfully added a new joint '%s' \n", joint->name.c_str());
}
}
else
{
if(debug) printf ("joint xml is not initialized correctly \n");
model.reset();
return model;
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
try
{
model->initTree(parent_link_tree);
}
catch(ParseError &e)
{
if(debug) printf ("Failed to build tree: %s \n", e.what());
model.reset();
return model;
}
// find the root link
try
{
model->initRoot(parent_link_tree);
}
catch(ParseError &e)
{
if(debug) printf ("Failed to find root link: %s \n", e.what());
model.reset();
return model;
}
return model;
}
bool exportMaterial(Material &material, TiXmlElement *config);
bool exportLink(Link &link, TiXmlElement *config);
bool exportJoint(Joint &joint, TiXmlElement *config);
TiXmlDocument* exportURDF(boost::shared_ptr<ModelInterface> &model)
{
TiXmlDocument *doc = new TiXmlDocument();
TiXmlElement *robot = new TiXmlElement("robot");
robot->SetAttribute("name", model->name_);
doc->LinkEndChild(robot);
for (std::map<std::string, boost::shared_ptr<Link> >::const_iterator l=model->links_.begin(); l!=model->links_.end(); l++)
exportLink(*(l->second), robot);
for (std::map<std::string, boost::shared_ptr<Joint> >::const_iterator j=model->joints_.begin(); j!=model->joints_.end(); j++)
{
if(debug) printf ("exporting joint [%s]\n",j->second->name.c_str());
exportJoint(*(j->second), robot);
}
return doc;
}
}
<commit_msg>parseURDF only loads from filename, not string<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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 the Willow Garage 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: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <vector>
#include "urdf_parser.h"
const bool debug = true;
namespace urdf{
bool parseMaterial(Material &material, TiXmlElement *config);
bool parseLink(Link &link, TiXmlElement *config);
bool parseJoint(Joint &joint, TiXmlElement *config);
// Added by achq on 2012/10/13 *******************//
/**
* @function isObjectURDF
*/
bool isObjectURDF( const std::string &_xml_string ) {
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *test_xml = xml_doc.FirstChildElement("object");
if ( !test_xml ) { return false; }
else { return true; }
}
/**
* @function isRobotURDF
*/
bool isRobotURDF( const std::string &_xml_string ) {
TiXmlDocument xml_doc;
xml_doc.Parse( _xml_string.c_str() );
TiXmlElement *test_xml = xml_doc.FirstChildElement("robot");
if ( !test_xml ) { return false; }
else { return true; }
}
// *************************************************//
boost::shared_ptr<ModelInterface> parseURDF(const std::string &xml_string)
{
boost::shared_ptr<ModelInterface> model(new ModelInterface);
model->clear();
TiXmlDocument xml_doc;
xml_doc.LoadFile(xml_string.c_str());
//xml_doc.Parse(xml_string.c_str());
TiXmlElement *robot_xml = xml_doc.FirstChildElement("robot");
if (!robot_xml)
{
// Added the object if by achq for DART - GRIP (2012/10/13
// all the rest is the same as original
robot_xml = xml_doc.FirstChildElement("object");
if( !robot_xml ) {
if(debug) printf ( "Could find neither a robot nor an object element in the xml file \n" );
model.reset();
return model;
}
else {
if(debug) printf ("Found an object file in the xml file! \n");
}
}
else {
if(debug) printf (" Found a robot object in urdf file! \n");
}
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
if(debug) printf ("No name given for the robot. \n");
model.reset();
return model;
}
model->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
try {
parseMaterial(*material, material_xml);
if (model->getMaterial(material->name))
{
if(debug) printf ("material '%s' is not unique. \n", material->name.c_str());
material.reset();
model.reset();
return model;
}
else
{
model->materials_.insert(make_pair(material->name,material));
if(debug) printf ("successfully added a new material '%s' \n", material->name.c_str());
}
}
catch (ParseError &e) {
if(debug) printf ("material xml is not initialized correctly \n");
material.reset();
model.reset();
return model;
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
try {
parseLink(*link, link_xml);
if (model->getLink(link->name))
{
if(debug) printf ("link '%s' is not unique. \n", link->name.c_str());
model.reset();
return model;
}
else
{
// set link visual material
if(debug) printf ("setting link '%s' material \n", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (model->getMaterial(link->visual->material_name))
{
if(debug) printf ("setting link '%s' material to '%s' \n", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = model->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
if(debug) printf ("link '%s' material '%s' defined in Visual. \n", link->name.c_str(),link->visual->material_name.c_str());
model->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
if(debug) printf ("link '%s' material '%s' undefined. \n", link->name.c_str(),link->visual->material_name.c_str());
model.reset();
return model;
}
}
}
}
model->links_.insert(make_pair(link->name,link));
if(debug) printf ("successfully added a new link '%s' \n", link->name.c_str());
}
}
catch (ParseError &e) {
if(debug) printf ("link xml is not initialized correctly \n");
model.reset();
return model;
}
}
if (model->links_.empty()){
if(debug) printf ("No link elements found in urdf file \n");
model.reset();
return model;
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (parseJoint(*joint, joint_xml))
{
if (model->getJoint(joint->name))
{
if(debug) printf ("joint '%s' is not unique. \n", joint->name.c_str());
model.reset();
return model;
}
else
{
model->joints_.insert(make_pair(joint->name,joint));
if(debug) printf ("successfully added a new joint '%s' \n", joint->name.c_str());
}
}
else
{
if(debug) printf ("joint xml is not initialized correctly \n");
model.reset();
return model;
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
try
{
model->initTree(parent_link_tree);
}
catch(ParseError &e)
{
if(debug) printf ("Failed to build tree: %s \n", e.what());
model.reset();
return model;
}
// find the root link
try
{
model->initRoot(parent_link_tree);
}
catch(ParseError &e)
{
if(debug) printf ("Failed to find root link: %s \n", e.what());
model.reset();
return model;
}
return model;
}
bool exportMaterial(Material &material, TiXmlElement *config);
bool exportLink(Link &link, TiXmlElement *config);
bool exportJoint(Joint &joint, TiXmlElement *config);
TiXmlDocument* exportURDF(boost::shared_ptr<ModelInterface> &model)
{
TiXmlDocument *doc = new TiXmlDocument();
TiXmlElement *robot = new TiXmlElement("robot");
robot->SetAttribute("name", model->name_);
doc->LinkEndChild(robot);
for (std::map<std::string, boost::shared_ptr<Link> >::const_iterator l=model->links_.begin(); l!=model->links_.end(); l++)
exportLink(*(l->second), robot);
for (std::map<std::string, boost::shared_ptr<Joint> >::const_iterator j=model->joints_.begin(); j!=model->joints_.end(); j++)
{
if(debug) printf ("exporting joint [%s]\n",j->second->name.c_str());
exportJoint(*(j->second), robot);
}
return doc;
}
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Bastian Holst <bastianholst@gmx.de>
//
// Self
#include "AbstractDataPlugin.h"
// Marble
#include "AbstractDataPluginModel.h"
#include "AbstractDataPluginItem.h"
#include "GeoPainter.h"
#include "GeoSceneLayer.h"
#include "MarbleModel.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
// Qt
#include <QtCore/QEvent>
#include <QtGui/QMouseEvent>
#include <QtGui/QRegion>
#include <QtDeclarative/QDeclarativeComponent>
#include <QtDeclarative/QDeclarativeItem>
#include <QtDeclarative/QDeclarativeContext>
namespace Marble
{
class AbstractDataPluginPrivate
{
public:
AbstractDataPluginPrivate()
: m_model( 0 ),
m_numberOfItems( 10 ),
m_delegate( 0 ),
m_delegateParent( 0 )
{
}
~AbstractDataPluginPrivate() {
delete m_model;
}
AbstractDataPluginModel *m_model;
quint32 m_numberOfItems;
QDeclarativeComponent* m_delegate;
QGraphicsItem* m_delegateParent;
QMap<AbstractDataPluginItem*,QDeclarativeItem*> m_delegateInstances;
};
AbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel )
: RenderPlugin( marbleModel ),
d( new AbstractDataPluginPrivate )
{
}
AbstractDataPlugin::~AbstractDataPlugin()
{
delete d;
}
bool AbstractDataPlugin::isInitialized() const
{
return model() != 0;
}
QStringList AbstractDataPlugin::backendTypes() const
{
return QStringList( name() );
}
QString AbstractDataPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList AbstractDataPlugin::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" );
}
bool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer)
{
Q_UNUSED( renderPos );
Q_UNUSED( layer );
if ( !d->m_model || !isInitialized() ) {
return true;
}
if ( d->m_delegate ) {
handleViewportChange( viewport );
} else {
QList<AbstractDataPluginItem*> items = d->m_model->items( viewport,
marbleModel(),
numberOfItems() );
painter->save();
// Paint the most important item at last
for( int i = items.size() - 1; i >= 0; --i ) {
items.at( i )->paintEvent( painter, viewport );
}
painter->restore();
}
return true;
}
AbstractDataPluginModel *AbstractDataPlugin::model() const
{
return d->m_model;
}
void AbstractDataPlugin::setModel( AbstractDataPluginModel* model )
{
if ( d->m_model ) {
disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );
delete d->m_model;
}
d->m_model = model;
connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );
connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this,
SLOT( favoriteItemsChanged( const QStringList& ) ) );
connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this,
SIGNAL( favoriteItemsOnlyChanged() ) );
emit favoritesModelChanged();
}
const PluginManager* AbstractDataPlugin::pluginManager() const
{
return marbleModel()->pluginManager();
}
quint32 AbstractDataPlugin::numberOfItems() const
{
return d->m_numberOfItems;
}
void AbstractDataPlugin::setNumberOfItems( quint32 number )
{
bool changed = ( number != d->m_numberOfItems );
d->m_numberOfItems = number;
if ( changed )
emit changedNumberOfItems( number );
}
QList<AbstractDataPluginItem *> AbstractDataPlugin::whichItemAt( const QPoint& curpos )
{
if ( d->m_model && enabled() && visible()) {
return d->m_model->whichItemAt( curpos );
}
else {
return QList<AbstractDataPluginItem *>();
}
}
RenderPlugin::RenderType AbstractDataPlugin::renderType() const
{
return Online;
}
void AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent )
{
qDeleteAll( d->m_delegateInstances.values() );
d->m_delegateInstances.clear();
d->m_delegate = delegate;
d->m_delegateParent = parent;
}
void AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly )
{
if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) {
d->m_model->setFavoriteItemsOnly( favoriteOnly );
}
}
bool AbstractDataPlugin::isFavoriteItemsOnly() const
{
return d->m_model->isFavoriteItemsOnly();
}
QObject *AbstractDataPlugin::favoritesModel()
{
return d->m_model ? d->m_model->favoritesModel() : 0;
}
void AbstractDataPlugin::handleViewportChange( ViewportParams* viewport )
{
QList<AbstractDataPluginItem*> orphane = d->m_delegateInstances.keys();
QList<AbstractDataPluginItem*> const items = d->m_model->items( viewport, marbleModel(), numberOfItems() );
foreach( AbstractDataPluginItem* item, items ) {
qreal x, y;
Marble::GeoDataCoordinates const coordinates = item->coordinate();
bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y );
if ( !d->m_delegateInstances.contains( item ) ) {
if ( !visible ) {
// We don't have, but don't need it either. Shouldn't happen though as the model checks for it already.
continue;
}
// Create a new QML object instance using the delegate as the factory. The original
// data plugin item is set as the context object, i.e. all its properties are available
// to QML directly with their names
QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) );
context->setContextObject( item );
QObject* component = d->m_delegate->create( context );
QDeclarativeItem* newItem = qobject_cast<QDeclarativeItem*>( component );
QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component );
if ( graphicsItem && newItem ) {
graphicsItem->setParentItem( d->m_delegateParent );
}
if ( newItem ) {
d->m_delegateInstances[item] = newItem;
} else {
mDebug() << "Failed to create delegate";
continue;
}
} else if ( !visible ) {
// Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later.
// Shouldn't happen though as the model checks for it already.
continue;
}
Q_ASSERT( visible );
QDeclarativeItem* declarativeItem = d->m_delegateInstances[item];
Q_ASSERT( declarativeItem );
// Make sure we have a valid bounding rect for collision detection
item->setProjection( viewport );
item->setSize( QSizeF( declarativeItem->boundingRect().size() ) );
int shiftX( 0 ), shiftY( 0 );
switch( declarativeItem->transformOrigin() ) {
case QDeclarativeItem::TopLeft:
case QDeclarativeItem::Top:
case QDeclarativeItem::TopRight:
break;
case QDeclarativeItem::Left:
case QDeclarativeItem::Center:
case QDeclarativeItem::Right:
shiftY = declarativeItem->height() / 2;
break;
case QDeclarativeItem::BottomLeft:
case QDeclarativeItem::Bottom:
case QDeclarativeItem::BottomRight:
shiftY = declarativeItem->height();
break;
}
switch( declarativeItem->transformOrigin() ) {
case QDeclarativeItem::TopLeft:
case QDeclarativeItem::Left:
case QDeclarativeItem::BottomLeft:
break;
case QDeclarativeItem::Top:
case QDeclarativeItem::Center:
case QDeclarativeItem::Bottom:
shiftX = declarativeItem->width() / 2;
break;
case QDeclarativeItem::TopRight:
case QDeclarativeItem::Right:
case QDeclarativeItem::BottomRight:
shiftX = declarativeItem->width();
break;
}
declarativeItem->setPos( x - shiftX, y - shiftY );
orphane.removeOne( item );
}
// Cleanup
foreach( AbstractDataPluginItem* item, orphane ) {
Q_ASSERT( d->m_delegateInstances.contains( item ) );
delete d->m_delegateInstances[item];
d->m_delegateInstances.remove( item );
}
}
void AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems )
{
Q_UNUSED( favoriteItems )
}
} // namespace Marble
#include "AbstractDataPlugin.moc"
<commit_msg>m_model can be 0.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009 Bastian Holst <bastianholst@gmx.de>
//
// Self
#include "AbstractDataPlugin.h"
// Marble
#include "AbstractDataPluginModel.h"
#include "AbstractDataPluginItem.h"
#include "GeoPainter.h"
#include "GeoSceneLayer.h"
#include "MarbleModel.h"
#include "ViewportParams.h"
#include "MarbleDebug.h"
// Qt
#include <QtCore/QEvent>
#include <QtGui/QMouseEvent>
#include <QtGui/QRegion>
#include <QtDeclarative/QDeclarativeComponent>
#include <QtDeclarative/QDeclarativeItem>
#include <QtDeclarative/QDeclarativeContext>
namespace Marble
{
class AbstractDataPluginPrivate
{
public:
AbstractDataPluginPrivate()
: m_model( 0 ),
m_numberOfItems( 10 ),
m_delegate( 0 ),
m_delegateParent( 0 )
{
}
~AbstractDataPluginPrivate() {
delete m_model;
}
AbstractDataPluginModel *m_model;
quint32 m_numberOfItems;
QDeclarativeComponent* m_delegate;
QGraphicsItem* m_delegateParent;
QMap<AbstractDataPluginItem*,QDeclarativeItem*> m_delegateInstances;
};
AbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel )
: RenderPlugin( marbleModel ),
d( new AbstractDataPluginPrivate )
{
}
AbstractDataPlugin::~AbstractDataPlugin()
{
delete d;
}
bool AbstractDataPlugin::isInitialized() const
{
return model() != 0;
}
QStringList AbstractDataPlugin::backendTypes() const
{
return QStringList( name() );
}
QString AbstractDataPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList AbstractDataPlugin::renderPosition() const
{
return QStringList( "ALWAYS_ON_TOP" );
}
bool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos, GeoSceneLayer * layer)
{
Q_UNUSED( renderPos );
Q_UNUSED( layer );
if ( !d->m_model || !isInitialized() ) {
return true;
}
if ( d->m_delegate ) {
handleViewportChange( viewport );
} else {
QList<AbstractDataPluginItem*> items = d->m_model->items( viewport,
marbleModel(),
numberOfItems() );
painter->save();
// Paint the most important item at last
for( int i = items.size() - 1; i >= 0; --i ) {
items.at( i )->paintEvent( painter, viewport );
}
painter->restore();
}
return true;
}
AbstractDataPluginModel *AbstractDataPlugin::model() const
{
return d->m_model;
}
void AbstractDataPlugin::setModel( AbstractDataPluginModel* model )
{
if ( d->m_model ) {
disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );
delete d->m_model;
}
d->m_model = model;
connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );
connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this,
SLOT( favoriteItemsChanged( const QStringList& ) ) );
connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this,
SIGNAL( favoriteItemsOnlyChanged() ) );
emit favoritesModelChanged();
}
const PluginManager* AbstractDataPlugin::pluginManager() const
{
return marbleModel()->pluginManager();
}
quint32 AbstractDataPlugin::numberOfItems() const
{
return d->m_numberOfItems;
}
void AbstractDataPlugin::setNumberOfItems( quint32 number )
{
bool changed = ( number != d->m_numberOfItems );
d->m_numberOfItems = number;
if ( changed )
emit changedNumberOfItems( number );
}
QList<AbstractDataPluginItem *> AbstractDataPlugin::whichItemAt( const QPoint& curpos )
{
if ( d->m_model && enabled() && visible()) {
return d->m_model->whichItemAt( curpos );
}
else {
return QList<AbstractDataPluginItem *>();
}
}
RenderPlugin::RenderType AbstractDataPlugin::renderType() const
{
return Online;
}
void AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent )
{
qDeleteAll( d->m_delegateInstances.values() );
d->m_delegateInstances.clear();
d->m_delegate = delegate;
d->m_delegateParent = parent;
}
void AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly )
{
if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) {
d->m_model->setFavoriteItemsOnly( favoriteOnly );
}
}
bool AbstractDataPlugin::isFavoriteItemsOnly() const
{
return d->m_model && d->m_model->isFavoriteItemsOnly();
}
QObject *AbstractDataPlugin::favoritesModel()
{
return d->m_model ? d->m_model->favoritesModel() : 0;
}
void AbstractDataPlugin::handleViewportChange( ViewportParams* viewport )
{
QList<AbstractDataPluginItem*> orphane = d->m_delegateInstances.keys();
QList<AbstractDataPluginItem*> const items = d->m_model->items( viewport, marbleModel(), numberOfItems() );
foreach( AbstractDataPluginItem* item, items ) {
qreal x, y;
Marble::GeoDataCoordinates const coordinates = item->coordinate();
bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y );
if ( !d->m_delegateInstances.contains( item ) ) {
if ( !visible ) {
// We don't have, but don't need it either. Shouldn't happen though as the model checks for it already.
continue;
}
// Create a new QML object instance using the delegate as the factory. The original
// data plugin item is set as the context object, i.e. all its properties are available
// to QML directly with their names
QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) );
context->setContextObject( item );
QObject* component = d->m_delegate->create( context );
QDeclarativeItem* newItem = qobject_cast<QDeclarativeItem*>( component );
QGraphicsItem* graphicsItem = qobject_cast<QGraphicsItem*>( component );
if ( graphicsItem && newItem ) {
graphicsItem->setParentItem( d->m_delegateParent );
}
if ( newItem ) {
d->m_delegateInstances[item] = newItem;
} else {
mDebug() << "Failed to create delegate";
continue;
}
} else if ( !visible ) {
// Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later.
// Shouldn't happen though as the model checks for it already.
continue;
}
Q_ASSERT( visible );
QDeclarativeItem* declarativeItem = d->m_delegateInstances[item];
Q_ASSERT( declarativeItem );
// Make sure we have a valid bounding rect for collision detection
item->setProjection( viewport );
item->setSize( QSizeF( declarativeItem->boundingRect().size() ) );
int shiftX( 0 ), shiftY( 0 );
switch( declarativeItem->transformOrigin() ) {
case QDeclarativeItem::TopLeft:
case QDeclarativeItem::Top:
case QDeclarativeItem::TopRight:
break;
case QDeclarativeItem::Left:
case QDeclarativeItem::Center:
case QDeclarativeItem::Right:
shiftY = declarativeItem->height() / 2;
break;
case QDeclarativeItem::BottomLeft:
case QDeclarativeItem::Bottom:
case QDeclarativeItem::BottomRight:
shiftY = declarativeItem->height();
break;
}
switch( declarativeItem->transformOrigin() ) {
case QDeclarativeItem::TopLeft:
case QDeclarativeItem::Left:
case QDeclarativeItem::BottomLeft:
break;
case QDeclarativeItem::Top:
case QDeclarativeItem::Center:
case QDeclarativeItem::Bottom:
shiftX = declarativeItem->width() / 2;
break;
case QDeclarativeItem::TopRight:
case QDeclarativeItem::Right:
case QDeclarativeItem::BottomRight:
shiftX = declarativeItem->width();
break;
}
declarativeItem->setPos( x - shiftX, y - shiftY );
orphane.removeOne( item );
}
// Cleanup
foreach( AbstractDataPluginItem* item, orphane ) {
Q_ASSERT( d->m_delegateInstances.contains( item ) );
delete d->m_delegateInstances[item];
d->m_delegateInstances.remove( item );
}
}
void AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems )
{
Q_UNUSED( favoriteItems )
}
} // namespace Marble
#include "AbstractDataPlugin.moc"
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/util/debug.hh>
#include <hpp/core/continuous-collision-checking/dichotomy.hh>
#include <hpp/core/straight-path.hh>
#include "continuous-collision-checking/dichotomy/body-pair-collision.hh"
namespace hpp {
namespace core {
namespace continuousCollisionChecking {
using dichotomy::BodyPairCollision;
using dichotomy::BodyPairCollisionPtr_t;
using dichotomy::BodyPairCollisions_t;
bool compareBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,
const BodyPairCollisionPtr_t& bodyPair2)
{
assert (!bodyPair1->validSubset ().list ().empty ());
assert (!bodyPair2->validSubset ().list ().empty ());
return bodyPair1->validSubset ().list ().begin ()->second <
bodyPair2->validSubset ().list ().begin ()->second;
}
bool compareReverseBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,
const BodyPairCollisionPtr_t& bodyPair2)
{
assert (!bodyPair1->validSubset ().list ().empty ());
assert (!bodyPair2->validSubset ().list ().empty ());
return bodyPair1->validSubset ().list ().rbegin ()->first >
bodyPair2->validSubset ().list ().rbegin ()->first;
}
// Partially sort a list where only the first element is not sorted
template <typename Compare>
void partialSort (BodyPairCollisions_t& list, Compare comp)
{
BodyPairCollisions_t::iterator it1 = list.begin ();
if (it1 == list.end ()) return;
BodyPairCollisions_t::iterator it2 = it1; ++it2;
while (it2 != list.end ()) {
if (comp (*it2, *it1))
std::iter_swap (it1, it2);
else
return;
it1 = it2;
++it2;
}
}
DichotomyPtr_t
Dichotomy::create (const DevicePtr_t& robot, const value_type& tolerance)
{
Dichotomy* ptr =
new Dichotomy (robot, tolerance);
DichotomyPtr_t shPtr (ptr);
return shPtr;
}
bool Dichotomy::validate
(const PathPtr_t& path, bool reverse, PathPtr_t& validPart)
{
StraightPathPtr_t straightPath = HPP_DYNAMIC_PTR_CAST
(StraightPath, path);
// for each BodyPairCollision
// - set path,
// - compute valid interval at start (end if reverse)
value_type t0 = path->timeRange ().first;
value_type t1 = path->timeRange ().second;
if (reverse) {
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
(*itPair)->path (straightPath);
// If collision at end point, return false
if (!(*itPair)->validateInterval (t1)) {
validPart = path->extract (interval_t (t1, t1));
return false;
}
assert ((*itPair)->validSubset ().contains (t1));
}
// Sort collision pairs
bodyPairCollisions_.sort (compareReverseBodyPairCol);
BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());
while (!first->validSubset ().contains (t0, true)) {
// find middle of first non valid interval
const std::list <interval_t>& intervals =
first->validSubset ().list ();
std::list <interval_t>::const_reverse_iterator lastInterval =
intervals.rbegin ();
std::list <interval_t>::const_reverse_iterator beforeLastInterval =
lastInterval; ++beforeLastInterval;
value_type upper = lastInterval->first;
value_type lower;
if (beforeLastInterval != intervals.rend ()) {
lower = beforeLastInterval->second;
} else {
lower = t0;
}
value_type middle = .5 * (lower + upper);
if (first->validateInterval (middle)) {
partialSort (bodyPairCollisions_, compareReverseBodyPairCol);
} else {
validPart = path->extract (interval_t (upper, t1));
return false;
}
first = *(bodyPairCollisions_.begin ());
}
} else {
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
(*itPair)->path (straightPath);
// If collision at start point, return false
bool valid = (*itPair)->validateInterval (t0);
if (!valid) {
validPart = path->extract (interval_t (t0, t0));
hppDout (error, "Initial position in collision.");
return false;
}
assert ((*itPair)->validSubset ().contains (t0));
}
// Sort collision pairs
bodyPairCollisions_.sort (compareBodyPairCol);
BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());
while (!first->validSubset ().contains (t1)) {
// find middle of first non valid interval
const std::list <interval_t>& intervals =
first->validSubset ().list ();
std::list <interval_t>::const_iterator firstInterval =
intervals.begin ();
std::list <interval_t>::const_iterator secondInterval =
firstInterval;
++secondInterval;
value_type lower = firstInterval->second;
value_type upper;
if (secondInterval != intervals.end ()) {
upper = secondInterval->first;
} else {
upper = t1;
}
value_type middle = .5 * (lower + upper);
if (first->validateInterval (middle)) {
partialSort (bodyPairCollisions_, compareBodyPairCol);
} else {
validPart = path->extract (interval_t (t0, lower));
hppDout (info, "Return path valid on [" << t0 << "," << lower
<< "]");
return false;
}
first = *(bodyPairCollisions_.begin ());
}
}
validPart = path;
hppDout (info, "Path valid defined on [" << t0 << "," << t1 << "]");
return true;
}
void Dichotomy::addObstacle
(const CollisionObjectPtr_t& object)
{
const JointVector_t& jv = robot_->getJointVector ();
for (JointVector_t::const_iterator itJoint = jv.begin ();
itJoint != jv.end (); ++itJoint) {
BodyPtr_t body = (*itJoint)->linkedBody ();
bool foundPair = false;
if (body) {
ObjectVector_t objects;
objects.push_back (object);
bodyPairCollisions_.push_back
(BodyPairCollision::create (*itJoint, objects, tolerance_));
}
}
}
void Dichotomy::removeObstacleFromJoint
(const JointPtr_t& joint, const CollisionObjectPtr_t& obstacle)
{
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
if (!(*itPair)->joint_b () && (*itPair)->joint_a () == joint) {
if ((*itPair)->removeObjectTo_b (obstacle)) {
if ((*itPair)->objects_b ().empty ()) {
bodyPairCollisions_.erase (itPair);
}
return;
}
}
}
}
Dichotomy::~Dichotomy ()
{
}
Dichotomy::Dichotomy
(const DevicePtr_t& robot, const value_type& tolerance) :
robot_ (robot), tolerance_ (tolerance),
bodyPairCollisions_ ()
{
// Tolerance should be equal to 0, otherwise end of valid
// sub-path might be in collision.
if (tolerance != 0) {
throw std::runtime_error ("Dichotomy path validation method does not"
"support penetration.");
}
typedef model::Device::CollisionPairs_t CollisionPairs_t;
// Build body pairs for collision checking
// First auto-collision
const CollisionPairs_t& colPairs = robot->collisionPairs
(model::COLLISION);
for (CollisionPairs_t::const_iterator itPair = colPairs.begin ();
itPair != colPairs.end (); ++itPair) {
bodyPairCollisions_.push_back (BodyPairCollision::create
(itPair->first, itPair->second,
tolerance_));
}
}
} // namespace continuousCollisionChecking
} // namespace core
} // namespace hpp
<commit_msg>Create one BodyPairCollision object for each pair (joint, obstacle) only for<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/util/debug.hh>
#include <hpp/core/continuous-collision-checking/dichotomy.hh>
#include <hpp/core/straight-path.hh>
#include "continuous-collision-checking/dichotomy/body-pair-collision.hh"
namespace hpp {
namespace core {
namespace continuousCollisionChecking {
using dichotomy::BodyPairCollision;
using dichotomy::BodyPairCollisionPtr_t;
using dichotomy::BodyPairCollisions_t;
bool compareBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,
const BodyPairCollisionPtr_t& bodyPair2)
{
assert (!bodyPair1->validSubset ().list ().empty ());
assert (!bodyPair2->validSubset ().list ().empty ());
return bodyPair1->validSubset ().list ().begin ()->second <
bodyPair2->validSubset ().list ().begin ()->second;
}
bool compareReverseBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,
const BodyPairCollisionPtr_t& bodyPair2)
{
assert (!bodyPair1->validSubset ().list ().empty ());
assert (!bodyPair2->validSubset ().list ().empty ());
return bodyPair1->validSubset ().list ().rbegin ()->first >
bodyPair2->validSubset ().list ().rbegin ()->first;
}
// Partially sort a list where only the first element is not sorted
template <typename Compare>
void partialSort (BodyPairCollisions_t& list, Compare comp)
{
BodyPairCollisions_t::iterator it1 = list.begin ();
if (it1 == list.end ()) return;
BodyPairCollisions_t::iterator it2 = it1; ++it2;
while (it2 != list.end ()) {
if (comp (*it2, *it1))
std::iter_swap (it1, it2);
else
return;
it1 = it2;
++it2;
}
}
DichotomyPtr_t
Dichotomy::create (const DevicePtr_t& robot, const value_type& tolerance)
{
Dichotomy* ptr =
new Dichotomy (robot, tolerance);
DichotomyPtr_t shPtr (ptr);
return shPtr;
}
bool Dichotomy::validate
(const PathPtr_t& path, bool reverse, PathPtr_t& validPart)
{
StraightPathPtr_t straightPath = HPP_DYNAMIC_PTR_CAST
(StraightPath, path);
// for each BodyPairCollision
// - set path,
// - compute valid interval at start (end if reverse)
value_type t0 = path->timeRange ().first;
value_type t1 = path->timeRange ().second;
if (reverse) {
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
(*itPair)->path (straightPath);
// If collision at end point, return false
if (!(*itPair)->validateInterval (t1)) {
validPart = path->extract (interval_t (t1, t1));
return false;
}
assert ((*itPair)->validSubset ().contains (t1));
}
// Sort collision pairs
bodyPairCollisions_.sort (compareReverseBodyPairCol);
BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());
while (!first->validSubset ().contains (t0, true)) {
// find middle of first non valid interval
const std::list <interval_t>& intervals =
first->validSubset ().list ();
std::list <interval_t>::const_reverse_iterator lastInterval =
intervals.rbegin ();
std::list <interval_t>::const_reverse_iterator beforeLastInterval =
lastInterval; ++beforeLastInterval;
value_type upper = lastInterval->first;
value_type lower;
if (beforeLastInterval != intervals.rend ()) {
lower = beforeLastInterval->second;
} else {
lower = t0;
}
value_type middle = .5 * (lower + upper);
if (first->validateInterval (middle)) {
partialSort (bodyPairCollisions_, compareReverseBodyPairCol);
} else {
validPart = path->extract (interval_t (upper, t1));
return false;
}
first = *(bodyPairCollisions_.begin ());
}
} else {
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
(*itPair)->path (straightPath);
// If collision at start point, return false
bool valid = (*itPair)->validateInterval (t0);
if (!valid) {
validPart = path->extract (interval_t (t0, t0));
hppDout (error, "Initial position in collision.");
return false;
}
assert ((*itPair)->validSubset ().contains (t0));
}
// Sort collision pairs
bodyPairCollisions_.sort (compareBodyPairCol);
BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());
while (!first->validSubset ().contains (t1)) {
// find middle of first non valid interval
const std::list <interval_t>& intervals =
first->validSubset ().list ();
std::list <interval_t>::const_iterator firstInterval =
intervals.begin ();
std::list <interval_t>::const_iterator secondInterval =
firstInterval;
++secondInterval;
value_type lower = firstInterval->second;
value_type upper;
if (secondInterval != intervals.end ()) {
upper = secondInterval->first;
} else {
upper = t1;
}
value_type middle = .5 * (lower + upper);
if (first->validateInterval (middle)) {
partialSort (bodyPairCollisions_, compareBodyPairCol);
} else {
validPart = path->extract (interval_t (t0, lower));
hppDout (info, "Return path valid on [" << t0 << "," << lower
<< "]");
return false;
}
first = *(bodyPairCollisions_.begin ());
}
}
validPart = path;
hppDout (info, "Path valid defined on [" << t0 << "," << t1 << "]");
return true;
}
void Dichotomy::addObstacle
(const CollisionObjectPtr_t& object)
{
const JointVector_t& jv = robot_->getJointVector ();
for (JointVector_t::const_iterator itJoint = jv.begin ();
itJoint != jv.end (); ++itJoint) {
BodyPtr_t body = (*itJoint)->linkedBody ();
bool foundPair = false;
if (body) {
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
if (((*itPair)->joint_a () == *itJoint) &&
(!(*itPair)->joint_b ())) {
(*itPair)->addObjectTo_b (object);
foundPair = true;
}
}
if (!foundPair) {
ObjectVector_t objects;
objects.push_back (object);
bodyPairCollisions_.push_back
(BodyPairCollision::create (*itJoint, objects, tolerance_));
}
}
}
}
void Dichotomy::removeObstacleFromJoint
(const JointPtr_t& joint, const CollisionObjectPtr_t& obstacle)
{
for (BodyPairCollisions_t::iterator itPair =
bodyPairCollisions_.begin ();
itPair != bodyPairCollisions_.end (); ++itPair) {
if (!(*itPair)->joint_b () && (*itPair)->joint_a () == joint) {
if ((*itPair)->removeObjectTo_b (obstacle)) {
if ((*itPair)->objects_b ().empty ()) {
bodyPairCollisions_.erase (itPair);
}
return;
}
}
}
}
Dichotomy::~Dichotomy ()
{
}
Dichotomy::Dichotomy
(const DevicePtr_t& robot, const value_type& tolerance) :
robot_ (robot), tolerance_ (tolerance),
bodyPairCollisions_ ()
{
// Tolerance should be equal to 0, otherwise end of valid
// sub-path might be in collision.
if (tolerance != 0) {
throw std::runtime_error ("Dichotomy path validation method does not"
"support penetration.");
}
typedef model::Device::CollisionPairs_t CollisionPairs_t;
// Build body pairs for collision checking
// First auto-collision
const CollisionPairs_t& colPairs = robot->collisionPairs
(model::COLLISION);
for (CollisionPairs_t::const_iterator itPair = colPairs.begin ();
itPair != colPairs.end (); ++itPair) {
bodyPairCollisions_.push_back (BodyPairCollision::create
(itPair->first, itPair->second,
tolerance_));
}
}
} // namespace continuousCollisionChecking
} // namespace core
} // namespace hpp
<|endoftext|>
|
<commit_before>/*
* AsyncServer.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_HTTP_ASYNC_SERVER_HPP
#define CORE_HTTP_ASYNC_SERVER_HPP
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <core/BoostThread.hpp>
#include <core/Error.hpp>
#include <core/BoostErrors.hpp>
#include <core/Log.hpp>
#include <core/ScheduledCommand.hpp>
#include <core/system/System.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/AsyncConnectionImpl.hpp>
#include <core/http/AsyncUriHandler.hpp>
#include <core/http/Util.hpp>
#include <core/http/UriHandler.hpp>
#include <core/http/SocketUtils.hpp>
#include <core/http/SocketAcceptorService.hpp>
namespace core {
namespace http {
template <typename ProtocolType>
class AsyncServer : boost::noncopyable
{
public:
AsyncServer(const std::string& serverName,
const std::string& baseUri = std::string())
: abortOnResourceError_(false),
serverName_(serverName),
baseUri_(baseUri),
acceptorService_(),
scheduledCommandTimer_(acceptorService_.ioService())
{
}
virtual ~AsyncServer()
{
}
void setAbortOnResourceError(bool abortOnResourceError)
{
abortOnResourceError_ = abortOnResourceError;
}
void addHandler(const std::string& prefix,
const AsyncUriHandlerFunction& handler)
{
uriHandlers_.add(AsyncUriHandler(baseUri_ + prefix, handler));
}
void addBlockingHandler(const std::string& prefix,
const UriHandlerFunction& handler)
{
addHandler(prefix,
boost::bind(handleAsyncConnectionSynchronously, handler, _1));
}
void setDefaultHandler(const AsyncUriHandlerFunction& handler)
{
defaultHandler_ = handler;
}
void setBlockingDefaultHandler(const UriHandlerFunction& handler)
{
setDefaultHandler(boost::bind(handleAsyncConnectionSynchronously,
handler,
_1));
}
void addScheduledCommand(boost::shared_ptr<ScheduledCommand> pCmd)
{
scheduledCommands_.push_back(pCmd);
}
Error run(std::size_t threadPoolSize = 1)
{
try
{
// get ready for next connection
acceptNextConnection();
// initialize scheduled command timer
waitForScheduledCommandTimer();
// block all signals for the creation of the thread pool
// (prevents signals from occurring on any of the handler threads)
core::system::SignalBlocker signalBlocker;
Error error = signalBlocker.blockAll();
if (error)
return error ;
// create the threads
for (std::size_t i=0; i < threadPoolSize; ++i)
{
// run the thread
boost::shared_ptr<boost::thread> pThread(new boost::thread(
&AsyncServer<ProtocolType>::runServiceThread,
this));
// add to list of threads
threads_.push_back(pThread);
}
}
catch(const boost::thread_resource_error& e)
{
return Error(boost::thread_error::ec_from_exception(e),
ERROR_LOCATION);
}
return Success();
}
void stop()
{
// close acceptor so we free up the main port immediately
boost::system::error_code closeEc;
acceptorService_.closeAcceptor(closeEc);
if (closeEc)
LOG_ERROR(Error(closeEc, ERROR_LOCATION));
// stop the server
acceptorService_.ioService().stop();
}
void waitUntilStopped()
{
// wait until all of the threads in the pool exit
for (std::size_t i=0; i < threads_.size(); ++i)
threads_[i]->join();
}
private:
void runServiceThread()
{
try
{
boost::system::error_code ec;
acceptorService_.ioService().run(ec);
if (ec)
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
CATCH_UNEXPECTED_EXCEPTION
}
void acceptNextConnection()
{
// create a new connection
ptrNextConnection_.reset(new AsyncConnectionImpl<ProtocolType>(
// controlling io_service
acceptorService_.ioService(),
// connection handler
boost::bind(&AsyncServer<ProtocolType>::handleConnection,
this, _1, _2),
// response filter
boost::bind(&AsyncServer<ProtocolType>::connectionResponseFilter,
this, _1)
));
// wait for next connection
acceptorService_.asyncAccept(
ptrNextConnection_->socket(),
boost::bind(&AsyncServer<ProtocolType>::handleAccept,
this,
boost::asio::placeholders::error)
);
}
void handleAccept(const boost::system::error_code& ec)
{
try
{
if (!ec)
{
// start connection
ptrNextConnection_->startReading();
}
else
{
// for errors, log and continue (but don't log operation aborted
// or bad file descriptor since it happens in the ordinary course
// of shutting down the server)
if (ec != boost::asio::error::operation_aborted &&
ec != boost::system::errc::bad_file_descriptor)
{
// log the error
LOG_ERROR(Error(ec, ERROR_LOCATION)) ;
// check for resource exhaustion
checkForResourceExhaustion(ec, ERROR_LOCATION);
}
}
}
catch(const boost::system::system_error& e)
{
// always log
LOG_ERROR_MESSAGE(std::string("Unexpected exception: ") + e.what());
// check for resource exhaustion
checkForResourceExhaustion(e.code(), ERROR_LOCATION);
}
CATCH_UNEXPECTED_EXCEPTION
// ALWAYS accept next connection
try
{
acceptNextConnection() ;
}
CATCH_UNEXPECTED_EXCEPTION
}
void handleConnection(
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> > pConnection,
http::Request* pRequest)
{
try
{
// call filter
onRequest(&(pConnection->socket()), pRequest);
// convert to cannonical HttpConnection
boost::shared_ptr<AsyncConnection> pAsyncConnection =
boost::shared_static_cast<AsyncConnection>(pConnection);
// call the appropriate handler to generate a response
std::string uri = pRequest->uri();
AsyncUriHandlerFunction handler = uriHandlers_.handlerFor(uri);
if (handler)
{
// call the handler
handler(pAsyncConnection) ;
}
else if (defaultHandler_)
{
// call the default handler
defaultHandler_(pAsyncConnection);
}
else
{
// log error
LOG_ERROR_MESSAGE("Handler not found for uri: " + pRequest->uri());
// return 404 not found
pConnection->response().setStatusCode(http::status::NotFound) ;
}
}
catch(const boost::system::system_error& e)
{
// always log
LOG_ERROR_MESSAGE(std::string("Unexpected exception: ") + e.what());
// check for resource exhaustion
checkForResourceExhaustion(e.code(), ERROR_LOCATION);
}
CATCH_UNEXPECTED_EXCEPTION
}
void connectionResponseFilter(http::Response* pResponse)
{
// set server header (evade ref-counting to defend against
// non-threadsafe std::string implementations)
pResponse->setHeader("Server", std::string(serverName_.c_str()));
}
void waitForScheduledCommandTimer()
{
// set expiration time for 3 seconds from now
boost::system::error_code ec;
scheduledCommandTimer_.expires_from_now(boost::posix_time::seconds(3),
ec);
// attempt to schedule timer (should always succeed but
// include error check to be paranoid/robust)
if (!ec)
{
scheduledCommandTimer_.async_wait(boost::bind(
&AsyncServer<ProtocolType>::handleScheduledCommandTimer,
this,
boost::asio::placeholders::error));
}
else
{
// unexpected error setting timer. log it
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
}
void handleScheduledCommandTimer(const boost::system::error_code& ec)
{
try
{
if (!ec)
{
// execute all commands
std::for_each(scheduledCommands_.begin(),
scheduledCommands_.end(),
boost::bind(&ScheduledCommand::execute, _1));
// remove any commands which are finished
scheduledCommands_.erase(
std::remove_if(scheduledCommands_.begin(),
scheduledCommands_.end(),
boost::bind(&ScheduledCommand::finished, _1)),
scheduledCommands_.end());
// wait for the timer again
waitForScheduledCommandTimer();
}
else
{
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
}
CATCH_UNEXPECTED_EXCEPTION
}
protected:
SocketAcceptorService<ProtocolType>& acceptorService()
{
return acceptorService_;
}
private:
virtual void onRequest(typename ProtocolType::socket* pSocket,
http::Request* pRequest)
{
}
void maybeAbortServer(const std::string& message,
const core::ErrorLocation& location)
{
if (abortOnResourceError_)
{
core::log::logErrorMessage("(ABORTING SERVER): " + message, location);
::abort();
}
else
{
core::log::logWarningMessage(
"Resource exhaustion error occurred (continuing to run)",
location);
}
}
void checkForResourceExhaustion(const boost::system::error_code& ec,
const core::ErrorLocation& location)
{
if ( ec.category() == boost::system::get_system_category() &&
(ec.value() == boost::system::errc::too_many_files_open ||
ec.value() == boost::system::errc::not_enough_memory) )
{
// our process has run out of memory or file handles. in this
// case the only way future requests can be serviced is if we
// abort and allow upstart to respawn us
maybeAbortServer("Resource exhaustion", location);
}
}
static void handleAsyncConnectionSynchronously(
const UriHandlerFunction& uriHandlerFunction,
boost::shared_ptr<AsyncConnection> pConnection)
{
uriHandlerFunction(pConnection->request(), &(pConnection->response()));
pConnection->writeResponse();
}
private:
bool abortOnResourceError_;
std::string serverName_;
std::string baseUri_;
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> > ptrNextConnection_;
AsyncUriHandlers uriHandlers_ ;
AsyncUriHandlerFunction defaultHandler_;
std::vector<boost::shared_ptr<boost::thread> > threads_;
SocketAcceptorService<ProtocolType> acceptorService_;
boost::asio::deadline_timer scheduledCommandTimer_;
std::vector<boost::shared_ptr<ScheduledCommand> > scheduledCommands_;
};
} // namespace http
} // namespace core
#endif // CORE_HTTP_ASYNC_SERVER_HPP
<commit_msg>don't log an error when the server scheduler timer receives operation cancelled<commit_after>/*
* AsyncServer.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_HTTP_ASYNC_SERVER_HPP
#define CORE_HTTP_ASYNC_SERVER_HPP
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <core/BoostThread.hpp>
#include <core/Error.hpp>
#include <core/BoostErrors.hpp>
#include <core/Log.hpp>
#include <core/ScheduledCommand.hpp>
#include <core/system/System.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/AsyncConnectionImpl.hpp>
#include <core/http/AsyncUriHandler.hpp>
#include <core/http/Util.hpp>
#include <core/http/UriHandler.hpp>
#include <core/http/SocketUtils.hpp>
#include <core/http/SocketAcceptorService.hpp>
namespace core {
namespace http {
template <typename ProtocolType>
class AsyncServer : boost::noncopyable
{
public:
AsyncServer(const std::string& serverName,
const std::string& baseUri = std::string())
: abortOnResourceError_(false),
serverName_(serverName),
baseUri_(baseUri),
acceptorService_(),
scheduledCommandTimer_(acceptorService_.ioService())
{
}
virtual ~AsyncServer()
{
}
void setAbortOnResourceError(bool abortOnResourceError)
{
abortOnResourceError_ = abortOnResourceError;
}
void addHandler(const std::string& prefix,
const AsyncUriHandlerFunction& handler)
{
uriHandlers_.add(AsyncUriHandler(baseUri_ + prefix, handler));
}
void addBlockingHandler(const std::string& prefix,
const UriHandlerFunction& handler)
{
addHandler(prefix,
boost::bind(handleAsyncConnectionSynchronously, handler, _1));
}
void setDefaultHandler(const AsyncUriHandlerFunction& handler)
{
defaultHandler_ = handler;
}
void setBlockingDefaultHandler(const UriHandlerFunction& handler)
{
setDefaultHandler(boost::bind(handleAsyncConnectionSynchronously,
handler,
_1));
}
void addScheduledCommand(boost::shared_ptr<ScheduledCommand> pCmd)
{
scheduledCommands_.push_back(pCmd);
}
Error run(std::size_t threadPoolSize = 1)
{
try
{
// get ready for next connection
acceptNextConnection();
// initialize scheduled command timer
waitForScheduledCommandTimer();
// block all signals for the creation of the thread pool
// (prevents signals from occurring on any of the handler threads)
core::system::SignalBlocker signalBlocker;
Error error = signalBlocker.blockAll();
if (error)
return error ;
// create the threads
for (std::size_t i=0; i < threadPoolSize; ++i)
{
// run the thread
boost::shared_ptr<boost::thread> pThread(new boost::thread(
&AsyncServer<ProtocolType>::runServiceThread,
this));
// add to list of threads
threads_.push_back(pThread);
}
}
catch(const boost::thread_resource_error& e)
{
return Error(boost::thread_error::ec_from_exception(e),
ERROR_LOCATION);
}
return Success();
}
void stop()
{
// close acceptor so we free up the main port immediately
boost::system::error_code closeEc;
acceptorService_.closeAcceptor(closeEc);
if (closeEc)
LOG_ERROR(Error(closeEc, ERROR_LOCATION));
// stop the server
acceptorService_.ioService().stop();
}
void waitUntilStopped()
{
// wait until all of the threads in the pool exit
for (std::size_t i=0; i < threads_.size(); ++i)
threads_[i]->join();
}
private:
void runServiceThread()
{
try
{
boost::system::error_code ec;
acceptorService_.ioService().run(ec);
if (ec)
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
CATCH_UNEXPECTED_EXCEPTION
}
void acceptNextConnection()
{
// create a new connection
ptrNextConnection_.reset(new AsyncConnectionImpl<ProtocolType>(
// controlling io_service
acceptorService_.ioService(),
// connection handler
boost::bind(&AsyncServer<ProtocolType>::handleConnection,
this, _1, _2),
// response filter
boost::bind(&AsyncServer<ProtocolType>::connectionResponseFilter,
this, _1)
));
// wait for next connection
acceptorService_.asyncAccept(
ptrNextConnection_->socket(),
boost::bind(&AsyncServer<ProtocolType>::handleAccept,
this,
boost::asio::placeholders::error)
);
}
void handleAccept(const boost::system::error_code& ec)
{
try
{
if (!ec)
{
// start connection
ptrNextConnection_->startReading();
}
else
{
// for errors, log and continue (but don't log operation aborted
// or bad file descriptor since it happens in the ordinary course
// of shutting down the server)
if (ec != boost::asio::error::operation_aborted &&
ec != boost::system::errc::bad_file_descriptor)
{
// log the error
LOG_ERROR(Error(ec, ERROR_LOCATION)) ;
// check for resource exhaustion
checkForResourceExhaustion(ec, ERROR_LOCATION);
}
}
}
catch(const boost::system::system_error& e)
{
// always log
LOG_ERROR_MESSAGE(std::string("Unexpected exception: ") + e.what());
// check for resource exhaustion
checkForResourceExhaustion(e.code(), ERROR_LOCATION);
}
CATCH_UNEXPECTED_EXCEPTION
// ALWAYS accept next connection
try
{
acceptNextConnection() ;
}
CATCH_UNEXPECTED_EXCEPTION
}
void handleConnection(
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> > pConnection,
http::Request* pRequest)
{
try
{
// call filter
onRequest(&(pConnection->socket()), pRequest);
// convert to cannonical HttpConnection
boost::shared_ptr<AsyncConnection> pAsyncConnection =
boost::shared_static_cast<AsyncConnection>(pConnection);
// call the appropriate handler to generate a response
std::string uri = pRequest->uri();
AsyncUriHandlerFunction handler = uriHandlers_.handlerFor(uri);
if (handler)
{
// call the handler
handler(pAsyncConnection) ;
}
else if (defaultHandler_)
{
// call the default handler
defaultHandler_(pAsyncConnection);
}
else
{
// log error
LOG_ERROR_MESSAGE("Handler not found for uri: " + pRequest->uri());
// return 404 not found
pConnection->response().setStatusCode(http::status::NotFound) ;
}
}
catch(const boost::system::system_error& e)
{
// always log
LOG_ERROR_MESSAGE(std::string("Unexpected exception: ") + e.what());
// check for resource exhaustion
checkForResourceExhaustion(e.code(), ERROR_LOCATION);
}
CATCH_UNEXPECTED_EXCEPTION
}
void connectionResponseFilter(http::Response* pResponse)
{
// set server header (evade ref-counting to defend against
// non-threadsafe std::string implementations)
pResponse->setHeader("Server", std::string(serverName_.c_str()));
}
void waitForScheduledCommandTimer()
{
// set expiration time for 3 seconds from now
boost::system::error_code ec;
scheduledCommandTimer_.expires_from_now(boost::posix_time::seconds(3),
ec);
// attempt to schedule timer (should always succeed but
// include error check to be paranoid/robust)
if (!ec)
{
scheduledCommandTimer_.async_wait(boost::bind(
&AsyncServer<ProtocolType>::handleScheduledCommandTimer,
this,
boost::asio::placeholders::error));
}
else
{
// unexpected error setting timer. log it
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
}
void handleScheduledCommandTimer(const boost::system::error_code& ec)
{
try
{
if (!ec)
{
// execute all commands
std::for_each(scheduledCommands_.begin(),
scheduledCommands_.end(),
boost::bind(&ScheduledCommand::execute, _1));
// remove any commands which are finished
scheduledCommands_.erase(
std::remove_if(scheduledCommands_.begin(),
scheduledCommands_.end(),
boost::bind(&ScheduledCommand::finished, _1)),
scheduledCommands_.end());
// wait for the timer again
waitForScheduledCommandTimer();
}
else
{
if (ec != boost::system::errc::operation_canceled)
LOG_ERROR(Error(ec, ERROR_LOCATION));
}
}
CATCH_UNEXPECTED_EXCEPTION
}
protected:
SocketAcceptorService<ProtocolType>& acceptorService()
{
return acceptorService_;
}
private:
virtual void onRequest(typename ProtocolType::socket* pSocket,
http::Request* pRequest)
{
}
void maybeAbortServer(const std::string& message,
const core::ErrorLocation& location)
{
if (abortOnResourceError_)
{
core::log::logErrorMessage("(ABORTING SERVER): " + message, location);
::abort();
}
else
{
core::log::logWarningMessage(
"Resource exhaustion error occurred (continuing to run)",
location);
}
}
void checkForResourceExhaustion(const boost::system::error_code& ec,
const core::ErrorLocation& location)
{
if ( ec.category() == boost::system::get_system_category() &&
(ec.value() == boost::system::errc::too_many_files_open ||
ec.value() == boost::system::errc::not_enough_memory) )
{
// our process has run out of memory or file handles. in this
// case the only way future requests can be serviced is if we
// abort and allow upstart to respawn us
maybeAbortServer("Resource exhaustion", location);
}
}
static void handleAsyncConnectionSynchronously(
const UriHandlerFunction& uriHandlerFunction,
boost::shared_ptr<AsyncConnection> pConnection)
{
uriHandlerFunction(pConnection->request(), &(pConnection->response()));
pConnection->writeResponse();
}
private:
bool abortOnResourceError_;
std::string serverName_;
std::string baseUri_;
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> > ptrNextConnection_;
AsyncUriHandlers uriHandlers_ ;
AsyncUriHandlerFunction defaultHandler_;
std::vector<boost::shared_ptr<boost::thread> > threads_;
SocketAcceptorService<ProtocolType> acceptorService_;
boost::asio::deadline_timer scheduledCommandTimer_;
std::vector<boost::shared_ptr<ScheduledCommand> > scheduledCommands_;
};
} // namespace http
} // namespace core
#endif // CORE_HTTP_ASYNC_SERVER_HPP
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Point.h>
void pointCallback(const geometry_msgs::Point::ConstPtr& msg) {
static tf2_ros::TransformBroadcaster br;
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = ros::Time::now();
transformStamped.header.frame_id = "kinect";
transformStamped.child_frame_id = "tomato";
transformStamped.transform.translation.x = msg->x;
transformStamped.transform.translation.y = msg->y;
transformStamped.transform.translation.z = msg->z;
transformStamped.transform.rotation.x = 0;
transformStamped.transform.rotation.y = 0;
transformStamped.transform.rotation.z = 0;
transformStamped.transform.rotation.w = 1;
br.sendTransform(transformStamped);
}
int main(int argc, char** argv){
ros::init(argc, argv, "tomato_broadcaster");
ros::NodeHandle node;
ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback);
ros::spin();
return 0;
}
<commit_msg>Add offset from rosparam on kinect_broadcaster<commit_after>#include <ros/ros.h>
#include <tf2_ros/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Point.h>
int offsetX, offsetY, offsetZ;
void pointCallback(const geometry_msgs::Point::ConstPtr& msg) {
static tf2_ros::TransformBroadcaster br;
geometry_msgs::TransformStamped transformStamped;
transformStamped.header.stamp = ros::Time::now();
transformStamped.header.frame_id = "kinect";
transformStamped.child_frame_id = "tomato";
transformStamped.transform.translation.x = msg->x + offsetX;
transformStamped.transform.translation.y = msg->y + offsetY;
transformStamped.transform.translation.z = msg->z + offsetZ;
transformStamped.transform.rotation.x = 0;
transformStamped.transform.rotation.y = 0;
transformStamped.transform.rotation.z = 0;
transformStamped.transform.rotation.w = 1;
br.sendTransform(transformStamped);
}
int main(int argc, char** argv){
ros::init(argc, argv, "tomato_broadcaster");
ros::NodeHandle node;
ros::NodeHandle private_node;
private_node.getParam("kinect_offset_x", offsetX);
private_node.getPrram("kinect_offset_y", offsetY);
private_node.getPrram("kinect_offset_z", offsetZ);
ros::Subscriber sub = node.subscribe("/tomato_point", 1, &pointCallback);
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsparql_tracker_direct_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>
#include <qsparqlconnection.h>
#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>
#include <qdebug.h>
// The gdbusintrospection.h header has a variable called 'signals', which
// gets substituted with the Qt 'signals' macro. So work round the
// problem by undefining it here.
#undef signals
#include <tracker-sparql.h>
QT_BEGIN_NAMESPACE
// The default for how often the result will emit the dataReady signal. Can be
// customized via QSparqlConnectionOptions.
#define DEFAULT_DATA_READY_INTERVAL 100
class QTrackerDirectDriverPrivate {
public:
QTrackerDirectDriverPrivate();
~QTrackerDirectDriverPrivate();
TrackerSparqlConnection *connection;
int dataReadyInterval;
};
class QTrackerDirectResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp);
~QTrackerDirectResultPrivate();
void terminate();
void setLastError(const QSparqlError& e);
void setBoolValue(bool v);
void dataReady(int totalCount);
TrackerSparqlCursor * cursor;
QVector<QString> columnNames;
QVector<QSparqlResultRow> results;
bool isFinished;
bool resultAlive; // whether the corresponding Result object is still alive
QEventLoop *loop;
int lastDataReady;
QTrackerDirectResult* q;
QTrackerDirectDriverPrivate *driverPrivate;
};
static void
async_cursor_next_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);
if (error != 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::BackendError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
if (!active) {
if (data->q->isBool()) {
data->setBoolValue( data->results.count() == 1
&& data->results[0].count() == 1
&& data->results[0].binding(0).value().toBool());
}
data->terminate();
return;
}
QSparqlResultRow resultRow;
gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);
if (data->columnNames.empty()) {
for (int i = 0; i < n_columns; i++) {
data->columnNames.append(QString::fromUtf8(tracker_sparql_cursor_get_variable_name(data->cursor, i)));
}
}
for (int i = 0; i < n_columns; i++) {
QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, 0));
QSparqlBinding binding;
binding.setName(data->columnNames[i]);
TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(data->cursor, i);
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:
break;
case TRACKER_SPARQL_VALUE_TYPE_URI:
binding.setValue(QUrl(value));
break;
case TRACKER_SPARQL_VALUE_TYPE_STRING:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#string"));
break;
case TRACKER_SPARQL_VALUE_TYPE_INTEGER:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#integer"));
break;
case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#double"));
break;
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#dateTime"));
break;
case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:
binding.setBlankNodeLabel(value);
break;
case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:
binding.setValue(value == QLatin1String("1") ? QString::fromLatin1("true") : QString::fromLatin1("false"),
QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#boolean"));
break;
default:
break;
}
resultRow.append(binding);
}
data->results.append(resultRow);
data->dataReady(data->results.count());
tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);
}
static void
async_query_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);
if (error != 0 || data->cursor == 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::StatementError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);
}
static void
async_update_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);
if (error != 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::StatementError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
data->terminate();
}
QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(
QTrackerDirectResult* result,
QTrackerDirectDriverPrivate *dpp)
: cursor(0), isFinished(false), resultAlive(true), loop(0), lastDataReady(0),
q(result), driverPrivate(dpp)
{
}
QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()
{
if (cursor != 0)
g_object_unref(cursor);
}
void QTrackerDirectResultPrivate::terminate()
{
isFinished = true;
dataReady(results.count());
q->emit finished();
if (loop != 0)
loop->exit();
}
void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)
{
q->setLastError(e);
}
void QTrackerDirectResultPrivate::setBoolValue(bool v)
{
q->setBoolValue(v);
}
void QTrackerDirectResultPrivate::dataReady(int totalCount)
{
bool doEmit = false;
if (isFinished && totalCount > lastDataReady) {
// emit the last dataChanged signal even if there is 1 additional item
doEmit = true;
}
else if (totalCount >= lastDataReady + driverPrivate->dataReadyInterval) {
doEmit = true;
}
if (doEmit) {
emit q->dataReady(totalCount);
lastDataReady = totalCount;
}
}
QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)
{
d = new QTrackerDirectResultPrivate(this, p);
}
QTrackerDirectResult::~QTrackerDirectResult()
{
if (!d->isFinished) {
// We're deleting the Result before the async data retrieval has
// finished. There is a pending async callback that will be called at
// some point, and that will have our ResultPrivate as user_data. Don't
// delete the ResultPrivate here, but just mark that we're no longer
// alive. The callback will then delete the ResultPrivate.
d->resultAlive = false;
}
else {
delete d;
}
}
QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,
QSparqlQuery::StatementType type)
{
QTrackerDirectResult* res = new QTrackerDirectResult(d);
res->setStatementType(type);
res->setQuery(query);
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
tracker_sparql_connection_query_async( d->connection,
query.toLatin1().constData(),
0,
async_query_callback,
res->d);
break;
}
case QSparqlQuery::InsertStatement:
case QSparqlQuery::DeleteStatement:
tracker_sparql_connection_update_async( d->connection,
query.toLatin1().constData(),
0,
0,
async_update_callback,
res->d);
{
break;
}
default:
qWarning() << "Tracker backend: unsupported statement type";
res->setLastError(QSparqlError(
QLatin1String("Unsupported statement type"),
QSparqlError::BackendError));
break;
}
return res;
}
void QTrackerDirectResult::cleanup()
{
setPos(QSparql::BeforeFirstRow);
}
QSparqlBinding QTrackerDirectResult::binding(int field) const
{
if (!isValid()) {
return QSparqlBinding();
}
if (field >= d->results[pos()].count() || field < 0) {
qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
return QSparqlBinding();
}
return d->results[pos()].binding(field);
}
QVariant QTrackerDirectResult::value(int field) const
{
if (!isValid()) {
return QVariant();
}
if (field >= d->results[pos()].count() || field < 0) {
qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
return QVariant();
}
return d->results[pos()].value(field);
}
void QTrackerDirectResult::waitForFinished()
{
if (d->isFinished)
return;
QEventLoop loop;
d->loop = &loop;
loop.exec();
d->loop = 0;
}
bool QTrackerDirectResult::isFinished() const
{
return d->isFinished;
}
int QTrackerDirectResult::size() const
{
return d->results.count();
}
QSparqlResultRow QTrackerDirectResult::current() const
{
if (!isValid()) {
return QSparqlResultRow();
}
if (pos() < 0 || pos() >= d->results.count())
return QSparqlResultRow();
return d->results[pos()];
}
QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()
: dataReadyInterval(DEFAULT_DATA_READY_INTERVAL)
{
}
QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}
QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDirectDriverPrivate();
/* Initialize GLib type system */
g_type_init();
}
QTrackerDirectDriver::~QTrackerDirectDriver()
{
delete d;
}
bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
return true;
case QSparqlConnection::AskQueries:
return true;
case QSparqlConnection::ConstructQueries:
return false;
case QSparqlConnection::UpdateQueries:
return true;
case QSparqlConnection::DefaultGraph:
return true;
}
return false;
}
QAtomicInt connectionCounter = 0;
bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
QVariant dataReadyInterval = options.option(QLatin1String("dataReadyInterval"));
if (!dataReadyInterval.isNull() && dataReadyInterval.type() == QVariant::Int)
d->dataReadyInterval = dataReadyInterval.toInt();
if (isOpen())
close();
GError *error = 0;
d->connection = tracker_sparql_connection_get(0, &error);
// maybe-TODO: Add the GCancellable
if (!d->connection) {
qWarning("Couldn't obtain a direct connection to the Tracker store: %s",
error ? error->message : "unknown error");
g_error_free(error);
return false;
}
setOpen(true);
setOpenError(false);
return true;
}
void QTrackerDirectDriver::close()
{
g_object_unref(d->connection);
if (isOpen()) {
setOpen(false);
setOpenError(false);
}
}
QT_END_NAMESPACE
#include "qsparql_tracker_direct.moc"
<commit_msg>Direct driver: g_object_unref the cursor earlier.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsparql_tracker_direct_p.h"
#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>
#include <qsparqlconnection.h>
#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>
#include <qdebug.h>
// The gdbusintrospection.h header has a variable called 'signals', which
// gets substituted with the Qt 'signals' macro. So work round the
// problem by undefining it here.
#undef signals
#include <tracker-sparql.h>
QT_BEGIN_NAMESPACE
// The default for how often the result will emit the dataReady signal. Can be
// customized via QSparqlConnectionOptions.
#define DEFAULT_DATA_READY_INTERVAL 100
class QTrackerDirectDriverPrivate {
public:
QTrackerDirectDriverPrivate();
~QTrackerDirectDriverPrivate();
TrackerSparqlConnection *connection;
int dataReadyInterval;
};
class QTrackerDirectResultPrivate : public QObject {
Q_OBJECT
public:
QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp);
~QTrackerDirectResultPrivate();
void terminate();
void setLastError(const QSparqlError& e);
void setBoolValue(bool v);
void dataReady(int totalCount);
TrackerSparqlCursor * cursor;
QVector<QString> columnNames;
QVector<QSparqlResultRow> results;
bool isFinished;
bool resultAlive; // whether the corresponding Result object is still alive
QEventLoop *loop;
int lastDataReady;
QTrackerDirectResult* q;
QTrackerDirectDriverPrivate *driverPrivate;
};
static void
async_cursor_next_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);
if (error != 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::BackendError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
if (!active) {
if (data->q->isBool()) {
data->setBoolValue( data->results.count() == 1
&& data->results[0].count() == 1
&& data->results[0].binding(0).value().toBool());
}
data->terminate();
return;
}
QSparqlResultRow resultRow;
gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);
if (data->columnNames.empty()) {
for (int i = 0; i < n_columns; i++) {
data->columnNames.append(QString::fromUtf8(tracker_sparql_cursor_get_variable_name(data->cursor, i)));
}
}
for (int i = 0; i < n_columns; i++) {
QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, 0));
QSparqlBinding binding;
binding.setName(data->columnNames[i]);
TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(data->cursor, i);
switch (type) {
case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:
break;
case TRACKER_SPARQL_VALUE_TYPE_URI:
binding.setValue(QUrl(value));
break;
case TRACKER_SPARQL_VALUE_TYPE_STRING:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#string"));
break;
case TRACKER_SPARQL_VALUE_TYPE_INTEGER:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#integer"));
break;
case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#double"));
break;
case TRACKER_SPARQL_VALUE_TYPE_DATETIME:
binding.setValue(value, QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#dateTime"));
break;
case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:
binding.setBlankNodeLabel(value);
break;
case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:
binding.setValue(value == QLatin1String("1") ? QString::fromLatin1("true") : QString::fromLatin1("false"),
QUrl::fromEncoded("http://www.w3.org/2001/XMLSchema#boolean"));
break;
default:
break;
}
resultRow.append(binding);
}
data->results.append(resultRow);
data->dataReady(data->results.count());
tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);
}
static void
async_query_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);
if (error != 0 || data->cursor == 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::StatementError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);
}
static void
async_update_callback( GObject *source_object,
GAsyncResult *result,
gpointer user_data)
{
Q_UNUSED(source_object);
QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
if (!data->resultAlive) {
// The user has deleted the Result object before this callback was
// called. Just delete the ResultPrivate here and do nothing.
delete data;
return;
}
GError *error = 0;
tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);
if (error != 0) {
QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
e.setType(QSparqlError::StatementError);
data->setLastError(e);
g_error_free(error);
data->terminate();
return;
}
data->terminate();
}
QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(
QTrackerDirectResult* result,
QTrackerDirectDriverPrivate *dpp)
: cursor(0), isFinished(false), resultAlive(true), loop(0), lastDataReady(0),
q(result), driverPrivate(dpp)
{
}
QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()
{
if (cursor != 0)
g_object_unref(cursor);
}
void QTrackerDirectResultPrivate::terminate()
{
isFinished = true;
dataReady(results.count());
q->emit finished();
if (cursor != 0) {
g_object_unref(cursor);
cursor = 0;
}
if (loop != 0)
loop->exit();
}
void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)
{
q->setLastError(e);
}
void QTrackerDirectResultPrivate::setBoolValue(bool v)
{
q->setBoolValue(v);
}
void QTrackerDirectResultPrivate::dataReady(int totalCount)
{
bool doEmit = false;
if (isFinished && totalCount > lastDataReady) {
// emit the last dataChanged signal even if there is 1 additional item
doEmit = true;
}
else if (totalCount >= lastDataReady + driverPrivate->dataReadyInterval) {
doEmit = true;
}
if (doEmit) {
emit q->dataReady(totalCount);
lastDataReady = totalCount;
}
}
QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)
{
d = new QTrackerDirectResultPrivate(this, p);
}
QTrackerDirectResult::~QTrackerDirectResult()
{
if (!d->isFinished) {
// We're deleting the Result before the async data retrieval has
// finished. There is a pending async callback that will be called at
// some point, and that will have our ResultPrivate as user_data. Don't
// delete the ResultPrivate here, but just mark that we're no longer
// alive. The callback will then delete the ResultPrivate.
d->resultAlive = false;
}
else {
delete d;
}
}
QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,
QSparqlQuery::StatementType type)
{
QTrackerDirectResult* res = new QTrackerDirectResult(d);
res->setStatementType(type);
res->setQuery(query);
switch (type) {
case QSparqlQuery::AskStatement:
case QSparqlQuery::SelectStatement:
{
tracker_sparql_connection_query_async( d->connection,
query.toLatin1().constData(),
0,
async_query_callback,
res->d);
break;
}
case QSparqlQuery::InsertStatement:
case QSparqlQuery::DeleteStatement:
tracker_sparql_connection_update_async( d->connection,
query.toLatin1().constData(),
0,
0,
async_update_callback,
res->d);
{
break;
}
default:
qWarning() << "Tracker backend: unsupported statement type";
res->setLastError(QSparqlError(
QLatin1String("Unsupported statement type"),
QSparqlError::BackendError));
break;
}
return res;
}
void QTrackerDirectResult::cleanup()
{
setPos(QSparql::BeforeFirstRow);
}
QSparqlBinding QTrackerDirectResult::binding(int field) const
{
if (!isValid()) {
return QSparqlBinding();
}
if (field >= d->results[pos()].count() || field < 0) {
qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
return QSparqlBinding();
}
return d->results[pos()].binding(field);
}
QVariant QTrackerDirectResult::value(int field) const
{
if (!isValid()) {
return QVariant();
}
if (field >= d->results[pos()].count() || field < 0) {
qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
return QVariant();
}
return d->results[pos()].value(field);
}
void QTrackerDirectResult::waitForFinished()
{
if (d->isFinished)
return;
QEventLoop loop;
d->loop = &loop;
loop.exec();
d->loop = 0;
}
bool QTrackerDirectResult::isFinished() const
{
return d->isFinished;
}
int QTrackerDirectResult::size() const
{
return d->results.count();
}
QSparqlResultRow QTrackerDirectResult::current() const
{
if (!isValid()) {
return QSparqlResultRow();
}
if (pos() < 0 || pos() >= d->results.count())
return QSparqlResultRow();
return d->results[pos()];
}
QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()
: dataReadyInterval(DEFAULT_DATA_READY_INTERVAL)
{
}
QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}
QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
: QSparqlDriver(parent)
{
d = new QTrackerDirectDriverPrivate();
/* Initialize GLib type system */
g_type_init();
}
QTrackerDirectDriver::~QTrackerDirectDriver()
{
delete d;
}
bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
switch (f) {
case QSparqlConnection::QuerySize:
return true;
case QSparqlConnection::AskQueries:
return true;
case QSparqlConnection::ConstructQueries:
return false;
case QSparqlConnection::UpdateQueries:
return true;
case QSparqlConnection::DefaultGraph:
return true;
}
return false;
}
QAtomicInt connectionCounter = 0;
bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
QVariant dataReadyInterval = options.option(QLatin1String("dataReadyInterval"));
if (!dataReadyInterval.isNull() && dataReadyInterval.type() == QVariant::Int)
d->dataReadyInterval = dataReadyInterval.toInt();
if (isOpen())
close();
GError *error = 0;
d->connection = tracker_sparql_connection_get(0, &error);
// maybe-TODO: Add the GCancellable
if (!d->connection) {
qWarning("Couldn't obtain a direct connection to the Tracker store: %s",
error ? error->message : "unknown error");
g_error_free(error);
return false;
}
setOpen(true);
setOpenError(false);
return true;
}
void QTrackerDirectDriver::close()
{
g_object_unref(d->connection);
if (isOpen()) {
setOpen(false);
setOpenError(false);
}
}
QT_END_NAMESPACE
#include "qsparql_tracker_direct.moc"
<|endoftext|>
|
<commit_before><commit_msg>add Dynamic Array class functions definitions<commit_after>#include <iostream>
#include <algorithm>
#include "DynamicArray.h"
DynamicArray::DynamicArray() {
}
DynamicArray::~DynamicArray() {
}
DynamicArray::DynamicArray(DynamicArray const & other) {
}
DynamicArray& DynamicArray::operator=(DynamicArray const & other) {
}
DynamicArray::~DynamicArray() {
}
void DynamicArray::free() {
}
void DynamicArray::reallocate(size_t newSize) {
}
void DynamicArray::add(int element) {
}
size_t DynamicArray::getAllocatedSize() const {
}
size_t DynamicArray::getLength() const {
}
int DynamicArray::getAt(size_t index) const {
}
void DynamicArray::setAt(size_t index, int value) {
}
void DynamicArray::print() const {
}
DynamicArray DynamicArray::operator+(DynamicArray const& rhs) const {
}
///
/// proxy , index.
///
///
/// proxy , .
///
/// :
/// 1. index
/// .
/// , proxy .
/// 2. proxy ,
/// . ,
/// , proxy .
///
DynamicArrayElementProxy DynamicArray::operator[](size_t index) {
}
///
/// proxy , index.
///
///
/// proxy , * *
/// .
///
const DynamicArrayElementProxy DynamicArray::operator[](size_t index) const {
}
/// ============================================================================
DynamicArrayElementProxy::DynamicArrayElementProxy(DynamicArray * pDynamicArray, size_t elementIndex) :
pParent(pDynamicArray),
parentElementIndex(elementIndex) {
}
DynamicArrayElementProxy::operator int() const {
}
DynamicArrayElementProxy & DynamicArrayElementProxy::operator=(int value) {
}<|endoftext|>
|
<commit_before>/**************************************************************************
*
* Copyright 2009-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <llvm-c/Core.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetInstrInfo.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/MemoryObject.h>
#if HAVE_LLVM >= 0x0300
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#else /* HAVE_LLVM < 0x0300 */
#include <llvm/Target/TargetRegistry.h>
#include <llvm/Target/TargetSelect.h>
#endif /* HAVE_LLVM < 0x0300 */
#if HAVE_LLVM >= 0x0209
#include <llvm/Support/Host.h>
#else /* HAVE_LLVM < 0x0209 */
#include <llvm/System/Host.h>
#endif /* HAVE_LLVM < 0x0209 */
#if HAVE_LLVM >= 0x0207
#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#endif /* HAVE_LLVM >= 0x0207 */
#include "util/u_math.h"
#include "util/u_debug.h"
#include "lp_bld_debug.h"
/**
* Check alignment.
*
* It is important that this check is not implemented as a macro or inlined
* function, as the compiler assumptions in respect to alignment of global
* and stack variables would often make the check a no op, defeating the
* whole purpose of the exercise.
*/
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
assert(util_is_power_of_two(alignment));
return ((uintptr_t)ptr & (alignment - 1)) == 0;
}
class raw_debug_ostream :
public llvm::raw_ostream
{
uint64_t pos;
void write_impl(const char *Ptr, size_t Size);
uint64_t current_pos() { return pos; }
uint64_t current_pos() const { return pos; }
#if HAVE_LLVM >= 0x207
uint64_t preferred_buffer_size() { return 512; }
#else
size_t preferred_buffer_size() { return 512; }
#endif
};
void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
if (Size > 0) {
char *lastPtr = (char *)&Ptr[Size];
char last = *lastPtr;
*lastPtr = 0;
_debug_printf("%*s", Size, Ptr);
*lastPtr = last;
pos += Size;
}
}
/**
* Same as LLVMDumpValue, but through our debugging channels.
*/
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
raw_debug_ostream os;
llvm::unwrap(value)->print(os);
os.flush();
#else
LLVMDumpValue(value);
#endif
}
#if HAVE_LLVM >= 0x0207
/*
* MemoryObject wrapper around a buffer of memory, to be used by MC
* disassembler.
*/
class BufferMemoryObject:
public llvm::MemoryObject
{
private:
const uint8_t *Bytes;
uint64_t Length;
public:
BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
Bytes(bytes), Length(length)
{
}
uint64_t getBase() const
{
return 0;
}
uint64_t getExtent() const
{
return Length;
}
int readByte(uint64_t addr, uint8_t *byte) const
{
if (addr > getExtent())
return -1;
*byte = Bytes[addr];
return 0;
}
};
#endif /* HAVE_LLVM >= 0x0207 */
/*
* Disassemble a function, using the LLVM MC disassembler.
*
* See also:
* - http://blog.llvm.org/2010/01/x86-disassembler.html
* - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
*/
extern "C" void
lp_disassemble(const void* func)
{
#if HAVE_LLVM >= 0x0207
using namespace llvm;
const uint8_t *bytes = (const uint8_t *)func;
/*
* Limit disassembly to this extent
*/
const uint64_t extent = 0x10000;
uint64_t max_pc = 0;
/*
* Initialize all used objects.
*/
std::string Triple = sys::getHostTriple();
std::string Error;
const Target *T = TargetRegistry::lookupTarget(Triple, Error);
#if HAVE_LLVM >= 0x0208
InitializeNativeTargetAsmPrinter();
#else
InitializeAllAsmPrinters();
#endif
InitializeAllDisassemblers();
#if HAVE_LLVM >= 0x0300
OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
#else
OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple));
#endif
if (!AsmInfo) {
debug_printf("error: no assembly info for target %s\n", Triple.c_str());
return;
}
#if HAVE_LLVM >= 0x0300
const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "");
OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
#else
OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
#endif
if (!DisAsm) {
debug_printf("error: no disassembler for target %s\n", Triple.c_str());
return;
}
raw_debug_ostream Out;
#if HAVE_LLVM >= 0x0300
unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
#else
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
#endif
#if HAVE_LLVM >= 0x0300
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI));
#elif HAVE_LLVM >= 0x0208
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
#else
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
#endif
if (!Printer) {
debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
return;
}
#if HAVE_LLVM >= 0x0300
TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "");
#else
TargetMachine *TM = T->createTargetMachine(Triple, "");
#endif
const TargetInstrInfo *TII = TM->getInstrInfo();
/*
* Wrap the data in a MemoryObject
*/
BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
uint64_t pc;
pc = 0;
while (true) {
MCInst Inst;
uint64_t Size;
/*
* Print address. We use addresses relative to the start of the function,
* so that between runs.
*/
debug_printf("%6lu:\t", (unsigned long)pc);
if (!DisAsm->getInstruction(Inst, Size, memoryObject,
pc,
#if HAVE_LLVM >= 0x0300
nulls(), nulls())) {
#else
nulls())) {
#endif
debug_printf("invalid\n");
pc += 1;
}
/*
* Output the bytes in hexidecimal format.
*/
if (0) {
unsigned i;
for (i = 0; i < Size; ++i) {
debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
}
for (; i < 16; ++i) {
debug_printf(" ");
}
}
/*
* Print the instruction.
*/
#if HAVE_LLVM >= 0x0300
Printer->printInst(&Inst, Out, "");
#elif HAVE_LLVM >= 0x208
Printer->printInst(&Inst, Out);
#else
Printer->printInst(&Inst);
#endif
Out.flush();
/*
* Advance.
*/
pc += Size;
#if HAVE_LLVM >= 0x0300
const MCInstrDesc &TID = TII->get(Inst.getOpcode());
#else
const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
#endif
/*
* Keep track of forward jumps to a nearby address.
*/
if (TID.isBranch()) {
for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
const MCOperand &operand = Inst.getOperand(i);
if (operand.isImm()) {
uint64_t jump;
/*
* FIXME: Handle both relative and absolute addresses correctly.
* EDInstInfo actually has this info, but operandTypes and
* operandFlags enums are not exposed in the public interface.
*/
if (1) {
/*
* PC relative addr.
*/
jump = pc + operand.getImm();
} else {
/*
* Absolute addr.
*/
jump = (uint64_t)operand.getImm();
}
/*
* Output the address relative to the function start, given
* that MC will print the addresses relative the current pc.
*/
debug_printf("\t\t; %lu", (unsigned long)jump);
/*
* Ignore far jumps given it could be actually a tail return to
* a random address.
*/
if (jump > max_pc &&
jump < extent) {
max_pc = jump;
}
}
}
}
debug_printf("\n");
/*
* Stop disassembling on return statements, if there is no record of a
* jump to a successive address.
*/
if (TID.isReturn()) {
if (pc > max_pc) {
break;
}
}
}
/*
* Print GDB command, useful to verify output.
*/
if (0) {
debug_printf("disassemble %p %p\n", bytes, bytes + pc);
}
debug_printf("\n");
#else /* HAVE_LLVM < 0x0207 */
(void)func;
#endif /* HAVE_LLVM < 0x0207 */
}
<commit_msg>gallivm: change sys::getHostTriple to sys::getDefaultTargetTriple for LLVM >= 0x0301<commit_after>/**************************************************************************
*
* Copyright 2009-2011 VMware, Inc.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS 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 <llvm-c/Core.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetInstrInfo.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/MemoryObject.h>
#if HAVE_LLVM >= 0x0300
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#else /* HAVE_LLVM < 0x0300 */
#include <llvm/Target/TargetRegistry.h>
#include <llvm/Target/TargetSelect.h>
#endif /* HAVE_LLVM < 0x0300 */
#if HAVE_LLVM >= 0x0209
#include <llvm/Support/Host.h>
#else /* HAVE_LLVM < 0x0209 */
#include <llvm/System/Host.h>
#endif /* HAVE_LLVM < 0x0209 */
#if HAVE_LLVM >= 0x0207
#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#endif /* HAVE_LLVM >= 0x0207 */
#include "util/u_math.h"
#include "util/u_debug.h"
#include "lp_bld_debug.h"
/**
* Check alignment.
*
* It is important that this check is not implemented as a macro or inlined
* function, as the compiler assumptions in respect to alignment of global
* and stack variables would often make the check a no op, defeating the
* whole purpose of the exercise.
*/
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
assert(util_is_power_of_two(alignment));
return ((uintptr_t)ptr & (alignment - 1)) == 0;
}
class raw_debug_ostream :
public llvm::raw_ostream
{
uint64_t pos;
void write_impl(const char *Ptr, size_t Size);
uint64_t current_pos() { return pos; }
uint64_t current_pos() const { return pos; }
#if HAVE_LLVM >= 0x207
uint64_t preferred_buffer_size() { return 512; }
#else
size_t preferred_buffer_size() { return 512; }
#endif
};
void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
if (Size > 0) {
char *lastPtr = (char *)&Ptr[Size];
char last = *lastPtr;
*lastPtr = 0;
_debug_printf("%*s", Size, Ptr);
*lastPtr = last;
pos += Size;
}
}
/**
* Same as LLVMDumpValue, but through our debugging channels.
*/
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
raw_debug_ostream os;
llvm::unwrap(value)->print(os);
os.flush();
#else
LLVMDumpValue(value);
#endif
}
#if HAVE_LLVM >= 0x0207
/*
* MemoryObject wrapper around a buffer of memory, to be used by MC
* disassembler.
*/
class BufferMemoryObject:
public llvm::MemoryObject
{
private:
const uint8_t *Bytes;
uint64_t Length;
public:
BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
Bytes(bytes), Length(length)
{
}
uint64_t getBase() const
{
return 0;
}
uint64_t getExtent() const
{
return Length;
}
int readByte(uint64_t addr, uint8_t *byte) const
{
if (addr > getExtent())
return -1;
*byte = Bytes[addr];
return 0;
}
};
#endif /* HAVE_LLVM >= 0x0207 */
/*
* Disassemble a function, using the LLVM MC disassembler.
*
* See also:
* - http://blog.llvm.org/2010/01/x86-disassembler.html
* - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
*/
extern "C" void
lp_disassemble(const void* func)
{
#if HAVE_LLVM >= 0x0207
using namespace llvm;
const uint8_t *bytes = (const uint8_t *)func;
/*
* Limit disassembly to this extent
*/
const uint64_t extent = 0x10000;
uint64_t max_pc = 0;
/*
* Initialize all used objects.
*/
#if HAVE_LLVM >= 0x0301
std::string Triple = sys::getDefaultTargetTriple();
#else
std::string Triple = sys::getHostTriple();
#endif
std::string Error;
const Target *T = TargetRegistry::lookupTarget(Triple, Error);
#if HAVE_LLVM >= 0x0208
InitializeNativeTargetAsmPrinter();
#else
InitializeAllAsmPrinters();
#endif
InitializeAllDisassemblers();
#if HAVE_LLVM >= 0x0300
OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
#else
OwningPtr<const MCAsmInfo> AsmInfo(T->createAsmInfo(Triple));
#endif
if (!AsmInfo) {
debug_printf("error: no assembly info for target %s\n", Triple.c_str());
return;
}
#if HAVE_LLVM >= 0x0300
const MCSubtargetInfo *STI = T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), "");
OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
#else
OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler());
#endif
if (!DisAsm) {
debug_printf("error: no disassembler for target %s\n", Triple.c_str());
return;
}
raw_debug_ostream Out;
#if HAVE_LLVM >= 0x0300
unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
#else
int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
#endif
#if HAVE_LLVM >= 0x0300
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *STI));
#elif HAVE_LLVM >= 0x0208
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo));
#else
OwningPtr<MCInstPrinter> Printer(
T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, Out));
#endif
if (!Printer) {
debug_printf("error: no instruction printer for target %s\n", Triple.c_str());
return;
}
#if HAVE_LLVM >= 0x0300
TargetMachine *TM = T->createTargetMachine(Triple, sys::getHostCPUName(), "");
#else
TargetMachine *TM = T->createTargetMachine(Triple, "");
#endif
const TargetInstrInfo *TII = TM->getInstrInfo();
/*
* Wrap the data in a MemoryObject
*/
BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);
uint64_t pc;
pc = 0;
while (true) {
MCInst Inst;
uint64_t Size;
/*
* Print address. We use addresses relative to the start of the function,
* so that between runs.
*/
debug_printf("%6lu:\t", (unsigned long)pc);
if (!DisAsm->getInstruction(Inst, Size, memoryObject,
pc,
#if HAVE_LLVM >= 0x0300
nulls(), nulls())) {
#else
nulls())) {
#endif
debug_printf("invalid\n");
pc += 1;
}
/*
* Output the bytes in hexidecimal format.
*/
if (0) {
unsigned i;
for (i = 0; i < Size; ++i) {
debug_printf("%02x ", ((const uint8_t*)bytes)[pc + i]);
}
for (; i < 16; ++i) {
debug_printf(" ");
}
}
/*
* Print the instruction.
*/
#if HAVE_LLVM >= 0x0300
Printer->printInst(&Inst, Out, "");
#elif HAVE_LLVM >= 0x208
Printer->printInst(&Inst, Out);
#else
Printer->printInst(&Inst);
#endif
Out.flush();
/*
* Advance.
*/
pc += Size;
#if HAVE_LLVM >= 0x0300
const MCInstrDesc &TID = TII->get(Inst.getOpcode());
#else
const TargetInstrDesc &TID = TII->get(Inst.getOpcode());
#endif
/*
* Keep track of forward jumps to a nearby address.
*/
if (TID.isBranch()) {
for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
const MCOperand &operand = Inst.getOperand(i);
if (operand.isImm()) {
uint64_t jump;
/*
* FIXME: Handle both relative and absolute addresses correctly.
* EDInstInfo actually has this info, but operandTypes and
* operandFlags enums are not exposed in the public interface.
*/
if (1) {
/*
* PC relative addr.
*/
jump = pc + operand.getImm();
} else {
/*
* Absolute addr.
*/
jump = (uint64_t)operand.getImm();
}
/*
* Output the address relative to the function start, given
* that MC will print the addresses relative the current pc.
*/
debug_printf("\t\t; %lu", (unsigned long)jump);
/*
* Ignore far jumps given it could be actually a tail return to
* a random address.
*/
if (jump > max_pc &&
jump < extent) {
max_pc = jump;
}
}
}
}
debug_printf("\n");
/*
* Stop disassembling on return statements, if there is no record of a
* jump to a successive address.
*/
if (TID.isReturn()) {
if (pc > max_pc) {
break;
}
}
}
/*
* Print GDB command, useful to verify output.
*/
if (0) {
debug_printf("disassemble %p %p\n", bytes, bytes + pc);
}
debug_printf("\n");
#else /* HAVE_LLVM < 0x0207 */
(void)func;
#endif /* HAVE_LLVM < 0x0207 */
}
<|endoftext|>
|
<commit_before>// Copyright (C) 2014 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/filter_view_pairs_from_relative_translation.h"
#include <ceres/rotation.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <memory>
#include <mutex> // NOLINT
#include <unordered_map>
#include "theia/math/util.h"
#include "theia/util/hash.h"
#include "theia/util/map_util.h"
#include "theia/util/random.h"
#include "theia/util/threadpool.h"
#include "theia/sfm/twoview_info.h"
#include "theia/sfm/types.h"
namespace theia {
using Eigen::Vector3d;
// Helper struct to maintain the graph for the translation projection problem.
struct MFASNode {
std::unordered_map<ViewId, double> incoming_nodes;
std::unordered_map<ViewId, double> outgoing_nodes;
double incoming_weight = 0;
double outgoing_weight = 0;
};
// Rotate the translation direction based on the known orientation such that the
// translation is in the global reference frame.
std::unordered_map<ViewIdPair, Vector3d>
RotateRelativeTranslationsToGlobalFrame(
const std::unordered_map<ViewId, Vector3d>& orientations,
const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs) {
std::unordered_map<ViewIdPair, Vector3d> rotated_translations;
rotated_translations.reserve(orientations.size());
for (const auto& view_pair : view_pairs) {
const Vector3d view_to_world_rotation =
-1.0 * FindOrDie(orientations, view_pair.first.first);
Vector3d rotated_translation;
ceres::AngleAxisRotatePoint(view_to_world_rotation.data(),
view_pair.second.position_2.data(),
rotated_translation.data());
rotated_translations.emplace(view_pair.first, rotated_translation);
}
return rotated_translations;
}
// Find the next view to add to the order. We attempt to choose a source (i.e.,
// a node with no incoming edges) or choose a node based on a heuristic such
// that it has the most source-like properties.
ViewId FindNextViewInOrder(
const std::unordered_map<ViewId, MFASNode>& degrees_for_view) {
ViewId best_choice = kInvalidViewId;
double best_score = 0;
for (const auto& view : degrees_for_view) {
// If the view is a source view, return it.
if (view.second.incoming_nodes.size() == 0) {
return view.first;
}
// Otherwise, keep track of the max score seen so far.
const double score = (view.second.outgoing_weight + 1.0) /
(view.second.incoming_weight + 1.0);
if (score > best_score) {
best_choice = view.first;
best_score = score;
}
}
return best_choice;
}
// Based on the 1D translation projections, compute an ordering of the
// translations.
std::unordered_map<ViewId, int> OrderTranslationsFromProjections(
const std::unordered_map<ViewIdPair, double>&
translation_direction_projections) {
// Compute the degrees of all vertices as the sum of weights coming in or out.
std::unordered_map<ViewId, MFASNode> degrees_for_view;
for (const auto& translation_projection : translation_direction_projections) {
const ViewIdPair view_id_pair =
(translation_projection.second > 0)
? translation_projection.first
: ViewIdPair(translation_projection.first.second,
translation_projection.first.first);
// Update the MFAS entry.
const double weight = std::abs(translation_projection.second);
degrees_for_view[view_id_pair.second].incoming_weight += weight;
degrees_for_view[view_id_pair.first].outgoing_weight += weight;
degrees_for_view[view_id_pair.second].incoming_nodes.emplace(
view_id_pair.first, weight);
degrees_for_view[view_id_pair.first].outgoing_nodes.emplace(
view_id_pair.second, weight);
}
// Compute the ordering.
const int num_views = degrees_for_view.size();
std::unordered_map<ViewId, int> translation_ordering;
for (int i = 0; i < num_views; i++) {
// Find the next view to add.
const ViewId next_view_in_order = FindNextViewInOrder(degrees_for_view);
translation_ordering[next_view_in_order] = i;
// Update the MFAS graph and remove the next view from the degrees_for_view.
const auto& next_view_info =
FindOrDie(degrees_for_view, next_view_in_order);
for (auto& neighbor_info : next_view_info.incoming_nodes) {
degrees_for_view[neighbor_info.first].outgoing_weight -=
neighbor_info.second;
degrees_for_view[neighbor_info.first].outgoing_nodes.erase(
next_view_in_order);
}
for (auto& neighbor_info : next_view_info.outgoing_nodes) {
degrees_for_view[neighbor_info.first].incoming_weight -=
neighbor_info.second;
degrees_for_view[neighbor_info.first].incoming_nodes.erase(
next_view_in_order);
}
degrees_for_view.erase(next_view_in_order);
}
return translation_ordering;
}
// Projects all the of the translation onto the given axis.
std::unordered_map<ViewIdPair, double> ProjectTranslationsOntoAxis(
const Vector3d& axis,
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations) {
std::unordered_map<ViewIdPair, double> projection_weights;
projection_weights.reserve(relative_translations.size());
for (const auto& relative_translation : relative_translations) {
const double projection_weight = relative_translation.second.dot(axis);
projection_weights.emplace(relative_translation.first, projection_weight);
}
return projection_weights;
}
// This chooses a random axis based on the given relative translations.
Vector3d ChooseRandomAxis(
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations) {
// Choose a random element in the relative translations.
const int random_index = RandInt(0, relative_translations.size() - 1);
auto it = relative_translations.begin();
std::advance(it, random_index);
Eigen::AngleAxisd noise_rotation(DegToRad(RandGaussian(0, 5.0)),
Vector3d::Random().normalized());
return noise_rotation * (it->second);
}
// Performs a single iterations of the translation filtering. This method is
// thread-safe.
void TranslationFilteringIteration(
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations,
std::mutex* mutex,
std::unordered_map<ViewIdPair, double>* bad_edge_weight) {
// Get a random vector to project all relative translations on to.
const Vector3d& random_axis = ChooseRandomAxis(relative_translations);
// Project all vectors.
const std::unordered_map<ViewIdPair, double>&
translation_direction_projections =
ProjectTranslationsOntoAxis(random_axis, relative_translations);
// Compute ordering.
const std::unordered_map<ViewId, int>& translation_ordering =
OrderTranslationsFromProjections(translation_direction_projections);
// Compute bad edge weights.
for (auto& edge : *bad_edge_weight) {
const int ordering_diff =
FindOrDie(translation_ordering, edge.first.second) -
FindOrDie(translation_ordering, edge.first.first);
const double& projection_weight_of_edge =
FindOrDieNoPrint(translation_direction_projections, edge.first);
VLOG(3) << "Edge (" << edge.first.first << ", " << edge.first.second
<< ") has ordering diff of " << ordering_diff
<< " and a projection of " << projection_weight_of_edge << " from "
<< FindOrDieNoPrint(relative_translations, edge.first).transpose();
// If the ordering is inconsistent, add the absolute value of the bad weight
// to the aggregate bad weight.
if ((ordering_diff < 0 && projection_weight_of_edge > 0) ||
(ordering_diff > 0 && projection_weight_of_edge < 0)) {
mutex->lock();
edge.second += std::abs(projection_weight_of_edge);
mutex->unlock();
}
}
}
void FilterViewPairsFromRelativeTranslation(
const FilterViewPairsFromRelativeTranslationOptions& options,
const std::unordered_map<ViewId, Vector3d>& orientations,
std::unordered_map<ViewIdPair, TwoViewInfo>* view_pairs) {
// Weights of edges that have been accumulated throughout the iterations. A
// higher weight means the edge is more likely to be bad.
std::unordered_map<ViewIdPair, double> bad_edge_weight;
for (const auto& view_pair : *view_pairs) {
bad_edge_weight[view_pair.first] = 0.0;
}
// Compute the adjusted translations so that they are oriented in the global
// frame.
const std::unordered_map<ViewIdPair, Vector3d>& rotated_translations =
RotateRelativeTranslationsToGlobalFrame(orientations, *view_pairs);
std::unique_ptr<ThreadPool> pool(new ThreadPool(options.num_threads));
std::mutex mutex;
for (int i = 0; i < options.num_iterations; i++) {
pool->Add(TranslationFilteringIteration,
rotated_translations,
&mutex,
&bad_edge_weight);
}
pool.reset(nullptr);
// Remove all the bad edges.
const double max_aggregated_projection_tolerance =
options.translation_projection_tolerance * options.num_iterations;
int num_view_pairs_removed = 0;
for (const auto& view_pair : bad_edge_weight) {
if (view_pair.second > max_aggregated_projection_tolerance) {
view_pairs->erase(view_pair.first);
++num_view_pairs_removed;
}
}
VLOG(1) << "Removed " << num_view_pairs_removed
<< " view pairs by relative translation filtering.";
}
} // namespace theia
<commit_msg>Using a gaussian density estimator for random axis projections. This increases performance and unit test is passing now.<commit_after>// Copyright (C) 2014 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/filter_view_pairs_from_relative_translation.h"
#include <ceres/rotation.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <memory>
#include <mutex> // NOLINT
#include <unordered_map>
#include "theia/math/util.h"
#include "theia/util/hash.h"
#include "theia/util/map_util.h"
#include "theia/util/random.h"
#include "theia/util/threadpool.h"
#include "theia/sfm/twoview_info.h"
#include "theia/sfm/types.h"
namespace theia {
using Eigen::Vector3d;
// Helper struct to maintain the graph for the translation projection problem.
struct MFASNode {
std::unordered_map<ViewId, double> incoming_nodes;
std::unordered_map<ViewId, double> outgoing_nodes;
double incoming_weight = 0;
double outgoing_weight = 0;
};
// Rotate the translation direction based on the known orientation such that the
// translation is in the global reference frame.
std::unordered_map<ViewIdPair, Vector3d>
RotateRelativeTranslationsToGlobalFrame(
const std::unordered_map<ViewId, Vector3d>& orientations,
const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs) {
std::unordered_map<ViewIdPair, Vector3d> rotated_translations;
rotated_translations.reserve(orientations.size());
for (const auto& view_pair : view_pairs) {
const Vector3d view_to_world_rotation =
-1.0 * FindOrDie(orientations, view_pair.first.first);
Vector3d rotated_translation;
ceres::AngleAxisRotatePoint(view_to_world_rotation.data(),
view_pair.second.position_2.data(),
rotated_translation.data());
rotated_translations.emplace(view_pair.first, rotated_translation);
}
return rotated_translations;
}
// Find the next view to add to the order. We attempt to choose a source (i.e.,
// a node with no incoming edges) or choose a node based on a heuristic such
// that it has the most source-like properties.
ViewId FindNextViewInOrder(
const std::unordered_map<ViewId, MFASNode>& degrees_for_view) {
ViewId best_choice = kInvalidViewId;
double best_score = 0;
for (const auto& view : degrees_for_view) {
// If the view is a source view, return it.
if (view.second.incoming_nodes.size() == 0) {
return view.first;
}
// Otherwise, keep track of the max score seen so far.
const double score = (view.second.outgoing_weight + 1.0) /
(view.second.incoming_weight + 1.0);
if (score > best_score) {
best_choice = view.first;
best_score = score;
}
}
return best_choice;
}
// Based on the 1D translation projections, compute an ordering of the
// translations.
std::unordered_map<ViewId, int> OrderTranslationsFromProjections(
const std::unordered_map<ViewIdPair, double>&
translation_direction_projections) {
// Compute the degrees of all vertices as the sum of weights coming in or out.
std::unordered_map<ViewId, MFASNode> degrees_for_view;
for (const auto& translation_projection : translation_direction_projections) {
const ViewIdPair view_id_pair =
(translation_projection.second > 0)
? translation_projection.first
: ViewIdPair(translation_projection.first.second,
translation_projection.first.first);
// Update the MFAS entry.
const double weight = std::abs(translation_projection.second);
degrees_for_view[view_id_pair.second].incoming_weight += weight;
degrees_for_view[view_id_pair.first].outgoing_weight += weight;
degrees_for_view[view_id_pair.second].incoming_nodes.emplace(
view_id_pair.first, weight);
degrees_for_view[view_id_pair.first].outgoing_nodes.emplace(
view_id_pair.second, weight);
}
// Compute the ordering.
const int num_views = degrees_for_view.size();
std::unordered_map<ViewId, int> translation_ordering;
for (int i = 0; i < num_views; i++) {
// Find the next view to add.
const ViewId next_view_in_order = FindNextViewInOrder(degrees_for_view);
translation_ordering[next_view_in_order] = i;
// Update the MFAS graph and remove the next view from the degrees_for_view.
const auto& next_view_info =
FindOrDie(degrees_for_view, next_view_in_order);
for (auto& neighbor_info : next_view_info.incoming_nodes) {
degrees_for_view[neighbor_info.first].outgoing_weight -=
neighbor_info.second;
degrees_for_view[neighbor_info.first].outgoing_nodes.erase(
next_view_in_order);
}
for (auto& neighbor_info : next_view_info.outgoing_nodes) {
degrees_for_view[neighbor_info.first].incoming_weight -=
neighbor_info.second;
degrees_for_view[neighbor_info.first].incoming_nodes.erase(
next_view_in_order);
}
degrees_for_view.erase(next_view_in_order);
}
return translation_ordering;
}
// Projects all the of the translation onto the given axis.
std::unordered_map<ViewIdPair, double> ProjectTranslationsOntoAxis(
const Vector3d& axis,
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations) {
std::unordered_map<ViewIdPair, double> projection_weights;
projection_weights.reserve(relative_translations.size());
for (const auto& relative_translation : relative_translations) {
const double projection_weight = relative_translation.second.dot(axis);
projection_weights.emplace(relative_translation.first, projection_weight);
}
return projection_weights;
}
// This chooses a random axis based on the given relative translations.
void ComputeMeanVariance(
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations,
Vector3d* mean,
Vector3d* variance) {
mean->setZero();
variance->setZero();
for (const auto& translation : relative_translations) {
*mean += translation.second;
}
*mean /= static_cast<double>(relative_translations.size());
for (const auto& translation : relative_translations) {
*variance += (translation.second - *mean).cwiseAbs2();
}
*variance /= static_cast<double>(relative_translations.size() - 1);
}
// Performs a single iterations of the translation filtering. This method is
// thread-safe.
void TranslationFilteringIteration(
const std::unordered_map<ViewIdPair, Vector3d>& relative_translations,
const Vector3d& direction_mean,
const Vector3d& direction_variance,
std::mutex* mutex,
std::unordered_map<ViewIdPair, double>* bad_edge_weight) {
// Get a random vector to project all relative translations on to.
const Vector3d random_axis(
RandGaussian(direction_mean[0], direction_variance[0]),
RandGaussian(direction_mean[1], direction_variance[1]),
RandGaussian(direction_mean[2], direction_variance[2]));
// Project all vectors.
const std::unordered_map<ViewIdPair, double>&
translation_direction_projections =
ProjectTranslationsOntoAxis(random_axis, relative_translations);
// Compute ordering.
const std::unordered_map<ViewId, int>& translation_ordering =
OrderTranslationsFromProjections(translation_direction_projections);
// Compute bad edge weights.
for (auto& edge : *bad_edge_weight) {
const int ordering_diff =
FindOrDie(translation_ordering, edge.first.second) -
FindOrDie(translation_ordering, edge.first.first);
const double& projection_weight_of_edge =
FindOrDieNoPrint(translation_direction_projections, edge.first);
VLOG(3) << "Edge (" << edge.first.first << ", " << edge.first.second
<< ") has ordering diff of " << ordering_diff
<< " and a projection of " << projection_weight_of_edge << " from "
<< FindOrDieNoPrint(relative_translations, edge.first).transpose();
// If the ordering is inconsistent, add the absolute value of the bad weight
// to the aggregate bad weight.
if ((ordering_diff < 0 && projection_weight_of_edge > 0) ||
(ordering_diff > 0 && projection_weight_of_edge < 0)) {
mutex->lock();
edge.second += std::abs(projection_weight_of_edge);
mutex->unlock();
}
}
}
void FilterViewPairsFromRelativeTranslation(
const FilterViewPairsFromRelativeTranslationOptions& options,
const std::unordered_map<ViewId, Vector3d>& orientations,
std::unordered_map<ViewIdPair, TwoViewInfo>* view_pairs) {
// Weights of edges that have been accumulated throughout the iterations. A
// higher weight means the edge is more likely to be bad.
std::unordered_map<ViewIdPair, double> bad_edge_weight;
for (const auto& view_pair : *view_pairs) {
bad_edge_weight[view_pair.first] = 0.0;
}
// Compute the adjusted translations so that they are oriented in the global
// frame.
const std::unordered_map<ViewIdPair, Vector3d>& rotated_translations =
RotateRelativeTranslationsToGlobalFrame(orientations, *view_pairs);
Vector3d translation_mean, translation_variance;
ComputeMeanVariance(rotated_translations,
&translation_mean,
&translation_variance);
std::unique_ptr<ThreadPool> pool(new ThreadPool(options.num_threads));
std::mutex mutex;
for (int i = 0; i < options.num_iterations; i++) {
pool->Add(TranslationFilteringIteration,
rotated_translations,
translation_mean,
translation_variance,
&mutex,
&bad_edge_weight);
}
pool.reset(nullptr);
// Remove all the bad edges.
const double max_aggregated_projection_tolerance =
options.translation_projection_tolerance * options.num_iterations;
int num_view_pairs_removed = 0;
for (const auto& view_pair : bad_edge_weight) {
VLOG(3) << "View pair (" << view_pair.first.first << ", "
<< view_pair.first.second << ") projection = " << view_pair.second;
if (view_pair.second > max_aggregated_projection_tolerance) {
view_pairs->erase(view_pair.first);
++num_view_pairs_removed;
}
}
VLOG(1) << "Removed " << num_view_pairs_removed
<< " view pairs by relative translation filtering.";
}
} // namespace theia
<|endoftext|>
|
<commit_before>
#include "PropertyGeneration.h"
#include "base_types.h"
#include "utils.h"
#include "logging.h"
#include "standard_properties.h"
#include <linux/videodev2.h>
#include <cstring>
#include <algorithm>
using namespace tcam;
std::vector<std::shared_ptr<Property>> tcam::generate_simulated_properties (std::vector<std::shared_ptr<Property>> props,
std::shared_ptr<PropertyImpl> impl)
{
std::vector<std::shared_ptr<Property>> new_properties;
// requirements for auto center
if (find_property(props, "Offset Auto Center") == nullptr &&
find_property(props, "Offset X") != nullptr &&
find_property(props, "Offset Y") != nullptr)
{
camera_property cp = {};
strcpy(cp.name, "Offset Auto Center");
cp.type = PROPERTY_TYPE_BOOLEAN;
cp.value.b.default_value = false;
cp.value.b.value = cp.value.b.default_value;
cp.flags = set_bit(cp.flags, PROPERTY_FLAG_EXTERNAL);
auto property_auto_offset = std::make_shared<PropertyBoolean>(impl, cp, Property::BOOLEAN);
// property_description pd = { EMULATED_PROPERTY, property_auto_offset};
tcam_log(TCAM_LOG_DEBUG, "Adding 'Offset Auto Center' to property list");
new_properties.push_back(property_auto_offset);
}
return new_properties;
}
bool tcam::handle_auto_center (const Property& new_property,
std::vector<std::shared_ptr<Property>>& props,
const IMG_SIZE& sensor,
const IMG_SIZE& current_format)
{
if (new_property.getType() != PROPERTY_TYPE_BOOLEAN)
{
return false;
}
auto p = static_cast<const PropertyBoolean&>(new_property);
if (p.getValue())
{
IMG_SIZE values = calculate_auto_center(sensor, current_format);
auto prop_off_x = find_property(props, "Offset X");
auto prop_off_y = find_property(props, "Offset Y");
std::static_pointer_cast<PropertyInteger>(prop_off_x)->setValue(values.width);
std::static_pointer_cast<PropertyInteger>(prop_off_y)->setValue(values.height);
// TODO: set properties read only
}
else
{
// TODO: remove read only
auto prop_off_x = find_property(props, "Offset X");
auto prop_off_y = find_property(props, "Offset Y");
std::static_pointer_cast<PropertyInteger>(prop_off_x)->setValue(0);
std::static_pointer_cast<PropertyInteger>(prop_off_y)->setValue(0);
}
}
<commit_msg>Switched property offset auto simulation to PROPERTY_ID usage<commit_after>
#include "PropertyGeneration.h"
#include "base_types.h"
#include "utils.h"
#include "logging.h"
#include "standard_properties.h"
#include <linux/videodev2.h>
#include <cstring>
#include <algorithm>
using namespace tcam;
std::vector<std::shared_ptr<Property>> tcam::generate_simulated_properties (std::vector<std::shared_ptr<Property>> props,
std::shared_ptr<PropertyImpl> impl)
{
std::vector<std::shared_ptr<Property>> new_properties;
// requirements for auto center
if (find_property(props, PROPERTY_OFFSET_AUTO) == nullptr &&
find_property(props, PROPERTY_OFFSET_X) != nullptr &&
find_property(props, PROPERTY_OFFSET_Y) != nullptr)
{
camera_property cp = {};
cp.id = PROPERTY_OFFSET_AUTO;
strcpy(cp.name, "Offset Auto Center");
cp.type = PROPERTY_TYPE_BOOLEAN;
cp.value.b.default_value = false;
cp.value.b.value = cp.value.b.default_value;
cp.flags = set_bit(cp.flags, PROPERTY_FLAG_EXTERNAL);
auto property_auto_offset = std::make_shared<PropertyBoolean>(impl, cp, Property::BOOLEAN);
// property_description pd = { EMULATED_PROPERTY, property_auto_offset};
tcam_log(TCAM_LOG_DEBUG, "Adding 'Offset Auto Center' to property list");
new_properties.push_back(property_auto_offset);
}
return new_properties;
}
bool tcam::handle_auto_center (const Property& new_property,
std::vector<std::shared_ptr<Property>>& props,
const IMG_SIZE& sensor,
const IMG_SIZE& current_format)
{
if (new_property.getType() != PROPERTY_TYPE_BOOLEAN)
{
return false;
}
auto p = static_cast<const PropertyBoolean&>(new_property);
if (p.getValue())
{
IMG_SIZE values = calculate_auto_center(sensor, current_format);
auto prop_off_x = find_property(props, "Offset X");
auto prop_off_y = find_property(props, "Offset Y");
std::static_pointer_cast<PropertyInteger>(prop_off_x)->setValue(values.width);
std::static_pointer_cast<PropertyInteger>(prop_off_y)->setValue(values.height);
// TODO: set properties read only
}
else
{
// TODO: remove read only
auto prop_off_x = find_property(props, "Offset X");
auto prop_off_y = find_property(props, "Offset Y");
std::static_pointer_cast<PropertyInteger>(prop_off_x)->setValue(0);
std::static_pointer_cast<PropertyInteger>(prop_off_y)->setValue(0);
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include <algorithm>
#include <vector>
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
namespace gpu = ::perftools::gputools;
namespace tensorflow {
namespace {
static void CheckStats(Allocator* a, int64 num_allocs, int64 bytes_in_use,
int64 max_bytes_in_use, int64 max_alloc_size) {
AllocatorStats stats;
a->GetStats(&stats);
LOG(INFO) << "Alloc stats: " << std::endl << stats.DebugString();
EXPECT_EQ(stats.bytes_in_use, bytes_in_use);
EXPECT_EQ(stats.max_bytes_in_use, max_bytes_in_use);
EXPECT_EQ(stats.num_allocs, num_allocs);
EXPECT_EQ(stats.max_alloc_size, max_alloc_size);
}
TEST(GPUBFCAllocatorTest, NoDups) {
GPUBFCAllocator a(0, 1 << 30);
CheckStats(&a, 0, 0, 0, 0);
// Allocate a lot of raw pointers
std::vector<void*> ptrs;
for (int s = 1; s < 1024; s++) {
void* raw = a.AllocateRaw(1, s);
ptrs.push_back(raw);
}
CheckStats(&a, 1023, 654336, 654336, 1024);
std::sort(ptrs.begin(), ptrs.end());
// Make sure none of them are equal, and that none of them overlap.
for (size_t i = 1; i < ptrs.size(); i++) {
ASSERT_NE(ptrs[i], ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(ptrs[i - 1]);
ASSERT_GT(req_size, 0);
ASSERT_GE(static_cast<char*>(ptrs[i]) - static_cast<char*>(ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < ptrs.size(); i++) {
a.DeallocateRaw(ptrs[i]);
}
CheckStats(&a, 1023, 0, 654336, 1024);
}
TEST(GPUBFCAllocatorTest, AllocationsAndDeallocations) {
GPUBFCAllocator a(0, 1 << 30);
// Allocate 256 raw pointers of sizes between 100 bytes and about
// a meg
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
std::vector<void*> initial_ptrs;
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
// Deallocate half of the memory, and keep track of the others.
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
// Allocate a lot of raw pointers
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
// Make sure none of them are equal
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
// Check that they don't overlap.
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
}
TEST(GPUBFCAllocatorTest, ExerciseCoalescing) {
GPUBFCAllocator a(0, 1 << 30);
CheckStats(&a, 0, 0, 0, 0);
float* first_ptr = a.Allocate<float>(1024);
a.DeallocateRaw(first_ptr);
CheckStats(&a, 1, 0, 4096, 4096);
for (int i = 0; i < 1024; ++i) {
// Allocate several buffers of different sizes, and then clean them
// all up. We should be able to repeat this endlessly without
// causing fragmentation and growth.
float* t1 = a.Allocate<float>(1024);
int64* t2 = a.Allocate<int64>(1048576);
double* t3 = a.Allocate<double>(2048);
float* t4 = a.Allocate<float>(10485760);
a.DeallocateRaw(t1);
a.DeallocateRaw(t2);
a.DeallocateRaw(t3);
a.DeallocateRaw(t4);
}
CheckStats(&a, 4097, 0, 1024 * sizeof(float) + 1048576 * sizeof(int64) +
2048 * sizeof(double) + 10485760 * sizeof(float),
10485760 * sizeof(float));
// At the end, we should have coalesced all memory into one region
// starting at the beginning, so validate that allocating a pointer
// starts from this region.
float* first_ptr_after = a.Allocate<float>(1024);
EXPECT_EQ(first_ptr, first_ptr_after);
a.DeallocateRaw(first_ptr_after);
}
TEST(GPUBFCAllocatorTest, AllocateZeroBufSize) {
GPUBFCAllocator a(0, 1 << 30);
float* ptr = a.Allocate<float>(0);
EXPECT_EQ(nullptr, ptr);
}
TEST(GPUBFCAllocatorTest, TracksSizes) {
GPUBFCAllocator a(0, 1 << 30);
EXPECT_EQ(true, a.TracksAllocationSizes());
}
TEST(GPUBFCAllocatorTest, AllocatedVsRequested) {
GPUBFCAllocator a(0, 1 << 30);
float* t1 = a.Allocate<float>(1);
EXPECT_EQ(4, a.RequestedSize(t1));
EXPECT_EQ(256, a.AllocatedSize(t1));
a.DeallocateRaw(t1);
}
TEST(GPUBFCAllocatorTest, TestCustomMemoryLimit) {
// Configure a 1MiB byte limit
GPUBFCAllocator a(0, 1 << 20);
float* first_ptr = a.Allocate<float>(1 << 6);
float* second_ptr = a.Allocate<float>(1 << 20);
EXPECT_NE(nullptr, first_ptr);
EXPECT_EQ(nullptr, second_ptr);
a.DeallocateRaw(first_ptr);
}
TEST(GPUBFCAllocatorTest, AllocationsAndDeallocationsWithGrowth) {
GPUOptions options;
options.set_allow_growth(true);
// Max of 2GiB, but starts out small.
GPUBFCAllocator a(0, 1LL << 31, options);
// Allocate 10 raw pointers of sizes between 100 bytes and about
// 64 megs.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
const int32 max_mem = 1 << 27;
std::vector<void*> initial_ptrs;
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem, 100), max_mem);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
// Deallocate half of the memory, and keep track of the others.
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
const int32 max_mem_2 = 1 << 26;
// Allocate a lot of raw pointers between 100 bytes and 64 megs.
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem_2, 100), max_mem_2);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
// Make sure none of them are equal
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
// Check that they don't overlap.
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
AllocatorStats stats;
a.GetStats(&stats);
LOG(INFO) << "Alloc stats: \n" << stats.DebugString();
}
static void BM_Allocation(int iters) {
GPUBFCAllocator a(0, 1uLL << 33);
// Exercise a few different allocation sizes
std::vector<size_t> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600,
1048576000, 2048576000};
int size_index = 0;
while (--iters > 0) {
size_t bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
}
}
BENCHMARK(BM_Allocation);
static void BM_AllocationThreaded(int iters, int num_threads) {
GPUBFCAllocator a(0, 1uLL << 33);
thread::ThreadPool pool(Env::Default(), "test", num_threads);
std::atomic_int_fast32_t count(iters);
mutex done_lock;
condition_variable done;
bool done_flag = false;
for (int t = 0; t < num_threads; t++) {
pool.Schedule([&a, &count, &done_lock, &done, &done_flag, iters]() {
// Exercise a few different allocation sizes
std::vector<int> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600};
int size_index = 0;
for (int i = 0; i < iters; i++) {
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
if (count.fetch_sub(1) == 1) {
mutex_lock l(done_lock);
done_flag = true;
done.notify_all();
break;
}
}
});
}
mutex_lock l(done_lock);
if (!done_flag) {
done.wait(l);
}
}
BENCHMARK(BM_AllocationThreaded)->Arg(1)->Arg(4)->Arg(16);
// A more complex benchmark that defers deallocation of an object for
// "delay" allocations.
static void BM_AllocationDelayed(int iters, int delay) {
GPUBFCAllocator a(0, 1 << 30);
// Exercise a few different allocation sizes
std::vector<int> sizes = {256, 4096, 16384, 4096, 512, 1024, 1024};
int size_index = 0;
std::vector<void*> ptrs;
for (int i = 0; i < delay; i++) {
ptrs.push_back(nullptr);
}
int pindex = 0;
while (--iters > 0) {
if (ptrs[pindex] != nullptr) {
a.DeallocateRaw(ptrs[pindex]);
ptrs[pindex] = nullptr;
}
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
ptrs[pindex] = p;
pindex = (pindex + 1) % ptrs.size();
}
for (int i = 0; i < ptrs.size(); i++) {
if (ptrs[i] != nullptr) {
a.DeallocateRaw(ptrs[i]);
}
}
}
BENCHMARK(BM_AllocationDelayed)->Arg(1)->Arg(10)->Arg(100)->Arg(1000);
} // namespace
} // namespace tensorflow
#endif // GOOGLE_CUDA
<commit_msg>Fix GPU BUILD Change: 119431584<commit_after>/* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA
#include "tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.h"
#include <algorithm>
#include <vector>
#include "tensorflow/core/common_runtime/gpu/gpu_init.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"
namespace gpu = ::perftools::gputools;
namespace tensorflow {
namespace {
static void CheckStats(Allocator* a, int64 num_allocs, int64 bytes_in_use,
int64 max_bytes_in_use, int64 max_alloc_size) {
AllocatorStats stats;
a->GetStats(&stats);
LOG(INFO) << "Alloc stats: " << std::endl << stats.DebugString();
EXPECT_EQ(stats.bytes_in_use, bytes_in_use);
EXPECT_EQ(stats.max_bytes_in_use, max_bytes_in_use);
EXPECT_EQ(stats.num_allocs, num_allocs);
EXPECT_EQ(stats.max_alloc_size, max_alloc_size);
}
TEST(GPUBFCAllocatorTest, NoDups) {
GPUBFCAllocator a(0, 1 << 30);
CheckStats(&a, 0, 0, 0, 0);
// Allocate a lot of raw pointers
std::vector<void*> ptrs;
for (int s = 1; s < 1024; s++) {
void* raw = a.AllocateRaw(1, s);
ptrs.push_back(raw);
}
CheckStats(&a, 1023, 654336, 654336, 1024);
std::sort(ptrs.begin(), ptrs.end());
// Make sure none of them are equal, and that none of them overlap.
for (size_t i = 1; i < ptrs.size(); i++) {
ASSERT_NE(ptrs[i], ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(ptrs[i - 1]);
ASSERT_GT(req_size, 0);
ASSERT_GE(static_cast<char*>(ptrs[i]) - static_cast<char*>(ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < ptrs.size(); i++) {
a.DeallocateRaw(ptrs[i]);
}
CheckStats(&a, 1023, 0, 654336, 1024);
}
TEST(GPUBFCAllocatorTest, AllocationsAndDeallocations) {
GPUBFCAllocator a(0, 1 << 30);
// Allocate 256 raw pointers of sizes between 100 bytes and about
// a meg
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
std::vector<void*> initial_ptrs;
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
// Deallocate half of the memory, and keep track of the others.
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
// Allocate a lot of raw pointers
for (int s = 1; s < 256; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % 1048576, 100), 1048576);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
// Make sure none of them are equal
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
// Check that they don't overlap.
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
}
TEST(GPUBFCAllocatorTest, ExerciseCoalescing) {
GPUBFCAllocator a(0, 1 << 30);
CheckStats(&a, 0, 0, 0, 0);
float* first_ptr = a.Allocate<float>(1024);
a.DeallocateRaw(first_ptr);
CheckStats(&a, 1, 0, 4096, 4096);
for (int i = 0; i < 1024; ++i) {
// Allocate several buffers of different sizes, and then clean them
// all up. We should be able to repeat this endlessly without
// causing fragmentation and growth.
float* t1 = a.Allocate<float>(1024);
int64* t2 = a.Allocate<int64>(1048576);
double* t3 = a.Allocate<double>(2048);
float* t4 = a.Allocate<float>(10485760);
a.DeallocateRaw(t1);
a.DeallocateRaw(t2);
a.DeallocateRaw(t3);
a.DeallocateRaw(t4);
}
CheckStats(&a, 4097, 0, 1024 * sizeof(float) + 1048576 * sizeof(int64) +
2048 * sizeof(double) + 10485760 * sizeof(float),
10485760 * sizeof(float));
// At the end, we should have coalesced all memory into one region
// starting at the beginning, so validate that allocating a pointer
// starts from this region.
float* first_ptr_after = a.Allocate<float>(1024);
EXPECT_EQ(first_ptr, first_ptr_after);
a.DeallocateRaw(first_ptr_after);
}
TEST(GPUBFCAllocatorTest, AllocateZeroBufSize) {
GPUBFCAllocator a(0, 1 << 30);
float* ptr = a.Allocate<float>(0);
EXPECT_EQ(nullptr, ptr);
}
TEST(GPUBFCAllocatorTest, TracksSizes) {
GPUBFCAllocator a(0, 1 << 30);
EXPECT_EQ(true, a.TracksAllocationSizes());
}
TEST(GPUBFCAllocatorTest, AllocatedVsRequested) {
GPUBFCAllocator a(0, 1 << 30);
float* t1 = a.Allocate<float>(1);
EXPECT_EQ(4, a.RequestedSize(t1));
EXPECT_EQ(256, a.AllocatedSize(t1));
a.DeallocateRaw(t1);
}
TEST(GPUBFCAllocatorTest, TestCustomMemoryLimit) {
// Configure a 1MiB byte limit
GPUBFCAllocator a(0, 1 << 20);
float* first_ptr = a.Allocate<float>(1 << 6);
float* second_ptr = a.Allocate<float>(1 << 20);
EXPECT_NE(nullptr, first_ptr);
EXPECT_EQ(nullptr, second_ptr);
a.DeallocateRaw(first_ptr);
}
TEST(GPUBFCAllocatorTest, AllocationsAndDeallocationsWithGrowth) {
GPUOptions options;
options.set_allow_growth(true);
// Max of 2GiB, but starts out small.
GPUBFCAllocator a(0, 1LL << 31, options);
// Allocate 10 raw pointers of sizes between 100 bytes and about
// 64 megs.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rand(&philox);
const int32 max_mem = 1 << 27;
std::vector<void*> initial_ptrs;
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem, 100), max_mem);
void* raw = a.AllocateRaw(1, size);
initial_ptrs.push_back(raw);
}
// Deallocate half of the memory, and keep track of the others.
std::vector<void*> existing_ptrs;
for (size_t i = 0; i < initial_ptrs.size(); i++) {
if (i % 2 == 1) {
a.DeallocateRaw(initial_ptrs[i]);
} else {
existing_ptrs.push_back(initial_ptrs[i]);
}
}
const int32 max_mem_2 = 1 << 26;
// Allocate a lot of raw pointers between 100 bytes and 64 megs.
for (int s = 1; s < 10; s++) {
size_t size = std::min<size_t>(
std::max<size_t>(rand.Rand32() % max_mem_2, 100), max_mem_2);
void* raw = a.AllocateRaw(1, size);
existing_ptrs.push_back(raw);
}
std::sort(existing_ptrs.begin(), existing_ptrs.end());
// Make sure none of them are equal
for (size_t i = 1; i < existing_ptrs.size(); i++) {
CHECK_NE(existing_ptrs[i], existing_ptrs[i - 1]); // No dups
size_t req_size = a.RequestedSize(existing_ptrs[i - 1]);
ASSERT_GT(req_size, 0);
// Check that they don't overlap.
ASSERT_GE(static_cast<char*>(existing_ptrs[i]) -
static_cast<char*>(existing_ptrs[i - 1]),
req_size);
}
for (size_t i = 0; i < existing_ptrs.size(); i++) {
a.DeallocateRaw(existing_ptrs[i]);
}
AllocatorStats stats;
a.GetStats(&stats);
LOG(INFO) << "Alloc stats: \n" << stats.DebugString();
}
static void BM_Allocation(int iters) {
GPUBFCAllocator a(0, 1uLL << 33);
// Exercise a few different allocation sizes
std::vector<size_t> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600,
1048576000, 2048576000};
int size_index = 0;
while (--iters > 0) {
size_t bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
}
}
BENCHMARK(BM_Allocation);
static void BM_AllocationThreaded(int iters, int num_threads) {
GPUBFCAllocator a(0, 1uLL << 33);
thread::ThreadPool pool(Env::Default(), "test", num_threads);
std::atomic_int_fast32_t count(iters);
mutex done_lock;
condition_variable done;
bool done_flag = false;
for (int t = 0; t < num_threads; t++) {
pool.Schedule([&a, &count, &done_lock, &done, &done_flag, iters]() {
// Exercise a few different allocation sizes
std::vector<int> sizes = {256, 4096, 16384, 524288,
512, 1048576, 10485760, 104857600};
int size_index = 0;
for (int i = 0; i < iters; i++) {
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
a.DeallocateRaw(p);
if (count.fetch_sub(1) == 1) {
mutex_lock l(done_lock);
done_flag = true;
done.notify_all();
break;
}
}
});
}
mutex_lock l(done_lock);
if (!done_flag) {
done.wait(l);
}
}
BENCHMARK(BM_AllocationThreaded)->Arg(1)->Arg(4)->Arg(16);
// A more complex benchmark that defers deallocation of an object for
// "delay" allocations.
static void BM_AllocationDelayed(int iters, int delay) {
GPUBFCAllocator a(0, 1 << 30);
// Exercise a few different allocation sizes
std::vector<int> sizes = {256, 4096, 16384, 4096, 512, 1024, 1024};
int size_index = 0;
std::vector<void*> ptrs;
for (int i = 0; i < delay; i++) {
ptrs.push_back(nullptr);
}
int pindex = 0;
while (--iters > 0) {
if (ptrs[pindex] != nullptr) {
a.DeallocateRaw(ptrs[pindex]);
ptrs[pindex] = nullptr;
}
int bytes = sizes[size_index++ % sizes.size()];
void* p = a.AllocateRaw(1, bytes);
ptrs[pindex] = p;
pindex = (pindex + 1) % ptrs.size();
}
for (int i = 0; i < ptrs.size(); i++) {
if (ptrs[i] != nullptr) {
a.DeallocateRaw(ptrs[i]);
}
}
}
BENCHMARK(BM_AllocationDelayed)->Arg(1)->Arg(10)->Arg(100)->Arg(1000);
} // namespace
} // namespace tensorflow
#endif // GOOGLE_CUDA
<|endoftext|>
|
<commit_before>#include "ScaledImageFactory.h"
#include <memory>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>
using namespace std;
// blends a foreground RGB triplet (fg) onto a background RGB triplet (bg)
// using the given alpha value; returns the blended result
// http://stackoverflow.com/questions/12011081/alpha-blending-2-rgba-colors-in-c/12016968#12016968
inline void BlendRgb
(
unsigned char* dst,
const unsigned char* fg,
const unsigned char* bg,
const unsigned char alpha
)
{
const unsigned int intAlpha = alpha + 1;
const unsigned int invAlpha = 256 - alpha;
for( size_t i = 0; i < 3; ++i )
{
dst[i] = ( ( intAlpha * fg[i] + invAlpha * bg[i] ) >> 8 );
}
}
// blends fg onto a repeating pattern of bg into dst
// bg dimensions must be powers-of-two
void BlendPattern
(
wxImage& dst,
const wxImage& fg,
const wxImage& bg
)
{
const size_t fgW = static_cast< size_t >( fg.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const size_t bgW = static_cast< size_t >( bg.GetWidth() );
const size_t bgH = static_cast< size_t >( bg.GetHeight() );
const unsigned char* fgData = fg.GetData();
const unsigned char* fgAlpha = fg.GetAlpha();
unsigned char* bgData = bg.GetData();
unsigned char* dstData = dst.GetData();
for( size_t y = 0; y < dstH; ++y )
{
unsigned char* dstPx = &dstData[ y * dstW * 3 ];
const unsigned char* fgPx = &fgData[ y * fgW * 3 ];
const unsigned char* fgAlphaPx = &fgAlpha[ y * fgW ];
const size_t bgY = ( y & ( bgH-1 ) ) * bgW * 3;
const unsigned char* bgRow = &bgData[ bgY ];
for( size_t x = 0; x < dstW; ++x )
{
const size_t bgX = ( x & ( bgW-1 ) ) * 3;
const unsigned char* bgPx = &bgRow[ bgX ];
BlendRgb( dstPx, fgPx, bgPx, *fgAlphaPx );
dstPx += 3;
fgPx += 3;
fgAlphaPx += 1;
}
}
}
void GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos, const int filter )
{
if( filter == -1 )
{
const size_t srcW = static_cast< size_t >( src.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const float scaleInv = 1.0f / scale;
// color
{
const unsigned char* srcData = src.GetData();
unsigned char* dstData = dst.GetData();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX * 3 ];
dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];
dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];
dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];
}
}
}
if( !src.HasAlpha() )
return;
// alpha
{
const unsigned char* srcData = src.GetAlpha();
unsigned char* dstData = dst.GetAlpha();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX ];
dstRow[ dstX + 0 ] = srcPx[ 0 ];
}
}
}
}
else
{
const stbir_filter filter = STBIR_FILTER_TRIANGLE;
const stbir_edge edge = STBIR_EDGE_CLAMP;
const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;
stbir_resize_subpixel
(
src.GetData(), src.GetWidth(), src.GetHeight(), 0,
dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
3,
0,
STBIR_ALPHA_CHANNEL_NONE,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
if( !src.HasAlpha() )
return;
stbir_resize_subpixel
(
src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,
dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
1,
0,
STBIR_FLAG_ALPHA_PREMULTIPLIED,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
}
}
// threadland
wxThread::ExitCode ScaledImageFactory::Entry()
{
JobItem job;
while( wxMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )
{
if( NULL == job.second.mImage || wxThread::This()->TestDestroy() )
break;
const ExtRect& rect = job.first;
Context& ctx = job.second;
ResultItem result;
result.mGeneration = ctx.mGeneration;
result.mRect = rect;
// skip this rect if it isn't currently visible
{
wxCriticalSectionLocker locker( mVisibleCs );
if( !mVisible.Intersects( get<2>( rect ) ) )
{
mResultQueue.Post( result );
continue;
}
}
wxImagePtr temp( new wxImage( get<2>( rect ).GetSize(), false ) );
if( ctx.mImage->HasAlpha() )
{
temp->SetAlpha( NULL );
}
GetScaledSubrect
(
*temp,
*ctx.mImage,
ctx.mScale,
get<2>( rect ).GetPosition(),
get<1>( rect )
);
if( ctx.mImage->HasAlpha() )
{
result.mImage = new wxImage( get<2>( rect ).GetSize(), false );
BlendPattern( *result.mImage, *temp, mStipple );
}
else
{
result.mImage = temp;
}
mResultQueue.Post( result );
wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
}
return static_cast< wxThread::ExitCode >( 0 );
}
ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
: mEventSink( eventSink ), mEventId( id )
{
size_t numThreads = wxThread::GetCPUCount();
if( numThreads <= 0 ) numThreads = 1;
if( numThreads > 1 ) numThreads--;
for( size_t i = 0; i < numThreads; ++i )
{
CreateThread();
}
for( wxThread*& thread : GetThreads() )
{
if( NULL == thread )
continue;
if( thread->Run() != wxTHREAD_NO_ERROR )
{
delete thread;
thread = NULL;
}
}
mCurrentCtx.mGeneration = 0;
mCurrentCtx.mScale = 1.0;
mStipple.LoadFile( "background.png" );
}
ScaledImageFactory::~ScaledImageFactory()
{
// clear job queue and send down "kill" jobs
mJobPool.Clear();
for( size_t i = 0; i < GetThreads().size(); ++i )
{
mJobPool.Post( JobItem( ExtRect(), Context() ) );
}
for( wxThread* thread : GetThreads() )
{
if( NULL == thread )
continue;
thread->Wait();
}
}
void ScaledImageFactory::SetImage( wxImagePtr& newImage )
{
if( NULL == newImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mImage = newImage;
mJobPool.Clear();
}
void ScaledImageFactory::SetScale( double newScale )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mGeneration++;
mCurrentCtx.mScale = newScale;
mJobPool.Clear();
}
bool ScaledImageFactory::AddRect( const ExtRect& rect )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
return( wxMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );
}
bool ScaledImageFactory::GetImage( ExtRect& rect, wxImagePtr& image )
{
ResultItem item;
wxMessageQueueError err;
while( true )
{
err = mResultQueue.ReceiveTimeout( 0, item );
if( wxMSGQUEUE_TIMEOUT == err )
return false;
if( wxMSGQUEUE_MISC_ERROR == err )
throw std::runtime_error( "ResultQueue misc error!" );
if( item.mGeneration != mCurrentCtx.mGeneration )
continue;
break;
}
rect = item.mRect;
image = item.mImage;
return true;
}
void ScaledImageFactory::SetVisibleArea( const wxRect& visible )
{
wxCriticalSectionLocker locker( mVisibleCs );
mVisible = visible;
}
<commit_msg>Fix error enums for jobpool<commit_after>#include "ScaledImageFactory.h"
#include <memory>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include <stb/stb_image_resize.h>
using namespace std;
// blends a foreground RGB triplet (fg) onto a background RGB triplet (bg)
// using the given alpha value; returns the blended result
// http://stackoverflow.com/questions/12011081/alpha-blending-2-rgba-colors-in-c/12016968#12016968
inline void BlendRgb
(
unsigned char* dst,
const unsigned char* fg,
const unsigned char* bg,
const unsigned char alpha
)
{
const unsigned int intAlpha = alpha + 1;
const unsigned int invAlpha = 256 - alpha;
for( size_t i = 0; i < 3; ++i )
{
dst[i] = ( ( intAlpha * fg[i] + invAlpha * bg[i] ) >> 8 );
}
}
// blends fg onto a repeating pattern of bg into dst
// bg dimensions must be powers-of-two
void BlendPattern
(
wxImage& dst,
const wxImage& fg,
const wxImage& bg
)
{
const size_t fgW = static_cast< size_t >( fg.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const size_t bgW = static_cast< size_t >( bg.GetWidth() );
const size_t bgH = static_cast< size_t >( bg.GetHeight() );
const unsigned char* fgData = fg.GetData();
const unsigned char* fgAlpha = fg.GetAlpha();
unsigned char* bgData = bg.GetData();
unsigned char* dstData = dst.GetData();
for( size_t y = 0; y < dstH; ++y )
{
unsigned char* dstPx = &dstData[ y * dstW * 3 ];
const unsigned char* fgPx = &fgData[ y * fgW * 3 ];
const unsigned char* fgAlphaPx = &fgAlpha[ y * fgW ];
const size_t bgY = ( y & ( bgH-1 ) ) * bgW * 3;
const unsigned char* bgRow = &bgData[ bgY ];
for( size_t x = 0; x < dstW; ++x )
{
const size_t bgX = ( x & ( bgW-1 ) ) * 3;
const unsigned char* bgPx = &bgRow[ bgX ];
BlendRgb( dstPx, fgPx, bgPx, *fgAlphaPx );
dstPx += 3;
fgPx += 3;
fgAlphaPx += 1;
}
}
}
void GetScaledSubrect( wxImage& dst, const wxImage& src, const double scale, const wxPoint& pos, const int filter )
{
if( filter == -1 )
{
const size_t srcW = static_cast< size_t >( src.GetWidth() );
const size_t dstW = static_cast< size_t >( dst.GetWidth() );
const size_t dstH = static_cast< size_t >( dst.GetHeight() );
const float scaleInv = 1.0f / scale;
// color
{
const unsigned char* srcData = src.GetData();
unsigned char* dstData = dst.GetData();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW * 3 ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW * 3 ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX * 3 ];
dstRow[ dstX * 3 + 0 ] = srcPx[ 0 ];
dstRow[ dstX * 3 + 1 ] = srcPx[ 1 ];
dstRow[ dstX * 3 + 2 ] = srcPx[ 2 ];
}
}
}
if( !src.HasAlpha() )
return;
// alpha
{
const unsigned char* srcData = src.GetAlpha();
unsigned char* dstData = dst.GetAlpha();
for( size_t dstY = 0; dstY < dstH; ++dstY )
{
unsigned char* dstRow = &dstData[ dstY * dstW ];
const size_t srcY( ( dstY + pos.y ) * scaleInv );
const unsigned char* srcRow = &srcData[ srcY * srcW ];
for( size_t dstX = 0; dstX < dstW; ++dstX )
{
const size_t srcX( ( dstX + pos.x ) * scaleInv );
const unsigned char* srcPx = &srcRow[ srcX ];
dstRow[ dstX + 0 ] = srcPx[ 0 ];
}
}
}
}
else
{
const stbir_filter filter = STBIR_FILTER_TRIANGLE;
const stbir_edge edge = STBIR_EDGE_CLAMP;
const stbir_colorspace colorspace = STBIR_COLORSPACE_SRGB;
stbir_resize_subpixel
(
src.GetData(), src.GetWidth(), src.GetHeight(), 0,
dst.GetData(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
3,
0,
STBIR_ALPHA_CHANNEL_NONE,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
if( !src.HasAlpha() )
return;
stbir_resize_subpixel
(
src.GetAlpha(), src.GetWidth(), src.GetHeight(), 0,
dst.GetAlpha(), dst.GetWidth(), dst.GetHeight(), 0,
STBIR_TYPE_UINT8,
1,
0,
STBIR_FLAG_ALPHA_PREMULTIPLIED,
edge, edge,
filter, filter,
colorspace,
NULL,
scale, scale,
static_cast< float >( pos.x ), static_cast< float >( pos.y )
);
}
}
// threadland
wxThread::ExitCode ScaledImageFactory::Entry()
{
JobItem job;
while( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Receive( job ) )
{
if( NULL == job.second.mImage || wxThread::This()->TestDestroy() )
break;
const ExtRect& rect = job.first;
Context& ctx = job.second;
ResultItem result;
result.mGeneration = ctx.mGeneration;
result.mRect = rect;
// skip this rect if it isn't currently visible
{
wxCriticalSectionLocker locker( mVisibleCs );
if( !mVisible.Intersects( get<2>( rect ) ) )
{
mResultQueue.Post( result );
continue;
}
}
wxImagePtr temp( new wxImage( get<2>( rect ).GetSize(), false ) );
if( ctx.mImage->HasAlpha() )
{
temp->SetAlpha( NULL );
}
GetScaledSubrect
(
*temp,
*ctx.mImage,
ctx.mScale,
get<2>( rect ).GetPosition(),
get<1>( rect )
);
if( ctx.mImage->HasAlpha() )
{
result.mImage = new wxImage( get<2>( rect ).GetSize(), false );
BlendPattern( *result.mImage, *temp, mStipple );
}
else
{
result.mImage = temp;
}
mResultQueue.Post( result );
wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
}
return static_cast< wxThread::ExitCode >( 0 );
}
ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
: mEventSink( eventSink ), mEventId( id )
{
size_t numThreads = wxThread::GetCPUCount();
if( numThreads <= 0 ) numThreads = 1;
if( numThreads > 1 ) numThreads--;
for( size_t i = 0; i < numThreads; ++i )
{
CreateThread();
}
for( wxThread*& thread : GetThreads() )
{
if( NULL == thread )
continue;
if( thread->Run() != wxTHREAD_NO_ERROR )
{
delete thread;
thread = NULL;
}
}
mCurrentCtx.mGeneration = 0;
mCurrentCtx.mScale = 1.0;
mStipple.LoadFile( "background.png" );
}
ScaledImageFactory::~ScaledImageFactory()
{
// clear job queue and send down "kill" jobs
mJobPool.Clear();
for( size_t i = 0; i < GetThreads().size(); ++i )
{
mJobPool.Post( JobItem( ExtRect(), Context() ) );
}
for( wxThread* thread : GetThreads() )
{
if( NULL == thread )
continue;
thread->Wait();
}
}
void ScaledImageFactory::SetImage( wxImagePtr& newImage )
{
if( NULL == newImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mImage = newImage;
mJobPool.Clear();
}
void ScaledImageFactory::SetScale( double newScale )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
mCurrentCtx.mGeneration++;
mCurrentCtx.mScale = newScale;
mJobPool.Clear();
}
bool ScaledImageFactory::AddRect( const ExtRect& rect )
{
if( NULL == mCurrentCtx.mImage )
throw std::runtime_error( "Image not set!" );
return( wxSORTABLEMSGQUEUE_NO_ERROR == mJobPool.Post( JobItem( rect, mCurrentCtx ) ) );
}
bool ScaledImageFactory::GetImage( ExtRect& rect, wxImagePtr& image )
{
ResultItem item;
wxMessageQueueError err;
while( true )
{
err = mResultQueue.ReceiveTimeout( 0, item );
if( wxMSGQUEUE_TIMEOUT == err )
return false;
if( wxMSGQUEUE_MISC_ERROR == err )
throw std::runtime_error( "ResultQueue misc error!" );
if( item.mGeneration != mCurrentCtx.mGeneration )
continue;
break;
}
rect = item.mRect;
image = item.mImage;
return true;
}
void ScaledImageFactory::SetVisibleArea( const wxRect& visible )
{
wxCriticalSectionLocker locker( mVisibleCs );
mVisible = visible;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
class A {
public:
template <class U>
A(U p) {
}
template <>
A(int p) { // expected-warning{{explicit specialization of 'A' within class scope in a Microsoft extension}}
}
template <class U>
void f(U p) {
}
template <>
void f(int p) { // expected-warning{{explicit specialization of 'f' within class scope in a Microsoft extension}}
}
void f(int p) {
}
};
void test1()
{
A a(3);
char* b ;
a.f(b);
a.f<int>(99);
a.f(100);
}
template <class T>
class B {
public:
template <class U>
B(U p) {
}
template <>
B(int p) { // expected-warning{{explicit specialization of 'B<T>' within class scope in a Microsoft extension}}
}
template <class U>
void f(U p) {
T y = 9;
}
template <>
void f(int p) { // expected-warning{{explicit specialization of 'f' within class scope in a Microsoft extension}}
T a = 3;
}
void f(int p) {
T a = 3;
}
};
void test2()
{
B<char> b(3);
char* ptr;
b.f(ptr);
b.f<int>(99);
b.f(100);
}
<commit_msg>fix typo in test.<commit_after>// RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s
class A {
public:
template <class U>
A(U p) {
}
template <>
A(int p) { // expected-warning{{explicit specialization of 'A' within class scope is a Microsoft extension}}
}
template <class U>
void f(U p) {
}
template <>
void f(int p) { // expected-warning{{explicit specialization of 'f' within class scope is a Microsoft extension}}
}
void f(int p) {
}
};
void test1()
{
A a(3);
char* b ;
a.f(b);
a.f<int>(99);
a.f(100);
}
template <class T>
class B {
public:
template <class U>
B(U p) {
}
template <>
B(int p) { // expected-warning{{explicit specialization of 'B<T>' within class scope is a Microsoft extension}}
}
template <class U>
void f(U p) {
T y = 9;
}
template <>
void f(int p) { // expected-warning{{explicit specialization of 'f' within class scope is a Microsoft extension}}
T a = 3;
}
void f(int p) {
T a = 3;
}
};
void test2()
{
B<char> b(3);
char* ptr;
b.f(ptr);
b.f<int>(99);
b.f(100);
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test quick_exit and at_quick_exit
#include <cstdlib>
#include <type_traits>
void f();
int main()
{
std::at_quick_exit(f);
quick_exit(0);
}
<commit_msg>Don't refer to a function that doesn't exist in the quick_exit test.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test quick_exit and at_quick_exit
#include <cstdlib>
#include <type_traits>
void f() {}
int main()
{
std::at_quick_exit(f);
quick_exit(0);
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/json_helper.hpp>
#include <metaverse/explorer/dispatch.hpp>
#include <metaverse/explorer/extensions/commands/issue.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
#include <metaverse/explorer/extensions/base_helper.hpp>
#include <metaverse/bitcoin/chain/attachment/asset/asset_detail.hpp>
using std::placeholders::_1;
namespace libbitcoin {
namespace explorer {
namespace commands {
console_result issue::invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
blockchain.is_account_passwd_valid(auth_.name, auth_.auth);
blockchain.uppercase_symbol(argument_.symbol);
// check asset symbol
check_asset_symbol(argument_.symbol);
// check fee
auto fee_of_issue = get_fee_of_issue_asset(blockchain, auth_.name);
if (argument_.fee == -1) {
argument_.fee = fee_of_issue;
}
else if (argument_.fee < fee_of_issue) {
throw asset_issue_poundage_exception{
"issue asset fee less than "
+ std::to_string(fee_of_issue) + " that's "
+ std::to_string(fee_of_issue / 100000000) + " ETPs"};
}
// fail if asset is already in blockchain
if (blockchain.is_asset_exist(argument_.symbol, false)) {
throw asset_symbol_existed_exception{
"asset " + argument_.symbol
+ " already exists in blockchain"};
}
// local database asset check
auto sh_asset = blockchain.get_account_unissued_asset(auth_.name, argument_.symbol);
if (!sh_asset) {
throw asset_symbol_notfound_exception{"asset " + argument_.symbol + " not found"};
}
auto to_did = sh_asset->get_issuer();
auto to_address = get_address_from_did(to_did, blockchain);
if (!blockchain.is_valid_address(to_address)) {
throw address_invalid_exception{"invalid asset issuer " + to_did};
}
std::string cert_symbol;
asset_cert_type cert_type = asset_cert_ns::none;
bool is_domain_cert_exist = false;
// domain cert check
auto&& domain = asset_cert::get_domain(argument_.symbol);
if (asset_cert::is_valid_domain(domain)) {
bool exist = blockchain.is_asset_cert_exist(domain, asset_cert_ns::domain);
if (!exist) {
// domain cert does not exist, issue new domain cert to this address
is_domain_cert_exist = false;
cert_type = asset_cert_ns::domain;
cert_symbol = domain;
}
else {
// if domain cert exists then check whether it belongs to the account.
is_domain_cert_exist = true;
auto cert = blockchain.get_account_asset_cert(auth_.name, domain, asset_cert_ns::domain);
if (cert) {
cert_symbol = domain;
cert_type = cert->get_type();
}
else {
// if domain cert does not belong to the account then check naming cert
exist = blockchain.is_asset_cert_exist(argument_.symbol, asset_cert_ns::naming);
if (!exist) {
throw asset_cert_notfound_exception{
"Domain cert " + argument_.symbol + " exists on the blockchain and is not owned by " + auth_.name};
}
else {
cert = blockchain.get_account_asset_cert(auth_.name, argument_.symbol, asset_cert_ns::naming);
if (!cert) {
throw asset_cert_notowned_exception{
"No domain cert or naming cert owned by " + auth_.name};
}
cert_symbol = argument_.symbol;
cert_type = cert->get_type();
}
}
}
}
// receiver
std::vector<receiver_record> receiver{
{to_address, argument_.symbol, 0, 0, utxo_attach_type::asset_issue, attachment("", to_did)}
};
// asset_cert utxo
auto certs = sh_asset->get_asset_cert_mask();
if (!certs.empty()) {
for (auto each_cert_type : certs) {
receiver.push_back(
{ to_address, argument_.symbol, 0, 0,
each_cert_type, utxo_attach_type::asset_cert_autoissue, attachment("", to_did)
});
}
}
// domain cert or naming cert
if (asset_cert::is_valid_domain(domain)) {
receiver.push_back(
{ to_address, cert_symbol, 0, 0, cert_type,
(is_domain_cert_exist ? utxo_attach_type::asset_cert : utxo_attach_type::asset_cert_autoissue),
attachment("", to_did)
});
}
auto issue_helper = issuing_asset(
*this, blockchain,
std::move(auth_.name), std::move(auth_.auth),
"", std::move(argument_.symbol),
std::move(option_.attenuation_model_param),
std::move(receiver), argument_.fee);
issue_helper.exec();
// json output
auto tx = issue_helper.get_transaction();
jv_output = config::json_helper(get_api_version()).prop_tree(tx, true);
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<commit_msg>fix compile error on Mac.<commit_after>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/json_helper.hpp>
#include <metaverse/explorer/dispatch.hpp>
#include <metaverse/explorer/extensions/commands/issue.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
#include <metaverse/explorer/extensions/base_helper.hpp>
#include <metaverse/bitcoin/chain/attachment/asset/asset_detail.hpp>
using std::placeholders::_1;
namespace libbitcoin {
namespace explorer {
namespace commands {
console_result issue::invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node)
{
auto& blockchain = node.chain_impl();
blockchain.is_account_passwd_valid(auth_.name, auth_.auth);
blockchain.uppercase_symbol(argument_.symbol);
// check asset symbol
check_asset_symbol(argument_.symbol);
// check fee
auto fee_of_issue = get_fee_of_issue_asset(blockchain, auth_.name);
if (argument_.fee == (uint64_t)-1) {
argument_.fee = fee_of_issue;
}
else if (argument_.fee < fee_of_issue) {
throw asset_issue_poundage_exception{
"issue asset fee less than "
+ std::to_string(fee_of_issue) + " that's "
+ std::to_string(fee_of_issue / 100000000) + " ETPs"};
}
// fail if asset is already in blockchain
if (blockchain.is_asset_exist(argument_.symbol, false)) {
throw asset_symbol_existed_exception{
"asset " + argument_.symbol
+ " already exists in blockchain"};
}
// local database asset check
auto sh_asset = blockchain.get_account_unissued_asset(auth_.name, argument_.symbol);
if (!sh_asset) {
throw asset_symbol_notfound_exception{"asset " + argument_.symbol + " not found"};
}
auto to_did = sh_asset->get_issuer();
auto to_address = get_address_from_did(to_did, blockchain);
if (!blockchain.is_valid_address(to_address)) {
throw address_invalid_exception{"invalid asset issuer " + to_did};
}
std::string cert_symbol;
asset_cert_type cert_type = asset_cert_ns::none;
bool is_domain_cert_exist = false;
// domain cert check
auto&& domain = asset_cert::get_domain(argument_.symbol);
if (asset_cert::is_valid_domain(domain)) {
bool exist = blockchain.is_asset_cert_exist(domain, asset_cert_ns::domain);
if (!exist) {
// domain cert does not exist, issue new domain cert to this address
is_domain_cert_exist = false;
cert_type = asset_cert_ns::domain;
cert_symbol = domain;
}
else {
// if domain cert exists then check whether it belongs to the account.
is_domain_cert_exist = true;
auto cert = blockchain.get_account_asset_cert(auth_.name, domain, asset_cert_ns::domain);
if (cert) {
cert_symbol = domain;
cert_type = cert->get_type();
}
else {
// if domain cert does not belong to the account then check naming cert
exist = blockchain.is_asset_cert_exist(argument_.symbol, asset_cert_ns::naming);
if (!exist) {
throw asset_cert_notfound_exception{
"Domain cert " + argument_.symbol + " exists on the blockchain and is not owned by " + auth_.name};
}
else {
cert = blockchain.get_account_asset_cert(auth_.name, argument_.symbol, asset_cert_ns::naming);
if (!cert) {
throw asset_cert_notowned_exception{
"No domain cert or naming cert owned by " + auth_.name};
}
cert_symbol = argument_.symbol;
cert_type = cert->get_type();
}
}
}
}
// receiver
std::vector<receiver_record> receiver{
{to_address, argument_.symbol, 0, 0, utxo_attach_type::asset_issue, attachment("", to_did)}
};
// asset_cert utxo
auto certs = sh_asset->get_asset_cert_mask();
if (!certs.empty()) {
for (auto each_cert_type : certs) {
receiver.push_back(
{ to_address, argument_.symbol, 0, 0,
each_cert_type, utxo_attach_type::asset_cert_autoissue, attachment("", to_did)
});
}
}
// domain cert or naming cert
if (asset_cert::is_valid_domain(domain)) {
receiver.push_back(
{ to_address, cert_symbol, 0, 0, cert_type,
(is_domain_cert_exist ? utxo_attach_type::asset_cert : utxo_attach_type::asset_cert_autoissue),
attachment("", to_did)
});
}
auto issue_helper = issuing_asset(
*this, blockchain,
std::move(auth_.name), std::move(auth_.auth),
"", std::move(argument_.symbol),
std::move(option_.attenuation_model_param),
std::move(receiver), argument_.fee);
issue_helper.exec();
// json output
auto tx = issue_helper.get_transaction();
jv_output = config::json_helper(get_api_version()).prop_tree(tx, true);
return console_result::okay;
}
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<|endoftext|>
|
<commit_before>#include "SymbianDTMFPrivate.h"
#include "SymbianCallInitiator.h"
SymbianDTMFPrivate::SymbianDTMFPrivate(SymbianCallInitiator *p)
: CActive(EPriorityNormal)
, iTelephony (NULL)
, parent (p)
{
iTelephony = CTelephony::NewL();
}//SymbianDTMFPrivate::SymbianDTMFPrivate
SymbianDTMFPrivate::~SymbianDTMFPrivate ()
{
Cancel();
if (NULL != iTelephony) {
delete iTelephony;
}
iTelephony = NULL;
parent = NULL;
}//SymbianDTMFPrivate::~SymbianDTMFPrivate
void
SymbianDTMFPrivate::RunL ()
{
qDebug("RunL");
bool bSuccess = (iStatus == KErrNone);
if (NULL != parent) {
qDebug("RunL about to call onDtmfSent");
parent->onDtmfSent (this, bSuccess);
}
qDebug("RunL called onDtmfSent");
}//SymbianDTMFPrivate::RunL
void
SymbianDTMFPrivate::DoCancel ()
{
iTelephony->CancelAsync(CTelephony::ESendDTMFTonesCancel);
}//SymbianDTMFPrivate::DoCancel
void
SymbianDTMFPrivate::sendDTMF (const QString &strTones)
{
if (NULL == iTelephony) {
qCritical ("CTelephony object not initialized");
return;
}
#define SIZE_LIMIT 40
if (strTones.length () > SIZE_LIMIT) {
qDebug ("Too many DTMF characters");
return;
}
TBuf<SIZE_LIMIT>aNumber;
#undef SIZE_LIMIT
TPtrC8 ptr(reinterpret_cast<const TUint8*>(strTones.toLatin1().constData()));
aNumber.Copy(ptr);
qDebug("Before sending DTMF");
iTelephony->SendDTMFTones(iStatus, aNumber);
qDebug("After sending DTMF");
SetActive ();
qDebug("After SetActive");
CleanupStack::PopAndDestroy();
qDebug("After PopAndDestroy");
}//SymbianDTMFPrivate::sendDTMF
<commit_msg>Test<commit_after>#include "SymbianDTMFPrivate.h"
#include "SymbianCallInitiator.h"
SymbianDTMFPrivate::SymbianDTMFPrivate(SymbianCallInitiator *p)
: CActive(EPriorityNormal)
, iTelephony (NULL)
, parent (p)
{
iTelephony = CTelephony::NewL();
}//SymbianDTMFPrivate::SymbianDTMFPrivate
SymbianDTMFPrivate::~SymbianDTMFPrivate ()
{
Cancel();
if (NULL != iTelephony) {
delete iTelephony;
}
iTelephony = NULL;
parent = NULL;
}//SymbianDTMFPrivate::~SymbianDTMFPrivate
void
SymbianDTMFPrivate::RunL ()
{
qDebug("RunL");
bool bSuccess = (iStatus == KErrNone);
if (NULL != parent) {
qDebug("RunL about to call onDtmfSent");
parent->onDtmfSent (this, bSuccess);
}
qDebug("RunL called onDtmfSent");
}//SymbianDTMFPrivate::RunL
void
SymbianDTMFPrivate::DoCancel ()
{
iTelephony->CancelAsync(CTelephony::ESendDTMFTonesCancel);
}//SymbianDTMFPrivate::DoCancel
void
SymbianDTMFPrivate::sendDTMF (const QString &strTones)
{
if (NULL == iTelephony) {
qCritical ("CTelephony object not initialized");
return;
}
#define SIZE_LIMIT 40
if (strTones.length () > SIZE_LIMIT) {
qDebug ("Too many DTMF characters");
return;
}
TBuf<SIZE_LIMIT>aNumber;
#undef SIZE_LIMIT
TPtrC8 ptr(reinterpret_cast<const TUint8*>(strTones.toLatin1().constData()));
aNumber.Copy(ptr);
qDebug("Before sending DTMF");
iTelephony->SendDTMFTones(iStatus, aNumber);
qDebug("After sending DTMF");
SetActive ();
qDebug("After SetActive");
}//SymbianDTMFPrivate::sendDTMF
<|endoftext|>
|
<commit_before>#include "Endpoint.h"
#include "System/Buffers/Buffer.h"
#include "System/Threading/Mutex.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef _WIN32
#include <winsock2.h>
#define s_addr S_un.S_addr
#define in_addr_t unsigned long
#undef SetPort
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
// global mutex for gethostbyname
static Mutex mutex;
#ifdef _WIN32
int inet_aton(const char *cp, struct in_addr *in)
{
// TODO: IPv6
if (strcmp(cp, "255.255.255.255") == 0)
{
in->s_addr = (u_long) 0xFFFFFFFF;
return 1;
}
in->s_addr = inet_addr(cp);
if (in->s_addr == INADDR_NONE)
return 0;
return 1;
}
int inet_pton(int /*af*/, const char* src, void* dst)
{
// HACK: inet_pton is only supported from Vista
return inet_aton(src, (struct in_addr*) dst);
}
#endif
// TODO this is temporary, we need a real DNS resolver
static bool DNS_ResolveIpv4(const char* name, struct in_addr* addr)
{
// FIXME gethostbyname is not multithread-safe!
struct hostent* hostent;
MutexGuard mutexGuard(mutex);
hostent = gethostbyname(name);
if (!hostent)
return false;
if (hostent->h_addrtype != AF_INET)
return false;
addr->s_addr = *(in_addr_t *) hostent->h_addr_list[0];
// TODO: getaddrinfo doesn't work with "localhost"
#ifdef DNS_RESOLVE_GETADDRINFO
struct addrinfo hints;
struct addrinfo* res;
memset((void*) &hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
if (!getaddrinfo(name, NULL, &hints, &res))
{
freeaddrinfo(res);
return false;
}
addr->s_addr = *(u_long *) res->ai_addr;
freeaddrinfo(res);
#endif
return true;
}
Endpoint::Endpoint()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
memset((char *) sa, 0, sizeof(sa));
sa->sin_family = 0; sa->sin_port = 0;
sa->sin_addr.s_addr = 0; sa->sin_zero[0] = 0;
buffer[0] = 0;
}
bool Endpoint::operator==(const Endpoint &other) const
{
struct sockaddr_in *sa = (struct sockaddr_in *) &saBuffer;
struct sockaddr_in *other_sa = (struct sockaddr_in *) &other.saBuffer;
return sa->sin_family == other_sa->sin_family &&
sa->sin_port == other_sa->sin_port &&
sa->sin_addr.s_addr == other_sa->sin_addr.s_addr;
}
bool Endpoint::operator!=(const Endpoint &other) const
{
return !operator==(other);
}
bool Endpoint::Set(const char* ip, int port, bool resolv)
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
memset((char *) sa, 0, sizeof(sa));
sa->sin_family = AF_INET;
sa->sin_port = htons((uint16_t)port);
if (inet_pton(AF_INET, ip, &sa->sin_addr) == 0)
{
if (resolv)
{
if (!DNS_ResolveIpv4(ip, &sa->sin_addr))
{
Log_Trace("DNS resolv failed");
return false;
}
else
return true;
}
Log_Trace("inet_aton() failed");
return false;
}
return true;
}
bool Endpoint::Set(const char* ip_port, bool resolv)
{
const char* p;
int port;
bool ret;
Buffer ipbuf;
p = ip_port;
if (!IsValidEndpoint(ReadBuffer(ip_port)))
return false;
p = strrchr(ip_port, ':');
if (p == NULL)
{
Log_Trace("No ':' in host specification");
return false;
}
ipbuf.Append(ip_port, p - ip_port);
ipbuf.NullTerminate();
p++;
port = -1;
port = atoi(p);
if (port < 1 || port > 65535)
{
Log_Trace("atoi() failed to produce a sensible value");
return false;
}
ret = Set(ipbuf.GetBuffer(), port, resolv);
return ret;
}
bool Endpoint::Set(ReadBuffer ip_port, bool resolv)
{
const char* p;
const char* start;
int port;
bool ret;
Buffer ipbuf;
Buffer portbuf;
if (!IsValidEndpoint(ReadBuffer(ip_port)))
return false;
start = p = ip_port.GetBuffer();
p = RevFindInBuffer(ip_port.GetBuffer(), ip_port.GetLength(), ':');
if (p == NULL)
{
Log_Trace("No ':' in host specification");
return false;
}
ipbuf.Append(start, p - start);
ipbuf.NullTerminate();
p++;
portbuf.Append(p, ip_port.GetLength() - (p - start));
portbuf.NullTerminate();
port = -1;
port = atoi(portbuf.GetBuffer());
if (port < 1 || port > 65535)
{
Log_Trace("atoi() failed to produce a sensible value");
return false;
}
ret = Set(ipbuf.GetBuffer(), port, resolv);
return ret;
}
bool Endpoint::SetPort(int port)
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
sa->sin_port = htons((uint16_t)port);
return true;
}
int Endpoint::GetPort()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
return ntohs(sa->sin_port);
}
Address Endpoint::GetAddress()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
return ntohl(sa->sin_addr.s_addr);
}
char* Endpoint::GetSockAddr()
{
return saBuffer;
}
const char* Endpoint::ToString()
{
return ToString(buffer);
}
const char* Endpoint::ToString(char s[ENDPOINT_STRING_SIZE])
{
struct sockaddr_in *sa = (struct sockaddr_in *) &saBuffer;
unsigned long addr;
// inet_ntoa is not thread-safe and have a memory-leak issue on Linux
addr = ntohl(sa->sin_addr.s_addr);
snprintf(s, ENDPOINT_STRING_SIZE, "%lu.%lu.%lu.%lu:%u",
(addr & 0xFF000000UL) >> 24,
(addr & 0x00FF0000UL) >> 16,
(addr & 0x0000FF00UL) >> 8,
(addr & 0x000000FFUL),
ntohs(sa->sin_port));
return s;
}
ReadBuffer Endpoint::ToReadBuffer()
{
size_t len;
// TODO: optimize out strlen by doing snprintf directly
ToString();
len = strlen(buffer);
return ReadBuffer(buffer, len);
}
bool Endpoint::IsSet()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
if (sa->sin_port == 0)
return false;
return true;
}
Address Endpoint::GetLoopbackAddress()
{
return INADDR_LOOPBACK;
}
bool Endpoint::IsValidEndpoint(ReadBuffer ip_port)
{
// Valid endpoint is either <IPv4-Address>:<port> or <IPv6-Address>:<port> or <Domain-Name>:<port>
// Valid IPv4-Address consists only from numbers and three dots between the numbers
// Valid IPv6-Adresses: http://en.wikipedia.org/wiki/IPv6#Addressing
// Valid domain names: http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
const char VALID_CHARS[] = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
unsigned i;
bool labelStart;
bool isNumeric;
bool isHexnum;
bool isPort;
bool isIPv6;
unsigned numCommas;
unsigned numPortChars;
char c;
char prev;
char sep;
char* lastColon;
// assuming fully numeric names
isNumeric = true;
isHexnum = true;
isPort = false;
numCommas = 0;
numPortChars = 0;
labelStart = true;
isIPv6 = false;
prev = ' ';
sep = ' ';
lastColon = NULL;
for (i = 0; i < ip_port.GetLength(); i++)
{
c = ip_port.GetCharAt(i);
if (c == '.' || c == ':')
{
if (i == 0)
{
// IPv4 and DNS must not start with comma or colon
if (c == '.')
return false;
isIPv6 = true;
isHexnum = true;
}
// labels must not end with hyphens
if (prev == VALID_CHARS[0])
return false;
if (c == '.')
{
labelStart = true;
numCommas++;
sep = c;
}
if (c == ':')
{
// cannot mix IPv4 and IPv6 addresses this way
// this however is legal in IPv6: ::ffff:192.0.2.128
if (isHexnum && sep != '.')
{
isIPv6 = true;
sep = ':';
isPort = true;
numPortChars = 0;
}
else
{
if (isPort && !isIPv6)
return false;
isPort = true;
numPortChars = 0;
}
lastColon = ip_port.GetBuffer() + i;
}
}
else
{
// labels must not start with hyphens
if (labelStart && c == VALID_CHARS[0])
return false;
if (isPort)
{
if (!isdigit(c))
{
if (isIPv6)
isPort = false;
else
return false;
}
else
numPortChars++;
}
if (isNumeric && !isdigit(c))
isNumeric = false;
if (isHexnum && !isxdigit(c))
{
if (isIPv6)
return false;
isHexnum = false;
}
if (strchr(VALID_CHARS, c) == NULL)
return false;
labelStart = false;
}
prev = c;
}
if (isNumeric && numCommas != 3)
return false;
if (isIPv6 && numCommas != 0 && numCommas != 3)
return false;
if (numPortChars < 1 || numPortChars > 5)
return false;
return true;
}
Mutex& Endpoint::GetMutex()
{
return mutex;
}
<commit_msg>Cosmetic.<commit_after>#include "Endpoint.h"
#include "System/Buffers/Buffer.h"
#include "System/Threading/Mutex.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#ifdef _WIN32
#include <winsock2.h>
#define s_addr S_un.S_addr
#define in_addr_t unsigned long
#undef SetPort
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
// global mutex for gethostbyname
static Mutex mutex;
#ifdef _WIN32
int inet_aton(const char *cp, struct in_addr *in)
{
// TODO: IPv6
if (strcmp(cp, "255.255.255.255") == 0)
{
in->s_addr = (u_long) 0xFFFFFFFF;
return 1;
}
in->s_addr = inet_addr(cp);
if (in->s_addr == INADDR_NONE)
return 0;
return 1;
}
int inet_pton(int /*af*/, const char* src, void* dst)
{
// HACK: inet_pton is only supported from Vista
return inet_aton(src, (struct in_addr*) dst);
}
#endif
// TODO this is temporary, we need a real DNS resolver
static bool DNS_ResolveIpv4(const char* name, struct in_addr* addr)
{
// FIXME gethostbyname is not multithread-safe!
struct hostent* hostent;
MutexGuard mutexGuard(mutex);
hostent = gethostbyname(name);
if (!hostent)
return false;
if (hostent->h_addrtype != AF_INET)
return false;
addr->s_addr = *(in_addr_t *) hostent->h_addr_list[0];
// TODO: getaddrinfo doesn't work with "localhost"
#ifdef DNS_RESOLVE_GETADDRINFO
struct addrinfo hints;
struct addrinfo* res;
memset((void*) &hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
if (!getaddrinfo(name, NULL, &hints, &res))
{
freeaddrinfo(res);
return false;
}
addr->s_addr = *(u_long *) res->ai_addr;
freeaddrinfo(res);
#endif
return true;
}
Endpoint::Endpoint()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
memset((char *) sa, 0, sizeof(sa));
sa->sin_family = 0; sa->sin_port = 0;
sa->sin_addr.s_addr = 0; sa->sin_zero[0] = 0;
buffer[0] = 0;
}
bool Endpoint::operator==(const Endpoint &other) const
{
struct sockaddr_in *sa = (struct sockaddr_in *) &saBuffer;
struct sockaddr_in *other_sa = (struct sockaddr_in *) &other.saBuffer;
return sa->sin_family == other_sa->sin_family &&
sa->sin_port == other_sa->sin_port &&
sa->sin_addr.s_addr == other_sa->sin_addr.s_addr;
}
bool Endpoint::operator!=(const Endpoint &other) const
{
return !operator==(other);
}
bool Endpoint::Set(const char* ip, int port, bool resolv)
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
memset((char *) sa, 0, sizeof(sa));
sa->sin_family = AF_INET;
sa->sin_port = htons((uint16_t)port);
if (inet_pton(AF_INET, ip, &sa->sin_addr) == 0)
{
if (resolv)
{
if (!DNS_ResolveIpv4(ip, &sa->sin_addr))
{
Log_Trace("DNS resolv failed");
return false;
}
else
return true;
}
Log_Trace("inet_aton() failed");
return false;
}
return true;
}
bool Endpoint::Set(const char* ip_port, bool resolv)
{
const char* p;
int port;
bool ret;
Buffer ipbuf;
p = ip_port;
if (!IsValidEndpoint(ReadBuffer(ip_port)))
return false;
p = strrchr(ip_port, ':');
if (p == NULL)
{
Log_Trace("No ':' in host specification");
return false;
}
ipbuf.Append(ip_port, p - ip_port);
ipbuf.NullTerminate();
p++;
port = -1;
port = atoi(p);
if (port < 1 || port > 65535)
{
Log_Trace("atoi() failed to produce a sensible value");
return false;
}
ret = Set(ipbuf.GetBuffer(), port, resolv);
return ret;
}
bool Endpoint::Set(ReadBuffer ip_port, bool resolv)
{
const char* p;
const char* start;
int port;
bool ret;
Buffer ipbuf;
Buffer portbuf;
if (!IsValidEndpoint(ReadBuffer(ip_port)))
return false;
start = p = ip_port.GetBuffer();
p = RevFindInBuffer(ip_port.GetBuffer(), ip_port.GetLength(), ':');
if (p == NULL)
{
Log_Trace("No ':' in host specification");
return false;
}
ipbuf.Append(start, p - start);
ipbuf.NullTerminate();
p++;
portbuf.Append(p, ip_port.GetLength() - (p - start));
portbuf.NullTerminate();
port = -1;
port = atoi(portbuf.GetBuffer());
if (port < 1 || port > 65535)
{
Log_Trace("atoi() failed to produce a sensible value");
return false;
}
ret = Set(ipbuf.GetBuffer(), port, resolv);
return ret;
}
bool Endpoint::SetPort(int port)
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
sa->sin_port = htons((uint16_t)port);
return true;
}
int Endpoint::GetPort()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
return ntohs(sa->sin_port);
}
Address Endpoint::GetAddress()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
return ntohl(sa->sin_addr.s_addr);
}
char* Endpoint::GetSockAddr()
{
return saBuffer;
}
const char* Endpoint::ToString()
{
return ToString(buffer);
}
const char* Endpoint::ToString(char s[ENDPOINT_STRING_SIZE])
{
struct sockaddr_in *sa = (struct sockaddr_in *) &saBuffer;
unsigned long addr;
// inet_ntoa is not thread-safe and have a memory-leak issue on Linux
addr = ntohl(sa->sin_addr.s_addr);
snprintf(s, ENDPOINT_STRING_SIZE, "%lu.%lu.%lu.%lu:%u",
(addr & 0xFF000000UL) >> 24,
(addr & 0x00FF0000UL) >> 16,
(addr & 0x0000FF00UL) >> 8,
(addr & 0x000000FFUL),
ntohs(sa->sin_port));
return s;
}
ReadBuffer Endpoint::ToReadBuffer()
{
size_t len;
// TODO: optimize out strlen by doing snprintf directly
ToString();
len = strlen(buffer);
return ReadBuffer(buffer, len);
}
bool Endpoint::IsSet()
{
struct sockaddr_in *sa;
sa = (struct sockaddr_in *) &saBuffer;
if (sa->sin_port == 0)
return false;
return true;
}
Address Endpoint::GetLoopbackAddress()
{
return INADDR_LOOPBACK;
}
bool Endpoint::IsValidEndpoint(ReadBuffer ip_port)
{
// Valid endpoint is either <IPv4-Address>:<port> or <IPv6-Address>:<port> or <Domain-Name>:<port>
// Valid IPv4-Address consists only from numbers and three dots between the numbers
// Valid IPv6-Adresses: http://en.wikipedia.org/wiki/IPv6#Addressing
// Valid domain names: http://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
const char VALID_CHARS[] = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
unsigned i;
bool labelStart;
bool isNumeric;
bool isHexnum;
bool isPort;
bool isIPv6;
unsigned numCommas;
unsigned numPortChars;
char c;
char prev;
char sep;
char* lastColon;
// assuming fully numeric names
isNumeric = true;
isHexnum = true;
isPort = false;
numCommas = 0;
numPortChars = 0;
labelStart = true;
isIPv6 = false;
prev = ' ';
sep = ' ';
lastColon = NULL;
for (i = 0; i < ip_port.GetLength(); i++)
{
c = ip_port.GetCharAt(i);
if (c == '.' || c == ':')
{
if (i == 0)
{
// IPv4 and DNS must not start with comma or colon
if (c == '.')
return false;
isIPv6 = true;
isHexnum = true;
}
// labels must not end with hyphens
if (prev == VALID_CHARS[0])
return false;
if (c == '.')
{
labelStart = true;
numCommas++;
sep = c;
}
if (c == ':')
{
// cannot mix IPv4 and IPv6 addresses this way
// this however is legal in IPv6: ::ffff:192.0.2.128
if (isHexnum && sep != '.')
{
isIPv6 = true;
sep = ':';
isPort = true;
numPortChars = 0;
}
else
{
if (isPort && !isIPv6)
return false;
isPort = true;
numPortChars = 0;
}
lastColon = ip_port.GetBuffer() + i;
}
}
else
{
// labels must not start with hyphens
if (labelStart && c == VALID_CHARS[0])
return false;
if (isPort)
{
if (!isdigit(c))
{
if (isIPv6)
isPort = false;
else
return false;
}
else
numPortChars++;
}
if (isNumeric && !isdigit(c))
isNumeric = false;
if (isHexnum && !isxdigit(c))
{
if (isIPv6)
return false;
isHexnum = false;
}
if (strchr(VALID_CHARS, c) == NULL)
return false;
labelStart = false;
}
prev = c;
}
if (isNumeric && numCommas != 3)
return false;
if (isIPv6 && numCommas != 0 && numCommas != 3)
return false;
if (numPortChars < 1 || numPortChars > 5)
return false;
return true;
}
Mutex& Endpoint::GetMutex()
{
return mutex;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Macro which loads and compiles the MUON macros:
//
// runSimulation.C - ok, comp, x; Laurent
// runReconstruction.C - ok, comp, x; Laurent
// fastMuonGen.C - ok, comp, x; Hermine, Alessandro
// fastMuonSim.C - ok, comp, x; Hermine, Alessandro
// DecodeRecoCocktail.C - ok, comp, README; Hermine, Alessandro
// ReadRecoCocktail.C - ok, comp, README; Hermine, Alessandro
// MergeMuonLight.C - x, comp, README; Hermine, Alessandro
// MakeMUONFullMisAlignment.C - ok, comp, README; Javier, Ivana
// MakeMUONResMisAlignment.C - ok, comp, README; Javier, Ivana
// MakeMUONZeroMisAlignment.C - ok, comp, README; Javier, Ivana
// MUONAlignment.C - ok, comp, README; Javier
// MUONCheck.C - ok, comp, x, Frederic, in test
// MUONCheckDI.C - x, !comp, x Artur
// MUONCheckMisAligner.C - ok, comp, x, Javier
// MUONdisplay.C - ok, comp, deprecated
// MUONefficiency.C - ok, comp, README; Christophe, in test
// MUONGenerateBusPatch.C - ok, comp, x, Christian
// MUONGenerateGeometryData.C - ok, comp, README; Ivana
// MUONGenerateTestGMS.C - ok, comp, READMEshuttle; Ivana
// MUONmassPlot_ESD.C - ok, comp, README, Christian
// MUONplotefficiency.C - ok, comp, README; Christophe
// MUONRawStreamTracker.C - x, comp, README; Christian
// MUONRawStreamTrigger.C - x, comp, README; Christian
// MUONRecoCheck.C - ok, comp, README; Hermine, Alessandro
// MUONResoEffChamber.C - ok, comp, x, Nicolas
// MUONStatusMap.C - ok, comp, x, Laurent
// MUONTrigger.C - ok, comp, README, Philippe C.
// MUONTriggerEfficiency.C - ok, comp, x, Philippe C., in test
// MUONTriggerEfficiencyPt.C - x, comp, README, Philippe C.
// MUONTriggerChamberEfficiency.C- x, comp, README, Diego
// TestMUONPreprocessor.C - ok, comp, READMEshuttle; Laurent
//
// 1st item:
// ok/fails/x - if the macro runs; x means that it was not tried either for lack
// of documentation, or expertise
//
// 2nd item:
// comp/x - if the macro can be compiled
//
// 3rd item:
// README*/x - if it is documented in README, x means no doxumentation outside the
// macro itself
//
// 4th item: - author(s), responsible for macro maintenance
//
// eventually
// 5th item: - if the macro is run within test scripts
//
// I. Hrivnacova
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TROOT.h>
#include <TSystem.h>
#include <TString.h>
#endif
void loadmacros ()
{
// Redefine include paths as some macros need
// to see more than what is define in rootlogon.C
//
TString includePath = "-I${ALICE_ROOT}/include ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping";
gSystem->SetIncludePath(includePath.Data());
// Load libraries not linked with aliroot
//
gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so");
gSystem->Load("libMUONshuttle.so");
gSystem->Load("libMUONevaluation.so");
// Load macros
//
gROOT->LoadMacro("$ALICE_ROOT/MUON/runSimulation.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/runReconstruction.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONGen.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONSim.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/DecodeRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/ReadRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MergeMuonLight.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONFullMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONResMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONZeroMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheck.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckDI.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckMisAligner.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateBusPatch.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateGeometryData.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateTestGMS.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONmassPlot_ESD.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONplotefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTracker.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRecoCheck.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONResoEffChamber.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONStatusMap.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiency.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiencyPt.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerChamberEfficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/TestMUONPreprocessor.C++");
}
<commit_msg>Uncommented MUONTriggerEfficiencyPt, migrated to data stores by Philippe C.<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Macro which loads and compiles the MUON macros:
//
// runSimulation.C - ok, comp, x; Laurent
// runReconstruction.C - ok, comp, x; Laurent
// fastMuonGen.C - ok, comp, x; Hermine, Alessandro
// fastMuonSim.C - ok, comp, x; Hermine, Alessandro
// DecodeRecoCocktail.C - ok, comp, README; Hermine, Alessandro
// ReadRecoCocktail.C - ok, comp, README; Hermine, Alessandro
// MergeMuonLight.C - x, comp, README; Hermine, Alessandro
// MakeMUONFullMisAlignment.C - ok, comp, README; Javier, Ivana
// MakeMUONResMisAlignment.C - ok, comp, README; Javier, Ivana
// MakeMUONZeroMisAlignment.C - ok, comp, README; Javier, Ivana
// MUONAlignment.C - ok, comp, README; Javier
// MUONCheck.C - ok, comp, x, Frederic, in test
// MUONCheckDI.C - x, !comp, x Artur
// MUONCheckMisAligner.C - ok, comp, x, Javier
// MUONdisplay.C - ok, comp, deprecated
// MUONefficiency.C - ok, comp, README; Christophe, in test
// MUONGenerateBusPatch.C - ok, comp, x, Christian
// MUONGenerateGeometryData.C - ok, comp, README; Ivana
// MUONGenerateTestGMS.C - ok, comp, READMEshuttle; Ivana
// MUONmassPlot_ESD.C - ok, comp, README, Christian
// MUONplotefficiency.C - ok, comp, README; Christophe
// MUONRawStreamTracker.C - x, comp, README; Christian
// MUONRawStreamTrigger.C - x, comp, README; Christian
// MUONRecoCheck.C - ok, comp, README; Hermine, Alessandro
// MUONResoEffChamber.C - ok, comp, x, Nicolas
// MUONStatusMap.C - ok, comp, x, Laurent
// MUONTrigger.C - ok, comp, README, Philippe C.
// MUONTriggerEfficiency.C - ok, comp, x, Philippe C., in test
// MUONTriggerEfficiencyPt.C - x, comp, README, Philippe C.
// MUONTriggerChamberEfficiency.C- x, comp, README, Diego
// TestMUONPreprocessor.C - ok, comp, READMEshuttle; Laurent
//
// 1st item:
// ok/fails/x - if the macro runs; x means that it was not tried either for lack
// of documentation, or expertise
//
// 2nd item:
// comp/x - if the macro can be compiled
//
// 3rd item:
// README*/x - if it is documented in README, x means no doxumentation outside the
// macro itself
//
// 4th item: - author(s), responsible for macro maintenance
//
// eventually
// 5th item: - if the macro is run within test scripts
//
// I. Hrivnacova
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TROOT.h>
#include <TSystem.h>
#include <TString.h>
#endif
void loadmacros ()
{
// Redefine include paths as some macros need
// to see more than what is define in rootlogon.C
//
TString includePath = "-I${ALICE_ROOT}/include ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping";
gSystem->SetIncludePath(includePath.Data());
// Load libraries not linked with aliroot
//
gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so");
gSystem->Load("libMUONshuttle.so");
gSystem->Load("libMUONevaluation.so");
// Load macros
//
gROOT->LoadMacro("$ALICE_ROOT/MUON/runSimulation.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/runReconstruction.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONGen.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/fastMUONSim.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/DecodeRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/ReadRecoCocktail.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MergeMuonLight.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONFullMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONResMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MakeMUONZeroMisAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONAlignment.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheck.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckDI.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONCheckMisAligner.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateBusPatch.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateGeometryData.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONGenerateTestGMS.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONmassPlot_ESD.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONplotefficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTracker.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRawStreamTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONRecoCheck.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONResoEffChamber.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONStatusMap.C++");
// gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTrigger.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerEfficiencyPt.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/MUONTriggerChamberEfficiency.C++");
gROOT->LoadMacro("$ALICE_ROOT/MUON/TestMUONPreprocessor.C++");
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "config/config.h"
#include "helpers.h"
#include "utilities/aktualizr_version.h"
namespace bpo = boost::program_options;
static void log_info_target(const std::string &prefix, const Config &config, const Uptane::Target &t) {
auto name = t.filename();
if (t.custom_version().length() > 0) {
name = t.custom_version();
}
LOG_INFO << prefix + name << "\tsha256:" << t.sha256Hash();
if (config.pacman.type == PackageManager::kOstreeDockerApp) {
bool shown = false;
auto apps = t.custom_data()["docker_apps"];
for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) {
if (!shown) {
shown = true;
LOG_INFO << "\tDocker Apps:";
}
if ((*i).isObject() && (*i).isMember("filename")) {
LOG_INFO << "\t\t" << i.key().asString() << " -> " << (*i)["filename"].asString();
} else {
LOG_ERROR << "\t\tInvalid custom data for docker-app: " << i.key().asString();
}
}
}
}
static int status_main(LiteClient &client, const bpo::variables_map &unused) {
(void)unused;
auto target = client.primary->getCurrent();
if (target.MatchTarget(Uptane::Target::Unknown())) {
LOG_INFO << "No active deployment found";
} else {
auto name = target.filename();
if (target.custom_version().length() > 0) {
name = target.custom_version();
}
log_info_target("Active image is: ", client.config, target);
}
return 0;
}
static int list_main(LiteClient &client, const bpo::variables_map &unused) {
(void)unused;
Uptane::HardwareIdentifier hwid(client.config.provision.primary_ecu_hardware_id);
LOG_INFO << "Refreshing target metadata";
if (!client.primary->updateImagesMeta()) {
LOG_WARNING << "Unable to update latest metadata, using local copy";
if (!client.primary->checkImagesMetaOffline()) {
LOG_ERROR << "Unable to use local copy of TUF data";
return 1;
}
}
LOG_INFO << "Updates available to " << hwid << ":";
for (auto &t : client.primary->allTargets()) {
for (auto const &it : t.hardwareIds()) {
if (it == hwid) {
log_info_target("", client.config, t);
break;
}
}
}
return 0;
}
static std::unique_ptr<Uptane::Target> find_target(const std::shared_ptr<SotaUptaneClient> &client,
Uptane::HardwareIdentifier &hwid, const std::string &version) {
std::unique_ptr<Uptane::Target> rv;
if (!client->updateImagesMeta()) {
LOG_WARNING << "Unable to update latest metadata, using local copy";
if (!client->checkImagesMetaOffline()) {
LOG_ERROR << "Unable to use local copy of TUF data";
throw std::runtime_error("Unable to find update");
}
}
bool find_latest = (version == "latest");
std::unique_ptr<Uptane::Target> latest = nullptr;
for (auto &t : client->allTargets()) {
for (auto const &it : t.hardwareIds()) {
if (it == hwid) {
if (find_latest) {
if (latest == nullptr || Version(latest->custom_version()) < Version(t.custom_version())) {
latest = std_::make_unique<Uptane::Target>(t);
}
} else if (version == t.filename() || version == t.custom_version()) {
return std_::make_unique<Uptane::Target>(t);
}
}
}
}
if (find_latest && latest != nullptr) {
return latest;
}
throw std::runtime_error("Unable to find update");
}
static int do_update(LiteClient &client, Uptane::Target &target) {
if (!client.primary->downloadImage(target).first) {
return 1;
}
if (client.primary->VerifyTarget(target) != TargetStatus::kGood) {
LOG_ERROR << "Downloaded target is invalid";
return 1;
}
auto iresult = client.primary->PackageInstall(target);
if (iresult.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
LOG_INFO << "Update complete. Please reboot the device to activate";
client.storage->savePrimaryInstalledVersion(target, InstalledVersionUpdateMode::kPending);
} else if (iresult.result_code.num_code == data::ResultCode::Numeric::kOk) {
client.storage->savePrimaryInstalledVersion(target, InstalledVersionUpdateMode::kCurrent);
} else {
LOG_ERROR << "Unable to install update: " << iresult.description;
return 1;
}
LOG_INFO << iresult.description;
return 0;
}
static int update_main(LiteClient &client, const bpo::variables_map &variables_map) {
Uptane::HardwareIdentifier hwid(client.config.provision.primary_ecu_hardware_id);
std::string version("latest");
if (variables_map.count("update-name") > 0) {
version = variables_map["update-name"].as<std::string>();
}
LOG_INFO << "Finding " << version << " to update to...";
auto target = find_target(client.primary, hwid, version);
LOG_INFO << "Updating to: " << *target;
return do_update(client, *target);
}
struct SubCommand {
const char *name;
int (*main)(LiteClient &, const bpo::variables_map &);
};
static SubCommand commands[] = {
{"status", status_main},
{"list", list_main},
{"update", update_main},
};
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0 || vm.count("command") == 0) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr version is: " << aktualizr_version() << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
std::string subs("Command to execute: ");
for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
if (i != 0) {
subs += ", ";
}
subs += commands[i].name;
}
bpo::options_description description("aktualizr-lite command line options");
// clang-format off
// Try to keep these options in the same order as Config::updateFromCommandLine().
// The first three are commandline only.
description.add_options()
("help,h", "print usage")
("version,v", "Current aktualizr version")
("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory")
("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)")
("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware ID of primary ecu")
("update-name", bpo::value<std::string>(), "optional name of the update when running \"update\". default=latest")
("command", bpo::value<std::string>(), subs.c_str());
// clang-format on
// consider the first positional argument as the aktualizr run mode
bpo::positional_options_description pos;
pos.add("command", 1);
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).positional(pos).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::exclude_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_FAILURE);
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// log boost error
LOG_ERROR << "boost command line option error: " << ex.what();
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
int main(int argc, char *argv[]) {
logger_init(isatty(1) == 1);
logger_set_threshold(boost::log::trivial::info);
bpo::variables_map commandline_map = parse_options(argc, argv);
int r = EXIT_FAILURE;
try {
if (geteuid() != 0) {
LOG_WARNING << "\033[31mRunning as non-root and may not work as expected!\033[0m\n";
}
Config config(commandline_map);
config.storage.uptane_metadata_path = BasedPath(config.storage.path / "metadata");
LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();
std::string cmd = commandline_map["command"].as<std::string>();
for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
if (cmd == commands[i].name) {
LiteClient client(config);
return commands[i].main(client, commandline_map);
}
}
throw bpo::invalid_option_value(cmd);
r = EXIT_SUCCESS;
} catch (const std::exception &ex) {
LOG_ERROR << ex.what();
}
return r;
}
<commit_msg>aktualizr-lite: version reporting<commit_after>#include <unistd.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include "config/config.h"
#include "helpers.h"
#include "utilities/aktualizr_version.h"
namespace bpo = boost::program_options;
static void log_info_target(const std::string &prefix, const Config &config, const Uptane::Target &t) {
auto name = t.filename();
if (t.custom_version().length() > 0) {
name = t.custom_version();
}
LOG_INFO << prefix + name << "\tsha256:" << t.sha256Hash();
if (config.pacman.type == PackageManager::kOstreeDockerApp) {
bool shown = false;
auto apps = t.custom_data()["docker_apps"];
for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) {
if (!shown) {
shown = true;
LOG_INFO << "\tDocker Apps:";
}
if ((*i).isObject() && (*i).isMember("filename")) {
LOG_INFO << "\t\t" << i.key().asString() << " -> " << (*i)["filename"].asString();
} else {
LOG_ERROR << "\t\tInvalid custom data for docker-app: " << i.key().asString();
}
}
}
}
static int status_main(LiteClient &client, const bpo::variables_map &unused) {
(void)unused;
auto target = client.primary->getCurrent();
if (target.MatchTarget(Uptane::Target::Unknown())) {
LOG_INFO << "No active deployment found";
} else {
auto name = target.filename();
if (target.custom_version().length() > 0) {
name = target.custom_version();
}
log_info_target("Active image is: ", client.config, target);
}
return 0;
}
static int list_main(LiteClient &client, const bpo::variables_map &unused) {
(void)unused;
Uptane::HardwareIdentifier hwid(client.config.provision.primary_ecu_hardware_id);
LOG_INFO << "Refreshing target metadata";
if (!client.primary->updateImagesMeta()) {
LOG_WARNING << "Unable to update latest metadata, using local copy";
if (!client.primary->checkImagesMetaOffline()) {
LOG_ERROR << "Unable to use local copy of TUF data";
return 1;
}
}
LOG_INFO << "Updates available to " << hwid << ":";
for (auto &t : client.primary->allTargets()) {
for (auto const &it : t.hardwareIds()) {
if (it == hwid) {
log_info_target("", client.config, t);
break;
}
}
}
return 0;
}
static std::unique_ptr<Uptane::Target> find_target(const std::shared_ptr<SotaUptaneClient> &client,
Uptane::HardwareIdentifier &hwid, const std::string &version) {
std::unique_ptr<Uptane::Target> rv;
if (!client->updateImagesMeta()) {
LOG_WARNING << "Unable to update latest metadata, using local copy";
if (!client->checkImagesMetaOffline()) {
LOG_ERROR << "Unable to use local copy of TUF data";
throw std::runtime_error("Unable to find update");
}
}
bool find_latest = (version == "latest");
std::unique_ptr<Uptane::Target> latest = nullptr;
for (auto &t : client->allTargets()) {
for (auto const &it : t.hardwareIds()) {
if (it == hwid) {
if (find_latest) {
if (latest == nullptr || Version(latest->custom_version()) < Version(t.custom_version())) {
latest = std_::make_unique<Uptane::Target>(t);
}
} else if (version == t.filename() || version == t.custom_version()) {
return std_::make_unique<Uptane::Target>(t);
}
}
}
}
if (find_latest && latest != nullptr) {
return latest;
}
throw std::runtime_error("Unable to find update");
}
static int do_update(LiteClient &client, Uptane::Target &target) {
if (!client.primary->downloadImage(target).first) {
return 1;
}
if (client.primary->VerifyTarget(target) != TargetStatus::kGood) {
LOG_ERROR << "Downloaded target is invalid";
return 1;
}
auto iresult = client.primary->PackageInstall(target);
if (iresult.result_code.num_code == data::ResultCode::Numeric::kNeedCompletion) {
LOG_INFO << "Update complete. Please reboot the device to activate";
client.storage->savePrimaryInstalledVersion(target, InstalledVersionUpdateMode::kPending);
} else if (iresult.result_code.num_code == data::ResultCode::Numeric::kOk) {
client.storage->savePrimaryInstalledVersion(target, InstalledVersionUpdateMode::kCurrent);
} else {
LOG_ERROR << "Unable to install update: " << iresult.description;
return 1;
}
LOG_INFO << iresult.description;
return 0;
}
static int update_main(LiteClient &client, const bpo::variables_map &variables_map) {
Uptane::HardwareIdentifier hwid(client.config.provision.primary_ecu_hardware_id);
std::string version("latest");
if (variables_map.count("update-name") > 0) {
version = variables_map["update-name"].as<std::string>();
}
LOG_INFO << "Finding " << version << " to update to...";
auto target = find_target(client.primary, hwid, version);
LOG_INFO << "Updating to: " << *target;
return do_update(client, *target);
}
struct SubCommand {
const char *name;
int (*main)(LiteClient &, const bpo::variables_map &);
};
static SubCommand commands[] = {
{"status", status_main},
{"list", list_main},
{"update", update_main},
};
void check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {
if (vm.count("help") != 0 || (vm.count("command") == 0 && vm.count("version") == 0)) {
std::cout << description << '\n';
exit(EXIT_SUCCESS);
}
if (vm.count("version") != 0) {
std::cout << "Current aktualizr version is: " << aktualizr_version() << "\n";
exit(EXIT_SUCCESS);
}
}
bpo::variables_map parse_options(int argc, char *argv[]) {
std::string subs("Command to execute: ");
for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
if (i != 0) {
subs += ", ";
}
subs += commands[i].name;
}
bpo::options_description description("aktualizr-lite command line options");
// clang-format off
// Try to keep these options in the same order as Config::updateFromCommandLine().
// The first three are commandline only.
description.add_options()
("help,h", "print usage")
("version,v", "Current aktualizr version")
("config,c", bpo::value<std::vector<boost::filesystem::path> >()->composing(), "configuration file or directory")
("loglevel", bpo::value<int>(), "set log level 0-5 (trace, debug, info, warning, error, fatal)")
("repo-server", bpo::value<std::string>(), "url of the uptane repo repository")
("ostree-server", bpo::value<std::string>(), "url of the ostree repository")
("primary-ecu-hardware-id", bpo::value<std::string>(), "hardware ID of primary ecu")
("update-name", bpo::value<std::string>(), "optional name of the update when running \"update\". default=latest")
("command", bpo::value<std::string>(), subs.c_str());
// clang-format on
// consider the first positional argument as the aktualizr run mode
bpo::positional_options_description pos;
pos.add("command", 1);
bpo::variables_map vm;
std::vector<std::string> unregistered_options;
try {
bpo::basic_parsed_options<char> parsed_options =
bpo::command_line_parser(argc, argv).options(description).positional(pos).allow_unregistered().run();
bpo::store(parsed_options, vm);
check_info_options(description, vm);
bpo::notify(vm);
unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::exclude_positional);
if (vm.count("help") == 0 && !unregistered_options.empty()) {
std::cout << description << "\n";
exit(EXIT_FAILURE);
}
} catch (const bpo::required_option &ex) {
// print the error and append the default commandline option description
std::cout << ex.what() << std::endl << description;
exit(EXIT_FAILURE);
} catch (const bpo::error &ex) {
check_info_options(description, vm);
// log boost error
LOG_ERROR << "boost command line option error: " << ex.what();
// print the error message to the standard output too, as the user provided
// a non-supported commandline option
std::cout << ex.what() << '\n';
// set the returnValue, thereby ctest will recognize
// that something went wrong
exit(EXIT_FAILURE);
}
return vm;
}
int main(int argc, char *argv[]) {
logger_init(isatty(1) == 1);
logger_set_threshold(boost::log::trivial::info);
bpo::variables_map commandline_map = parse_options(argc, argv);
int r = EXIT_FAILURE;
try {
if (geteuid() != 0) {
LOG_WARNING << "\033[31mRunning as non-root and may not work as expected!\033[0m\n";
}
Config config(commandline_map);
config.storage.uptane_metadata_path = BasedPath(config.storage.path / "metadata");
LOG_DEBUG << "Current directory: " << boost::filesystem::current_path().string();
std::string cmd = commandline_map["command"].as<std::string>();
for (size_t i = 0; i < sizeof(commands) / sizeof(SubCommand); i++) {
if (cmd == commands[i].name) {
LiteClient client(config);
return commands[i].main(client, commandline_map);
}
}
throw bpo::invalid_option_value(cmd);
r = EXIT_SUCCESS;
} catch (const std::exception &ex) {
LOG_ERROR << ex.what();
}
return r;
}
<|endoftext|>
|
<commit_before>#include "Graphics.h"
using namespace std;
GraphicsInternals::GraphicsInternals(Bin* const bin, ThreadManager* const manager)
: bin(bin), manager(manager) {}
GraphicsInternals::~GraphicsInternals() {}
void GraphicsInternals::openWindow(const string& name)
{
window.create(sf::VideoMode(bin->getWidth(), bin->getHeight()), name, sf::Style::Default);
}
void GraphicsInternals::drawMap()
{
sf::CircleShape hexa((*bin->getAllHexes()).getRadius(), 6); //Each hex will be a circle with 6 sides
hexa.rotate(30);
hexa.setOutlineThickness(0.8);
hexa.setOutlineColor(sf::Color::Blue);
hexa.setFillColor(sf::Color::White);
hexa.setOrigin((*bin->getAllHexes()).getRadius(), (*bin->getAllHexes()).getRadius());
for (const Bin::Hex& hex : bin->getAllHexes())
{
hexa.setPosition(hex.getX(), hex.getY());
window.draw(hexa);
}
}
void GraphicsInternals::drawEntities()
{
//Every ent will be a red ring with a red dot at it's center
if (bin->count())
for (const Entity& entity : bin->getAll())
{
#include "../Compiler/EntityDrawCode.cpp"
}
}
void GraphicsInternals::manageEvents()
{
//check window events
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
{
manager->kill();
window.close();
}
// catch the resize events
if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
window.setView(sf::View(visibleArea));
}
//zoom
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
{
// create a view half the size of the default view
sf::View view = window.getView();
if (event.mouseWheelScroll.delta <= -1)
view.zoom(1.1);
else if (event.mouseWheelScroll.delta >= 1)
view.zoom(0.9);
window.setView(view);
}
}
}
void GraphicsInternals::input()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
sf::View view = window.getView();
view.move(-moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
sf::View view = window.getView();
view.move(moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
sf::View view = window.getView();
view.move(0, -moveSensitivity);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
sf::View view = window.getView();
view.move(0, moveSensitivity);
window.setView(view);
}
}
#include "../Plugins/Graphics/Graphics.cpp"
<commit_msg>Add Speed Controls (+/-)<commit_after>#include "Graphics.h"
using namespace std;
GraphicsInternals::GraphicsInternals(Bin* const bin, ThreadManager* const manager)
: bin(bin), manager(manager) {}
GraphicsInternals::~GraphicsInternals() {}
void GraphicsInternals::openWindow(const string& name)
{
window.create(sf::VideoMode(bin->getWidth(), bin->getHeight()), name, sf::Style::Default);
}
void GraphicsInternals::drawMap()
{
sf::CircleShape hexa((*bin->getAllHexes()).getRadius(), 6); //Each hex will be a circle with 6 sides
hexa.rotate(30);
hexa.setOutlineThickness(0.8);
hexa.setOutlineColor(sf::Color::Blue);
hexa.setFillColor(sf::Color::White);
hexa.setOrigin((*bin->getAllHexes()).getRadius(), (*bin->getAllHexes()).getRadius());
for (const Bin::Hex& hex : bin->getAllHexes())
{
hexa.setPosition(hex.getX(), hex.getY());
window.draw(hexa);
}
}
void GraphicsInternals::drawEntities()
{
//Every ent will be a red ring with a red dot at it's center
if (bin->count())
for (const Entity& entity : bin->getAll())
{
#include "../Compiler/EntityDrawCode.cpp"
}
}
void GraphicsInternals::manageEvents()
{
//check window events
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
{
manager->kill();
window.close();
}
// catch the resize events
if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
window.setView(sf::View(visibleArea));
}
//zoom
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
{
// create a view half the size of the default view
sf::View view = window.getView();
if (event.mouseWheelScroll.delta <= -1)
view.zoom(1.1);
else if (event.mouseWheelScroll.delta >= 1)
view.zoom(0.9);
window.setView(view);
}
}
}
void GraphicsInternals::input()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
sf::View view = window.getView();
view.move(-moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
sf::View view = window.getView();
view.move(moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
sf::View view = window.getView();
view.move(0, -moveSensitivity);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
sf::View view = window.getView();
view.move(0, moveSensitivity);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Add))
{
manager->setSpeed(manager->getSpeed()*2);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Subtract))
{
manager->setSpeed(manager->getSpeed()/2);
}
}
#include "../Plugins/Graphics/Graphics.cpp"
<|endoftext|>
|
<commit_before>#include "Graphics.h"
using namespace std;
GraphicsInternals::GraphicsInternals(Bin* const bin, ThreadManager* const manager)
: bin(bin), manager(manager) {}
GraphicsInternals::~GraphicsInternals() {}
void GraphicsInternals::openWindow(const string& name)
{
window.create(sf::VideoMode(bin->getWidth(), bin->getHeight()), name, sf::Style::Default);
}
void GraphicsInternals::drawMap()
{
sf::CircleShape hexa((*bin->getAllHexes()).getRadius(), 6); //Each hex will be a circle with 6 sides
hexa.rotate(30);
hexa.setOutlineThickness(0.8);
hexa.setOutlineColor(sf::Color::Black);
hexa.setFillColor(sf::Color::White);
for (const Bin::Hex& hex : bin->getAllHexes())
{
hexa.setPosition(hex.getX(), hex.getY());
window.draw(hexa);
}
}
void GraphicsInternals::drawEntities()
{
//Every ent will be a red ring with a red dot at it's center
sf::CircleShape circularEnt(2, 30); //Each ent will be a circle of radius x
circularEnt.setOrigin(2, 2);
circularEnt.setOutlineThickness(0.8);
circularEnt.setOutlineColor(sf::Color::Red);
circularEnt.setFillColor(sf::Color::Transparent);
sf::CircleShape entCenter(0.2, 30); //Each ent will be a circle of radius
entCenter.setOrigin(0.2, 0.2);
entCenter.setFillColor(sf::Color::Red);
for (const Entity& entity : bin->getAll())
{
//Draw circle for entitiy
circularEnt.setPosition(entity.getX(), entity.getY());
window.draw(circularEnt);
//Draw point for center
entCenter.setPosition(entity.getX(), entity.getY());
window.draw(entCenter);
}
}
void GraphicsInternals::manageEvents()
{
//check window events
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
{
manager->kill();
window.close();
}
// catch the resize events
if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
window.setView(sf::View(visibleArea));
}
//zoom
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
{
// create a view half the size of the default view
sf::View view = window.getView();
if (event.mouseWheelScroll.delta <= -1)
view.zoom(1.1);
else if (event.mouseWheelScroll.delta >= 1)
view.zoom(0.9);
window.setView(view);
}
}
}
void GraphicsInternals::input()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
sf::View view = window.getView();
view.move(-moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
sf::View view = window.getView();
view.move(moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
sf::View view = window.getView();
view.move(0, -moveSensitivity);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
sf::View view = window.getView();
view.move(0, moveSensitivity);
window.setView(view);
}
}
#include "../Plugins/Graphics/Graphics.cpp"
<commit_msg>Adjusted Hex Origin<commit_after>#include "Graphics.h"
using namespace std;
GraphicsInternals::GraphicsInternals(Bin* const bin, ThreadManager* const manager)
: bin(bin), manager(manager) {}
GraphicsInternals::~GraphicsInternals() {}
void GraphicsInternals::openWindow(const string& name)
{
window.create(sf::VideoMode(bin->getWidth(), bin->getHeight()), name, sf::Style::Default);
}
void GraphicsInternals::drawMap()
{
sf::CircleShape hexa((*bin->getAllHexes()).getRadius(), 6); //Each hex will be a circle with 6 sides
hexa.rotate(30);
hexa.setOutlineThickness(0.8);
hexa.setOutlineColor(sf::Color::Blue);
hexa.setFillColor(sf::Color::White);
hexa.setOrigin((*bin->getAllHexes()).getRadius(), (*bin->getAllHexes()).getRadius());
for (const Bin::Hex& hex : bin->getAllHexes())
{
hexa.setPosition(hex.getX(), hex.getY());
window.draw(hexa);
}
}
void GraphicsInternals::drawEntities()
{
//Every ent will be a red ring with a red dot at it's center
sf::CircleShape circularEnt(2, 30); //Each ent will be a circle of radius x
circularEnt.setOrigin(2, 2);
circularEnt.setOutlineThickness(0.8);
circularEnt.setOutlineColor(sf::Color::Red);
circularEnt.setFillColor(sf::Color::Transparent);
sf::CircleShape entCenter(0.2, 30); //Each ent will be a circle of radius
entCenter.setOrigin(0.2, 0.2);
entCenter.setFillColor(sf::Color::Red);
for (const Entity& entity : bin->getAll())
{
//Draw circle for entitiy
circularEnt.setPosition(entity.getX(), entity.getY());
window.draw(circularEnt);
//Draw point for center
entCenter.setPosition(entity.getX(), entity.getY());
window.draw(entCenter);
}
}
void GraphicsInternals::manageEvents()
{
//check window events
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
{
manager->kill();
window.close();
}
// catch the resize events
if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0, 0, event.size.width, event.size.height);
window.setView(sf::View(visibleArea));
}
//zoom
if (event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
{
// create a view half the size of the default view
sf::View view = window.getView();
if (event.mouseWheelScroll.delta <= -1)
view.zoom(1.1);
else if (event.mouseWheelScroll.delta >= 1)
view.zoom(0.9);
window.setView(view);
}
}
}
void GraphicsInternals::input()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
sf::View view = window.getView();
view.move(-moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
sf::View view = window.getView();
view.move(moveSensitivity, 0);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
sf::View view = window.getView();
view.move(0, -moveSensitivity);
window.setView(view);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
sf::View view = window.getView();
view.move(0, moveSensitivity);
window.setView(view);
}
}
#include "../Plugins/Graphics/Graphics.cpp"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* Copyright (c) 2007-2008 The Florida State 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 the copyright holders 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.
*
* Authors: Gabe Black
* Stephen Hines
*/
#ifndef __ARCH_ARM_PREDECODER_HH__
#define __ARCH_ARM_PREDECODER_HH__
#include "arch/arm/types.hh"
#include "base/misc.hh"
#include "base/types.hh"
class ThreadContext;
namespace ArmISA
{
class Predecoder
{
protected:
ThreadContext * tc;
//The extended machine instruction being generated
ExtMachInst emi;
MachInst data;
bool bigThumb;
int offset;
public:
Predecoder(ThreadContext * _tc) :
tc(_tc), data(0), bigThumb(false), offset(0)
{}
ThreadContext * getTC()
{
return tc;
}
void setTC(ThreadContext * _tc)
{
tc = _tc;
}
void reset()
{
bigThumb = false;
offset = 0;
emi = 0;
}
void process()
{
if (!emi.thumb) {
emi.instBits = data;
emi.sevenAndFour = bits(data, 7) && bits(data, 4);
emi.isMisc = (bits(data, 24, 23) == 0x2 &&
bits(data, 20) == 0);
DPRINTF(Predecoder, "Arm inst.\n");
} else {
uint16_t word = (data >> (offset * 8));
if (bigThumb) {
// A 32 bit thumb inst is half collected.
emi.instBits = emi.instBits | word;
bigThumb = false;
offset += 2;
DPRINTF(Predecoder, "Second half of 32 bit Thumb.\n");
} else {
uint16_t highBits = word & 0xF800;
if (highBits == 0xE800 || highBits == 0xF000 ||
highBits == 0xF800) {
// The start of a 32 bit thumb inst.
emi.bigThumb = 1;
if (offset == 0) {
// We've got the whole thing.
DPRINTF(Predecoder,
"All of 32 bit Thumb.\n");
emi.instBits = (data >> 16) | (data << 16);
offset += 4;
} else {
// We only have the first half word.
DPRINTF(Predecoder,
"First half of 32 bit Thumb.\n");
emi.instBits = (uint32_t)word << 16;
bigThumb = true;
offset += 2;
}
} else {
// A 16 bit thumb inst.
DPRINTF(Predecoder, "16 bit Thumb.\n");
offset += 2;
emi.instBits = word;
// Set the condition code field artificially.
emi.condCode = COND_UC;
}
}
}
}
//Use this to give data to the predecoder. This should be used
//when there is control flow.
void moreBytes(Addr pc, Addr fetchPC, MachInst inst)
{
data = inst;
offset = (fetchPC >= pc) ? 0 : pc - fetchPC;
emi.thumb = (pc & (ULL(1) << PcTBitShift)) ? 1 : 0;
process();
}
//Use this to give data to the predecoder. This should be used
//when instructions are executed in order.
void moreBytes(MachInst machInst)
{
moreBytes(0, 0, machInst);
}
bool needMoreBytes()
{
return sizeof(MachInst) > offset;
}
bool extMachInstReady()
{
// The only way an instruction wouldn't be ready is if this is a
// 32 bit ARM instruction that's not 32 bit aligned.
return !bigThumb;
}
int getInstSize()
{
return (!emi.thumb || emi.bigThumb) ? 4 : 2;
}
//This returns a constant reference to the ExtMachInst to avoid a copy
ExtMachInst getExtMachInst()
{
ExtMachInst thisEmi = emi;
emi = 0;
return thisEmi;
}
};
};
#endif // __ARCH_ARM_PREDECODER_HH__
<commit_msg>ARM: Make the predecoder print out the ExtMachInst it gathered when traced.<commit_after>/*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2006 The Regents of The University of Michigan
* Copyright (c) 2007-2008 The Florida State 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 the copyright holders 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.
*
* Authors: Gabe Black
* Stephen Hines
*/
#ifndef __ARCH_ARM_PREDECODER_HH__
#define __ARCH_ARM_PREDECODER_HH__
#include "arch/arm/types.hh"
#include "base/misc.hh"
#include "base/types.hh"
class ThreadContext;
namespace ArmISA
{
class Predecoder
{
protected:
ThreadContext * tc;
//The extended machine instruction being generated
ExtMachInst emi;
MachInst data;
bool bigThumb;
int offset;
public:
Predecoder(ThreadContext * _tc) :
tc(_tc), data(0), bigThumb(false), offset(0)
{}
ThreadContext * getTC()
{
return tc;
}
void setTC(ThreadContext * _tc)
{
tc = _tc;
}
void reset()
{
bigThumb = false;
offset = 0;
emi = 0;
}
void process()
{
if (!emi.thumb) {
emi.instBits = data;
emi.sevenAndFour = bits(data, 7) && bits(data, 4);
emi.isMisc = (bits(data, 24, 23) == 0x2 &&
bits(data, 20) == 0);
DPRINTF(Predecoder, "Arm inst.\n");
} else {
uint16_t word = (data >> (offset * 8));
if (bigThumb) {
// A 32 bit thumb inst is half collected.
emi.instBits = emi.instBits | word;
bigThumb = false;
offset += 2;
DPRINTF(Predecoder, "Second half of 32 bit Thumb: %#x.\n",
emi.instBits);
} else {
uint16_t highBits = word & 0xF800;
if (highBits == 0xE800 || highBits == 0xF000 ||
highBits == 0xF800) {
// The start of a 32 bit thumb inst.
emi.bigThumb = 1;
if (offset == 0) {
// We've got the whole thing.
emi.instBits = (data >> 16) | (data << 16);
DPRINTF(Predecoder, "All of 32 bit Thumb: %#x.\n",
emi.instBits);
offset += 4;
} else {
// We only have the first half word.
DPRINTF(Predecoder,
"First half of 32 bit Thumb.\n");
emi.instBits = (uint32_t)word << 16;
bigThumb = true;
offset += 2;
}
} else {
// A 16 bit thumb inst.
offset += 2;
emi.instBits = word;
// Set the condition code field artificially.
emi.condCode = COND_UC;
DPRINTF(Predecoder, "16 bit Thumb: %#x.\n",
emi.instBits);
}
}
}
}
//Use this to give data to the predecoder. This should be used
//when there is control flow.
void moreBytes(Addr pc, Addr fetchPC, MachInst inst)
{
data = inst;
offset = (fetchPC >= pc) ? 0 : pc - fetchPC;
emi.thumb = (pc & (ULL(1) << PcTBitShift)) ? 1 : 0;
process();
}
//Use this to give data to the predecoder. This should be used
//when instructions are executed in order.
void moreBytes(MachInst machInst)
{
moreBytes(0, 0, machInst);
}
bool needMoreBytes()
{
return sizeof(MachInst) > offset;
}
bool extMachInstReady()
{
// The only way an instruction wouldn't be ready is if this is a
// 32 bit ARM instruction that's not 32 bit aligned.
return !bigThumb;
}
int getInstSize()
{
return (!emi.thumb || emi.bigThumb) ? 4 : 2;
}
//This returns a constant reference to the ExtMachInst to avoid a copy
ExtMachInst getExtMachInst()
{
ExtMachInst thisEmi = emi;
emi = 0;
return thisEmi;
}
};
};
#endif // __ARCH_ARM_PREDECODER_HH__
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007-2016 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* @file
* @brief Source for Ar microkernel mutexes.
*/
#include "ar_internal.h"
#include <string.h>
#include <assert.h>
using namespace Ar;
//------------------------------------------------------------------------------
// Implementation
//------------------------------------------------------------------------------
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_create(ar_mutex_t * mutex, const char * name)
{
if (!mutex)
{
return kArInvalidParameterError;
}
ar_status_t status = ar_semaphore_create(&mutex->m_sem, name, 1);
if (status == kArSuccess)
{
// Start without an owner.
mutex->m_owner = NULL;
mutex->m_ownerLockCount = 0;
mutex->m_originalPriority = 0;
// Set the blocked list to sort by priority.
mutex->m_sem.m_blockedList.m_predicate = ar_thread_sort_by_priority;
#if AR_GLOBAL_OBJECT_LISTS
mutex->m_sem.m_createdNode.m_obj = mutex;
g_ar.allObjects.semaphores.remove(&mutex->m_sem.m_createdNode);
g_ar.allObjects.mutexes.add(&mutex->m_sem.m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS
}
return status;
}
// See ar_kernel.h for documentation of this function.
//! @todo Return error when deleting a mutex that is still locked.
ar_status_t ar_mutex_delete(ar_mutex_t * mutex)
{
if (!mutex)
{
return kArInvalidParameterError;
}
#if AR_GLOBAL_OBJECT_LISTS
g_ar.allObjects.mutexes.remove(&mutex->m_sem.m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS
return kArSuccess;
}
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_get(ar_mutex_t * mutex, uint32_t timeout)
{
if (!mutex)
{
return kArInvalidParameterError;
}
// Handle locked kernel in irq state by deferring the get.
if (ar_port_get_irq_state() && g_ar.lockCount)
{
return ar_post_deferred_action(kArDeferredMutexGet, mutex);
}
{
KernelLock guard;
// If this thread already owns the mutex, just increment the count.
if (g_ar.currentThread == mutex->m_owner)
{
++mutex->m_ownerLockCount;
return kArSuccess;
}
// Otherwise attempt to get the mutex.
else
{
// Will we block?
if (mutex->m_sem.m_count == 0)
{
// Return immediately if the timeout is 0. No reason to call into the sem code.
if (timeout == kArNoTimeout)
{
return kArTimeoutError;
}
// Check if we need to hoist the owning thread's priority to our own.
ar_thread_t * self = g_ar.currentThread;
if (self->m_priority > mutex->m_owner->m_priority)
{
if (!mutex->m_originalPriority)
{
mutex->m_originalPriority = mutex->m_owner->m_priority;
}
mutex->m_owner->m_priority = self->m_priority;
}
}
ar_status_t result = ar_semaphore_get(&mutex->m_sem, timeout);
if (result == kArSuccess)
{
// Set the owner now that we own the lock.
mutex->m_owner = g_ar.currentThread;
++mutex->m_ownerLockCount;
}
else if (result == kArTimeoutError)
{
//! @todo Need to handle timeout after hoisting the owner thread.
}
return result;
}
}
}
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_put(ar_mutex_t * mutex)
{
if (!mutex)
{
return kArInvalidParameterError;
}
// Handle locked kernel in irq state by deferring the put.
if (ar_port_get_irq_state() && g_ar.lockCount)
{
return ar_post_deferred_action(kArDeferredMutexPut, mutex);
}
ar_status_t result = kArSuccess;
{
KernelLock guard;
// Nothing to do if the mutex is already unlocked.
if (mutex->m_ownerLockCount == 0)
{
return kArAlreadyUnlockedError;
}
// Only the owning thread can unlock a mutex.
ar_thread_t * self = g_ar.currentThread;
if (self != mutex->m_owner)
{
return kArNotOwnerError;
}
// We are the owner of the mutex, so decrement its recursive lock count.
if (--mutex->m_ownerLockCount == 0)
{
// The lock count has reached zero, so put the semaphore and clear the owner.
// The owner is cleared first since putting the sem can cause us to
// switch threads.
mutex->m_owner = NULL;
result = ar_semaphore_put(&mutex->m_sem);
// Restore this thread's priority if it had been raised.
uint8_t original = mutex->m_originalPriority;
if (original)
{
mutex->m_originalPriority = 0;
ar_thread_set_priority(self, original);
}
}
}
return result;
}
// See ar_kernel.h for documentation of this function.
bool ar_mutex_is_locked(ar_mutex_t * mutex)
{
return mutex ? mutex->m_sem.m_count == 0 : false;
}
// See ar_kernel.h for documentation of this function.
ar_thread_t * ar_mutex_get_owner(ar_mutex_t * mutex)
{
return mutex ? (ar_thread_t *)mutex->m_owner : NULL;
}
// See ar_kernel.h for documentation of this function.
const char * ar_mutex_get_name(ar_mutex_t * mutex)
{
return mutex ? mutex->m_sem.m_name : NULL;
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<commit_msg>Fixed regression in mutex.<commit_after>/*
* Copyright (c) 2007-2016 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
* @file
* @brief Source for Ar microkernel mutexes.
*/
#include "ar_internal.h"
#include <string.h>
#include <assert.h>
using namespace Ar;
//------------------------------------------------------------------------------
// Implementation
//------------------------------------------------------------------------------
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_create(ar_mutex_t * mutex, const char * name)
{
if (!mutex)
{
return kArInvalidParameterError;
}
ar_status_t status = ar_semaphore_create(&mutex->m_sem, name, 1);
if (status == kArSuccess)
{
// Start without an owner.
mutex->m_owner = NULL;
mutex->m_ownerLockCount = 0;
mutex->m_originalPriority = 0;
// Set the blocked list to sort by priority.
mutex->m_sem.m_blockedList.m_predicate = ar_thread_sort_by_priority;
#if AR_GLOBAL_OBJECT_LISTS
mutex->m_sem.m_createdNode.m_obj = mutex;
g_ar.allObjects.semaphores.remove(&mutex->m_sem.m_createdNode);
g_ar.allObjects.mutexes.add(&mutex->m_sem.m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS
}
return status;
}
// See ar_kernel.h for documentation of this function.
//! @todo Return error when deleting a mutex that is still locked.
ar_status_t ar_mutex_delete(ar_mutex_t * mutex)
{
if (!mutex)
{
return kArInvalidParameterError;
}
#if AR_GLOBAL_OBJECT_LISTS
g_ar.allObjects.mutexes.remove(&mutex->m_sem.m_createdNode);
#endif // AR_GLOBAL_OBJECT_LISTS
return kArSuccess;
}
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_get(ar_mutex_t * mutex, uint32_t timeout)
{
if (!mutex)
{
return kArInvalidParameterError;
}
// Handle locked kernel in irq state by deferring the get.
if (ar_port_get_irq_state() && g_ar.lockCount)
{
return ar_post_deferred_action(kArDeferredMutexGet, mutex);
}
{
KernelLock guard;
// If this thread already owns the mutex, just increment the count.
if (g_ar.currentThread == mutex->m_owner)
{
++mutex->m_ownerLockCount;
return kArSuccess;
}
// Otherwise attempt to get the mutex.
else
{
// Will we block?
if (mutex->m_sem.m_count == 0)
{
// Return immediately if the timeout is 0. No reason to call into the sem code.
if (timeout == kArNoTimeout)
{
return kArTimeoutError;
}
// Check if we need to hoist the owning thread's priority to our own.
ar_thread_t * self = g_ar.currentThread;
if (self->m_priority > mutex->m_owner->m_priority)
{
if (!mutex->m_originalPriority)
{
mutex->m_originalPriority = mutex->m_owner->m_priority;
}
mutex->m_owner->m_priority = self->m_priority;
}
}
ar_status_t result;
{
KernelUnlock unlock;
result = ar_semaphore_get(&mutex->m_sem, timeout);
}
if (result == kArSuccess)
{
// Set the owner now that we own the lock.
mutex->m_owner = g_ar.currentThread;
++mutex->m_ownerLockCount;
}
else if (result == kArTimeoutError)
{
//! @todo Need to handle timeout after hoisting the owner thread.
}
return result;
}
}
}
// See ar_kernel.h for documentation of this function.
ar_status_t ar_mutex_put(ar_mutex_t * mutex)
{
if (!mutex)
{
return kArInvalidParameterError;
}
// Handle locked kernel in irq state by deferring the put.
if (ar_port_get_irq_state() && g_ar.lockCount)
{
return ar_post_deferred_action(kArDeferredMutexPut, mutex);
}
ar_status_t result = kArSuccess;
{
KernelLock guard;
// Nothing to do if the mutex is already unlocked.
if (mutex->m_ownerLockCount == 0)
{
return kArAlreadyUnlockedError;
}
// Only the owning thread can unlock a mutex.
ar_thread_t * self = g_ar.currentThread;
if (self != mutex->m_owner)
{
return kArNotOwnerError;
}
// We are the owner of the mutex, so decrement its recursive lock count.
if (--mutex->m_ownerLockCount == 0)
{
// The lock count has reached zero, so put the semaphore and clear the owner.
// The owner is cleared first since putting the sem can cause us to
// switch threads.
mutex->m_owner = NULL;
{
KernelUnlock unlock;
result = ar_semaphore_put(&mutex->m_sem);
}
// Restore this thread's priority if it had been raised.
uint8_t original = mutex->m_originalPriority;
if (original)
{
mutex->m_originalPriority = 0;
ar_thread_set_priority(self, original);
}
}
}
return result;
}
// See ar_kernel.h for documentation of this function.
bool ar_mutex_is_locked(ar_mutex_t * mutex)
{
return mutex ? mutex->m_sem.m_count == 0 : false;
}
// See ar_kernel.h for documentation of this function.
ar_thread_t * ar_mutex_get_owner(ar_mutex_t * mutex)
{
return mutex ? (ar_thread_t *)mutex->m_owner : NULL;
}
// See ar_kernel.h for documentation of this function.
const char * ar_mutex_get_name(ar_mutex_t * mutex)
{
return mutex ? mutex->m_sem.m_name : NULL;
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#ifndef ARGPARSE_FORMATTER_HPP
#define ARGPARSE_FORMATTER_HPP
#include <string>
namespace argparse {
class ArgumentParser;
class Formatter {
public:
virtual ~Formatter() {};
virtual void set_parser(ArgumentParser* parser) = 0;
virtual std::string format_usage() const = 0;
virtual std::string format_description() const = 0;
virtual std::string format_arguments() const = 0;
virtual std::string format_epilog() const = 0;
virtual std::string format_version() const = 0;
};
class DefaultFormatter : public Formatter {
public:
DefaultFormatter(size_t option_arg_width=20, size_t total_width=80);
void set_parser(ArgumentParser* parser) override;
std::string format_usage() const override;
std::string format_description() const override;
std::string format_arguments() const override;
std::string format_epilog() const override;
std::string format_version() const override;
private:
size_t option_name_width_;
size_t total_width_;
ArgumentParser* parser_;
};
} //namespace
#endif
<commit_msg>Remove extra semicolon<commit_after>#ifndef ARGPARSE_FORMATTER_HPP
#define ARGPARSE_FORMATTER_HPP
#include <string>
namespace argparse {
class ArgumentParser;
class Formatter {
public:
virtual ~Formatter() {}
virtual void set_parser(ArgumentParser* parser) = 0;
virtual std::string format_usage() const = 0;
virtual std::string format_description() const = 0;
virtual std::string format_arguments() const = 0;
virtual std::string format_epilog() const = 0;
virtual std::string format_version() const = 0;
};
class DefaultFormatter : public Formatter {
public:
DefaultFormatter(size_t option_arg_width=20, size_t total_width=80);
void set_parser(ArgumentParser* parser) override;
std::string format_usage() const override;
std::string format_description() const override;
std::string format_arguments() const override;
std::string format_epilog() const override;
std::string format_version() const override;
private:
size_t option_name_width_;
size_t total_width_;
ArgumentParser* parser_;
};
} //namespace
#endif
<|endoftext|>
|
<commit_before>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "modsecurity/audit_log.h"
#include <stddef.h>
#include <stdio.h>
#include <ctype.h>
#include <fstream>
#include "modsecurity/rule_message.h"
#include "src/audit_log/writer/https.h"
#include "src/audit_log/writer/parallel.h"
#include "src/audit_log/writer/serial.h"
#include "src/audit_log/writer/writer.h"
#include "src/utils/regex.h"
#define PARTS_CONSTAINS(a, c) \
if (new_parts.find(toupper(a)) != std::string::npos \
|| new_parts.find(tolower(a)) != std::string::npos) { \
parts = parts | c; \
}
#define PARTS_CONSTAINS_REM(a, c) \
if (new_parts.find(toupper(a)) != std::string::npos \
|| new_parts.find(tolower(a)) != std::string::npos) { \
parts = parts & ~c; \
}
#define AL_MERGE_STRING_CONF(a, c) \
if (a.empty() == false) { \
c = a; \
}
namespace modsecurity {
namespace audit_log {
AuditLog::AuditLog()
: m_path1(""),
m_path2(""),
m_storage_dir(""),
m_format(NotSetAuditLogFormat),
m_parts(-1),
m_filePermission(-1),
m_directoryPermission(-1),
m_status(NotSetLogStatus),
m_type(NotSetAuditLogType),
m_relevant(""),
m_writer(NULL) { }
AuditLog::~AuditLog() {
if (m_writer) {
delete m_writer;
m_writer = NULL;
}
}
bool AuditLog::setStorageDirMode(int permission) {
this->m_directoryPermission = permission;
return true;
}
bool AuditLog::setFileMode(int permission) {
this->m_filePermission = permission;
return true;
}
int AuditLog::getFilePermission() const {
if (m_filePermission == -1) {
return m_defaultFilePermission;
}
return m_filePermission;
}
int AuditLog::getDirectoryPermission() const {
if (m_directoryPermission == -1) {
return m_defaultDirectoryPermission;
}
return m_directoryPermission;
}
bool AuditLog::setStatus(AuditLogStatus status) {
this->m_status = status;
return true;
}
bool AuditLog::setRelevantStatus(const std::basic_string<char>& status) {
this->m_relevant = std::string(status);
return true;
}
bool AuditLog::setStorageDir(const std::basic_string<char>& path) {
this->m_storage_dir = path;
return true;
}
bool AuditLog::setFilePath1(const std::basic_string<char>& path) {
this->m_path1 = path;
return true;
}
bool AuditLog::setFilePath2(const std::basic_string<char>& path) {
this->m_path2 = path;
return true;
}
bool AuditLog::setFormat(AuditLogFormat fmt) {
this->m_format = fmt;
return true;
}
int AuditLog::addParts(int parts, const std::string& new_parts) {
PARTS_CONSTAINS('A', AAuditLogPart)
PARTS_CONSTAINS('B', BAuditLogPart)
PARTS_CONSTAINS('C', CAuditLogPart)
PARTS_CONSTAINS('D', DAuditLogPart)
PARTS_CONSTAINS('E', EAuditLogPart)
PARTS_CONSTAINS('F', FAuditLogPart)
PARTS_CONSTAINS('G', GAuditLogPart)
PARTS_CONSTAINS('H', HAuditLogPart)
PARTS_CONSTAINS('I', IAuditLogPart)
PARTS_CONSTAINS('J', JAuditLogPart)
PARTS_CONSTAINS('K', KAuditLogPart)
PARTS_CONSTAINS('Z', ZAuditLogPart)
return parts;
}
int AuditLog::removeParts(int parts, const std::string& new_parts) {
PARTS_CONSTAINS_REM('A', AAuditLogPart)
PARTS_CONSTAINS_REM('B', BAuditLogPart)
PARTS_CONSTAINS_REM('C', CAuditLogPart)
PARTS_CONSTAINS_REM('D', DAuditLogPart)
PARTS_CONSTAINS_REM('E', EAuditLogPart)
PARTS_CONSTAINS_REM('F', FAuditLogPart)
PARTS_CONSTAINS_REM('G', GAuditLogPart)
PARTS_CONSTAINS_REM('H', HAuditLogPart)
PARTS_CONSTAINS_REM('I', IAuditLogPart)
PARTS_CONSTAINS_REM('J', JAuditLogPart)
PARTS_CONSTAINS_REM('K', KAuditLogPart)
PARTS_CONSTAINS_REM('Z', ZAuditLogPart)
return parts;
}
bool AuditLog::setParts(const std::basic_string<char>& new_parts) {
int parts = 0;
PARTS_CONSTAINS('A', AAuditLogPart)
PARTS_CONSTAINS('B', BAuditLogPart)
PARTS_CONSTAINS('C', CAuditLogPart)
PARTS_CONSTAINS('D', DAuditLogPart)
PARTS_CONSTAINS('E', EAuditLogPart)
PARTS_CONSTAINS('F', FAuditLogPart)
PARTS_CONSTAINS('G', GAuditLogPart)
PARTS_CONSTAINS('H', HAuditLogPart)
PARTS_CONSTAINS('I', IAuditLogPart)
PARTS_CONSTAINS('J', JAuditLogPart)
PARTS_CONSTAINS('K', KAuditLogPart)
PARTS_CONSTAINS('Z', ZAuditLogPart)
m_parts = parts;
return true;
}
int AuditLog::getParts() const {
if (m_parts == -1) {
return m_defaultParts;
}
return m_parts;
}
bool AuditLog::setType(AuditLogType audit_type) {
this->m_type = audit_type;
return true;
}
bool AuditLog::init(std::string *error) {
audit_log::writer::Writer *tmp_writer;
if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
if (m_writer) {
delete m_writer;
m_writer = NULL;
}
return true;
}
if (m_type == ParallelAuditLogType) {
tmp_writer = new audit_log::writer::Parallel(this);
} else if (m_type == HttpsAuditLogType) {
tmp_writer = new audit_log::writer::Https(this);
} else {
/*
* if (m_type == SerialAuditLogType
* || m_type == NotSetAuditLogType)
*
*/
tmp_writer = new audit_log::writer::Serial(this);
}
if (tmp_writer == NULL) {
error->assign("Writer memory alloc failed!");
return false;
}
if (tmp_writer->init(error) == false) {
delete tmp_writer;
return false;
}
/* Sanity check */
if (m_status == RelevantOnlyAuditLogStatus) {
if (m_relevant.empty()) {
/*
error->assign("m_relevant cannot be null while status is set to " \
"RelevantOnly");
return false;
*/
// FIXME: this should be a warning. There is not point to
// have the logs on relevant only if nothing is relevant.
//
// Not returning an error to keep the compatibility with v2.
}
}
if (m_writer) {
delete m_writer;
}
m_writer = tmp_writer;
return true;
}
bool AuditLog::isRelevant(int status) {
std::string sstatus = std::to_string(status);
if (m_relevant.empty()) {
return false;
}
if (sstatus.empty()) {
return true;
}
return Utils::regex_search(sstatus,
Utils::Regex(m_relevant)) != 0;
}
bool AuditLog::saveIfRelevant(Transaction *transaction) {
return saveIfRelevant(transaction, -1);
}
bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) {
bool saveAnyway = false;
if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
ms_dbg_a(transaction, 5, "Audit log engine was not set.");
return true;
}
for (RuleMessage &i : transaction->m_rulesMessages) {
if (i.m_noAuditLog == false) {
saveAnyway = true;
break;
}
}
if ((m_status == RelevantOnlyAuditLogStatus
&& this->isRelevant(transaction->m_httpCodeReturned) == false)
&& saveAnyway == false) {
ms_dbg_a(transaction, 9, "Return code `" +
std::to_string(transaction->m_httpCodeReturned) + "'" \
" is not interesting to audit logs, relevant code(s): `" +
m_relevant + "'.");
return false;
}
if (parts == -1) {
parts = m_parts;
}
ms_dbg_a(transaction, 5, "Saving this request as part " \
"of the audit logs.");
if (m_writer == NULL) {
ms_dbg_a(transaction, 1, "Internal error, audit log writer is null");
} else {
std::string error;
bool a = m_writer->write(transaction, parts, &error);
if (a == false) {
ms_dbg_a(transaction, 1, "Cannot save the audit log: " + error);
return false;
}
}
return true;
}
bool AuditLog::close() {
return true;
}
bool AuditLog::merge(AuditLog *from, std::string *error) {
AL_MERGE_STRING_CONF(from->m_path1, m_path1);
AL_MERGE_STRING_CONF(from->m_path2, m_path2);
AL_MERGE_STRING_CONF(from->m_storage_dir, m_storage_dir);
AL_MERGE_STRING_CONF(from->m_relevant, m_relevant);
if (from->m_filePermission != -1) {
m_filePermission = from->m_filePermission;
}
if (from->m_directoryPermission != -1) {
m_directoryPermission = from->m_directoryPermission;
}
if (from->m_type != NotSetAuditLogType) {
m_type = from->m_type;
}
if (from->m_status != NotSetLogStatus) {
m_status = from->m_status;
}
if (from->m_parts != -1) {
m_parts = from->m_parts;
}
if (from->m_format != NotSetAuditLogFormat) {
m_format = from->m_format;
}
return init(error);
}
} // namespace audit_log
} // namespace modsecurity
<commit_msg>Remove old commented-out re: audit log, relevant<commit_after>/*
* ModSecurity, http://www.modsecurity.org/
* Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* 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
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*
*/
#include "modsecurity/audit_log.h"
#include <stddef.h>
#include <stdio.h>
#include <ctype.h>
#include <fstream>
#include "modsecurity/rule_message.h"
#include "src/audit_log/writer/https.h"
#include "src/audit_log/writer/parallel.h"
#include "src/audit_log/writer/serial.h"
#include "src/audit_log/writer/writer.h"
#include "src/utils/regex.h"
#define PARTS_CONSTAINS(a, c) \
if (new_parts.find(toupper(a)) != std::string::npos \
|| new_parts.find(tolower(a)) != std::string::npos) { \
parts = parts | c; \
}
#define PARTS_CONSTAINS_REM(a, c) \
if (new_parts.find(toupper(a)) != std::string::npos \
|| new_parts.find(tolower(a)) != std::string::npos) { \
parts = parts & ~c; \
}
#define AL_MERGE_STRING_CONF(a, c) \
if (a.empty() == false) { \
c = a; \
}
namespace modsecurity {
namespace audit_log {
AuditLog::AuditLog()
: m_path1(""),
m_path2(""),
m_storage_dir(""),
m_format(NotSetAuditLogFormat),
m_parts(-1),
m_filePermission(-1),
m_directoryPermission(-1),
m_status(NotSetLogStatus),
m_type(NotSetAuditLogType),
m_relevant(""),
m_writer(NULL) { }
AuditLog::~AuditLog() {
if (m_writer) {
delete m_writer;
m_writer = NULL;
}
}
bool AuditLog::setStorageDirMode(int permission) {
this->m_directoryPermission = permission;
return true;
}
bool AuditLog::setFileMode(int permission) {
this->m_filePermission = permission;
return true;
}
int AuditLog::getFilePermission() const {
if (m_filePermission == -1) {
return m_defaultFilePermission;
}
return m_filePermission;
}
int AuditLog::getDirectoryPermission() const {
if (m_directoryPermission == -1) {
return m_defaultDirectoryPermission;
}
return m_directoryPermission;
}
bool AuditLog::setStatus(AuditLogStatus status) {
this->m_status = status;
return true;
}
bool AuditLog::setRelevantStatus(const std::basic_string<char>& status) {
this->m_relevant = std::string(status);
return true;
}
bool AuditLog::setStorageDir(const std::basic_string<char>& path) {
this->m_storage_dir = path;
return true;
}
bool AuditLog::setFilePath1(const std::basic_string<char>& path) {
this->m_path1 = path;
return true;
}
bool AuditLog::setFilePath2(const std::basic_string<char>& path) {
this->m_path2 = path;
return true;
}
bool AuditLog::setFormat(AuditLogFormat fmt) {
this->m_format = fmt;
return true;
}
int AuditLog::addParts(int parts, const std::string& new_parts) {
PARTS_CONSTAINS('A', AAuditLogPart)
PARTS_CONSTAINS('B', BAuditLogPart)
PARTS_CONSTAINS('C', CAuditLogPart)
PARTS_CONSTAINS('D', DAuditLogPart)
PARTS_CONSTAINS('E', EAuditLogPart)
PARTS_CONSTAINS('F', FAuditLogPart)
PARTS_CONSTAINS('G', GAuditLogPart)
PARTS_CONSTAINS('H', HAuditLogPart)
PARTS_CONSTAINS('I', IAuditLogPart)
PARTS_CONSTAINS('J', JAuditLogPart)
PARTS_CONSTAINS('K', KAuditLogPart)
PARTS_CONSTAINS('Z', ZAuditLogPart)
return parts;
}
int AuditLog::removeParts(int parts, const std::string& new_parts) {
PARTS_CONSTAINS_REM('A', AAuditLogPart)
PARTS_CONSTAINS_REM('B', BAuditLogPart)
PARTS_CONSTAINS_REM('C', CAuditLogPart)
PARTS_CONSTAINS_REM('D', DAuditLogPart)
PARTS_CONSTAINS_REM('E', EAuditLogPart)
PARTS_CONSTAINS_REM('F', FAuditLogPart)
PARTS_CONSTAINS_REM('G', GAuditLogPart)
PARTS_CONSTAINS_REM('H', HAuditLogPart)
PARTS_CONSTAINS_REM('I', IAuditLogPart)
PARTS_CONSTAINS_REM('J', JAuditLogPart)
PARTS_CONSTAINS_REM('K', KAuditLogPart)
PARTS_CONSTAINS_REM('Z', ZAuditLogPart)
return parts;
}
bool AuditLog::setParts(const std::basic_string<char>& new_parts) {
int parts = 0;
PARTS_CONSTAINS('A', AAuditLogPart)
PARTS_CONSTAINS('B', BAuditLogPart)
PARTS_CONSTAINS('C', CAuditLogPart)
PARTS_CONSTAINS('D', DAuditLogPart)
PARTS_CONSTAINS('E', EAuditLogPart)
PARTS_CONSTAINS('F', FAuditLogPart)
PARTS_CONSTAINS('G', GAuditLogPart)
PARTS_CONSTAINS('H', HAuditLogPart)
PARTS_CONSTAINS('I', IAuditLogPart)
PARTS_CONSTAINS('J', JAuditLogPart)
PARTS_CONSTAINS('K', KAuditLogPart)
PARTS_CONSTAINS('Z', ZAuditLogPart)
m_parts = parts;
return true;
}
int AuditLog::getParts() const {
if (m_parts == -1) {
return m_defaultParts;
}
return m_parts;
}
bool AuditLog::setType(AuditLogType audit_type) {
this->m_type = audit_type;
return true;
}
bool AuditLog::init(std::string *error) {
audit_log::writer::Writer *tmp_writer;
if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
if (m_writer) {
delete m_writer;
m_writer = NULL;
}
return true;
}
if (m_type == ParallelAuditLogType) {
tmp_writer = new audit_log::writer::Parallel(this);
} else if (m_type == HttpsAuditLogType) {
tmp_writer = new audit_log::writer::Https(this);
} else {
/*
* if (m_type == SerialAuditLogType
* || m_type == NotSetAuditLogType)
*
*/
tmp_writer = new audit_log::writer::Serial(this);
}
if (tmp_writer == NULL) {
error->assign("Writer memory alloc failed!");
return false;
}
if (tmp_writer->init(error) == false) {
delete tmp_writer;
return false;
}
if (m_writer) {
delete m_writer;
}
m_writer = tmp_writer;
return true;
}
bool AuditLog::isRelevant(int status) {
std::string sstatus = std::to_string(status);
if (m_relevant.empty()) {
return false;
}
if (sstatus.empty()) {
return true;
}
return Utils::regex_search(sstatus,
Utils::Regex(m_relevant)) != 0;
}
bool AuditLog::saveIfRelevant(Transaction *transaction) {
return saveIfRelevant(transaction, -1);
}
bool AuditLog::saveIfRelevant(Transaction *transaction, int parts) {
bool saveAnyway = false;
if (m_status == OffAuditLogStatus || m_status == NotSetLogStatus) {
ms_dbg_a(transaction, 5, "Audit log engine was not set.");
return true;
}
for (RuleMessage &i : transaction->m_rulesMessages) {
if (i.m_noAuditLog == false) {
saveAnyway = true;
break;
}
}
if ((m_status == RelevantOnlyAuditLogStatus
&& this->isRelevant(transaction->m_httpCodeReturned) == false)
&& saveAnyway == false) {
ms_dbg_a(transaction, 9, "Return code `" +
std::to_string(transaction->m_httpCodeReturned) + "'" \
" is not interesting to audit logs, relevant code(s): `" +
m_relevant + "'.");
return false;
}
if (parts == -1) {
parts = m_parts;
}
ms_dbg_a(transaction, 5, "Saving this request as part " \
"of the audit logs.");
if (m_writer == NULL) {
ms_dbg_a(transaction, 1, "Internal error, audit log writer is null");
} else {
std::string error;
bool a = m_writer->write(transaction, parts, &error);
if (a == false) {
ms_dbg_a(transaction, 1, "Cannot save the audit log: " + error);
return false;
}
}
return true;
}
bool AuditLog::close() {
return true;
}
bool AuditLog::merge(AuditLog *from, std::string *error) {
AL_MERGE_STRING_CONF(from->m_path1, m_path1);
AL_MERGE_STRING_CONF(from->m_path2, m_path2);
AL_MERGE_STRING_CONF(from->m_storage_dir, m_storage_dir);
AL_MERGE_STRING_CONF(from->m_relevant, m_relevant);
if (from->m_filePermission != -1) {
m_filePermission = from->m_filePermission;
}
if (from->m_directoryPermission != -1) {
m_directoryPermission = from->m_directoryPermission;
}
if (from->m_type != NotSetAuditLogType) {
m_type = from->m_type;
}
if (from->m_status != NotSetLogStatus) {
m_status = from->m_status;
}
if (from->m_parts != -1) {
m_parts = from->m_parts;
}
if (from->m_format != NotSetAuditLogFormat) {
m_format = from->m_format;
}
return init(error);
}
} // namespace audit_log
} // namespace modsecurity
<|endoftext|>
|
<commit_before>#include "pch.h"
#include "axl_io_PCap.h"
#include "axl_err_Error.h"
namespace axl {
namespace io {
//.............................................................................
bool
CPCap::Open (
const char* pDevice,
size_t SnapshotSize,
bool IsPromiscious,
uint_t ReadTimeout
)
{
Close ();
char ErrorBuffer [PCAP_ERRBUF_SIZE];
m_h = pcap_open_live (
pDevice,
SnapshotSize,
IsPromiscious,
ReadTimeout,
ErrorBuffer
);
if (!m_h)
{
err::SetStringError (ErrorBuffer);
return false;
}
return true;
}
bool
CPCap::SetFilter (const char* pFilter)
{
bpf_program Program;
int Result = pcap_compile (m_h, &Program, (char*) pFilter, true, 0);
if (Result == -1)
{
char ErrorBuffer [PCAP_ERRBUF_SIZE];
pcap_perror (m_h, ErrorBuffer);
err::SetStringError (ErrorBuffer);
return false;
}
Result = pcap_setfilter (m_h, &Program);
pcap_freecode (&Program);
return Result == 0;
}
bool
CPCap::SetBlockingMode (bool IsBlocking)
{
char ErrorBuffer [PCAP_ERRBUF_SIZE];
int Result = pcap_setnonblock (m_h, !IsBlocking, ErrorBuffer);
if (Result == -1)
{
err::SetStringError (ErrorBuffer);
return false;
}
return true;
}
size_t
CPCap::Read (
void* p,
size_t Size
)
{
pcap_pkthdr* pHdr;
const uchar_t* pData;
int Result = pcap_next_ex (m_h, &pHdr, &pData);
if (Result == -1)
{
char ErrorBuffer [PCAP_ERRBUF_SIZE];
pcap_perror (m_h, ErrorBuffer);
err::SetStringError (ErrorBuffer);
return -1;
}
if (Result != 1) // special values
return Result;
size_t CopySize = AXL_MIN (pHdr->caplen, Size);
memcpy (p, pData, CopySize);
return CopySize;
}
size_t
CPCap::Write (
const void* p,
size_t Size
)
{
#if (_AXL_ENV == AXL_ENV_WIN)
int Result = pcap_sendpacket (m_h, (const u_char*) p, (int) Size);
#else
int Result = pcap_inject (m_h, p, (int) Size);
#endif
if (Result == -1)
{
char ErrorBuffer [PCAP_ERRBUF_SIZE];
pcap_perror (m_h, ErrorBuffer);
err::SetStringError (ErrorBuffer);
return -1;
}
return Size;
}
//.............................................................................
} // namespace io
} // namespace axl
<commit_msg>[axl.io] bugfix: pcap_perror -> pcap_geterr (i misunderstood the meaning of pcap_perror)<commit_after>#include "pch.h"
#include "axl_io_PCap.h"
#include "axl_err_Error.h"
namespace axl {
namespace io {
//.............................................................................
bool
CPCap::Open (
const char* pDevice,
size_t SnapshotSize,
bool IsPromiscious,
uint_t ReadTimeout
)
{
Close ();
char ErrorBuffer [PCAP_ERRBUF_SIZE];
m_h = pcap_open_live (
pDevice,
SnapshotSize,
IsPromiscious,
ReadTimeout,
ErrorBuffer
);
if (!m_h)
{
err::SetStringError (ErrorBuffer);
return false;
}
return true;
}
bool
CPCap::SetFilter (const char* pFilter)
{
bpf_program Program;
int Result = pcap_compile (m_h, &Program, (char*) pFilter, true, 0);
if (Result == -1)
{
err::SetStringError (pcap_geterr (m_h));
return false;
}
Result = pcap_setfilter (m_h, &Program);
pcap_freecode (&Program);
return Result == 0;
}
bool
CPCap::SetBlockingMode (bool IsBlocking)
{
char ErrorBuffer [PCAP_ERRBUF_SIZE];
int Result = pcap_setnonblock (m_h, !IsBlocking, ErrorBuffer);
if (Result == -1)
{
err::SetStringError (ErrorBuffer);
return false;
}
return true;
}
size_t
CPCap::Read (
void* p,
size_t Size
)
{
pcap_pkthdr* pHdr;
const uchar_t* pData;
int Result = pcap_next_ex (m_h, &pHdr, &pData);
if (Result == -1)
{
err::SetStringError (pcap_geterr (m_h));
return -1;
}
if (Result != 1) // special values
return Result;
size_t CopySize = AXL_MIN (pHdr->caplen, Size);
memcpy (p, pData, CopySize);
return CopySize;
}
size_t
CPCap::Write (
const void* p,
size_t Size
)
{
#if (_AXL_ENV == AXL_ENV_WIN)
int Result = pcap_sendpacket (m_h, (const u_char*) p, (int) Size);
#else
int Result = pcap_inject (m_h, p, (int) Size);
#endif
if (Result == -1)
{
err::SetStringError (pcap_geterr (m_h));
return -1;
}
return Size;
}
//.............................................................................
} // namespace io
} // namespace axl
<|endoftext|>
|
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
* Pernilla Sveningsson <estel@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "backend/SDLbackend.h"
#include "exception.h"
#ifdef WIN32
# include "win32.h"
#endif
static const int sdl_flags = SDL_OPENGL | SDL_DOUBLEBUF;
static PlatformBackend* factory(void){
return new SDLBackend;
}
void SDLBackend::register_factory(){
PlatformBackend::register_factory("sdl", ::factory);
}
SDLBackend::SDLBackend()
: PlatformBackend()
, _lock(false) {
}
SDLBackend::~SDLBackend(){
}
int SDLBackend::init(const Vector2ui &resolution, bool fullscreen){
set_resolution(resolution.width, resolution.height);
int flags = sdl_flags;
if ( fullscreen ){
flags |= SDL_FULLSCREEN;
}
_fullscreen = fullscreen;
SDL_Init(SDL_INIT_VIDEO);
SDL_SetVideoMode(resolution.width, resolution.height, 0, flags);
SDL_EnableUNICODE(1);
#ifdef WIN32
SetConsoleOutputCP(65001);
#endif
return 0;
}
void SDLBackend::cleanup(){
SDL_Quit();
}
void SDLBackend::poll(bool& running){
SDL_Event event;
while(SDL_PollEvent(&event) ){
switch(event.type){
case SDL_KEYDOWN:
if ( event.key.keysym.sym == SDLK_ESCAPE ){
running = false;
}
if ( (event.key.keysym.sym == SDLK_RETURN) && (event.key.keysym.mod & KMOD_ALT)){
_fullscreen = !_fullscreen;
int flags = sdl_flags;
if ( _fullscreen ){
flags |= SDL_FULLSCREEN;
}
SDL_SetVideoMode(resolution().width, resolution().height, 0, flags);
}
break;
case SDL_VIDEORESIZE:
printf("video resize\n");
set_resolution(event.resize.w, event.resize.h);
break;
case SDL_QUIT:
running = false;
break;
}
}
}
void SDLBackend::swap_buffers() const {
SDL_GL_SwapBuffers();
}
void SDLBackend::lock_mouse(bool state){
_lock = state;
if ( _lock ){
SDL_WarpMouse(center().x, center().y);
}
}
<commit_msg>dies on errors<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
* Pernilla Sveningsson <estel@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "backend/SDLbackend.h"
#include "exception.h"
#ifdef WIN32
# include "win32.h"
#endif
static const int sdl_flags = SDL_OPENGL | SDL_DOUBLEBUF;
static PlatformBackend* factory(void){
return new SDLBackend;
}
void SDLBackend::register_factory(){
PlatformBackend::register_factory("sdl", ::factory);
}
SDLBackend::SDLBackend()
: PlatformBackend()
, _lock(false) {
}
SDLBackend::~SDLBackend(){
}
int SDLBackend::init(const Vector2ui &resolution, bool fullscreen){
set_resolution(resolution.width, resolution.height);
int flags = sdl_flags;
if ( fullscreen ){
flags |= SDL_FULLSCREEN;
}
_fullscreen = fullscreen;
if ( SDL_Init(SDL_INIT_VIDEO) < 0 ){
throw exception("Unable to init SDL: %s", SDL_GetError());
}
if ( SDL_SetVideoMode(resolution.width, resolution.height, 0, flags) == NULL ){
throw exception("Unable to init SDL: %s", SDL_GetError());
}
SDL_EnableUNICODE(1);
#ifdef WIN32
SetConsoleOutputCP(65001);
#endif
return 0;
}
void SDLBackend::cleanup(){
SDL_Quit();
}
void SDLBackend::poll(bool& running){
SDL_Event event;
while(SDL_PollEvent(&event) ){
switch(event.type){
case SDL_KEYDOWN:
if ( event.key.keysym.sym == SDLK_ESCAPE ){
running = false;
}
if ( (event.key.keysym.sym == SDLK_RETURN) && (event.key.keysym.mod & KMOD_ALT)){
_fullscreen = !_fullscreen;
int flags = sdl_flags;
if ( _fullscreen ){
flags |= SDL_FULLSCREEN;
}
SDL_SetVideoMode(resolution().width, resolution().height, 0, flags);
}
break;
case SDL_VIDEORESIZE:
printf("video resize\n");
set_resolution(event.resize.w, event.resize.h);
break;
case SDL_QUIT:
running = false;
break;
}
}
}
void SDLBackend::swap_buffers() const {
SDL_GL_SwapBuffers();
}
void SDLBackend::lock_mouse(bool state){
_lock = state;
if ( _lock ){
SDL_WarpMouse(center().x, center().y);
}
}
<|endoftext|>
|
<commit_before>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"
Timer pilotTimer;
bool _headingHoldEnabled = false;
int _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right; // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;
void Pilot::device_setup(){
pilotTimer.reset();
Serial.println(F("log:pilot setup complete;"));
}
void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
if( command.cmp("holdHeading_toggle")){
if (_headingHoldEnabled) {
_headingHoldEnabled = false;
raw_Left = 0;
raw_Right = 0;
hdg_Error_Integral = 0; // Reset error integrator
tgt_Hdg = -500; // -500 = system not in hdg hold
int argsToSend[] = {1,00}; //include number of parms as last parm
command.pushCommand("yaw",argsToSend);
Serial.println(F("log:heading_hold_disabled;"));
} else {
_headingHoldEnabled = true;
if(command.args[0]==0){
_headingHoldTarget = navdata::HDGD;
} else {
_headingHoldTarget = command.args[1];
}
tgt_Hdg = _headingHoldTarget;
Serial.print(F("log:heading_hold_enabled on="));
Serial.print(tgt_Hdg);
Serial.println(';');
}
Serial.print(F("targetHeading:"));
if (_headingHoldEnabled) {
Serial.print(tgt_Hdg);
} else {
Serial.print(DISABLED);
}
Serial.println(';');
}
if( command.cmp("holdDepth_toggle")){
if (_depthHoldEnabled) {
_depthHoldEnabled = false;
raw_lift = 0;
target_depth = 0;
int argsToSend[] = {1,0}; //include number of parms as last parm
command.pushCommand("lift",argsToSend);
Serial.println(F("log:depth_hold_disabled;"));
} else {
_depthHoldEnabled = true;
if(command.args[0]==0){
_depthHoldTarget = navdata::DEAP*100; //casting to cm
} else {
_depthHoldTarget = command.args[1];
}
target_depth = _depthHoldTarget;
Serial.print(F("log:depth_hold_enabled on="));
Serial.print(target_depth);
Serial.println(';');
}
Serial.print(F("targetDepth:"));
if (_depthHoldEnabled) {
Serial.print(target_depth);
} else {
Serial.pitnt(DISABLED);
}
Serial.println(';');
}
if (pilotTimer.elapsed (50)) {
// Autopilot Test #3 6 Jan 2014
// Hold vehicle at arbitrary heading
// Integer math; proportional control plus basic integrator
// No hysteresis around 180 degree error
// Check whether hold mode is on
if (_depthHoldEnabled)
{
depth = navdata::DEAP*100;
depth_Error = target_depth-depth; //positive error = positive lift = go deaper.
raw_lift = depth_Error * loop_Gain;
lift = constrain(raw_lift, -50, 50);
Serial.println(F("log:dhold pushing command;"));
Serial.print(F("dp_er:"));
Serial.print(depth_Error);
Serial.println(';');
int argsToSend[] = {1,lift}; //include number of parms as last parm
command.pushCommand("lift",argsToSend);
}
if (_headingHoldEnabled)
{
// Code for hold mode here
hdg = navdata::HDGD;
// Calculate heading error
hdg_Error = hdg - tgt_Hdg;
if (hdg_Error > 180)
{
hdg_Error = hdg_Error - 360;
}
if (hdg_Error < -179)
{
hdg_Error = hdg_Error + 360;
}
// Run error accumulator (integrator)
hdg_Error_Integral = hdg_Error_Integral + hdg_Error;
// Calculator motor outputs
raw_yaw = -1 * hdg_Error * loop_Gain;
// raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
// raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);
// Constrain and output to motors
yaw = constrain(raw_yaw, -50, 50);
Serial.println(F("log:hold pushing command;"));
Serial.print(F("p_er:"));
Serial.print(hdg_Error);
Serial.println(';');
int argsToSend[] = {1,yaw}; //include number of parms as last parm
command.pushCommand("yaw",argsToSend);
}
}
}
#endif
<commit_msg>Fix spelling in Arduino 2<commit_after>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"
Timer pilotTimer;
bool _headingHoldEnabled = false;
int _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right; // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;
void Pilot::device_setup(){
pilotTimer.reset();
Serial.println(F("log:pilot setup complete;"));
}
void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
if( command.cmp("holdHeading_toggle")){
if (_headingHoldEnabled) {
_headingHoldEnabled = false;
raw_Left = 0;
raw_Right = 0;
hdg_Error_Integral = 0; // Reset error integrator
tgt_Hdg = -500; // -500 = system not in hdg hold
int argsToSend[] = {1,00}; //include number of parms as last parm
command.pushCommand("yaw",argsToSend);
Serial.println(F("log:heading_hold_disabled;"));
} else {
_headingHoldEnabled = true;
if(command.args[0]==0){
_headingHoldTarget = navdata::HDGD;
} else {
_headingHoldTarget = command.args[1];
}
tgt_Hdg = _headingHoldTarget;
Serial.print(F("log:heading_hold_enabled on="));
Serial.print(tgt_Hdg);
Serial.println(';');
}
Serial.print(F("targetHeading:"));
if (_headingHoldEnabled) {
Serial.print(tgt_Hdg);
} else {
Serial.print(DISABLED);
}
Serial.println(';');
}
if( command.cmp("holdDepth_toggle")){
if (_depthHoldEnabled) {
_depthHoldEnabled = false;
raw_lift = 0;
target_depth = 0;
int argsToSend[] = {1,0}; //include number of parms as last parm
command.pushCommand("lift",argsToSend);
Serial.println(F("log:depth_hold_disabled;"));
} else {
_depthHoldEnabled = true;
if(command.args[0]==0){
_depthHoldTarget = navdata::DEAP*100; //casting to cm
} else {
_depthHoldTarget = command.args[1];
}
target_depth = _depthHoldTarget;
Serial.print(F("log:depth_hold_enabled on="));
Serial.print(target_depth);
Serial.println(';');
}
Serial.print(F("targetDepth:"));
if (_depthHoldEnabled) {
Serial.print(target_depth);
} else {
Serial.print(DISABLED);
}
Serial.println(';');
}
if (pilotTimer.elapsed (50)) {
// Autopilot Test #3 6 Jan 2014
// Hold vehicle at arbitrary heading
// Integer math; proportional control plus basic integrator
// No hysteresis around 180 degree error
// Check whether hold mode is on
if (_depthHoldEnabled)
{
depth = navdata::DEAP*100;
depth_Error = target_depth-depth; //positive error = positive lift = go deaper.
raw_lift = depth_Error * loop_Gain;
lift = constrain(raw_lift, -50, 50);
Serial.println(F("log:dhold pushing command;"));
Serial.print(F("dp_er:"));
Serial.print(depth_Error);
Serial.println(';');
int argsToSend[] = {1,lift}; //include number of parms as last parm
command.pushCommand("lift",argsToSend);
}
if (_headingHoldEnabled)
{
// Code for hold mode here
hdg = navdata::HDGD;
// Calculate heading error
hdg_Error = hdg - tgt_Hdg;
if (hdg_Error > 180)
{
hdg_Error = hdg_Error - 360;
}
if (hdg_Error < -179)
{
hdg_Error = hdg_Error + 360;
}
// Run error accumulator (integrator)
hdg_Error_Integral = hdg_Error_Integral + hdg_Error;
// Calculator motor outputs
raw_yaw = -1 * hdg_Error * loop_Gain;
// raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
// raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);
// Constrain and output to motors
yaw = constrain(raw_yaw, -50, 50);
Serial.println(F("log:hold pushing command;"));
Serial.print(F("p_er:"));
Serial.print(hdg_Error);
Serial.println(';');
int argsToSend[] = {1,yaw}; //include number of parms as last parm
command.pushCommand("yaw",argsToSend);
}
}
}
#endif
<|endoftext|>
|
<commit_before>
#include "common.h"
// interface header
#include "LuaServer.h"
// system headers
#include <stdio.h>
#include <ctype.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
// common headers
#include "bzfsAPI.h"
#include "TextUtils.h"
#include "bzfio.h"
// bzfs headers
#include "../bzfs.h"
#include "../CmdLineOptions.h"
//local headers
#include "LuaHeader.h"
#include "BZDB.h"
#include "CallIns.h"
#include "CallOuts.h"
#include "Constants.h"
#include "FetchURL.h"
#include "MapObject.h"
#include "RawLink.h"
#include "SlashCmd.h"
#include "Double.h"
//============================================================================//
//============================================================================//
static lua_State* L = NULL;
static bool CreateLuaState(const string& script);
static string EnvExpand(const string& path);
//============================================================================//
//============================================================================//
static string directory = "./";
static bool SetupLuaDirectory(const string& fileName);
extern const string& GetLuaDirectory() { return directory; } // extern
//============================================================================//
//============================================================================//
static bool fileExists(const string& file)
{
FILE* f = fopen(file.c_str(), "r");
if (f == NULL) {
return false;
}
fclose(f);
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::init(const string& cmdLine)
{
if (cmdLine.empty()) {
return false;
}
bool dieHard = false;
logDebugMessage(1, "loading LuaServer\n");
if (L != NULL) {
logDebugMessage(1, "LuaServer is already loaded\n");
return false;
}
// dieHard check
string scriptFile = cmdLine.c_str();
if (scriptFile.size() > 8) {
if (scriptFile.substr(0, 8) == "dieHard,") {
dieHard = true;
scriptFile = scriptFile.substr(8);
}
}
// leading tilde => $HOME substitution
if (!scriptFile.empty() && (scriptFile[0] == '~')) {
scriptFile = "$HOME" + scriptFile.substr(1);
}
scriptFile = EnvExpand(scriptFile);
if (!fileExists(scriptFile)) {
scriptFile = string(bz_pluginBinPath()) + "/" + scriptFile;
}
if (!fileExists(scriptFile)) {
logDebugMessage(1, "LuaServer: could not find the script file\n");
if (dieHard) {
exit(2);
}
return false;
}
SetupLuaDirectory(scriptFile);
if (!CreateLuaState(scriptFile)) {
if (dieHard) {
exit(3);
}
return false;
}
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::kill()
{
if (L == NULL) {
return false;
}
CallIns::Shutdown(); // send the call-in
RawLink::CleanUp(L);
FetchURL::CleanUp(L);
SlashCmd::CleanUp(L);
MapObject::CleanUp(L);
CallIns::CleanUp(L);
lua_close(L);
L = NULL;
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::isActive()
{
return (L != NULL);
}
//============================================================================//
//============================================================================//
lua_State* LuaServer::GetL()
{
return L;
}
//============================================================================//
//============================================================================//
void LuaServer::recvCommand(const string& cmdLine, int playerIndex)
{
vector<string> args = TextUtils::tokenize(cmdLine, " \t", 3);
GameKeeper::Player* p = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (p == NULL) {
return;
}
if (args[0] != "/luaserver") {
return; // something is amiss, bail
}
if (args.size() < 2) {
sendMessage(ServerPlayer, playerIndex,
"/luaserver < status | disable | reload >");
return;
}
if (args[1] == "status") {
if (isActive()) {
sendMessage(ServerPlayer, playerIndex, "LuaServer is enabled");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer is disabled");
}
return;
}
if (args[1] == "disable") {
if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
sendMessage(ServerPlayer, playerIndex,
"You do not have permission to control LuaServer");
return;
}
if (isActive()) {
kill();
sendMessage(ServerPlayer, playerIndex, "LuaServer has been disabled");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer is not loaded");
}
return;
}
if (args[1] == "reload") {
if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
sendMessage(ServerPlayer, playerIndex,
"You do not have permission to control LuaServer");
return;
}
kill();
bool success = false;
if (args.size() > 2) {
success = init(args[2]);
} else {
success = init(clOptions->luaServer);
}
if (success) {
sendMessage(ServerPlayer, playerIndex, "LuaServer reload succeeded");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer reload failed");
}
return;
}
if (L != NULL) {
CallIns::RecvCommand(cmdLine);
}
return;
}
//============================================================================//
//============================================================================//
static bool SetupLuaDirectory(const string& fileName)
{
const string::size_type pos = fileName.find_last_of("/\\");
if (pos == string::npos) {
directory = "./";
} else {
directory = fileName.substr(0, pos + 1);
}
return true;
}
//============================================================================//
//============================================================================//
static bool CreateLuaState(const string& script)
{
if (L != NULL) {
return false;
}
L = luaL_newstate();
luaL_openlibs(L);
CallIns::PushEntries(L);
lua_pushvalue(L, LUA_GLOBALSINDEX);
LuaDouble::PushEntries(L);
lua_pop(L, 1);
lua_pushliteral(L, "bz");
lua_newtable(L); {
CallOuts::PushEntries(L);
MapObject::PushEntries(L);
SlashCmd::PushEntries(L);
FetchURL::PushEntries(L);
RawLink::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
lua_pushliteral(L, "BZ");
lua_newtable(L); {
Constants::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
lua_pushliteral(L, "bzdb");
lua_newtable(L); {
LuaBZDB::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
if (luaL_dofile(L, script.c_str()) != 0) {
logDebugMessage(1, "lua init error: %s\n", lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
return true;
}
//============================================================================//
//============================================================================//
static string EnvExpand(const string& path)
{
string::size_type pos = path.find('$');
if (pos == string::npos) {
return path;
}
if (path[pos + 1] == '$') { // allow $$ escapes
return path.substr(0, pos + 1) + EnvExpand(path.substr(pos + 2));
}
const char* b = path.c_str(); // beginning of string
const char* s = b + pos + 1; // start of the key name
const char* e = s; // end of the key Name
while ((*e != 0) && (isalnum(*e) || (*e == '_'))) {
e++;
}
const string head = path.substr(0, pos);
const string key = path.substr(pos + 1, e - s);
const string tail = path.substr(e - b);
const char* env = getenv(key.c_str());
const string value = (env == NULL) ? "" : env;
return head + value + EnvExpand(tail);
}
//============================================================================//
//============================================================================//
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>* setup the LuaServer lua 'package.path' and 'package.cpath' variables<commit_after>
#include "common.h"
// interface header
#include "LuaServer.h"
// system headers
#include <stdio.h>
#include <ctype.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
// common headers
#include "bzfsAPI.h"
#include "TextUtils.h"
#include "bzfio.h"
// bzfs headers
#include "../bzfs.h"
#include "../CmdLineOptions.h"
//local headers
#include "LuaHeader.h"
#include "BZDB.h"
#include "CallIns.h"
#include "CallOuts.h"
#include "Constants.h"
#include "FetchURL.h"
#include "MapObject.h"
#include "RawLink.h"
#include "SlashCmd.h"
#include "Double.h"
//============================================================================//
//============================================================================//
static lua_State* L = NULL;
static bool CreateLuaState(const string& script);
static string EnvExpand(const string& path);
//============================================================================//
//============================================================================//
static string directory = "./";
static bool SetupLuaDirectory(const string& fileName);
extern const string& GetLuaDirectory() { return directory; } // extern
//============================================================================//
//============================================================================//
static bool fileExists(const string& file)
{
FILE* f = fopen(file.c_str(), "r");
if (f == NULL) {
return false;
}
fclose(f);
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::init(const string& cmdLine)
{
if (cmdLine.empty()) {
return false;
}
bool dieHard = false;
logDebugMessage(1, "loading LuaServer\n");
if (L != NULL) {
logDebugMessage(1, "LuaServer is already loaded\n");
return false;
}
// dieHard check
string scriptFile = cmdLine.c_str();
if (scriptFile.size() > 8) {
if (scriptFile.substr(0, 8) == "dieHard,") {
dieHard = true;
scriptFile = scriptFile.substr(8);
}
}
// leading tilde => $HOME substitution
if (!scriptFile.empty() && (scriptFile[0] == '~')) {
scriptFile = "$HOME" + scriptFile.substr(1);
}
scriptFile = EnvExpand(scriptFile);
if (!fileExists(scriptFile)) {
scriptFile = string(bz_pluginBinPath()) + "/" + scriptFile;
}
if (!fileExists(scriptFile)) {
logDebugMessage(1, "LuaServer: could not find the script file\n");
if (dieHard) {
exit(2);
}
return false;
}
SetupLuaDirectory(scriptFile);
if (!CreateLuaState(scriptFile)) {
if (dieHard) {
exit(3);
}
return false;
}
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::kill()
{
if (L == NULL) {
return false;
}
CallIns::Shutdown(); // send the call-in
RawLink::CleanUp(L);
FetchURL::CleanUp(L);
SlashCmd::CleanUp(L);
MapObject::CleanUp(L);
CallIns::CleanUp(L);
lua_close(L);
L = NULL;
return true;
}
//============================================================================//
//============================================================================//
bool LuaServer::isActive()
{
return (L != NULL);
}
//============================================================================//
//============================================================================//
lua_State* LuaServer::GetL()
{
return L;
}
//============================================================================//
//============================================================================//
void LuaServer::recvCommand(const string& cmdLine, int playerIndex)
{
vector<string> args = TextUtils::tokenize(cmdLine, " \t", 3);
GameKeeper::Player* p = GameKeeper::Player::getPlayerByIndex(playerIndex);
if (p == NULL) {
return;
}
if (args[0] != "/luaserver") {
return; // something is amiss, bail
}
if (args.size() < 2) {
sendMessage(ServerPlayer, playerIndex,
"/luaserver < status | disable | reload >");
return;
}
if (args[1] == "status") {
if (isActive()) {
sendMessage(ServerPlayer, playerIndex, "LuaServer is enabled");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer is disabled");
}
return;
}
if (args[1] == "disable") {
if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
sendMessage(ServerPlayer, playerIndex,
"You do not have permission to control LuaServer");
return;
}
if (isActive()) {
kill();
sendMessage(ServerPlayer, playerIndex, "LuaServer has been disabled");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer is not loaded");
}
return;
}
if (args[1] == "reload") {
if (!p->accessInfo.hasPerm(PlayerAccessInfo::luaServer)) {
sendMessage(ServerPlayer, playerIndex,
"You do not have permission to control LuaServer");
return;
}
kill();
bool success = false;
if (args.size() > 2) {
success = init(args[2]);
} else {
success = init(clOptions->luaServer);
}
if (success) {
sendMessage(ServerPlayer, playerIndex, "LuaServer reload succeeded");
} else {
sendMessage(ServerPlayer, playerIndex, "LuaServer reload failed");
}
return;
}
if (L != NULL) {
CallIns::RecvCommand(cmdLine);
}
return;
}
//============================================================================//
//============================================================================//
static bool SetupLuaDirectory(const string& fileName)
{
const string::size_type pos = fileName.find_last_of("/\\");
if (pos == string::npos) {
directory = "./";
} else {
directory = fileName.substr(0, pos + 1);
}
return true;
}
//============================================================================//
//============================================================================//
static bool CreateLuaState(const string& script)
{
if (L != NULL) {
return false;
}
L = luaL_newstate();
luaL_openlibs(L);
const string path = directory + "?.lua";
const string cpath = directory + "?.so;" + directory + "?.dll";
lua_getglobal(L, "package");
lua_pushstdstring(L, path); lua_setfield(L, -2, "path");
lua_pushstdstring(L, cpath); lua_setfield(L, -2, "cpath");
lua_pop(L, 1);
CallIns::PushEntries(L);
lua_pushvalue(L, LUA_GLOBALSINDEX);
LuaDouble::PushEntries(L);
lua_pop(L, 1);
lua_pushliteral(L, "bz");
lua_newtable(L); {
CallOuts::PushEntries(L);
MapObject::PushEntries(L);
SlashCmd::PushEntries(L);
FetchURL::PushEntries(L);
RawLink::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
lua_pushliteral(L, "BZ");
lua_newtable(L); {
Constants::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
lua_pushliteral(L, "bzdb");
lua_newtable(L); {
LuaBZDB::PushEntries(L);
}
lua_rawset(L, LUA_GLOBALSINDEX);
if (luaL_dofile(L, script.c_str()) != 0) {
logDebugMessage(1, "lua init error: %s\n", lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
return true;
}
//============================================================================//
//============================================================================//
static string EnvExpand(const string& path)
{
string::size_type pos = path.find('$');
if (pos == string::npos) {
return path;
}
if (path[pos + 1] == '$') { // allow $$ escapes
return path.substr(0, pos + 1) + EnvExpand(path.substr(pos + 2));
}
const char* b = path.c_str(); // beginning of string
const char* s = b + pos + 1; // start of the key name
const char* e = s; // end of the key Name
while ((*e != 0) && (isalnum(*e) || (*e == '_'))) {
e++;
}
const string head = path.substr(0, pos);
const string key = path.substr(pos + 1, e - s);
const string tail = path.substr(e - b);
const char* env = getenv(key.c_str());
const string value = (env == NULL) ? "" : env;
return head + value + EnvExpand(tail);
}
//============================================================================//
//============================================================================//
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/**
* @file save_restore_model_test.cpp
* @author Neil Slagle
*
* Here we have tests for the SaveRestoreModel class.
*/
#include <mlpack/core/util/save_restore_utility.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#define ARGSTR(a) a,#a
using namespace mlpack;
using namespace mlpack::util;
BOOST_AUTO_TEST_SUITE(SaveRestoreUtilityTest);
/*
* Exhibit proper save restore utility usage of child class proper usage.
*/
class SaveRestoreTest
{
private:
size_t anInt;
SaveRestoreUtility saveRestore;
public:
SaveRestoreTest()
{
saveRestore = SaveRestoreUtility();
anInt = 0;
}
bool SaveModel(std::string filename)
{
saveRestore.SaveParameter(anInt, "anInt");
return saveRestore.WriteFile(filename);
}
bool LoadModel(std::string filename)
{
bool success = saveRestore.ReadFile(filename);
if (success)
anInt = saveRestore.LoadParameter(anInt, "anInt");
return success;
}
size_t AnInt() { return anInt; }
void AnInt(size_t s) { this->anInt = s; }
};
/**
* Perform a save and restore on basic types.
*/
BOOST_AUTO_TEST_CASE(SaveBasicTypes)
{
bool b = false;
char c = 67;
unsigned u = 34;
size_t s = 12;
short sh = 100;
int i = -23;
float f = -2.34f;
double d = 3.14159;
std::string cc = "Hello world!";
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(b));
sRM->SaveParameter(ARGSTR(c));
sRM->SaveParameter(ARGSTR(u));
sRM->SaveParameter(ARGSTR(s));
sRM->SaveParameter(ARGSTR(sh));
sRM->SaveParameter(ARGSTR(i));
sRM->SaveParameter(ARGSTR(f));
sRM->SaveParameter(ARGSTR(d));
sRM->SaveParameter(ARGSTR(cc));
sRM->WriteFile("test_basic_types.xml");
sRM->ReadFile("test_basic_types.xml");
bool b2 = sRM->LoadParameter(ARGSTR(b));
char c2 = sRM->LoadParameter(ARGSTR(c));
unsigned u2 = sRM->LoadParameter(ARGSTR(u));
size_t s2 = sRM->LoadParameter(ARGSTR(s));
short sh2 = sRM->LoadParameter(ARGSTR(sh));
int i2 = sRM->LoadParameter(ARGSTR(i));
float f2 = sRM->LoadParameter(ARGSTR(f));
double d2 = sRM->LoadParameter(ARGSTR(d));
std::string cc2 = sRM->LoadParameter(ARGSTR(cc));
BOOST_REQUIRE(b == b2);
BOOST_REQUIRE(c == c2);
BOOST_REQUIRE(u == u2);
BOOST_REQUIRE(s == s2);
BOOST_REQUIRE(sh == sh2);
BOOST_REQUIRE(i == i2);
BOOST_REQUIRE(cc == cc2);
BOOST_REQUIRE_CLOSE(f, f2, 1e-5);
BOOST_REQUIRE_CLOSE(d, d2, 1e-5);
delete sRM;
}
BOOST_AUTO_TEST_CASE(SaveRestoreStdVector)
{
size_t numbers[] = {0,3,6,2,6};
std::vector<size_t> vec (numbers,
numbers + sizeof (numbers) / sizeof (size_t));
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(vec));
sRM->WriteFile("test_std_vector_type.xml");
sRM->ReadFile("test_std_vector_type.xml");
std::vector<size_t> loadee = sRM->LoadParameter(ARGSTR(vec));
for (size_t index = 0; index < loadee.size(); ++index)
BOOST_REQUIRE_EQUAL(numbers[index], loadee[index]);
}
/**
* Test the arma::mat functionality.
*/
BOOST_AUTO_TEST_CASE(SaveArmaMat)
{
arma::mat matrix;
matrix << 1.2 << 2.3 << -0.1 << arma::endr
<< 3.5 << 2.4 << -1.2 << arma::endr
<< -0.1 << 3.4 << -7.8 << arma::endr;
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(matrix));
sRM->WriteFile("test_arma_mat_type.xml");
sRM->ReadFile("test_arma_mat_type.xml");
arma::mat matrix2 = sRM->LoadParameter(ARGSTR(matrix));
for (size_t row = 0; row < matrix.n_rows; ++row)
for (size_t column = 0; column < matrix.n_cols; ++column)
BOOST_REQUIRE_CLOSE(matrix(row,column), matrix2(row,column), 1e-5);
delete sRM;
}
/**
* Test SaveRestoreModel proper usage in child classes and loading from
* separately defined objects
*/
BOOST_AUTO_TEST_CASE(SaveRestoreModelChildClassUsage)
{
SaveRestoreTest* saver = new SaveRestoreTest();
SaveRestoreTest* loader = new SaveRestoreTest();
size_t s = 1200;
const char* filename = "anInt.xml";
saver->AnInt(s);
saver->SaveModel(filename);
delete saver;
loader->LoadModel(filename);
BOOST_REQUIRE(loader->AnInt() == s);
delete loader;
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Fix syntax.<commit_after>/**
* @file save_restore_model_test.cpp
* @author Neil Slagle
*
* Here we have tests for the SaveRestoreModel class.
*/
#include <mlpack/core/util/save_restore_utility.hpp>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
#define ARGSTR(a) a,#a
using namespace mlpack;
using namespace mlpack::util;
BOOST_AUTO_TEST_SUITE(SaveRestoreUtilityTest);
/*
* Exhibit proper save restore utility usage of child class proper usage.
*/
class SaveRestoreTest
{
private:
size_t anInt;
SaveRestoreUtility saveRestore;
public:
SaveRestoreTest()
{
saveRestore = SaveRestoreUtility();
anInt = 0;
}
bool SaveModel(std::string filename)
{
saveRestore.SaveParameter(anInt, "anInt");
return saveRestore.WriteFile(filename);
}
bool LoadModel(std::string filename)
{
bool success = saveRestore.ReadFile(filename);
if (success)
anInt = saveRestore.LoadParameter(anInt, "anInt");
return success;
}
size_t AnInt() { return anInt; }
void AnInt(size_t s) { this->anInt = s; }
};
/**
* Perform a save and restore on basic types.
*/
BOOST_AUTO_TEST_CASE(SaveBasicTypes)
{
bool b = false;
char c = 67;
unsigned u = 34;
size_t s = 12;
short sh = 100;
int i = -23;
float f = -2.34f;
double d = 3.14159;
std::string cc = "Hello world!";
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(b));
sRM->SaveParameter(ARGSTR(c));
sRM->SaveParameter(ARGSTR(u));
sRM->SaveParameter(ARGSTR(s));
sRM->SaveParameter(ARGSTR(sh));
sRM->SaveParameter(ARGSTR(i));
sRM->SaveParameter(ARGSTR(f));
sRM->SaveParameter(ARGSTR(d));
sRM->SaveParameter(ARGSTR(cc));
sRM->WriteFile("test_basic_types.xml");
sRM->ReadFile("test_basic_types.xml");
bool b2 = sRM->LoadParameter(ARGSTR(b));
char c2 = sRM->LoadParameter(ARGSTR(c));
unsigned u2 = sRM->LoadParameter(ARGSTR(u));
size_t s2 = sRM->LoadParameter(ARGSTR(s));
short sh2 = sRM->LoadParameter(ARGSTR(sh));
int i2 = sRM->LoadParameter(ARGSTR(i));
float f2 = sRM->LoadParameter(ARGSTR(f));
double d2 = sRM->LoadParameter(ARGSTR(d));
std::string cc2 = sRM->LoadParameter(ARGSTR(cc));
BOOST_REQUIRE(b == b2);
BOOST_REQUIRE(c == c2);
BOOST_REQUIRE(u == u2);
BOOST_REQUIRE(s == s2);
BOOST_REQUIRE(sh == sh2);
BOOST_REQUIRE(i == i2);
BOOST_REQUIRE(cc == cc2);
BOOST_REQUIRE_CLOSE(f, f2, 1e-5);
BOOST_REQUIRE_CLOSE(d, d2, 1e-5);
delete sRM;
}
BOOST_AUTO_TEST_CASE(SaveRestoreStdVector)
{
size_t numbers[] = {0,3,6,2,6};
std::vector<size_t> vec (numbers,
numbers + sizeof (numbers) / sizeof (size_t));
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(vec));
sRM->WriteFile("test_std_vector_type.xml");
sRM->ReadFile("test_std_vector_type.xml");
std::vector<size_t> loadee = sRM->LoadParameter(ARGSTR(vec));
for (size_t index = 0; index < loadee.size(); ++index)
BOOST_REQUIRE_EQUAL(numbers[index], loadee[index]);
}
/**
* Test the arma::mat functionality.
*/
BOOST_AUTO_TEST_CASE(SaveArmaMat)
{
arma::mat matrix;
matrix << 1.2 << 2.3 << -0.1 << arma::endr
<< 3.5 << 2.4 << -1.2 << arma::endr
<< -0.1 << 3.4 << -7.8 << arma::endr;
SaveRestoreUtility* sRM = new SaveRestoreUtility();
sRM->SaveParameter(ARGSTR(matrix));
sRM->WriteFile("test_arma_mat_type.xml");
sRM->ReadFile("test_arma_mat_type.xml");
arma::mat matrix2 = sRM->LoadParameter(ARGSTR(matrix));
for (size_t row = 0; row < matrix.n_rows; ++row)
for (size_t column = 0; column < matrix.n_cols; ++column)
BOOST_REQUIRE_CLOSE(matrix(row, column), matrix2(row, column), 1e-5);
delete sRM;
}
/**
* Test SaveRestoreModel proper usage in child classes and loading from
* separately defined objects
*/
BOOST_AUTO_TEST_CASE(SaveRestoreModelChildClassUsage)
{
SaveRestoreTest* saver = new SaveRestoreTest();
SaveRestoreTest* loader = new SaveRestoreTest();
size_t s = 1200;
const char* filename = "anInt.xml";
saver->AnInt(s);
saver->SaveModel(filename);
delete saver;
loader->LoadModel(filename);
BOOST_REQUIRE(loader->AnInt() == s);
delete loader;
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|>
|
<commit_before>/* $Id$ */
// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.
TVirtualProof* connectProof(const char* proofServer)
{
TVirtualProof* proof = TProof::Open(proofServer);
if (!proof)
{
printf("ERROR: PROOF connection not established.\n");
return 0;
}
// enable the new packetizer
//proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));
proof->ClearInput();
return proof;
}
Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
// if not proof load libraries
if (!gProof)
{
TObjArray* librariesList = libraries.Tokenize(";");
for (Int_t i=0; i<librariesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
if (!str)
continue;
printf("Loading %s...", str->String().Data());
Int_t result = CheckLoadLibrary(str->String());
if (result < 0)
{
printf("failed\n");
//return kFALSE;
}
else
printf("succeeded\n");
}
}
else
{
if (useAliRoot > 0)
ProofEnableAliRoot(useAliRoot);
TObjArray* packagesList = packages.Tokenize(";");
for (Int_t i=0; i<packagesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
if (!str)
continue;
/*if (!EnablePackageLocal(str->String()))
{
printf("Loading of package %s locally failed\n", str->String().Data());
return kFALSE;
}*/
if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
{
printf("Uploading of package %s failed\n", str->String().Data());
return kFALSE;
}
if (gProof->EnablePackage(str->String()))
{
printf("Loading of package %s failed\n", str->String().Data());
return kFALSE;
}
}
}
return kTRUE;
}
Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "")
{
if (!gProof)
chain->GetUserInfo()->AddAll(inputList);
else
{
for (Int_t i=0; i<inputList->GetEntries(); ++i)
gProof->AddInput(inputList->At(i));
}
TStopwatch timer;
timer.Start();
Long64_t result = -1;
if (gProof)
result = chain->MakeTDSet()->Process(selectorName, option);
else
result = chain->Process(selectorName, option);
if (result < 0)
printf("ERROR: Executing process failed with %d.\n", result);
timer.Stop();
timer.Print();
return result;
}
void ProofEnableAliRoot(Int_t aliroot)
{
// enables a locally deployed AliRoot in a PROOF cluster
/* executes the following commands on each node:
gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
gSystem->Load("libMinuit");
gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
*/
const char* location = 0;
const char* target = "tgt_linux";
switch (aliroot)
{
case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break;
case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break;
case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break;
default: return;
}
gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
gProof->AddIncludePath(Form("%s/include", location));
gProof->AddDynamicPath(Form("%s/lib/%s", location, target));
// load all libraries
gProof->Exec("gSystem->Load(\"libMinuit\")");
gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}
Bool_t EnablePackageLocal(const char* package)
{
printf("Enabling package %s locally...\n", package);
TString currentDir(gSystem->pwd());
if (!gSystem->cd(package))
return kFALSE;
gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
gSystem->cd(currentDir);
return kTRUE;
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
// deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
// when localAliRoot is false ESD.par is also deployed
TProof::Reset(proofServer);
TVirtualProof* proof = TProof::Open(proofServer);
proof->ClearPackages();
if (localAliRoot)
ProofEnableAliRoot();
else
{
proof->UploadPackage("$ALICE_ROOT/ESD.par");
proof->EnablePackage("ESD");
}
proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
proof->EnablePackage("PWG0base");
proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
proof->EnablePackage("PWG0dep");
}
<commit_msg>adding entries parameter to execute function<commit_after>/* $Id$ */
// Helper macros can be found in this file
// A set of them can be used to connect to proof and execute selectors.
TVirtualProof* connectProof(const char* proofServer)
{
TVirtualProof* proof = TProof::Open(proofServer);
if (!proof)
{
printf("ERROR: PROOF connection not established.\n");
return 0;
}
// enable the new packetizer
//proof->AddInput(new TNamed("PROOF_Packetizer", "TPacketizerProgressive"));
proof->ClearInput();
return proof;
}
Bool_t prepareQuery(TString libraries, TString packages, Int_t useAliRoot)
{
// if not proof load libraries
if (!gProof)
{
TObjArray* librariesList = libraries.Tokenize(";");
for (Int_t i=0; i<librariesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (librariesList->At(i));
if (!str)
continue;
printf("Loading %s...", str->String().Data());
Int_t result = CheckLoadLibrary(str->String());
if (result < 0)
{
printf("failed\n");
//return kFALSE;
}
else
printf("succeeded\n");
}
}
else
{
if (useAliRoot > 0)
ProofEnableAliRoot(useAliRoot);
TObjArray* packagesList = packages.Tokenize(";");
for (Int_t i=0; i<packagesList->GetEntries(); ++i)
{
TObjString* str = dynamic_cast<TObjString*> (packagesList->At(i));
if (!str)
continue;
/*if (!EnablePackageLocal(str->String()))
{
printf("Loading of package %s locally failed\n", str->String().Data());
return kFALSE;
}*/
if (gProof->UploadPackage(Form("%s.par", str->String().Data())))
{
printf("Uploading of package %s failed\n", str->String().Data());
return kFALSE;
}
if (gProof->EnablePackage(str->String()))
{
printf("Loading of package %s failed\n", str->String().Data());
return kFALSE;
}
}
}
return kTRUE;
}
Int_t executeQuery(TChain* chain, TList* inputList, TString selectorName, const char* option = "", Long64_t entries = TChain::kBigNumber)
{
if (!gProof)
chain->GetUserInfo()->AddAll(inputList);
else
{
for (Int_t i=0; i<inputList->GetEntries(); ++i)
gProof->AddInput(inputList->At(i));
}
TStopwatch timer;
timer.Start();
Long64_t result = -1;
if (gProof)
result = chain->MakeTDSet()->Process(selectorName, option, entries);
else
result = chain->Process(selectorName, option, entries);
if (result < 0)
printf("ERROR: Executing process failed with %d.\n", result);
timer.Stop();
timer.Print();
return result;
}
void ProofEnableAliRoot(Int_t aliroot)
{
// enables a locally deployed AliRoot in a PROOF cluster
/* executes the following commands on each node:
gSystem->Setenv("ALICE_ROOT", "/home/alicecaf/ALICE/aliroot-head")
gSystem->AddIncludePath("/home/alicecaf/ALICE/aliroot-head/include");
gSystem->SetDynamicPath(Form("%s:%s", gSystem->GetDynamicPath(), "/home/alicecaf/ALICE/aliroot-head/lib/tgt_linux"))
gSystem->Load("libMinuit");
gROOT->Macro("$ALICE_ROOT/macros/loadlibs.C");
*/
const char* location = 0;
const char* target = "tgt_linux";
switch (aliroot)
{
case 1: location = "/home/alicecaf/ALICE/aliroot-v4-04-Release"; break;
case 2: location = "/home/alicecaf/ALICE/aliroot-head"; break;
case 11: location = "/data1/qfiete/aliroot-head"; target = "tgt_linuxx8664gcc"; break;
default: return;
}
gProof->Exec(Form("gSystem->Setenv(\"ALICE_ROOT\", \"%s\")", location), kTRUE);
gProof->AddIncludePath(Form("%s/include", location));
gProof->AddDynamicPath(Form("%s/lib/%s", location, target));
// load all libraries
gProof->Exec("gSystem->Load(\"libMinuit\")");
gProof->Exec("gROOT->Macro(\"$ALICE_ROOT/macros/loadlibs.C\")");
}
Bool_t EnablePackageLocal(const char* package)
{
printf("Enabling package %s locally...\n", package);
TString currentDir(gSystem->pwd());
if (!gSystem->cd(package))
return kFALSE;
gROOT->ProcessLine(".x PROOF-INF/SETUP.C");
gSystem->cd(currentDir);
return kTRUE;
}
Int_t CheckLoadLibrary(const char* library)
{
// checks if a library is already loaded, if not loads the library
if (strlen(gSystem->GetLibraries(Form("%s.so", library), "", kFALSE)) > 0)
return 1;
return gSystem->Load(library);
}
void redeployPackages(const char* proofServer, Bool_t localAliRoot = kTRUE)
{
// deploys PWG0base and PWG0dep (the latter only when localAliRoot is true) that are expected in $ALICE_ROOT
// when localAliRoot is false ESD.par is also deployed
TProof::Reset(proofServer);
TVirtualProof* proof = TProof::Open(proofServer);
proof->ClearPackages();
if (localAliRoot)
ProofEnableAliRoot();
else
{
proof->UploadPackage("$ALICE_ROOT/ESD.par");
proof->EnablePackage("ESD");
}
proof->UploadPackage("$ALICE_ROOT/PWG0base.par");
proof->EnablePackage("PWG0base");
proof->UploadPackage("$ALICE_ROOT/PWG0dep.par");
proof->EnablePackage("PWG0dep");
}
<|endoftext|>
|
<commit_before>// PolyHook.cpp : Defines the entry point for the console application.
//
#include <tchar.h>
#include "PolyHook.h"
#define PLH_SHOW_DEBUG_MESSAGES 1 //To print messages even in release
typedef int(__stdcall* tMessageBoxA)(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
tMessageBoxA oMessageBoxA;
typedef void(__stdcall* tVirtNoParams)(DWORD_PTR pThis);
tVirtNoParams oVirtNoParams;
typedef void(__stdcall* tGetCurrentThreadId)();
tGetCurrentThreadId oGetCurrentThreadID;
typedef int(__stdcall* tVEH)(int intparam);
tVEH oVEHTest;
PLH::VEHHook* VEHHook;
DWORD __stdcall hkGetCurrentThreadId()
{
printf("Called hkGetCurrentThreadID\n");
return 1337;
}
int __stdcall hkMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
printf("In Hook\n");
return oMessageBoxA(hWnd, lpText, lpCaption, uType);
}
void __stdcall hkVirtNoParams(DWORD_PTR pThis)
{
printf("hk Virt Called\n");
return oVirtNoParams(pThis);
}
__declspec(noinline) int __stdcall VEHTest(int param)
{
printf("VEHFunc %d\n",param);
return 3;
}
__declspec(noinline) int __stdcall hkVEHTest(int param)
{
printf("hkVEH %d\n",param);
auto ProtectionObject = VEHHook->GetProtectionObject();
return oVEHTest(param);
}
class VirtualTest
{
public:
virtual void NoParamVirt()
{
volatile int x = 0;
printf("Called Virt\n");
}
virtual void BS()
{
volatile int y = 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
///X86/x64 Detour Example
//PLH::Detour* Hook = new PLH::Detour();
//Hook->SetupHook((BYTE*)&MessageBoxA,(BYTE*) &hkMessageBoxA); //can cast to byte* to
//Hook->Hook();
//oMessageBoxA = Hook->GetOriginal<tMessageBoxA>();
//MessageBoxA(NULL, "Message", "Sample", MB_OK);
//Hook->UnHook();
//MessageBoxA(NULL, "Message", "Sample", MB_OK);
///x86/x64 IAT Hook Example
//PLH::IATHook* Hook = new PLH::IATHook();
//Hook->SetupHook("kernel32.dll", "GetCurrentThreadId", (BYTE*)&hkGetCurrentThreadId);
//Hook->Hook();
//oGetCurrentThreadID = Hook->GetOriginal<tGetCurrentThreadId>();
//printf("Thread ID:%d \n", GetCurrentThreadId());
//Hook->UnHook();
//printf("Real Thread ID:%d\n", GetCurrentThreadId());
///x86/x64 VFuncDetour Example
//VirtualTest* ClassToHook = new VirtualTest();
//PLH::VFuncDetour* VirtHook = new PLH::VFuncDetour();
//VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
//VirtHook->Hook();
//oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
//ClassToHook->NoParamVirt();
//VirtHook->UnHook();
//ClassToHook->NoParamVirt();
///x86/x64 VFuncSwap Example
/*PLH::VFuncSwap* VirtHook = new PLH::VFuncSwap();
VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
VirtHook->Hook();
oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
ClassToHook->NoParamVirt();
VirtHook->UnHook();
ClassToHook->NoParamVirt();*/
///x86/x64 VTableSwap Example
//PLH::VTableSwap* VTableHook = new PLH::VTableSwap();
//VTableHook->SetupHook((BYTE*)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
//VTableHook->Hook();
//oVirtNoParams = VTableHook->GetOriginal<tVirtNoParams>();
//ClassToHook->NoParamVirt();
//VTableHook->UnHook();
//ClassToHook->NoParamVirt();
/*!!!!IMPORTANT!!!!!: Since this demo is small it's possible for internal methods to be on the same memory page
as the VEHTest function. If that happens the GUARD_PAGE type method will fail with an unexpected exception.
If this method is used in larger applications this risk is increadibly small, to the point where it should not
be worried about.
*/
///x86/x64 VEH Example (GUARD_PAGE and INT3_BP)
<<<<<<< HEAD
VEHHook = new PLH::VEHHook();
VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::HARDWARE_BP);
=======
/*VEHHook = new PLH::VEHHook();
VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::INT3_BP);
>>>>>>> refs/remotes/origin/master
VEHHook->Hook();
oVEHTest = VEHHook->GetOriginal<tVEH>();
VEHTest(3);
VEHHook->UnHook();
VEHTest(1);
<<<<<<< HEAD
printf("%s %s\n", (VEHHook->GetLastError().GetSeverity() == PLH::RuntimeError::Severity::NoError) ? "No Error" : "Error",
VEHHook->GetLastError().GetString().c_str());
=======
VEHHook->PrintError(VEHHook->GetLastError());*/
>>>>>>> refs/remotes/origin/master
Sleep(100000);
return 0;
}
<commit_msg>Cleaned Main<commit_after>// PolyHook.cpp : Defines the entry point for the console application.
//
#include <tchar.h>
#include "PolyHook.h"
#define PLH_SHOW_DEBUG_MESSAGES 1 //To print messages even in release
typedef int(__stdcall* tMessageBoxA)(HWND hWnd,LPCTSTR lpText,LPCTSTR lpCaption,UINT uType);
tMessageBoxA oMessageBoxA;
typedef void(__stdcall* tVirtNoParams)(DWORD_PTR pThis);
tVirtNoParams oVirtNoParams;
typedef void(__stdcall* tGetCurrentThreadId)();
tGetCurrentThreadId oGetCurrentThreadID;
typedef int(__stdcall* tVEH)(int intparam);
tVEH oVEHTest;
PLH::VEHHook* VEHHook;
DWORD __stdcall hkGetCurrentThreadId()
{
printf("Called hkGetCurrentThreadID\n");
return 1337;
}
int __stdcall hkMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
printf("In Hook\n");
return oMessageBoxA(hWnd, lpText, lpCaption, uType);
}
void __stdcall hkVirtNoParams(DWORD_PTR pThis)
{
printf("hk Virt Called\n");
return oVirtNoParams(pThis);
}
__declspec(noinline) int __stdcall VEHTest(int param)
{
printf("VEHFunc %d\n",param);
return 3;
}
__declspec(noinline) int __stdcall hkVEHTest(int param)
{
printf("hkVEH %d\n",param);
auto ProtectionObject = VEHHook->GetProtectionObject();
return oVEHTest(param);
}
class VirtualTest
{
public:
virtual void NoParamVirt()
{
volatile int x = 0;
printf("Called Virt\n");
}
virtual void BS()
{
volatile int y = 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
///X86/x64 Detour Example
//PLH::Detour* Hook = new PLH::Detour();
//Hook->SetupHook((BYTE*)&MessageBoxA,(BYTE*) &hkMessageBoxA); //can cast to byte* to
//Hook->Hook();
//oMessageBoxA = Hook->GetOriginal<tMessageBoxA>();
//MessageBoxA(NULL, "Message", "Sample", MB_OK);
//Hook->UnHook();
//MessageBoxA(NULL, "Message", "Sample", MB_OK);
///x86/x64 IAT Hook Example
//PLH::IATHook* Hook = new PLH::IATHook();
//Hook->SetupHook("kernel32.dll", "GetCurrentThreadId", (BYTE*)&hkGetCurrentThreadId);
//Hook->Hook();
//oGetCurrentThreadID = Hook->GetOriginal<tGetCurrentThreadId>();
//printf("Thread ID:%d \n", GetCurrentThreadId());
//Hook->UnHook();
//printf("Real Thread ID:%d\n", GetCurrentThreadId());
///x86/x64 VFuncDetour Example
//VirtualTest* ClassToHook = new VirtualTest();
//PLH::VFuncDetour* VirtHook = new PLH::VFuncDetour();
//VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
//VirtHook->Hook();
//oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
//ClassToHook->NoParamVirt();
//VirtHook->UnHook();
//ClassToHook->NoParamVirt();
///x86/x64 VFuncSwap Example
/*PLH::VFuncSwap* VirtHook = new PLH::VFuncSwap();
VirtHook->SetupHook(*(BYTE***)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
VirtHook->Hook();
oVirtNoParams = VirtHook->GetOriginal<tVirtNoParams>();
ClassToHook->NoParamVirt();
VirtHook->UnHook();
ClassToHook->NoParamVirt();*/
///x86/x64 VTableSwap Example
//PLH::VTableSwap* VTableHook = new PLH::VTableSwap();
//VTableHook->SetupHook((BYTE*)ClassToHook, 0, (BYTE*)&hkVirtNoParams);
//VTableHook->Hook();
//oVirtNoParams = VTableHook->GetOriginal<tVirtNoParams>();
//ClassToHook->NoParamVirt();
//VTableHook->UnHook();
//ClassToHook->NoParamVirt();
/*!!!!IMPORTANT!!!!!: Since this demo is small it's possible for internal methods to be on the same memory page
as the VEHTest function. If that happens the GUARD_PAGE type method will fail with an unexpected exception.
If this method is used in larger applications this risk is increadibly small, to the point where it should not
be worried about.
*/
///x86/x64 VEH Example (GUARD_PAGE and INT3_BP)
/*VEHHook = new PLH::VEHHook();
VEHHook->SetupHook((BYTE*)&VEHTest, (BYTE*)&hkVEHTest, PLH::VEHHook::VEHMethod::INT3_BP);
VEHHook->Hook();
oVEHTest = VEHHook->GetOriginal<tVEH>();
VEHTest(3);
VEHHook->UnHook();
VEHTest(1);
VEHHook->PrintError(VEHHook->GetLastError());*/
Sleep(100000);
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* MarkerDetector.cpp
* Example_MarkerBasedAR
******************************************************************************
* by Khvedchenia Ievgen, 5th Dec 2012
* http://computer-vision-talks.com
******************************************************************************
* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
////////////////////////////////////////////////////////////////////
// Standard includes:
#include <iostream>
#include <sstream>
////////////////////////////////////////////////////////////////////
// File includes:
#include "MarkerDetector.hpp"
#include "Marker.hpp"
#include "TinyLA.hpp"
MarkerDetector::MarkerDetector(CameraCalibration calibration)
: m_minContourLengthAllowed(100)
, markerSize(100,100)
{
cv::Mat(3,3, CV_32F, const_cast<float*>(&calibration.getIntrinsic().data[0])).copyTo(camMatrix);
cv::Mat(4,1, CV_32F, const_cast<float*>(&calibration.getDistorsion().data[0])).copyTo(distCoeff);
bool centerOrigin = true;
if (centerOrigin)
{
m_markerCorners3d.push_back(cv::Point3f(-0.5f,-0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(+0.5f,-0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(+0.5f,+0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(-0.5f,+0.5f,0));
}
else
{
m_markerCorners3d.push_back(cv::Point3f(0,0,0));
m_markerCorners3d.push_back(cv::Point3f(1,0,0));
m_markerCorners3d.push_back(cv::Point3f(1,1,0));
m_markerCorners3d.push_back(cv::Point3f(0,1,0));
}
m_markerCorners2d.push_back(cv::Point2f(0,0));
m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,0));
m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,markerSize.height-1));
m_markerCorners2d.push_back(cv::Point2f(0,markerSize.height-1));
}
void MarkerDetector::processFrame(const cv::Mat& frame)
{
m_markers.clear();
findMarkers(frame, m_markers);
}
void MarkerDetector::getTransformations(std::vector<Transformation>& t) const
{
t.clear();
for (size_t i=0; i<m_markers.size(); i++)
{
t.push_back(m_markers[i].transformation);
}
}
bool MarkerDetector::findMarkers(const cv::Mat& frame, std::vector<Marker>& detectedMarkers)
{
// Convert the image to grayscale
prepareImage(frame, m_grayscaleImage);
// Make it binary
performThreshold(m_grayscaleImage, m_thresholdImg);
// Detect contours
findContours(m_thresholdImg, m_contours, m_grayscaleImage.cols / 5);
// Find closed contours that can be approximated with 4 points
findCandidates(m_contours, detectedMarkers);
// Find is them are markers
recognizeMarkers(m_grayscaleImage, detectedMarkers);
// Calculate their poses
estimatePosition(detectedMarkers);
//sort by id
std::sort(detectedMarkers.begin(), detectedMarkers.end());
return false;
}
void MarkerDetector::prepareImage(const cv::Mat& frame, cv::Mat& grayscale) const
{
// Convert to grayscale
if (frame.channels() == 4)
cv::cvtColor(frame, grayscale, CV_BGRA2GRAY);
else if (frame.channels() == 3)
cv::cvtColor(frame, grayscale, CV_BGR2GRAY);
else if (frame.channels() == 1)
frame.copyTo(grayscale);
}
void MarkerDetector::performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg) const
{
cv::threshold(grayscale, thresholdImg, 127, 255, cv::THRESH_BINARY_INV);
/*
cv::adaptiveThreshold(grayscale, // Input image
thresholdImg,// Result binary image
255, //
cv::ADAPTIVE_THRESH_GAUSSIAN_C, //
cv::THRESH_BINARY_INV, //
7, //
7 //
);
*/
#ifdef SHOW_DEBUG_IMAGES
cv::showAndSave("Threshold image", thresholdImg);
#endif
}
void MarkerDetector::findContours(cv::Mat& thresholdImg, ContoursVector& contours, int minContourPointsAllowed) const
{
ContoursVector allContours;
cv::findContours(thresholdImg, allContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
contours.clear();
for (size_t i=0; i<allContours.size(); i++)
{
int contourSize = allContours[i].size();
if (contourSize > minContourPointsAllowed)
{
contours.push_back(allContours[i]);
}
}
#ifdef SHOW_DEBUG_IMAGES
{
cv::Mat contoursImage(thresholdImg.size(), CV_8UC1);
contoursImage = cv::Scalar(0);
cv::drawContours(contoursImage, contours, -1, cv::Scalar(255), 2, CV_AA);
cv::showAndSave("Contours", contoursImage);
}
#endif
}
void MarkerDetector::findCandidates
(
const ContoursVector& contours,
std::vector<Marker>& detectedMarkers
)
{
std::vector<cv::Point> approxCurve;
std::vector<Marker> possibleMarkers;
// For each contour, analyze if it is a parallelepiped likely to be the marker
for (size_t i=0; i<contours.size(); i++)
{
// Approximate to a polygon
double eps = contours[i].size() * 0.05;
cv::approxPolyDP(contours[i], approxCurve, eps, true);
// We interested only in polygons that contains only four points
if (approxCurve.size() != 4)
continue;
// And they have to be convex
if (!cv::isContourConvex(approxCurve))
continue;
// Ensure that the distance between consecutive points is large enough
float minDist = std::numeric_limits<float>::max();
for (int i = 0; i < 4; i++)
{
cv::Point side = approxCurve[i] - approxCurve[(i+1)%4];
float squaredSideLength = side.dot(side);
minDist = std::min(minDist, squaredSideLength);
}
// Check that distance is not very small
if (minDist < m_minContourLengthAllowed)
continue;
// All tests are passed. Save marker candidate:
Marker m;
for (int i = 0; i<4; i++)
m.points.push_back( cv::Point2f(approxCurve[i].x,approxCurve[i].y) );
// Sort the points in anti-clockwise order
// Trace a line between the first and second point.
// If the third point is at the right side, then the points are anti-clockwise
cv::Point v1 = m.points[1] - m.points[0];
cv::Point v2 = m.points[2] - m.points[0];
double o = (v1.x * v2.y) - (v1.y * v2.x);
if (o < 0.0) //if the third point is in the left side, then sort in anti-clockwise order
std::swap(m.points[1], m.points[3]);
possibleMarkers.push_back(m);
}
// Remove these elements which corners are too close to each other.
// First detect candidates for removal:
std::vector< std::pair<int,int> > tooNearCandidates;
for (size_t i=0;i<possibleMarkers.size();i++)
{
const Marker& m1 = possibleMarkers[i];
//calculate the average distance of each corner to the nearest corner of the other marker candidate
for (size_t j=i+1;j<possibleMarkers.size();j++)
{
const Marker& m2 = possibleMarkers[j];
float distSquared = 0;
for (int c = 0; c < 4; c++)
{
cv::Point v = m1.points[c] - m2.points[c];
distSquared += v.dot(v);
}
distSquared /= 4;
if (distSquared < 100)
{
tooNearCandidates.push_back(std::pair<int,int>(i,j));
}
}
}
// Mark for removal the element of the pair with smaller perimeter
std::vector<bool> removalMask (possibleMarkers.size(), false);
for (size_t i=0; i<tooNearCandidates.size(); i++)
{
float p1 = perimeter(possibleMarkers[tooNearCandidates[i].first ].points);
float p2 = perimeter(possibleMarkers[tooNearCandidates[i].second].points);
size_t removalIndex;
if (p1 > p2)
removalIndex = tooNearCandidates[i].second;
else
removalIndex = tooNearCandidates[i].first;
removalMask[removalIndex] = true;
}
// Return candidates
detectedMarkers.clear();
for (size_t i=0;i<possibleMarkers.size();i++)
{
if (!removalMask[i])
detectedMarkers.push_back(possibleMarkers[i]);
}
}
void MarkerDetector::recognizeMarkers(const cv::Mat& grayscale, std::vector<Marker>& detectedMarkers)
{
std::vector<Marker> goodMarkers;
// Identify the markers
for (size_t i=0;i<detectedMarkers.size();i++)
{
Marker& marker = detectedMarkers[i];
// Find the perspective transformation that brings current marker to rectangular form
cv::Mat markerTransform = cv::getPerspectiveTransform(marker.points, m_markerCorners2d);
// Transform image to get a canonical marker image
cv::warpPerspective(grayscale, canonicalMarkerImage, markerTransform, markerSize);
#ifdef SHOW_DEBUG_IMAGES
{
cv::Mat markerImage = grayscale.clone();
marker.drawContour(markerImage);
cv::Mat markerSubImage = markerImage(cv::boundingRect(marker.points));
cv::showAndSave("Source marker" + ToString(i), markerSubImage);
cv::showAndSave("Marker " + ToString(i) + " after warp", canonicalMarkerImage);
}
#endif
int nRotations;
int id = Marker::getMarkerId(canonicalMarkerImage, nRotations);
if (id !=- 1)
{
marker.id = id;
//sort the points so that they are always in the same order no matter the camera orientation
std::rotate(marker.points.begin(), marker.points.begin() + 4 - nRotations, marker.points.end());
goodMarkers.push_back(marker);
}
}
// Refine marker corners using sub pixel accuracy
if (goodMarkers.size() > 0)
{
std::vector<cv::Point2f> preciseCorners(4 * goodMarkers.size());
for (size_t i=0; i<goodMarkers.size(); i++)
{
const Marker& marker = goodMarkers[i];
for (int c = 0; c <4; c++)
{
preciseCorners[i*4 + c] = marker.points[c];
}
}
cv::TermCriteria termCriteria = cv::TermCriteria(cv::TermCriteria::MAX_ITER | cv::TermCriteria::EPS, 30, 0.01);
cv::cornerSubPix(grayscale, preciseCorners, cvSize(5,5), cvSize(-1,-1), termCriteria);
// Copy refined corners position back to markers
for (size_t i=0; i<goodMarkers.size(); i++)
{
Marker& marker = goodMarkers[i];
for (int c=0;c<4;c++)
{
marker.points[c] = preciseCorners[i*4 + c];
}
}
}
#if SHOW_DEBUG_IMAGES
{
cv::Mat markerCornersMat(grayscale.size(), grayscale.type());
markerCornersMat = cv::Scalar(0);
for (size_t i=0; i<goodMarkers.size(); i++)
{
goodMarkers[i].drawContour(markerCornersMat, cv::Scalar(255));
}
cv::showAndSave("Markers refined edges", grayscale * 0.5 + markerCornersMat);
}
#endif
detectedMarkers = goodMarkers;
}
void MarkerDetector::estimatePosition(std::vector<Marker>& detectedMarkers)
{
for (size_t i=0; i<detectedMarkers.size(); i++)
{
Marker& m = detectedMarkers[i];
cv::Mat Rvec;
cv::Mat_<float> Tvec;
cv::Mat raux,taux;
cv::solvePnP(m_markerCorners3d, m.points, camMatrix, distCoeff,raux,taux);
raux.convertTo(Rvec,CV_32F);
taux.convertTo(Tvec ,CV_32F);
cv::Mat_<float> rotMat(3,3);
cv::Rodrigues(Rvec, rotMat);
// Copy to transformation matrix
for (int col=0; col<3; col++)
{
for (int row=0; row<3; row++)
{
m.transformation.r().mat[row][col] = rotMat(row,col); // Copy rotation component
}
m.transformation.t().data[col] = Tvec(col); // Copy translation component
}
// Since solvePnP finds camera location, w.r.t to marker pose, to get marker pose w.r.t to the camera we invert it.
m.transformation = m.transformation.getInverted();
}
}
<commit_msg>Fix compilation error under linux<commit_after>/*****************************************************************************
* MarkerDetector.cpp
* Example_MarkerBasedAR
******************************************************************************
* by Khvedchenia Ievgen, 5th Dec 2012
* http://computer-vision-talks.com
******************************************************************************
* Ch2 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
////////////////////////////////////////////////////////////////////
// Standard includes:
#include <iostream>
#include <sstream>
#include <limits>
////////////////////////////////////////////////////////////////////
// File includes:
#include "MarkerDetector.hpp"
#include "Marker.hpp"
#include "TinyLA.hpp"
MarkerDetector::MarkerDetector(CameraCalibration calibration)
: m_minContourLengthAllowed(100)
, markerSize(100,100)
{
cv::Mat(3,3, CV_32F, const_cast<float*>(&calibration.getIntrinsic().data[0])).copyTo(camMatrix);
cv::Mat(4,1, CV_32F, const_cast<float*>(&calibration.getDistorsion().data[0])).copyTo(distCoeff);
bool centerOrigin = true;
if (centerOrigin)
{
m_markerCorners3d.push_back(cv::Point3f(-0.5f,-0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(+0.5f,-0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(+0.5f,+0.5f,0));
m_markerCorners3d.push_back(cv::Point3f(-0.5f,+0.5f,0));
}
else
{
m_markerCorners3d.push_back(cv::Point3f(0,0,0));
m_markerCorners3d.push_back(cv::Point3f(1,0,0));
m_markerCorners3d.push_back(cv::Point3f(1,1,0));
m_markerCorners3d.push_back(cv::Point3f(0,1,0));
}
m_markerCorners2d.push_back(cv::Point2f(0,0));
m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,0));
m_markerCorners2d.push_back(cv::Point2f(markerSize.width-1,markerSize.height-1));
m_markerCorners2d.push_back(cv::Point2f(0,markerSize.height-1));
}
void MarkerDetector::processFrame(const cv::Mat& frame)
{
m_markers.clear();
findMarkers(frame, m_markers);
}
void MarkerDetector::getTransformations(std::vector<Transformation>& t) const
{
t.clear();
for (size_t i=0; i<m_markers.size(); i++)
{
t.push_back(m_markers[i].transformation);
}
}
bool MarkerDetector::findMarkers(const cv::Mat& frame, std::vector<Marker>& detectedMarkers)
{
// Convert the image to grayscale
prepareImage(frame, m_grayscaleImage);
// Make it binary
performThreshold(m_grayscaleImage, m_thresholdImg);
// Detect contours
findContours(m_thresholdImg, m_contours, m_grayscaleImage.cols / 5);
// Find closed contours that can be approximated with 4 points
findCandidates(m_contours, detectedMarkers);
// Find is them are markers
recognizeMarkers(m_grayscaleImage, detectedMarkers);
// Calculate their poses
estimatePosition(detectedMarkers);
//sort by id
std::sort(detectedMarkers.begin(), detectedMarkers.end());
return false;
}
void MarkerDetector::prepareImage(const cv::Mat& frame, cv::Mat& grayscale) const
{
// Convert to grayscale
if (frame.channels() == 4)
cv::cvtColor(frame, grayscale, cv::COLOR_BGRA2GRAY);
else if (frame.channels() == 3)
cv::cvtColor(frame, grayscale, cv::COLOR_BGR2GRAY);
else if (frame.channels() == 1)
frame.copyTo(grayscale);
}
void MarkerDetector::performThreshold(const cv::Mat& grayscale, cv::Mat& thresholdImg) const
{
cv::threshold(grayscale, thresholdImg, 127, 255, cv::THRESH_BINARY_INV);
/*
cv::adaptiveThreshold(grayscale, // Input image
thresholdImg,// Result binary image
255, //
cv::ADAPTIVE_THRESH_GAUSSIAN_C, //
cv::THRESH_BINARY_INV, //
7, //
7 //
);
*/
#ifdef SHOW_DEBUG_IMAGES
cv::showAndSave("Threshold image", thresholdImg);
#endif
}
void MarkerDetector::findContours(cv::Mat& thresholdImg, ContoursVector& contours, int minContourPointsAllowed) const
{
ContoursVector allContours;
cv::findContours(thresholdImg, allContours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
contours.clear();
for (size_t i=0; i<allContours.size(); i++)
{
int contourSize = allContours[i].size();
if (contourSize > minContourPointsAllowed)
{
contours.push_back(allContours[i]);
}
}
#ifdef SHOW_DEBUG_IMAGES
{
cv::Mat contoursImage(thresholdImg.size(), CV_8UC1);
contoursImage = cv::Scalar(0);
cv::drawContours(contoursImage, contours, -1, cv::Scalar(255), 2, CV_AA);
cv::showAndSave("Contours", contoursImage);
}
#endif
}
void MarkerDetector::findCandidates
(
const ContoursVector& contours,
std::vector<Marker>& detectedMarkers
)
{
std::vector<cv::Point> approxCurve;
std::vector<Marker> possibleMarkers;
// For each contour, analyze if it is a parallelepiped likely to be the marker
for (size_t i=0; i<contours.size(); i++)
{
// Approximate to a polygon
double eps = contours[i].size() * 0.05;
cv::approxPolyDP(contours[i], approxCurve, eps, true);
// We interested only in polygons that contains only four points
if (approxCurve.size() != 4)
continue;
// And they have to be convex
if (!cv::isContourConvex(approxCurve))
continue;
// Ensure that the distance between consecutive points is large enough
float minDist = std::numeric_limits<float>::max();
for (int i = 0; i < 4; i++)
{
cv::Point side = approxCurve[i] - approxCurve[(i+1)%4];
float squaredSideLength = side.dot(side);
minDist = std::min(minDist, squaredSideLength);
}
// Check that distance is not very small
if (minDist < m_minContourLengthAllowed)
continue;
// All tests are passed. Save marker candidate:
Marker m;
for (int i = 0; i<4; i++)
m.points.push_back( cv::Point2f(approxCurve[i].x,approxCurve[i].y) );
// Sort the points in anti-clockwise order
// Trace a line between the first and second point.
// If the third point is at the right side, then the points are anti-clockwise
cv::Point v1 = m.points[1] - m.points[0];
cv::Point v2 = m.points[2] - m.points[0];
double o = (v1.x * v2.y) - (v1.y * v2.x);
if (o < 0.0) //if the third point is in the left side, then sort in anti-clockwise order
std::swap(m.points[1], m.points[3]);
possibleMarkers.push_back(m);
}
// Remove these elements which corners are too close to each other.
// First detect candidates for removal:
std::vector< std::pair<int,int> > tooNearCandidates;
for (size_t i=0;i<possibleMarkers.size();i++)
{
const Marker& m1 = possibleMarkers[i];
//calculate the average distance of each corner to the nearest corner of the other marker candidate
for (size_t j=i+1;j<possibleMarkers.size();j++)
{
const Marker& m2 = possibleMarkers[j];
float distSquared = 0;
for (int c = 0; c < 4; c++)
{
cv::Point v = m1.points[c] - m2.points[c];
distSquared += v.dot(v);
}
distSquared /= 4;
if (distSquared < 100)
{
tooNearCandidates.push_back(std::pair<int,int>(i,j));
}
}
}
// Mark for removal the element of the pair with smaller perimeter
std::vector<bool> removalMask (possibleMarkers.size(), false);
for (size_t i=0; i<tooNearCandidates.size(); i++)
{
float p1 = perimeter(possibleMarkers[tooNearCandidates[i].first ].points);
float p2 = perimeter(possibleMarkers[tooNearCandidates[i].second].points);
size_t removalIndex;
if (p1 > p2)
removalIndex = tooNearCandidates[i].second;
else
removalIndex = tooNearCandidates[i].first;
removalMask[removalIndex] = true;
}
// Return candidates
detectedMarkers.clear();
for (size_t i=0;i<possibleMarkers.size();i++)
{
if (!removalMask[i])
detectedMarkers.push_back(possibleMarkers[i]);
}
}
void MarkerDetector::recognizeMarkers(const cv::Mat& grayscale, std::vector<Marker>& detectedMarkers)
{
std::vector<Marker> goodMarkers;
// Identify the markers
for (size_t i=0;i<detectedMarkers.size();i++)
{
Marker& marker = detectedMarkers[i];
// Find the perspective transformation that brings current marker to rectangular form
cv::Mat markerTransform = cv::getPerspectiveTransform(marker.points, m_markerCorners2d);
// Transform image to get a canonical marker image
cv::warpPerspective(grayscale, canonicalMarkerImage, markerTransform, markerSize);
#ifdef SHOW_DEBUG_IMAGES
{
cv::Mat markerImage = grayscale.clone();
marker.drawContour(markerImage);
cv::Mat markerSubImage = markerImage(cv::boundingRect(marker.points));
cv::showAndSave("Source marker" + ToString(i), markerSubImage);
cv::showAndSave("Marker " + ToString(i) + " after warp", canonicalMarkerImage);
}
#endif
int nRotations;
int id = Marker::getMarkerId(canonicalMarkerImage, nRotations);
if (id !=- 1)
{
marker.id = id;
//sort the points so that they are always in the same order no matter the camera orientation
std::rotate(marker.points.begin(), marker.points.begin() + 4 - nRotations, marker.points.end());
goodMarkers.push_back(marker);
}
}
// Refine marker corners using sub pixel accuracy
if (goodMarkers.size() > 0)
{
std::vector<cv::Point2f> preciseCorners(4 * goodMarkers.size());
for (size_t i=0; i<goodMarkers.size(); i++)
{
const Marker& marker = goodMarkers[i];
for (int c = 0; c <4; c++)
{
preciseCorners[i*4 + c] = marker.points[c];
}
}
cv::TermCriteria termCriteria = cv::TermCriteria(cv::TermCriteria::MAX_ITER | cv::TermCriteria::EPS, 30, 0.01);
cv::cornerSubPix(grayscale, preciseCorners, cvSize(5,5), cvSize(-1,-1), termCriteria);
// Copy refined corners position back to markers
for (size_t i=0; i<goodMarkers.size(); i++)
{
Marker& marker = goodMarkers[i];
for (int c=0;c<4;c++)
{
marker.points[c] = preciseCorners[i*4 + c];
}
}
}
#if SHOW_DEBUG_IMAGES
{
cv::Mat markerCornersMat(grayscale.size(), grayscale.type());
markerCornersMat = cv::Scalar(0);
for (size_t i=0; i<goodMarkers.size(); i++)
{
goodMarkers[i].drawContour(markerCornersMat, cv::Scalar(255));
}
cv::showAndSave("Markers refined edges", grayscale * 0.5 + markerCornersMat);
}
#endif
detectedMarkers = goodMarkers;
}
void MarkerDetector::estimatePosition(std::vector<Marker>& detectedMarkers)
{
for (size_t i=0; i<detectedMarkers.size(); i++)
{
Marker& m = detectedMarkers[i];
cv::Mat Rvec;
cv::Mat_<float> Tvec;
cv::Mat raux,taux;
cv::solvePnP(m_markerCorners3d, m.points, camMatrix, distCoeff,raux,taux);
raux.convertTo(Rvec,CV_32F);
taux.convertTo(Tvec ,CV_32F);
cv::Mat_<float> rotMat(3,3);
cv::Rodrigues(Rvec, rotMat);
// Copy to transformation matrix
for (int col=0; col<3; col++)
{
for (int row=0; row<3; row++)
{
m.transformation.r().mat[row][col] = rotMat(row,col); // Copy rotation component
}
m.transformation.t().data[col] = Tvec(col); // Copy translation component
}
// Since solvePnP finds camera location, w.r.t to marker pose, to get marker pose w.r.t to the camera we invert it.
m.transformation = m.transformation.getInverted();
}
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
//
// OpenFlight loader for OpenSceneGraph
//
// Copyright (C) 2005-2007 Brede Johansen
//
#include <osg/Notify>
#include <osg/TexEnv>
#include <osg/Texture2D>
#include <osg/StateSet>
#include <osg/GL>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include "AttrData.h"
#include "DataInputStream.h"
using namespace osg;
using namespace osgDB;
using namespace flt;
class ReaderWriterATTR : public osgDB::ReaderWriter
{
public:
virtual const char* className() const { return "ATTR Image Attribute Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"attr");
}
virtual ReadResult readObject(const std::string& fileName, const ReaderWriter::Options*) const;
};
ReaderWriter::ReadResult ReaderWriterATTR::readObject(const std::string& file, const ReaderWriter::Options* options) const
{
using std::ios;
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
std::ifstream fin;
fin.imbue(std::locale::classic());
fin.open(fileName.c_str(), std::ios::in | std::ios::binary);
if ( fin.fail())
return ReadResult::ERROR_IN_READING_FILE;
flt::DataInputStream in(fin.rdbuf());
AttrData* attr = new AttrData;
try
{
attr->texels_u = in.readInt32();
attr->textel_v = in.readInt32();
attr->direction_u = in.readInt32();
attr->direction_v = in.readInt32();
attr->x_up = in.readInt32();
attr->y_up = in.readInt32();
attr->fileFormat = in.readInt32();
attr->minFilterMode = in.readInt32();
attr->magFilterMode = in.readInt32();
attr->wrapMode = in.readInt32(AttrData::WRAP_REPEAT);
attr->wrapMode_u = in.readInt32();
if (attr->wrapMode_u == AttrData::WRAP_NONE)
attr->wrapMode_u = attr->wrapMode;
attr->wrapMode_v = in.readInt32();
if (attr->wrapMode_v == AttrData::WRAP_NONE)
attr->wrapMode_v = attr->wrapMode;
attr->modifyFlag = in.readInt32();
attr->pivot_x = in.readInt32();
attr->pivot_y = in.readInt32();
// v11 ends here
// if (in.eof() || (_flt_version <= 11)) return true;
#if 1
attr->texEnvMode = in.readInt32(AttrData::TEXENV_MODULATE);
attr->intensityAsAlpha = in.readInt32();
in.forward(4*8);
attr->size_u = in.readFloat64();
attr->size_v = in.readFloat64();
attr->originCode = in.readInt32();
attr->kernelVersion = in.readInt32();
attr->intFormat = in.readInt32();
attr->extFormat = in.readInt32();
attr->useMips = in.readInt32();
for (int n=0; n<8; n++)
attr->of_mips[n] = in.readFloat32();
attr->useLodScale = in.readInt32();
attr->lod0 = in.readFloat32();
attr->scale0 = in.readFloat32();
attr->lod1 = in.readFloat32();
attr->scale1 = in.readFloat32();
attr->lod2 = in.readFloat32();
attr->scale2 = in.readFloat32();
attr->lod3 = in.readFloat32();
attr->scale3 = in.readFloat32();
attr->lod4 = in.readFloat32();
attr->scale4 = in.readFloat32();
attr->lod5 = in.readFloat32();
attr->scale5 = in.readFloat32();
attr->lod6 = in.readFloat32();
attr->scale6 = in.readFloat32();
attr->lod7 = in.readFloat32();
attr->scale7 = in.readFloat32();
attr->clamp = in.readFloat32();
attr->magFilterAlpha = in.readInt32();
attr->magFilterColor = in.readInt32();
in.forward(4);
in.forward(4*8);
attr->lambertMeridian = in.readFloat64();
attr->lambertUpperLat = in.readFloat64();
attr->lambertlowerLat = in.readFloat64();
in.forward(8);
in.forward(4*5);
attr->useDetail = in.readInt32( );
attr->txDetail_j = in.readInt32();
attr->txDetail_k = in.readInt32();
attr->txDetail_m = in.readInt32();
attr->txDetail_n = in.readInt32();
attr->txDetail_s = in.readInt32( );
attr->useTile = in.readInt32();
attr->txTile_ll_u= in.readFloat32();
attr->txTile_ll_v = in.readFloat32();
attr->txTile_ur_u = in.readFloat32();
attr->txTile_ur_v = in.readFloat32();
attr->projection = in.readInt32();
attr->earthModel = in.readInt32();
in.forward(4);
attr->utmZone = in.readInt32();
attr->imageOrigin = in.readInt32();
attr->geoUnits = in.readInt32();
in.forward(4);
in.forward(4);
attr->hemisphere = in.readInt32();
in.forward(4);
in.forward(4);
in.forward(149*4);
attr->comments = in.readString(512);
// v12 ends here
// if (in.eof() || (_flt_version <= 12)) return true;
in.forward(13*4);
attr->attrVersion = in.readInt32();
attr->controlPoints = in.readInt32();
in.forward(4);
#endif
}
catch(...)
{
if (!fin.eof())
{
throw;
}
}
fin.close();
return attr;
}
// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(attr, ReaderWriterATTR)
<commit_msg>From Andreas Ekstrand and Lars Nilsson, fix for reading Texture Attribute file <commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
//
// OpenFlight loader for OpenSceneGraph
//
// Copyright (C) 2005-2007 Brede Johansen
//
#include <osg/Notify>
#include <osg/TexEnv>
#include <osg/Texture2D>
#include <osg/StateSet>
#include <osg/GL>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/Registry>
#include "AttrData.h"
#include "DataInputStream.h"
using namespace osg;
using namespace osgDB;
using namespace flt;
class ReaderWriterATTR : public osgDB::ReaderWriter
{
public:
virtual const char* className() const { return "ATTR Image Attribute Reader/Writer"; }
virtual bool acceptsExtension(const std::string& extension) const
{
return equalCaseInsensitive(extension,"attr");
}
virtual ReadResult readObject(const std::string& fileName, const ReaderWriter::Options*) const;
};
ReaderWriter::ReadResult ReaderWriterATTR::readObject(const std::string& file, const ReaderWriter::Options* options) const
{
using std::ios;
std::string ext = osgDB::getLowerCaseFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
std::ifstream fin;
fin.imbue(std::locale::classic());
fin.open(fileName.c_str(), std::ios::in | std::ios::binary);
if ( fin.fail())
return ReadResult::ERROR_IN_READING_FILE;
flt::DataInputStream in(fin.rdbuf());
AttrData* attr = new AttrData;
try
{
attr->texels_u = in.readInt32();
attr->textel_v = in.readInt32();
attr->direction_u = in.readInt32();
attr->direction_v = in.readInt32();
attr->x_up = in.readInt32();
attr->y_up = in.readInt32();
attr->fileFormat = in.readInt32();
attr->minFilterMode = in.readInt32();
attr->magFilterMode = in.readInt32();
attr->wrapMode = in.readInt32(AttrData::WRAP_REPEAT);
attr->wrapMode_u = in.readInt32();
if (attr->wrapMode_u == AttrData::WRAP_NONE)
attr->wrapMode_u = attr->wrapMode;
attr->wrapMode_v = in.readInt32();
if (attr->wrapMode_v == AttrData::WRAP_NONE)
attr->wrapMode_v = attr->wrapMode;
attr->modifyFlag = in.readInt32();
attr->pivot_x = in.readInt32();
attr->pivot_y = in.readInt32();
// v11 ends here
// if (in.eof() || (_flt_version <= 11)) return true;
#if 1
attr->texEnvMode = in.readInt32(AttrData::TEXENV_MODULATE);
attr->intensityAsAlpha = in.readInt32();
in.forward(4*8);
in.forward(4);
attr->size_u = in.readFloat64();
attr->size_v = in.readFloat64();
attr->originCode = in.readInt32();
attr->kernelVersion = in.readInt32();
attr->intFormat = in.readInt32();
attr->extFormat = in.readInt32();
attr->useMips = in.readInt32();
for (int n=0; n<8; n++)
attr->of_mips[n] = in.readFloat32();
attr->useLodScale = in.readInt32();
attr->lod0 = in.readFloat32();
attr->scale0 = in.readFloat32();
attr->lod1 = in.readFloat32();
attr->scale1 = in.readFloat32();
attr->lod2 = in.readFloat32();
attr->scale2 = in.readFloat32();
attr->lod3 = in.readFloat32();
attr->scale3 = in.readFloat32();
attr->lod4 = in.readFloat32();
attr->scale4 = in.readFloat32();
attr->lod5 = in.readFloat32();
attr->scale5 = in.readFloat32();
attr->lod6 = in.readFloat32();
attr->scale6 = in.readFloat32();
attr->lod7 = in.readFloat32();
attr->scale7 = in.readFloat32();
attr->clamp = in.readFloat32();
attr->magFilterAlpha = in.readInt32();
attr->magFilterColor = in.readInt32();
in.forward(4);
in.forward(4*8);
attr->lambertMeridian = in.readFloat64();
attr->lambertUpperLat = in.readFloat64();
attr->lambertlowerLat = in.readFloat64();
in.forward(8);
in.forward(4*5);
attr->useDetail = in.readInt32( );
attr->txDetail_j = in.readInt32();
attr->txDetail_k = in.readInt32();
attr->txDetail_m = in.readInt32();
attr->txDetail_n = in.readInt32();
attr->txDetail_s = in.readInt32( );
attr->useTile = in.readInt32();
attr->txTile_ll_u= in.readFloat32();
attr->txTile_ll_v = in.readFloat32();
attr->txTile_ur_u = in.readFloat32();
attr->txTile_ur_v = in.readFloat32();
attr->projection = in.readInt32();
attr->earthModel = in.readInt32();
in.forward(4);
attr->utmZone = in.readInt32();
attr->imageOrigin = in.readInt32();
attr->geoUnits = in.readInt32();
in.forward(4);
in.forward(4);
attr->hemisphere = in.readInt32();
in.forward(4);
in.forward(4);
in.forward(149*4);
attr->comments = in.readString(512);
// v12 ends here
// if (in.eof() || (_flt_version <= 12)) return true;
in.forward(14*4);
attr->attrVersion = in.readInt32();
attr->controlPoints = in.readInt32();
in.forward(4);
#endif
}
catch(...)
{
if (!fin.eof())
{
throw;
}
}
fin.close();
return attr;
}
// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(attr, ReaderWriterATTR)
<|endoftext|>
|
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al.
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "clone_database.h"
#include "../core/datatypes.h"
#include "../core/settings.h"
#include "../../template_db/block_backend.h"
#include "../../template_db/file_blocks.h"
#include "../../template_db/random_file.h"
template< class TIndex >
void clone_bin_file(const File_Properties& src_file_prop, const File_Properties& dest_file_prop,
Transaction& transaction, std::string dest_db_dir, const Clone_Settings& clone_settings)
{
try
{
if (src_file_prop.get_block_size() * src_file_prop.get_compression_factor()
!= dest_file_prop.get_block_size() * dest_file_prop.get_compression_factor())
{
std::cout<<"Block sizes of source and destination format are incompatible.\n";
return;
}
uint32 block_size = src_file_prop.get_block_size() * src_file_prop.get_compression_factor();
File_Blocks_Index< TIndex >& src_idx =
*dynamic_cast< File_Blocks_Index< TIndex >* >(transaction.data_index(&src_file_prop));
File_Blocks< TIndex, typename std::set< TIndex >::const_iterator, Default_Range_Iterator< TIndex > >
src_file(&src_idx);
File_Blocks_Index< TIndex > dest_idx(dest_file_prop, true, false, dest_db_dir, "",
clone_settings.compression_method);
File_Blocks< TIndex, typename std::set< TIndex >::const_iterator, Default_Range_Iterator< TIndex > >
dest_file(&dest_idx);
typename File_Blocks< TIndex, typename std::set< TIndex >::const_iterator,
Default_Range_Iterator< TIndex > >::Flat_Iterator
src_it = src_file.flat_begin();
uint32 max_keysize = 0;
while (!src_it.is_end())
{
if (max_keysize > 0)
{
uint64* buf = src_file.read_block(src_it, false);
dest_file.insert_block(
dest_file.write_end(), buf, std::min(max_keysize, block_size),
src_it.block_it->max_keysize, src_it.block_it->index);
max_keysize = std::max(max_keysize, block_size) - block_size;
}
else
{
uint64* buf = src_file.read_block(src_it);
dest_file.insert_block(dest_file.write_end(), buf, src_it.block_it->max_keysize);
if (src_it.block_it->max_keysize > block_size)
max_keysize = src_it.block_it->max_keysize - block_size;
}
++src_it;
}
}
catch (File_Error e)
{
std::cout<<e.origin<<' '<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<'\n';
}
}
template< typename Key, typename TIndex >
void clone_map_file(const File_Properties& file_prop, Transaction& transaction, std::string dest_db_dir, Clone_Settings clone_settings)
{
try
{
Random_File_Index& src_idx = *transaction.random_index(&file_prop);
Random_File< Key, TIndex > src_file(&src_idx);
Random_File_Index dest_idx(file_prop, true, false, dest_db_dir, "", clone_settings.map_compression_method);
Random_File< Key, TIndex > dest_file(&dest_idx);
for (std::vector< uint32 >::size_type i = 0; i < src_idx.get_blocks().size(); ++i)
{
if (src_idx.get_blocks()[i].pos != src_idx.npos)
{
for (uint32 j = 0; j < src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of(); ++j)
{
TIndex val =
src_file.get(i*(src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of()) + j);
if (!(val == TIndex(uint32(0))))
dest_file.put(i*(src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of()) + j, val);
}
}
}
}
catch (File_Error e)
{
std::cout<<e.origin<<' '<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<'\n';
}
}
void clone_database(Transaction& transaction, const std::string& dest_db_dir, const Clone_Settings& clone_settings)
{
clone_bin_file< Uint32_Index >(*osm_base_settings().NODES, *osm_base_settings().NODES,
transaction, dest_db_dir, clone_settings);
clone_map_file< Node_Skeleton::Id_Type, Uint32_Index >(*osm_base_settings().NODES, transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*osm_base_settings().NODE_TAGS_LOCAL, *osm_base_settings().NODE_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*osm_base_settings().NODE_TAGS_GLOBAL, *osm_base_settings().NODE_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().NODE_KEYS, *osm_base_settings().NODE_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*osm_base_settings().WAYS, *osm_base_settings().WAYS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Way_Skeleton::Id_Type, Uint31_Index >(*osm_base_settings().WAYS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*osm_base_settings().WAY_TAGS_LOCAL, *osm_base_settings().WAY_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*osm_base_settings().WAY_TAGS_GLOBAL, *osm_base_settings().WAY_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().WAY_KEYS, *osm_base_settings().WAY_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*osm_base_settings().RELATIONS, *osm_base_settings().RELATIONS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Relation_Skeleton::Id_Type, Uint31_Index >(
*osm_base_settings().RELATIONS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().RELATION_ROLES, *osm_base_settings().RELATION_ROLES,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(
*osm_base_settings().RELATION_TAGS_LOCAL, *osm_base_settings().RELATION_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(
*osm_base_settings().RELATION_TAGS_GLOBAL, *osm_base_settings().RELATION_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().RELATION_KEYS, *osm_base_settings().RELATION_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().NODES_META, *meta_settings().NODES_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().WAYS_META, *meta_settings().WAYS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().RELATIONS_META, *meta_settings().RELATIONS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*meta_settings().USER_DATA, *meta_settings().USER_DATA,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*meta_settings().USER_INDICES, *meta_settings().USER_INDICES,
transaction, dest_db_dir, clone_settings);
{
clone_bin_file< Uint31_Index >(*attic_settings().NODES, *attic_settings().NODES,
transaction, dest_db_dir, clone_settings);
clone_map_file< Node_Skeleton::Id_Type, Uint31_Index >(*attic_settings().NODES, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().NODES_UNDELETED, *attic_settings().NODES_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Node::Id_Type >(*attic_settings().NODE_IDX_LIST, *attic_settings().NODE_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*attic_settings().NODE_TAGS_LOCAL, *attic_settings().NODE_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*attic_settings().NODE_TAGS_GLOBAL, *attic_settings().NODE_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().NODES_META, *attic_settings().NODES_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().NODE_CHANGELOG, *attic_settings().NODE_CHANGELOG,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS, *attic_settings().WAYS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Way_Skeleton::Id_Type, Uint31_Index >(*attic_settings().WAYS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS_UNDELETED, *attic_settings().WAYS_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Way::Id_Type >(*attic_settings().WAY_IDX_LIST, *attic_settings().WAY_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*attic_settings().WAY_TAGS_LOCAL, *attic_settings().WAY_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*attic_settings().WAY_TAGS_GLOBAL, *attic_settings().WAY_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS_META, *attic_settings().WAYS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().WAY_CHANGELOG, *attic_settings().WAY_CHANGELOG,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS, *attic_settings().RELATIONS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Relation_Skeleton::Id_Type, Uint31_Index >(*attic_settings().RELATIONS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS_UNDELETED, *attic_settings().RELATIONS_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Relation::Id_Type >(*attic_settings().RELATION_IDX_LIST, *attic_settings().RELATION_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(
*attic_settings().RELATION_TAGS_LOCAL, *attic_settings().RELATION_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(
*attic_settings().RELATION_TAGS_GLOBAL, *attic_settings().RELATION_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS_META, *attic_settings().RELATIONS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().RELATION_CHANGELOG, *attic_settings().RELATION_CHANGELOG,
transaction, dest_db_dir, clone_settings);
}
}
<commit_msg>Fixed a subtle bug in the cloning mechanism.<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al.
*
* This file is part of Overpass_API.
*
* Overpass_API is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Overpass_API is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Overpass_API. If not, see <http://www.gnu.org/licenses/>.
*/
#include "clone_database.h"
#include "../core/datatypes.h"
#include "../core/settings.h"
#include "../../template_db/block_backend.h"
#include "../../template_db/file_blocks.h"
#include "../../template_db/random_file.h"
template< class TIndex >
void clone_bin_file(const File_Properties& src_file_prop, const File_Properties& dest_file_prop,
Transaction& transaction, std::string dest_db_dir, const Clone_Settings& clone_settings)
{
try
{
if (src_file_prop.get_block_size() * src_file_prop.get_compression_factor()
!= dest_file_prop.get_block_size() * dest_file_prop.get_compression_factor())
{
std::cout<<"Block sizes of source and destination format are incompatible.\n";
return;
}
uint32 block_size = src_file_prop.get_block_size() * src_file_prop.get_compression_factor();
File_Blocks_Index< TIndex >& src_idx =
*dynamic_cast< File_Blocks_Index< TIndex >* >(transaction.data_index(&src_file_prop));
File_Blocks< TIndex, typename std::set< TIndex >::const_iterator, Default_Range_Iterator< TIndex > >
src_file(&src_idx);
File_Blocks_Index< TIndex > dest_idx(dest_file_prop, true, false, dest_db_dir, "",
clone_settings.compression_method);
File_Blocks< TIndex, typename std::set< TIndex >::const_iterator, Default_Range_Iterator< TIndex > >
dest_file(&dest_idx);
typename File_Blocks< TIndex, typename std::set< TIndex >::const_iterator,
Default_Range_Iterator< TIndex > >::Flat_Iterator
src_it = src_file.flat_begin();
uint32 excess_bytes = 0;
while (!src_it.is_end())
{
if (excess_bytes > 0)
{
uint64* buf = src_file.read_block(src_it, false);
dest_file.insert_block(
dest_file.write_end(), buf, std::min(excess_bytes, block_size),
src_it.block_it->max_keysize, src_it.block_it->index);
excess_bytes = std::max(excess_bytes, block_size) - block_size;
}
else
{
uint64* buf = src_file.read_block(src_it);
dest_file.insert_block(dest_file.write_end(), buf, src_it.block_it->max_keysize);
if (src_it.block_it->max_keysize + 4 > block_size)
excess_bytes = src_it.block_it->max_keysize + 4 - block_size;
}
++src_it;
}
}
catch (File_Error e)
{
std::cout<<e.origin<<' '<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<'\n';
}
}
template< typename Key, typename TIndex >
void clone_map_file(const File_Properties& file_prop, Transaction& transaction, std::string dest_db_dir, Clone_Settings clone_settings)
{
try
{
Random_File_Index& src_idx = *transaction.random_index(&file_prop);
Random_File< Key, TIndex > src_file(&src_idx);
Random_File_Index dest_idx(file_prop, true, false, dest_db_dir, "", clone_settings.map_compression_method);
Random_File< Key, TIndex > dest_file(&dest_idx);
for (std::vector< uint32 >::size_type i = 0; i < src_idx.get_blocks().size(); ++i)
{
if (src_idx.get_blocks()[i].pos != src_idx.npos)
{
for (uint32 j = 0; j < src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of(); ++j)
{
TIndex val =
src_file.get(i*(src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of()) + j);
if (!(val == TIndex(uint32(0))))
dest_file.put(i*(src_idx.get_block_size()*src_idx.get_compression_factor()/TIndex::max_size_of()) + j, val);
}
}
}
}
catch (File_Error e)
{
std::cout<<e.origin<<' '<<e.error_number<<' '<<strerror(e.error_number)<<' '<<e.filename<<'\n';
}
}
void clone_database(Transaction& transaction, const std::string& dest_db_dir, const Clone_Settings& clone_settings)
{
clone_bin_file< Uint32_Index >(*osm_base_settings().NODES, *osm_base_settings().NODES,
transaction, dest_db_dir, clone_settings);
clone_map_file< Node_Skeleton::Id_Type, Uint32_Index >(*osm_base_settings().NODES, transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*osm_base_settings().NODE_TAGS_LOCAL, *osm_base_settings().NODE_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*osm_base_settings().NODE_TAGS_GLOBAL, *osm_base_settings().NODE_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().NODE_KEYS, *osm_base_settings().NODE_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*osm_base_settings().WAYS, *osm_base_settings().WAYS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Way_Skeleton::Id_Type, Uint31_Index >(*osm_base_settings().WAYS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*osm_base_settings().WAY_TAGS_LOCAL, *osm_base_settings().WAY_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*osm_base_settings().WAY_TAGS_GLOBAL, *osm_base_settings().WAY_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().WAY_KEYS, *osm_base_settings().WAY_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*osm_base_settings().RELATIONS, *osm_base_settings().RELATIONS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Relation_Skeleton::Id_Type, Uint31_Index >(
*osm_base_settings().RELATIONS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().RELATION_ROLES, *osm_base_settings().RELATION_ROLES,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(
*osm_base_settings().RELATION_TAGS_LOCAL, *osm_base_settings().RELATION_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(
*osm_base_settings().RELATION_TAGS_GLOBAL, *osm_base_settings().RELATION_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*osm_base_settings().RELATION_KEYS, *osm_base_settings().RELATION_KEYS,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().NODES_META, *meta_settings().NODES_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().WAYS_META, *meta_settings().WAYS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*meta_settings().RELATIONS_META, *meta_settings().RELATIONS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*meta_settings().USER_DATA, *meta_settings().USER_DATA,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint32_Index >(*meta_settings().USER_INDICES, *meta_settings().USER_INDICES,
transaction, dest_db_dir, clone_settings);
{
clone_bin_file< Uint31_Index >(*attic_settings().NODES, *attic_settings().NODES,
transaction, dest_db_dir, clone_settings);
clone_map_file< Node_Skeleton::Id_Type, Uint31_Index >(*attic_settings().NODES, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().NODES_UNDELETED, *attic_settings().NODES_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Node::Id_Type >(*attic_settings().NODE_IDX_LIST, *attic_settings().NODE_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*attic_settings().NODE_TAGS_LOCAL, *attic_settings().NODE_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*attic_settings().NODE_TAGS_GLOBAL, *attic_settings().NODE_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().NODES_META, *attic_settings().NODES_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().NODE_CHANGELOG, *attic_settings().NODE_CHANGELOG,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS, *attic_settings().WAYS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Way_Skeleton::Id_Type, Uint31_Index >(*attic_settings().WAYS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS_UNDELETED, *attic_settings().WAYS_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Way::Id_Type >(*attic_settings().WAY_IDX_LIST, *attic_settings().WAY_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(*attic_settings().WAY_TAGS_LOCAL, *attic_settings().WAY_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(*attic_settings().WAY_TAGS_GLOBAL, *attic_settings().WAY_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().WAYS_META, *attic_settings().WAYS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().WAY_CHANGELOG, *attic_settings().WAY_CHANGELOG,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS, *attic_settings().RELATIONS,
transaction, dest_db_dir, clone_settings);
clone_map_file< Relation_Skeleton::Id_Type, Uint31_Index >(*attic_settings().RELATIONS, transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS_UNDELETED, *attic_settings().RELATIONS_UNDELETED,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Relation::Id_Type >(*attic_settings().RELATION_IDX_LIST, *attic_settings().RELATION_IDX_LIST,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Local >(
*attic_settings().RELATION_TAGS_LOCAL, *attic_settings().RELATION_TAGS_LOCAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Tag_Index_Global >(
*attic_settings().RELATION_TAGS_GLOBAL, *attic_settings().RELATION_TAGS_GLOBAL,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Uint31_Index >(*attic_settings().RELATIONS_META, *attic_settings().RELATIONS_META,
transaction, dest_db_dir, clone_settings);
clone_bin_file< Timestamp >(*attic_settings().RELATION_CHANGELOG, *attic_settings().RELATION_CHANGELOG,
transaction, dest_db_dir, clone_settings);
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen 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 Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ingen/Node.hpp"
#include "ingen/URIs.hpp"
#include "ingen/client/ObjectModel.hpp"
namespace Ingen {
namespace Client {
ObjectModel::ObjectModel(URIs& uris, const Raul::Path& path)
: Node(uris, path)
, _path(path)
, _symbol((path == "/") ? "root" : path.symbol())
{
}
ObjectModel::ObjectModel(const ObjectModel& copy)
: Node(copy)
, _parent(copy._parent)
, _path(copy._path)
, _symbol(copy._symbol)
{
}
ObjectModel::~ObjectModel()
{
}
bool
ObjectModel::is_a(const Raul::URI& type) const
{
return has_property(_uris.rdf_type, _uris.forge.alloc_uri(type));
}
void
ObjectModel::on_property(const Raul::URI& uri, const Atom& value)
{
_signal_property.emit(uri, value);
}
void
ObjectModel::on_property_removed(const Raul::URI& uri, const Atom& value)
{
_signal_property_removed.emit(uri, value);
}
const Atom&
ObjectModel::get_property(const Raul::URI& key) const
{
static const Atom null_atom;
Resource::Properties::const_iterator i = properties().find(key);
return (i != properties().end()) ? i->second : null_atom;
}
bool
ObjectModel::polyphonic() const
{
const Atom& polyphonic = get_property(_uris.ingen_polyphonic);
return (polyphonic.is_valid() && polyphonic.get<int32_t>());
}
/** Merge the data of `o` with self, as much as possible.
*
* This will merge the two models, but with any conflict take the value in
* `o` as correct. The paths of the two models MUST be equal.
*/
void
ObjectModel::set(SPtr<ObjectModel> o)
{
assert(_path == o->path());
if (o->_parent)
_parent = o->_parent;
for (auto v : o->properties()) {
Resource::set_property(v.first, v.second);
_signal_property.emit(v.first, v.second);
}
}
void
ObjectModel::set_path(const Raul::Path& p)
{
_path = p;
_symbol = Raul::Symbol(p.is_root() ? "root" : p.symbol());
_signal_moved.emit();
}
void
ObjectModel::set_parent(SPtr<ObjectModel> p)
{
assert(_path.is_child_of(p->path()));
_parent = p;
}
} // namespace Client
} // namespace Ingen
<commit_msg>Fix renaming.<commit_after>/*
This file is part of Ingen.
Copyright 2007-2012 David Robillard <http://drobilla.net/>
Ingen is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or any later version.
Ingen 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 Affero General Public License for details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ingen/Node.hpp"
#include "ingen/URIs.hpp"
#include "ingen/client/ObjectModel.hpp"
namespace Ingen {
namespace Client {
ObjectModel::ObjectModel(URIs& uris, const Raul::Path& path)
: Node(uris, path)
, _path(path)
, _symbol((path == "/") ? "root" : path.symbol())
{
}
ObjectModel::ObjectModel(const ObjectModel& copy)
: Node(copy)
, _parent(copy._parent)
, _path(copy._path)
, _symbol(copy._symbol)
{
}
ObjectModel::~ObjectModel()
{
}
bool
ObjectModel::is_a(const Raul::URI& type) const
{
return has_property(_uris.rdf_type, _uris.forge.alloc_uri(type));
}
void
ObjectModel::on_property(const Raul::URI& uri, const Atom& value)
{
_signal_property.emit(uri, value);
}
void
ObjectModel::on_property_removed(const Raul::URI& uri, const Atom& value)
{
_signal_property_removed.emit(uri, value);
}
const Atom&
ObjectModel::get_property(const Raul::URI& key) const
{
static const Atom null_atom;
Resource::Properties::const_iterator i = properties().find(key);
return (i != properties().end()) ? i->second : null_atom;
}
bool
ObjectModel::polyphonic() const
{
const Atom& polyphonic = get_property(_uris.ingen_polyphonic);
return (polyphonic.is_valid() && polyphonic.get<int32_t>());
}
/** Merge the data of `o` with self, as much as possible.
*
* This will merge the two models, but with any conflict take the value in
* `o` as correct. The paths of the two models MUST be equal.
*/
void
ObjectModel::set(SPtr<ObjectModel> o)
{
assert(_path == o->path());
if (o->_parent)
_parent = o->_parent;
for (auto v : o->properties()) {
Resource::set_property(v.first, v.second);
_signal_property.emit(v.first, v.second);
}
}
void
ObjectModel::set_path(const Raul::Path& p)
{
_path = p;
_symbol = Raul::Symbol(p.is_root() ? "root" : p.symbol());
set_uri(Node::path_to_uri(p));
_signal_moved.emit();
}
void
ObjectModel::set_parent(SPtr<ObjectModel> p)
{
assert(_path.is_child_of(p->path()));
_parent = p;
}
} // namespace Client
} // namespace Ingen
<|endoftext|>
|
<commit_before>/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChipDeviceScanner.h"
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include "BluezObjectList.h"
#include "MainLoop.h"
#include "Types.h"
#include <errno.h>
#include <lib/support/logging/CHIPLogging.h>
#include <pthread.h>
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
struct GObjectUnref
{
template <typename T>
void operator()(T * value)
{
g_object_unref(value);
}
};
using GCancellableUniquePtr = std::unique_ptr<GCancellable, GObjectUnref>;
using GDBusObjectManagerUniquePtr = std::unique_ptr<GDBusObjectManager, GObjectUnref>;
/// Retrieve CHIP device identification info from the device advertising data
bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIdentificationInfo & aDeviceInfo)
{
GVariant * serviceData = bluez_device1_get_service_data(&aDevice);
VerifyOrReturnError(serviceData != nullptr, false);
GVariant * dataValue = g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr);
VerifyOrReturnError(dataValue != nullptr, false);
size_t dataLen = 0;
const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t));
VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false);
memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo));
return true;
}
} // namespace
ChipDeviceScanner::ChipDeviceScanner(GDBusObjectManager * manager, BluezAdapter1 * adapter, GCancellable * cancellable,
ChipDeviceScannerDelegate * delegate) :
mManager(manager),
mAdapter(adapter), mCancellable(cancellable), mDelegate(delegate)
{
g_object_ref(mAdapter);
g_object_ref(mCancellable);
g_object_ref(mManager);
}
ChipDeviceScanner::~ChipDeviceScanner()
{
StopScan();
// In case the timeout timer is still active
chip::DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, this);
g_object_unref(mManager);
g_object_unref(mCancellable);
g_object_unref(mAdapter);
mManager = nullptr;
mAdapter = nullptr;
mCancellable = nullptr;
mDelegate = nullptr;
}
std::unique_ptr<ChipDeviceScanner> ChipDeviceScanner::Create(BluezAdapter1 * adapter, ChipDeviceScannerDelegate * delegate)
{
GError * error = nullptr;
GCancellableUniquePtr cancellable(g_cancellable_new(), GObjectUnref());
if (!cancellable)
{
return std::unique_ptr<ChipDeviceScanner>();
}
GDBusObjectManagerUniquePtr manager(
g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE,
"/", bluez_object_manager_client_get_proxy_type,
nullptr /* unused user data in the Proxy Type Func */,
nullptr /*destroy notify */, cancellable.get(), &error),
GObjectUnref());
if (!manager)
{
ChipLogError(Ble, "Failed to get DBUS object manager for device scanning: %s", error->message);
g_error_free(error);
return std::unique_ptr<ChipDeviceScanner>();
}
return std::make_unique<ChipDeviceScanner>(manager.get(), adapter, cancellable.get(), delegate);
}
CHIP_ERROR ChipDeviceScanner::StartScan(unsigned timeoutMs)
{
ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(MainLoop::Instance().EnsureStarted());
mIsScanning = true; // optimistic, to allow all callbacks to check this
if (!MainLoop::Instance().Schedule(MainLoopStartScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan start.");
mIsScanning = false;
return CHIP_ERROR_INTERNAL;
}
CHIP_ERROR err = chip::DeviceLayer::SystemLayer().StartTimer(timeoutMs, TimerExpiredCallback, static_cast<void *>(this));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule scan timeout.");
StopScan();
return err;
}
return CHIP_NO_ERROR;
}
void ChipDeviceScanner::TimerExpiredCallback(chip::System::Layer * layer, void * appState)
{
static_cast<ChipDeviceScanner *>(appState)->StopScan();
}
CHIP_ERROR ChipDeviceScanner::StopScan()
{
ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR);
ReturnErrorCodeIf(mIsStopping, CHIP_NO_ERROR);
mIsStopping = true;
g_cancellable_cancel(mCancellable); // in case we are currently running a scan
if (mObjectAddedSignal)
{
g_signal_handler_disconnect(mManager, mObjectAddedSignal);
mObjectAddedSignal = 0;
}
if (mInterfaceChangedSignal)
{
g_signal_handler_disconnect(mManager, mInterfaceChangedSignal);
mInterfaceChangedSignal = 0;
}
if (!MainLoop::Instance().ScheduleAndWait(MainLoopStopScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan stop.");
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
int ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error))
{
ChipLogError(Ble, "Failed to stop discovery %s", error->message);
g_error_free(error);
}
ChipDeviceScannerDelegate * delegate = self->mDelegate;
self->mIsScanning = false;
// callback is explicitly allowed to delete the scanner (hence no more
// references to 'self' here)
delegate->OnScanComplete();
return 0;
}
void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::SignalInterfaceChanged(GDBusObjectManagerClient * manager, GDBusObjectProxy * object,
GDBusProxy * aInterface, GVariant * aChangedProperties,
const gchar * const * aInvalidatedProps, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::ReportDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(device));
return;
}
mDelegate->OnDeviceScanned(device, deviceInfo);
}
void ChipDeviceScanner::RemoveDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
return;
}
const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(device));
GError * error = nullptr;
if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error))
{
ChipLogDetail(Ble, "Failed to remove device %s: %s", devicePath, error->message);
g_error_free(error);
}
}
int ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self);
self->mInterfaceChangedSignal =
g_signal_connect(self->mManager, "interface-proxy-properties-changed", G_CALLBACK(SignalInterfaceChanged), self);
ChipLogProgress(Ble, "BLE removing known devices.");
for (BluezObject & object : BluezObjectList(self->mManager))
{
self->RemoveDevice(bluez_object_get_device1(&object));
}
/* Search for matter/chip UUID only */
GVariantBuilder uuidsBuilder;
GVariant * uuids;
g_variant_builder_init(&uuidsBuilder, G_VARIANT_TYPE("as"));
g_variant_builder_add(&uuidsBuilder, "s", CHIP_BLE_UUID_SERVICE_STRING);
uuids = g_variant_builder_end(&uuidsBuilder);
/* Search for LE only: Advertises */
GVariantBuilder filterBuilder;
GVariant * filter;
g_variant_builder_init(&filterBuilder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le"));
g_variant_builder_add(&filterBuilder, "{sv}", "UUIDs", uuids);
filter = g_variant_builder_end(&filterBuilder);
if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, &error))
{
/* Not critical: ignore if fails */
ChipLogError(Ble, "Failed to set discovery filters: %s", error->message);
g_error_free(error);
}
ChipLogProgress(Ble, "BLE initiating scan.");
if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error))
{
ChipLogError(Ble, "Failed to start discovery: %s", error->message);
g_error_free(error);
self->mIsScanning = false;
self->mDelegate->OnScanComplete();
}
return 0;
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
<commit_msg>[bluez] Remove filtering by service UUID (#9782)<commit_after>/*
*
* Copyright (c) 2021 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChipDeviceScanner.h"
#if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
#include "BluezObjectList.h"
#include "MainLoop.h"
#include "Types.h"
#include <errno.h>
#include <lib/support/logging/CHIPLogging.h>
#include <pthread.h>
namespace chip {
namespace DeviceLayer {
namespace Internal {
namespace {
struct GObjectUnref
{
template <typename T>
void operator()(T * value)
{
g_object_unref(value);
}
};
using GCancellableUniquePtr = std::unique_ptr<GCancellable, GObjectUnref>;
using GDBusObjectManagerUniquePtr = std::unique_ptr<GDBusObjectManager, GObjectUnref>;
/// Retrieve CHIP device identification info from the device advertising data
bool BluezGetChipDeviceInfo(BluezDevice1 & aDevice, chip::Ble::ChipBLEDeviceIdentificationInfo & aDeviceInfo)
{
GVariant * serviceData = bluez_device1_get_service_data(&aDevice);
VerifyOrReturnError(serviceData != nullptr, false);
GVariant * dataValue = g_variant_lookup_value(serviceData, CHIP_BLE_UUID_SERVICE_STRING, nullptr);
VerifyOrReturnError(dataValue != nullptr, false);
size_t dataLen = 0;
const void * dataBytes = g_variant_get_fixed_array(dataValue, &dataLen, sizeof(uint8_t));
VerifyOrReturnError(dataBytes != nullptr && dataLen >= sizeof(aDeviceInfo), false);
memcpy(&aDeviceInfo, dataBytes, sizeof(aDeviceInfo));
return true;
}
} // namespace
ChipDeviceScanner::ChipDeviceScanner(GDBusObjectManager * manager, BluezAdapter1 * adapter, GCancellable * cancellable,
ChipDeviceScannerDelegate * delegate) :
mManager(manager),
mAdapter(adapter), mCancellable(cancellable), mDelegate(delegate)
{
g_object_ref(mAdapter);
g_object_ref(mCancellable);
g_object_ref(mManager);
}
ChipDeviceScanner::~ChipDeviceScanner()
{
StopScan();
// In case the timeout timer is still active
chip::DeviceLayer::SystemLayer().CancelTimer(TimerExpiredCallback, this);
g_object_unref(mManager);
g_object_unref(mCancellable);
g_object_unref(mAdapter);
mManager = nullptr;
mAdapter = nullptr;
mCancellable = nullptr;
mDelegate = nullptr;
}
std::unique_ptr<ChipDeviceScanner> ChipDeviceScanner::Create(BluezAdapter1 * adapter, ChipDeviceScannerDelegate * delegate)
{
GError * error = nullptr;
GCancellableUniquePtr cancellable(g_cancellable_new(), GObjectUnref());
if (!cancellable)
{
return std::unique_ptr<ChipDeviceScanner>();
}
GDBusObjectManagerUniquePtr manager(
g_dbus_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE,
"/", bluez_object_manager_client_get_proxy_type,
nullptr /* unused user data in the Proxy Type Func */,
nullptr /*destroy notify */, cancellable.get(), &error),
GObjectUnref());
if (!manager)
{
ChipLogError(Ble, "Failed to get DBUS object manager for device scanning: %s", error->message);
g_error_free(error);
return std::unique_ptr<ChipDeviceScanner>();
}
return std::make_unique<ChipDeviceScanner>(manager.get(), adapter, cancellable.get(), delegate);
}
CHIP_ERROR ChipDeviceScanner::StartScan(unsigned timeoutMs)
{
ReturnErrorCodeIf(mIsScanning, CHIP_ERROR_INCORRECT_STATE);
ReturnErrorOnFailure(MainLoop::Instance().EnsureStarted());
mIsScanning = true; // optimistic, to allow all callbacks to check this
if (!MainLoop::Instance().Schedule(MainLoopStartScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan start.");
mIsScanning = false;
return CHIP_ERROR_INTERNAL;
}
CHIP_ERROR err = chip::DeviceLayer::SystemLayer().StartTimer(timeoutMs, TimerExpiredCallback, static_cast<void *>(this));
if (err != CHIP_NO_ERROR)
{
ChipLogError(Ble, "Failed to schedule scan timeout.");
StopScan();
return err;
}
return CHIP_NO_ERROR;
}
void ChipDeviceScanner::TimerExpiredCallback(chip::System::Layer * layer, void * appState)
{
static_cast<ChipDeviceScanner *>(appState)->StopScan();
}
CHIP_ERROR ChipDeviceScanner::StopScan()
{
ReturnErrorCodeIf(!mIsScanning, CHIP_NO_ERROR);
ReturnErrorCodeIf(mIsStopping, CHIP_NO_ERROR);
mIsStopping = true;
g_cancellable_cancel(mCancellable); // in case we are currently running a scan
if (mObjectAddedSignal)
{
g_signal_handler_disconnect(mManager, mObjectAddedSignal);
mObjectAddedSignal = 0;
}
if (mInterfaceChangedSignal)
{
g_signal_handler_disconnect(mManager, mInterfaceChangedSignal);
mInterfaceChangedSignal = 0;
}
if (!MainLoop::Instance().ScheduleAndWait(MainLoopStopScan, this))
{
ChipLogError(Ble, "Failed to schedule BLE scan stop.");
return CHIP_ERROR_INTERNAL;
}
return CHIP_NO_ERROR;
}
int ChipDeviceScanner::MainLoopStopScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
if (!bluez_adapter1_call_stop_discovery_sync(self->mAdapter, nullptr /* not cancellable */, &error))
{
ChipLogError(Ble, "Failed to stop discovery %s", error->message);
g_error_free(error);
}
ChipDeviceScannerDelegate * delegate = self->mDelegate;
self->mIsScanning = false;
// callback is explicitly allowed to delete the scanner (hence no more
// references to 'self' here)
delegate->OnScanComplete();
return 0;
}
void ChipDeviceScanner::SignalObjectAdded(GDBusObjectManager * manager, GDBusObject * object, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::SignalInterfaceChanged(GDBusObjectManagerClient * manager, GDBusObjectProxy * object,
GDBusProxy * aInterface, GVariant * aChangedProperties,
const gchar * const * aInvalidatedProps, ChipDeviceScanner * self)
{
self->ReportDevice(bluez_object_get_device1(BLUEZ_OBJECT(object)));
}
void ChipDeviceScanner::ReportDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
ChipLogDetail(Ble, "Device %s does not look like a CHIP device.", bluez_device1_get_address(device));
return;
}
mDelegate->OnDeviceScanned(device, deviceInfo);
}
void ChipDeviceScanner::RemoveDevice(BluezDevice1 * device)
{
if (device == nullptr)
{
return;
}
if (strcmp(bluez_device1_get_adapter(device), g_dbus_proxy_get_object_path(G_DBUS_PROXY(mAdapter))) != 0)
{
return;
}
chip::Ble::ChipBLEDeviceIdentificationInfo deviceInfo;
if (!BluezGetChipDeviceInfo(*device, deviceInfo))
{
return;
}
const auto devicePath = g_dbus_proxy_get_object_path(G_DBUS_PROXY(device));
GError * error = nullptr;
if (!bluez_adapter1_call_remove_device_sync(mAdapter, devicePath, nullptr, &error))
{
ChipLogDetail(Ble, "Failed to remove device %s: %s", devicePath, error->message);
g_error_free(error);
}
}
int ChipDeviceScanner::MainLoopStartScan(ChipDeviceScanner * self)
{
GError * error = nullptr;
self->mObjectAddedSignal = g_signal_connect(self->mManager, "object-added", G_CALLBACK(SignalObjectAdded), self);
self->mInterfaceChangedSignal =
g_signal_connect(self->mManager, "interface-proxy-properties-changed", G_CALLBACK(SignalInterfaceChanged), self);
ChipLogProgress(Ble, "BLE removing known devices.");
for (BluezObject & object : BluezObjectList(self->mManager))
{
self->RemoveDevice(bluez_object_get_device1(&object));
}
// Search for LE only.
// Do NOT add filtering by UUID as it is done by the following kernel function:
// https://github.com/torvalds/linux/blob/bdb575f872175ed0ecf2638369da1cb7a6e86a14/net/bluetooth/mgmt.c#L9258.
// The function requires that devices advertise its services' UUIDs in UUID16/32/128 fields
// while the Matter specification requires only FLAGS (0x01) and SERVICE_DATA_16 (0x16) fields
// in the advertisement packets.
GVariantBuilder filterBuilder;
g_variant_builder_init(&filterBuilder, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&filterBuilder, "{sv}", "Transport", g_variant_new_string("le"));
GVariant * filter = g_variant_builder_end(&filterBuilder);
if (!bluez_adapter1_call_set_discovery_filter_sync(self->mAdapter, filter, self->mCancellable, &error))
{
// Not critical: ignore if fails
ChipLogError(Ble, "Failed to set discovery filters: %s", error->message);
g_error_free(error);
}
ChipLogProgress(Ble, "BLE initiating scan.");
if (!bluez_adapter1_call_start_discovery_sync(self->mAdapter, self->mCancellable, &error))
{
ChipLogError(Ble, "Failed to start discovery: %s", error->message);
g_error_free(error);
self->mIsScanning = false;
self->mDelegate->OnScanComplete();
}
return 0;
}
} // namespace Internal
} // namespace DeviceLayer
} // namespace chip
#endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "cpprefactoringchanges.h"
#include <TranslationUnit.h>
#include <AST.h>
#include <cpptools/cppcodeformatter.h>
#include <cpptools/cppmodelmanager.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QTextBlock>
using namespace CPlusPlus;
using namespace CppTools;
using namespace Utils;
CppRefactoringChanges::CppRefactoringChanges(const Snapshot &snapshot)
: m_snapshot(snapshot)
, m_modelManager(Internal::CppModelManager::instance())
{
Q_ASSERT(m_modelManager);
m_workingCopy = m_modelManager->workingCopy();
}
const Snapshot &CppRefactoringChanges::snapshot() const
{
return m_snapshot;
}
CppRefactoringFile CppRefactoringChanges::file(const QString &fileName)
{
return CppRefactoringFile(fileName, this);
}
void CppRefactoringChanges::indentSelection(const QTextCursor &selection) const
{
// ### shares code with CPPEditor::indent()
QTextDocument *doc = selection.document();
QTextBlock block = doc->findBlock(selection.selectionStart());
const QTextBlock end = doc->findBlock(selection.selectionEnd()).next();
const TextEditor::TabSettings &tabSettings(TextEditor::TextEditorSettings::instance()->tabSettings());
CppTools::QtStyleCodeFormatter codeFormatter(tabSettings);
codeFormatter.updateStateUntil(block);
do {
int indent;
int padding;
codeFormatter.indentFor(block, &indent, &padding);
tabSettings.indentLine(block, indent + padding, padding);
codeFormatter.updateLineStateChange(block);
block = block.next();
} while (block.isValid() && block != end);
}
void CppRefactoringChanges::fileChanged(const QString &fileName)
{
m_modelManager->updateSourceFiles(QStringList(fileName));
}
CppRefactoringFile::CppRefactoringFile()
{ }
CppRefactoringFile::CppRefactoringFile(const QString &fileName, CppRefactoringChanges *refactoringChanges)
: RefactoringFile(fileName, refactoringChanges)
{ }
CppRefactoringFile::CppRefactoringFile(TextEditor::BaseTextEditor *editor, CPlusPlus::Document::Ptr document)
: RefactoringFile()
, m_cppDocument(document)
{
m_fileName = document->fileName();
m_editor = editor;
}
Document::Ptr CppRefactoringFile::cppDocument() const
{
if (!m_cppDocument || !m_cppDocument->translationUnit() ||
!m_cppDocument->translationUnit()->ast()) {
const QString source = document()->toPlainText();
const QString name = fileName();
const Snapshot &snapshot = refactoringChanges()->snapshot();
const QByteArray contents = snapshot.preprocessedCode(source, name);
m_cppDocument = snapshot.documentFromSource(contents, name);
m_cppDocument->check();
}
return m_cppDocument;
}
Scope *CppRefactoringFile::scopeAt(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getTokenStartPosition(index, &line, &column);
return cppDocument()->scopeAt(line, column);
}
bool CppRefactoringFile::isCursorOn(unsigned tokenIndex) const
{
QTextCursor tc = cursor();
int cursorBegin = tc.selectionStart();
int start = startOf(tokenIndex);
int end = endOf(tokenIndex);
if (cursorBegin >= start && cursorBegin <= end)
return true;
return false;
}
bool CppRefactoringFile::isCursorOn(const AST *ast) const
{
QTextCursor tc = cursor();
int cursorBegin = tc.selectionStart();
int start = startOf(ast);
int end = endOf(ast);
if (cursorBegin >= start && cursorBegin <= end)
return true;
return false;
}
ChangeSet::Range CppRefactoringFile::range(unsigned tokenIndex) const
{
const Token &token = tokenAt(tokenIndex);
unsigned line, column;
cppDocument()->translationUnit()->getPosition(token.begin(), &line, &column);
const int start = document()->findBlockByNumber(line - 1).position() + column - 1;
return ChangeSet::Range(start, start + token.length());
}
ChangeSet::Range CppRefactoringFile::range(AST *ast) const
{
return ChangeSet::Range(startOf(ast), endOf(ast));
}
int CppRefactoringFile::startOf(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getPosition(tokenAt(index).begin(), &line, &column);
return document()->findBlockByNumber(line - 1).position() + column - 1;
}
int CppRefactoringFile::startOf(const AST *ast) const
{
return startOf(ast->firstToken());
}
int CppRefactoringFile::endOf(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getPosition(tokenAt(index).end(), &line, &column);
return document()->findBlockByNumber(line - 1).position() + column - 1;
}
int CppRefactoringFile::endOf(const AST *ast) const
{
unsigned end = ast->lastToken();
Q_ASSERT(end > 0);
return endOf(end - 1);
}
void CppRefactoringFile::startAndEndOf(unsigned index, int *start, int *end) const
{
unsigned line, column;
Token token(tokenAt(index));
cppDocument()->translationUnit()->getPosition(token.begin(), &line, &column);
*start = document()->findBlockByNumber(line - 1).position() + column - 1;
*end = *start + token.length();
}
QString CppRefactoringFile::textOf(const AST *ast) const
{
return textOf(startOf(ast), endOf(ast));
}
const Token &CppRefactoringFile::tokenAt(unsigned index) const
{
return cppDocument()->translationUnit()->tokenAt(index);
}
CppRefactoringChanges *CppRefactoringFile::refactoringChanges() const
{
return static_cast<CppRefactoringChanges *>(m_refactoringChanges);
}
<commit_msg>Fixed regression in tst_Codegen.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "cpprefactoringchanges.h"
#include <TranslationUnit.h>
#include <AST.h>
#include <cpptools/cppcodeformatter.h>
#include <cpptools/cppmodelmanager.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/tabsettings.h>
#include <QtGui/QTextBlock>
using namespace CPlusPlus;
using namespace CppTools;
using namespace Utils;
CppRefactoringChanges::CppRefactoringChanges(const Snapshot &snapshot)
: m_snapshot(snapshot)
, m_modelManager(Internal::CppModelManager::instance())
{
Q_ASSERT(m_modelManager);
m_workingCopy = m_modelManager->workingCopy();
}
const Snapshot &CppRefactoringChanges::snapshot() const
{
return m_snapshot;
}
CppRefactoringFile CppRefactoringChanges::file(const QString &fileName)
{
return CppRefactoringFile(fileName, this);
}
void CppRefactoringChanges::indentSelection(const QTextCursor &selection) const
{
// ### shares code with CPPEditor::indent()
QTextDocument *doc = selection.document();
QTextBlock block = doc->findBlock(selection.selectionStart());
const QTextBlock end = doc->findBlock(selection.selectionEnd()).next();
const TextEditor::TabSettings &tabSettings(TextEditor::TextEditorSettings::instance()->tabSettings());
CppTools::QtStyleCodeFormatter codeFormatter(tabSettings);
codeFormatter.updateStateUntil(block);
do {
int indent;
int padding;
codeFormatter.indentFor(block, &indent, &padding);
tabSettings.indentLine(block, indent + padding, padding);
codeFormatter.updateLineStateChange(block);
block = block.next();
} while (block.isValid() && block != end);
}
void CppRefactoringChanges::fileChanged(const QString &fileName)
{
m_modelManager->updateSourceFiles(QStringList(fileName));
}
CppRefactoringFile::CppRefactoringFile()
{ }
CppRefactoringFile::CppRefactoringFile(const QString &fileName, CppRefactoringChanges *refactoringChanges)
: RefactoringFile(fileName, refactoringChanges)
{
const Snapshot &snapshot = refactoringChanges->snapshot();
m_cppDocument = snapshot.document(fileName);
}
CppRefactoringFile::CppRefactoringFile(TextEditor::BaseTextEditor *editor, CPlusPlus::Document::Ptr document)
: RefactoringFile()
, m_cppDocument(document)
{
m_fileName = document->fileName();
m_editor = editor;
}
Document::Ptr CppRefactoringFile::cppDocument() const
{
if (!m_cppDocument || !m_cppDocument->translationUnit() ||
!m_cppDocument->translationUnit()->ast()) {
const QString source = document()->toPlainText();
const QString name = fileName();
const Snapshot &snapshot = refactoringChanges()->snapshot();
const QByteArray contents = snapshot.preprocessedCode(source, name);
m_cppDocument = snapshot.documentFromSource(contents, name);
m_cppDocument->check();
}
return m_cppDocument;
}
Scope *CppRefactoringFile::scopeAt(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getTokenStartPosition(index, &line, &column);
return cppDocument()->scopeAt(line, column);
}
bool CppRefactoringFile::isCursorOn(unsigned tokenIndex) const
{
QTextCursor tc = cursor();
int cursorBegin = tc.selectionStart();
int start = startOf(tokenIndex);
int end = endOf(tokenIndex);
if (cursorBegin >= start && cursorBegin <= end)
return true;
return false;
}
bool CppRefactoringFile::isCursorOn(const AST *ast) const
{
QTextCursor tc = cursor();
int cursorBegin = tc.selectionStart();
int start = startOf(ast);
int end = endOf(ast);
if (cursorBegin >= start && cursorBegin <= end)
return true;
return false;
}
ChangeSet::Range CppRefactoringFile::range(unsigned tokenIndex) const
{
const Token &token = tokenAt(tokenIndex);
unsigned line, column;
cppDocument()->translationUnit()->getPosition(token.begin(), &line, &column);
const int start = document()->findBlockByNumber(line - 1).position() + column - 1;
return ChangeSet::Range(start, start + token.length());
}
ChangeSet::Range CppRefactoringFile::range(AST *ast) const
{
return ChangeSet::Range(startOf(ast), endOf(ast));
}
int CppRefactoringFile::startOf(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getPosition(tokenAt(index).begin(), &line, &column);
return document()->findBlockByNumber(line - 1).position() + column - 1;
}
int CppRefactoringFile::startOf(const AST *ast) const
{
return startOf(ast->firstToken());
}
int CppRefactoringFile::endOf(unsigned index) const
{
unsigned line, column;
cppDocument()->translationUnit()->getPosition(tokenAt(index).end(), &line, &column);
return document()->findBlockByNumber(line - 1).position() + column - 1;
}
int CppRefactoringFile::endOf(const AST *ast) const
{
unsigned end = ast->lastToken();
Q_ASSERT(end > 0);
return endOf(end - 1);
}
void CppRefactoringFile::startAndEndOf(unsigned index, int *start, int *end) const
{
unsigned line, column;
Token token(tokenAt(index));
cppDocument()->translationUnit()->getPosition(token.begin(), &line, &column);
*start = document()->findBlockByNumber(line - 1).position() + column - 1;
*end = *start + token.length();
}
QString CppRefactoringFile::textOf(const AST *ast) const
{
return textOf(startOf(ast), endOf(ast));
}
const Token &CppRefactoringFile::tokenAt(unsigned index) const
{
return cppDocument()->translationUnit()->tokenAt(index);
}
CppRefactoringChanges *CppRefactoringFile::refactoringChanges() const
{
return static_cast<CppRefactoringChanges *>(m_refactoringChanges);
}
<|endoftext|>
|
<commit_before>#include "qmljspreviewrunner.h"
#include <projectexplorer/environment.h>
#include <utils/synchronousprocess.h>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QDebug>
namespace QmlJSEditor {
namespace Internal {
QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) :
QObject(parent)
{
// prepend creator/bin dir to search path (only useful for special creator-qml package)
const QString searchPath = QCoreApplication::applicationDirPath()
+ Utils::SynchronousProcess::pathSeparator()
+ QString(qgetenv("PATH"));
m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qml"));
ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment();
m_applicationLauncher.setEnvironment(environment.toStringList());
}
void QmlJSPreviewRunner::run(const QString &filename)
{
QString errorMessage;
if (!filename.isEmpty()) {
m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath,
QStringList() << filename);
} else {
errorMessage = "No file specified.";
}
if (!errorMessage.isEmpty())
QMessageBox::warning(0, tr("Failed to preview Qt Quick file"),
tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage));
}
} // namespace Internal
} // namespace QmlJSEditor
<commit_msg>Fix QtQuick->Preview shortcut to start a qmlviewer<commit_after>#include "qmljspreviewrunner.h"
#include <projectexplorer/environment.h>
#include <utils/synchronousprocess.h>
#include <QtGui/QMessageBox>
#include <QtGui/QApplication>
#include <QDebug>
namespace QmlJSEditor {
namespace Internal {
QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) :
QObject(parent)
{
// prepend creator/bin dir to search path (only useful for special creator-qml package)
const QString searchPath = QCoreApplication::applicationDirPath()
+ Utils::SynchronousProcess::pathSeparator()
+ QString(qgetenv("PATH"));
m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qmlviewer"));
ProjectExplorer::Environment environment = ProjectExplorer::Environment::systemEnvironment();
m_applicationLauncher.setEnvironment(environment.toStringList());
}
void QmlJSPreviewRunner::run(const QString &filename)
{
QString errorMessage;
if (!filename.isEmpty()) {
m_applicationLauncher.start(ProjectExplorer::ApplicationLauncher::Gui, m_qmlViewerDefaultPath,
QStringList() << filename);
} else {
errorMessage = "No file specified.";
}
if (!errorMessage.isEmpty())
QMessageBox::warning(0, tr("Failed to preview Qt Quick file"),
tr("Could not preview Qt Quick (QML) file. Reason: \n%1").arg(errorMessage));
}
} // namespace Internal
} // namespace QmlJSEditor
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012-2015 The SSDB 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 <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include "../util/log.h"
#include "../util/strings.h"
#include "SSDB.h"
void welcome(){
printf("ssdb-split - Split ssdb-server\n");
printf("Copyright (c) 2012-2015 ssdb.io\n");
printf("\n");
}
void usage(int argc, char **argv){
printf("Usage:\n");
printf(" %sr\n", argv[0]);
printf("\n");
printf("Options:\n");
printf(" xx - \n");
}
ssdb::Client *src_client;
ssdb::Client *dst_client;
const int COPY_BATCH_SIZE = 2;
int copy_kv_data(const std::string &start_key, const std::string &end_key);
int main(int argc, char **argv){
welcome();
const char *src_ip = "127.0.0.1";
int src_port = 8888;
const char *dst_ip = "127.0.0.1";
int dst_port = 8889;
src_client = ssdb::Client::connect(src_ip, src_port);
if(src_client == NULL){
printf("fail to connect to src server!\n");
return 0;
}
dst_client = ssdb::Client::connect(dst_ip, dst_port);
if(dst_client == NULL){
printf("fail to connect to dst server!\n");
return 0;
}
std::string start_key;
while(1){
std::vector<std::string> keys;
ssdb::Status s;
s = src_client->keys(start_key, "", COPY_BATCH_SIZE, &keys);
if(!s.ok()){
log_error("response error: %s", s.code().c_str());
break;
}
if(keys.empty()){
break;
}
std::string end_key = keys[keys.size() - 1];
// 1. lock key range in ("", end_key]
log_debug("lock (\"\", \"%s\"] for read", str_escape(end_key).c_str());
// 2. copy keys in range (start_key, end_key]
log_debug("copy (\"%s\", \"%s\"] begin", str_escape(start_key).c_str(), str_escape(end_key).c_str());
int ret = copy_kv_data(start_key, end_key);
if(ret == -1){
log_error("copy error!");
break;
}
log_debug("copy (\"%s\", \"%s\"] end", str_escape(start_key).c_str(), str_escape(end_key).c_str());
start_key = end_key;
}
delete src_client;
delete dst_client;
return 0;
}
int copy_kv_data(const std::string &start_key, const std::string &end_key){
int ret = 0;
ssdb::Status s;
std::string iterate_key_start = start_key;
while(1){
std::vector<std::string> keys;
ssdb::Status s;
s = src_client->keys(iterate_key_start, end_key, COPY_BATCH_SIZE + 100, &keys);
if(!s.ok()){
log_error("response error: %s", s.code().c_str());
return -1;
}
if(keys.empty()){
break;
}
ret += (int)keys.size();
// copy keys one by one, because scan() may exceed max_packet_size
for(int i=0; i<keys.size(); i++){
const std::string &key = keys[i];
std::string val;
s = src_client->get(key, &val);
if(!s.ok()){
log_error("read from src error: %s", s.code().c_str());
return -1;
}
//log_debug("copy %s = %s", key.c_str(), val.c_str());
s = dst_client->set(key, val);
if(!s.ok()){
log_error("write to dst error: %s", s.code().c_str());
return -1;
}
}
iterate_key_start = keys[keys.size() - 1];
if(iterate_key_start == end_key){
break;
}
}
return ret;
}
<commit_msg>update<commit_after>/*
Copyright (c) 2012-2015 The SSDB 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 <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include "../util/log.h"
#include "../util/strings.h"
#include "SSDB.h"
void welcome(){
printf("ssdb-split - Split ssdb-server\n");
printf("Copyright (c) 2012-2015 ssdb.io\n");
printf("\n");
}
void usage(int argc, char **argv){
printf("Usage:\n");
printf(" %sr\n", argv[0]);
printf("\n");
printf("Options:\n");
printf(" xx - \n");
}
ssdb::Client *src_client;
ssdb::Client *dst_client;
const int COPY_BATCH_SIZE = 2;
int copy_kv_data(const std::string &start_key, const std::string &end_key);
int main(int argc, char **argv){
welcome();
const char *src_ip = "127.0.0.1";
int src_port = 8888;
const char *dst_ip = "127.0.0.1";
int dst_port = 8889;
src_client = ssdb::Client::connect(src_ip, src_port);
if(src_client == NULL){
printf("fail to connect to src server!\n");
return 0;
}
dst_client = ssdb::Client::connect(dst_ip, dst_port);
if(dst_client == NULL){
printf("fail to connect to dst server!\n");
return 0;
}
std::string start_key;
std::string end_key;
while(1){
std::vector<std::string> keys;
ssdb::Status s;
start_key = end_key;
s = src_client->keys(start_key, "", COPY_BATCH_SIZE, &keys);
if(!s.ok()){
log_error("response error: %s", s.code().c_str());
break;
}
if(keys.empty()){
break;
}
end_key = keys[keys.size() - 1];
// 0. CLUSTER: log source shrink range
log_debug("lock (\"\", \"%s\"] for read", str_escape(end_key).c_str());
// 1. SOURCE: lock key range ("", end_key] for read
// 2. CLUSTER: copy keys in range (start_key, end_key]
log_debug("copy (\"%s\", \"%s\"] begin", str_escape(start_key).c_str(), str_escape(end_key).c_str());
int ret = copy_kv_data(start_key, end_key);
if(ret == -1){
log_error("copy error!");
break;
}
log_debug("copy (\"%s\", \"%s\"] end", str_escape(start_key).c_str(), str_escape(end_key).c_str());
// 3. CLUSTER: log destination expand range
// 4. DESTINATION: expand range
// 5. SOURCE: delete depricated keys
}
// end. CLUSTER: end splitting
delete src_client;
delete dst_client;
return 0;
}
int copy_kv_data(const std::string &start_key, const std::string &end_key){
int ret = 0;
ssdb::Status s;
std::string iterate_key_start = start_key;
while(1){
std::vector<std::string> keys;
ssdb::Status s;
s = src_client->keys(iterate_key_start, end_key, COPY_BATCH_SIZE + 100, &keys);
if(!s.ok()){
log_error("response error: %s", s.code().c_str());
return -1;
}
if(keys.empty()){
break;
}
ret += (int)keys.size();
// copy keys one by one, because scan() may exceed max_packet_size
for(int i=0; i<keys.size(); i++){
const std::string &key = keys[i];
std::string val;
s = src_client->get(key, &val);
if(!s.ok()){
log_error("read from src error: %s", s.code().c_str());
return -1;
}
//log_debug("copy %s = %s", key.c_str(), val.c_str());
s = dst_client->set(key, val);
if(!s.ok()){
log_error("write to dst error: %s", s.code().c_str());
return -1;
}
}
iterate_key_start = keys[keys.size() - 1];
if(iterate_key_start == end_key){
break;
}
}
return ret;
}
<|endoftext|>
|
<commit_before>#ifndef NANOCV_THREAD_LOOP_H
#define NANOCV_THREAD_LOOP_H
#include "thread_pool.h"
namespace ncv
{
///
/// \brief split a loop computation of the given size using a thread pool
///
template
<
typename tsize,
class toperator
>
void thread_loopi(tsize N, toperator op, thread_pool_t& pool)
{
const tsize n_tasks = static_cast<tsize>(pool.n_workers());
const tsize task_size = N / n_tasks + 1;
for (tsize t = 0; t < n_tasks; t ++)
{
pool.enqueue([=,&op]()
{
for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
{
op(i);
}
});
}
pool.wait();
}
///
/// \brief split a loop computation of the given size using a thread pool
///
template
<
typename tsize,
class toperator
>
void thread_loopit(tsize N, toperator op, thread_pool_t& pool)
{
const tsize n_tasks = static_cast<tsize>(pool.n_workers());
const tsize task_size = N / n_tasks + 1;
for (tsize t = 0; t < n_tasks; t ++)
{
pool.enqueue([=,&op]()
{
for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
{
op(i, t);
}
});
}
pool.wait();
}
///
/// \brief split a loop computation of the given size using multiple threads
///
template
<
typename tsize,
class toperator
>
void thread_loopi(tsize N, toperator op, tsize nthreads = tsize(0))
{
thread_pool_t pool(nthreads);
thread_loopi(N, op, pool);
}
///
/// \brief split a loop computation of the given size using multiple threads
///
template
<
typename tsize,
class toperator
>
void thread_loopit(tsize N, toperator op, tsize nthreads = tsize(0))
{
thread_pool_t pool(nthreads);
thread_loopit(N, op, pool);
}
}
#endif // NANOCV_THREAD_LOOP_H
<commit_msg>comments<commit_after>#ifndef NANOCV_THREAD_LOOP_H
#define NANOCV_THREAD_LOOP_H
#include "thread_pool.h"
namespace ncv
{
///
/// \brief split a loop computation of the given size using a thread pool
/// NB: the operator receives the index of the sample to process: op(i)
///
template
<
typename tsize,
class toperator
>
void thread_loopi(tsize N, toperator op, thread_pool_t& pool)
{
const tsize n_tasks = static_cast<tsize>(pool.n_workers());
const tsize task_size = N / n_tasks + 1;
for (tsize t = 0; t < n_tasks; t ++)
{
pool.enqueue([=,&op]()
{
for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
{
op(i);
}
});
}
pool.wait();
}
///
/// \brief split a loop computation of the given size using a thread pool
/// NB: the operator receives the index of the sample to process and the assigned thread index: op(i, t)
///
template
<
typename tsize,
class toperator
>
void thread_loopit(tsize N, toperator op, thread_pool_t& pool)
{
const tsize n_tasks = static_cast<tsize>(pool.n_workers());
const tsize task_size = N / n_tasks + 1;
for (tsize t = 0; t < n_tasks; t ++)
{
pool.enqueue([=,&op]()
{
for (tsize i = t * task_size, iend = std::min(i + task_size, N); i < iend; i ++)
{
op(i, t);
}
});
}
pool.wait();
}
///
/// \brief split a loop computation of the given size using multiple threads
///
template
<
typename tsize,
class toperator
>
void thread_loopi(tsize N, toperator op, tsize nthreads = tsize(0))
{
thread_pool_t pool(nthreads);
thread_loopi(N, op, pool);
}
///
/// \brief split a loop computation of the given size using multiple threads
///
template
<
typename tsize,
class toperator
>
void thread_loopit(tsize N, toperator op, tsize nthreads = tsize(0))
{
thread_pool_t pool(nthreads);
thread_loopit(N, op, pool);
}
}
#endif // NANOCV_THREAD_LOOP_H
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <vector>
#include <Support/CmdLine.h>
#include <Support/CmdLineUtil.h>
#include "input/keyboard.h"
#include "input/mouse.h"
#include "manip/camera_manipulator.h"
#include "viewer_base.h"
using namespace support;
using namespace visionaray;
using manipulators = std::vector<std::shared_ptr<camera_manipulator>>;
using cmdline_options = std::vector<std::shared_ptr<cl::OptionBase>>;
struct viewer_base::impl
{
manipulators manips;
cmdline_options options;
cl::CmdLine cmd;
bool full_screen = false;
int width = 512;
int height = 512;
std::string window_title = "";
vec3 bgcolor = { 0.1f, 0.4f, 1.0f };
impl(int width, int height, std::string window_title);
void init(int argc, char** argv);
void parse_cmd_line(int argc, char** argv);
};
viewer_base::impl::impl(int width, int height, std::string window_title)
: width(width)
, height(height)
, window_title(window_title)
{
// add default options (-fullscreen, -width, -height, -bgcolor)
options.emplace_back( cl::makeOption<bool&>(
cl::Parser<>(),
"fullscreen",
cl::Desc("Full screen window"),
cl::ArgDisallowed,
cl::init(viewer_base::impl::full_screen)
) );
options.emplace_back( cl::makeOption<int&>(
cl::Parser<>(),
"width",
cl::Desc("Window width"),
cl::ArgRequired,
cl::init(viewer_base::impl::width)
) );
options.emplace_back( cl::makeOption<int&>(
cl::Parser<>(),
"height",
cl::Desc("Window height"),
cl::ArgRequired,
cl::init(viewer_base::impl::height)
) );
options.emplace_back( cl::makeOption<vec3&, cl::ScalarType>(
[&](StringRef name, StringRef /*arg*/, vec3& value)
{
cl::Parser<>()(name + "-r", cmd.bump(), value.x);
cl::Parser<>()(name + "-g", cmd.bump(), value.y);
cl::Parser<>()(name + "-b", cmd.bump(), value.z);
},
"bgcolor",
cl::Desc("Background color"),
cl::ArgDisallowed,
cl::init(viewer_base::impl::bgcolor)
) );
}
void viewer_base::impl::init(int argc, char** argv)
{
parse_cmd_line(argc, argv);
}
//-------------------------------------------------------------------------------------------------
// Parse default command line options
//
void viewer_base::impl::parse_cmd_line(int argc, char** argv)
{
for (auto& opt : options)
{
cmd.add(*opt);
}
auto args = std::vector<std::string>(argv + 1, argv + argc);
cl::expandWildcards(args);
cl::expandResponseFiles(args, cl::TokenizeUnix());
cmd.parse(args);
}
viewer_base::viewer_base(
int width,
int height,
std::string window_title
)
: impl_(new impl(width, height, window_title))
{
}
viewer_base::~viewer_base()
{
}
void viewer_base::init(int argc, char** argv)
{
impl_->init(argc, argv);
}
void viewer_base::add_manipulator( std::shared_ptr<camera_manipulator> manip )
{
impl_->manips.push_back(manip);
}
void viewer_base::add_cmdline_option( std::shared_ptr<cl::OptionBase> option )
{
impl_->options.emplace_back(option);
}
std::string viewer_base::window_title() const
{
return impl_->window_title;
}
bool viewer_base::full_screen() const
{
return impl_->full_screen;
}
int viewer_base::width() const
{
return impl_->width;
}
int viewer_base::height() const
{
return impl_->height;
}
vec3 viewer_base::background_color() const
{
return impl_->bgcolor;
}
void viewer_base::event_loop()
{
}
void viewer_base::resize(int width, int height)
{
impl_->width = width;
impl_->height = height;
}
void viewer_base::toggle_full_screen()
{
impl_->full_screen = !impl_->full_screen;
}
//-------------------------------------------------------------------------------------------------
// Event handlers
//
void viewer_base::on_display()
{
}
void viewer_base::on_idle()
{
}
void viewer_base::on_key_press(visionaray::key_event const& event)
{
if (event.key() == keyboard::F5)
{
toggle_full_screen();
}
if (event.key() == keyboard::Escape && impl_->full_screen)
{
toggle_full_screen();
}
for (auto& manip : impl_->manips)
{
manip->handle_key_press(event);
}
}
void viewer_base::on_key_release(visionaray::key_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_key_release(event);
}
}
void viewer_base::on_mouse_move(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_move(event);
}
}
void viewer_base::on_mouse_down(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_down(event);
}
}
void viewer_base::on_mouse_up(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_up(event);
}
}
void viewer_base::on_resize(int w, int h)
{
glViewport(0, 0, w, h);
}
<commit_msg>Update width and height when viewer gets resized<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <vector>
#include <Support/CmdLine.h>
#include <Support/CmdLineUtil.h>
#include "input/keyboard.h"
#include "input/mouse.h"
#include "manip/camera_manipulator.h"
#include "viewer_base.h"
using namespace support;
using namespace visionaray;
using manipulators = std::vector<std::shared_ptr<camera_manipulator>>;
using cmdline_options = std::vector<std::shared_ptr<cl::OptionBase>>;
struct viewer_base::impl
{
manipulators manips;
cmdline_options options;
cl::CmdLine cmd;
bool full_screen = false;
int width = 512;
int height = 512;
std::string window_title = "";
vec3 bgcolor = { 0.1f, 0.4f, 1.0f };
impl(int width, int height, std::string window_title);
void init(int argc, char** argv);
void parse_cmd_line(int argc, char** argv);
};
viewer_base::impl::impl(int width, int height, std::string window_title)
: width(width)
, height(height)
, window_title(window_title)
{
// add default options (-fullscreen, -width, -height, -bgcolor)
options.emplace_back( cl::makeOption<bool&>(
cl::Parser<>(),
"fullscreen",
cl::Desc("Full screen window"),
cl::ArgDisallowed,
cl::init(viewer_base::impl::full_screen)
) );
options.emplace_back( cl::makeOption<int&>(
cl::Parser<>(),
"width",
cl::Desc("Window width"),
cl::ArgRequired,
cl::init(viewer_base::impl::width)
) );
options.emplace_back( cl::makeOption<int&>(
cl::Parser<>(),
"height",
cl::Desc("Window height"),
cl::ArgRequired,
cl::init(viewer_base::impl::height)
) );
options.emplace_back( cl::makeOption<vec3&, cl::ScalarType>(
[&](StringRef name, StringRef /*arg*/, vec3& value)
{
cl::Parser<>()(name + "-r", cmd.bump(), value.x);
cl::Parser<>()(name + "-g", cmd.bump(), value.y);
cl::Parser<>()(name + "-b", cmd.bump(), value.z);
},
"bgcolor",
cl::Desc("Background color"),
cl::ArgDisallowed,
cl::init(viewer_base::impl::bgcolor)
) );
}
void viewer_base::impl::init(int argc, char** argv)
{
parse_cmd_line(argc, argv);
}
//-------------------------------------------------------------------------------------------------
// Parse default command line options
//
void viewer_base::impl::parse_cmd_line(int argc, char** argv)
{
for (auto& opt : options)
{
cmd.add(*opt);
}
auto args = std::vector<std::string>(argv + 1, argv + argc);
cl::expandWildcards(args);
cl::expandResponseFiles(args, cl::TokenizeUnix());
cmd.parse(args);
}
viewer_base::viewer_base(
int width,
int height,
std::string window_title
)
: impl_(new impl(width, height, window_title))
{
}
viewer_base::~viewer_base()
{
}
void viewer_base::init(int argc, char** argv)
{
impl_->init(argc, argv);
}
void viewer_base::add_manipulator( std::shared_ptr<camera_manipulator> manip )
{
impl_->manips.push_back(manip);
}
void viewer_base::add_cmdline_option( std::shared_ptr<cl::OptionBase> option )
{
impl_->options.emplace_back(option);
}
std::string viewer_base::window_title() const
{
return impl_->window_title;
}
bool viewer_base::full_screen() const
{
return impl_->full_screen;
}
int viewer_base::width() const
{
return impl_->width;
}
int viewer_base::height() const
{
return impl_->height;
}
vec3 viewer_base::background_color() const
{
return impl_->bgcolor;
}
void viewer_base::event_loop()
{
}
void viewer_base::resize(int width, int height)
{
impl_->width = width;
impl_->height = height;
}
void viewer_base::toggle_full_screen()
{
impl_->full_screen = !impl_->full_screen;
}
//-------------------------------------------------------------------------------------------------
// Event handlers
//
void viewer_base::on_display()
{
}
void viewer_base::on_idle()
{
}
void viewer_base::on_key_press(visionaray::key_event const& event)
{
if (event.key() == keyboard::F5)
{
toggle_full_screen();
}
if (event.key() == keyboard::Escape && impl_->full_screen)
{
toggle_full_screen();
}
for (auto& manip : impl_->manips)
{
manip->handle_key_press(event);
}
}
void viewer_base::on_key_release(visionaray::key_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_key_release(event);
}
}
void viewer_base::on_mouse_move(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_move(event);
}
}
void viewer_base::on_mouse_down(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_down(event);
}
}
void viewer_base::on_mouse_up(visionaray::mouse_event const& event)
{
for (auto& manip : impl_->manips)
{
manip->handle_mouse_up(event);
}
}
void viewer_base::on_resize(int w, int h)
{
impl_->width = w;
impl_->height = h;
glViewport(0, 0, w, h);
}
<|endoftext|>
|
<commit_before>#include "components/builder.hpp"
#include "utils/math.hpp"
#include "utils/string.hpp"
POLYBAR_NS
void builder::set_lazy(bool mode) {
m_lazy = mode;
}
string builder::flush() {
if (m_lazy) {
while (m_counters[syntaxtag::A] > 0) cmd_close(true);
while (m_counters[syntaxtag::B] > 0) background_close(true);
while (m_counters[syntaxtag::F] > 0) color_close(true);
while (m_counters[syntaxtag::T] > 0) font_close(true);
while (m_counters[syntaxtag::U] > 0) line_color_close(true);
while (m_counters[syntaxtag::u] > 0) underline_close(true);
while (m_counters[syntaxtag::o] > 0) overline_close(true);
}
string output = m_output.data();
// reset values
m_output.clear();
for (auto& counter : m_counters) counter.second = 0;
for (auto& value : m_colors) value.second = "";
m_fontindex = 1;
return string_util::replace_all(output, string{BUILDER_SPACE_TOKEN}, " ");
}
void builder::append(string text) {
string str(text);
auto len = str.length();
if (len > 2 && str[0] == '"' && str[len - 1] == '"')
m_output += str.substr(1, len - 2);
else
m_output += str;
}
void builder::node(string str, bool add_space) {
string::size_type n, m;
string s(str);
while (true) {
if (s.empty()) {
break;
} else if ((n = s.find("%{F-}")) == 0) {
color_close(!m_lazy);
s.erase(0, 5);
} else if ((n = s.find("%{F#")) == 0 && (m = s.find("}")) != string::npos) {
if (m - n - 4 == 2)
color_alpha(s.substr(n + 3, m - 3));
else
color(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{B-}")) == 0) {
background_close(!m_lazy);
s.erase(0, 5);
} else if ((n = s.find("%{B#")) == 0 && (m = s.find("}")) != string::npos) {
background(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{T-}")) == 0) {
font_close(!m_lazy);
s.erase(0, 5);
} else if ((n = s.find("%{T")) == 0 && (m = s.find("}")) != string::npos) {
font(std::atoi(s.substr(n + 3, m - 3).c_str()));
s.erase(n, m + 1);
} else if ((n = s.find("%{U-}")) == 0) {
line_color_close(!m_lazy);
s.erase(0, 5);
} else if ((n = s.find("%{U#")) == 0 && (m = s.find("}")) != string::npos) {
line_color(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{+u}")) == 0) {
underline();
s.erase(0, 5);
} else if ((n = s.find("%{+o}")) == 0) {
overline();
s.erase(0, 5);
} else if ((n = s.find("%{-u}")) == 0) {
underline_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{-o}")) == 0) {
overline_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{A}")) == 0) {
cmd_close(true);
s.erase(0, 4);
} else if ((n = s.find("%{")) == 0 && (m = s.find("}")) != string::npos) {
append(s.substr(n, m + 1));
s.erase(n, m + 1);
} else if ((n = s.find("%{")) > 0) {
append(s.substr(0, n));
s.erase(0, n);
} else
break;
}
if (!s.empty())
append(s);
if (add_space)
space();
}
void builder::node(string str, int font_index, bool add_space) {
font(font_index);
node(str, add_space);
font_close();
}
// void builder::node(progressbar_t bar, float perc, bool add_space) {
// if (!bar)
// return;
// node(bar->get_output(math_util::cap<float>(0, 100, perc)), add_space);
// }
void builder::node(label_t label, bool add_space) {
if (!label || !*label)
return;
auto text = label->get();
if (label->m_maxlen > 0 && text.length() > label->m_maxlen) {
text = text.substr(0, label->m_maxlen) + "...";
}
if ((label->m_overline.empty() && m_counters[syntaxtag::o] > 0) ||
(m_counters[syntaxtag::o] > 0 && label->m_margin > 0))
overline_close(true);
if ((label->m_underline.empty() && m_counters[syntaxtag::u] > 0) ||
(m_counters[syntaxtag::u] > 0 && label->m_margin > 0))
underline_close(true);
if (label->m_margin > 0)
space(label->m_margin);
if (!label->m_overline.empty())
overline(label->m_overline);
if (!label->m_underline.empty())
underline(label->m_underline);
background(label->m_background);
color(label->m_foreground);
if (label->m_padding > 0)
space(label->m_padding);
node(text, label->m_font, add_space);
if (label->m_padding > 0)
space(label->m_padding);
color_close(m_lazy && label->m_margin > 0);
background_close(m_lazy && label->m_margin > 0);
if (!label->m_underline.empty() || (label->m_margin > 0 && m_counters[syntaxtag::u] > 0))
underline_close(m_lazy && label->m_margin > 0);
if (!label->m_overline.empty() || (label->m_margin > 0 && m_counters[syntaxtag::o] > 0))
overline_close(m_lazy && label->m_margin > 0);
if (label->m_margin > 0)
space(label->m_margin);
}
// void builder::node(ramp_t ramp, float perc, bool add_space) {
// if (!ramp)
// return;
// node(ramp->get_by_percentage(math_util::cap<float>(0, 100, perc)), add_space);
// }
// void builder::node(animation_t animation, bool add_space) {
// if (!animation)
// return;
// node(animation->get(), add_space);
// }
void builder::offset(int pixels) {
if (pixels != 0)
tag_open('O', std::to_string(pixels));
}
void builder::space(int width) {
if (width == DEFAULT_SPACING)
width = m_bar.spacing;
if (width <= 0)
return;
string str(width, ' ');
append(str);
}
void builder::remove_trailing_space(int width) {
if (width == DEFAULT_SPACING)
width = m_bar.spacing;
if (width <= 0)
return;
string::size_type spacing = width;
string str(spacing, ' ');
if (m_output.length() >= spacing && m_output.substr(m_output.length() - spacing) == str)
m_output = m_output.substr(0, m_output.length() - spacing);
}
void builder::invert() {
tag_open('R', "");
}
void builder::font(int index) {
if (index <= 0 && m_counters[syntaxtag::T] > 0)
font_close(true);
if (index <= 0 || index == m_fontindex)
return;
if (m_lazy && m_counters[syntaxtag::T] > 0)
font_close(true);
m_counters[syntaxtag::T]++;
m_fontindex = index;
tag_open('T', std::to_string(index));
}
void builder::font_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::T] <= 0)
return;
m_counters[syntaxtag::T]--;
m_fontindex = 1;
tag_close('T');
}
void builder::background(string color) {
if (color.length() == 2 || (color.find("#") == 0 && color.length() == 3)) {
color = "#" + color.substr(color.length() - 2);
auto bg = m_bar.background.source();
color += bg.substr(bg.length() - (bg.length() < 6 ? 3 : 6));
} else if (color.length() >= 7 && color == "#" + string(color.length() - 1, color[1])) {
color = color.substr(0, 4);
}
if (color.empty() && m_counters[syntaxtag::B] > 0)
background_close(true);
if (color.empty() || color == m_colors[syntaxtag::B])
return;
if (m_lazy && m_counters[syntaxtag::B] > 0)
background_close(true);
m_counters[syntaxtag::B]++;
m_colors[syntaxtag::B] = color;
tag_open('B', color);
}
void builder::background_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::B] <= 0)
return;
m_counters[syntaxtag::B]--;
m_colors[syntaxtag::B] = "";
tag_close('B');
}
void builder::color(string color_) {
auto color(color_);
if (color.length() == 2 || (color.find("#") == 0 && color.length() == 3)) {
color = "#" + color.substr(color.length() - 2);
auto fg = m_bar.foreground.source();
color += fg.substr(fg.length() - (fg.length() < 6 ? 3 : 6));
} else if (color.length() >= 7 && color == "#" + string(color.length() - 1, color[1])) {
color = color.substr(0, 4);
}
if (color.empty() && m_counters[syntaxtag::F] > 0)
color_close(true);
if (color.empty() || color == m_colors[syntaxtag::F])
return;
if (m_lazy && m_counters[syntaxtag::F] > 0)
color_close(true);
m_counters[syntaxtag::F]++;
m_colors[syntaxtag::F] = color;
tag_open('F', color);
}
void builder::color_alpha(string alpha_) {
auto alpha(alpha_);
string val = m_bar.foreground.source();
if (alpha.find("#") == std::string::npos) {
alpha = "#" + alpha;
}
if (alpha.size() == 4) {
color(alpha);
return;
}
if (val.size() < 6 && val.size() > 2) {
val.append(val.substr(val.size() - 3));
}
color((alpha.substr(0, 3) + val.substr(val.size() - 6)).substr(0, 9));
}
void builder::color_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::F] <= 0)
return;
m_counters[syntaxtag::F]--;
m_colors[syntaxtag::F] = "";
tag_close('F');
}
void builder::line_color(string color) {
if (color.empty() && m_counters[syntaxtag::U] > 0)
line_color_close(true);
if (color.empty() || color == m_colors[syntaxtag::U])
return;
if (m_lazy && m_counters[syntaxtag::U] > 0)
line_color_close(true);
m_counters[syntaxtag::U]++;
m_colors[syntaxtag::U] = color;
tag_open('U', color);
}
void builder::line_color_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::U] <= 0)
return;
m_counters[syntaxtag::U]--;
m_colors[syntaxtag::U] = "";
tag_close('U');
}
void builder::overline(string color) {
if (!color.empty())
line_color(color);
if (m_counters[syntaxtag::o] > 0)
return;
m_counters[syntaxtag::o]++;
append("%{+o}");
}
void builder::overline_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::o] <= 0)
return;
m_counters[syntaxtag::o]--;
append("%{-o}");
}
void builder::underline(string color) {
if (!color.empty())
line_color(color);
if (m_counters[syntaxtag::u] > 0)
return;
m_counters[syntaxtag::u]++;
append("%{+u}");
}
void builder::underline_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::u] <= 0)
return;
m_counters[syntaxtag::u]--;
append("%{-u}");
}
void builder::cmd(mousebtn index, string action, bool condition) {
int button = static_cast<int>(index);
if (!condition || action.empty())
return;
action = string_util::replace_all(action, ":", "\\:");
action = string_util::replace_all(action, "$", "\\$");
action = string_util::replace_all(action, "}", "\\}");
action = string_util::replace_all(action, "{", "\\{");
action = string_util::replace_all(action, "%", "\x0025");
append("%{A" + std::to_string(button) + ":" + action + ":}");
m_counters[syntaxtag::A]++;
}
void builder::cmd_close(bool force) {
if (m_counters[syntaxtag::A] > 0 || force)
append("%{A}");
if (m_counters[syntaxtag::A] > 0)
m_counters[syntaxtag::A]--;
}
void builder::tag_open(char tag, string value) {
append("%{" + string({tag}) + value + "}");
}
void builder::tag_close(char tag) {
append("%{" + string({tag}) + "-}");
}
POLYBAR_NS_END
<commit_msg>fix(builder): Always close raw syntax tags<commit_after>#include "components/builder.hpp"
#include "utils/math.hpp"
#include "utils/string.hpp"
POLYBAR_NS
void builder::set_lazy(bool mode) {
m_lazy = mode;
}
string builder::flush() {
if (m_lazy) {
while (m_counters[syntaxtag::A] > 0) cmd_close(true);
while (m_counters[syntaxtag::B] > 0) background_close(true);
while (m_counters[syntaxtag::F] > 0) color_close(true);
while (m_counters[syntaxtag::T] > 0) font_close(true);
while (m_counters[syntaxtag::U] > 0) line_color_close(true);
while (m_counters[syntaxtag::u] > 0) underline_close(true);
while (m_counters[syntaxtag::o] > 0) overline_close(true);
}
string output = m_output.data();
// reset values
m_output.clear();
for (auto& counter : m_counters) counter.second = 0;
for (auto& value : m_colors) value.second = "";
m_fontindex = 1;
return string_util::replace_all(output, string{BUILDER_SPACE_TOKEN}, " ");
}
void builder::append(string text) {
string str(text);
auto len = str.length();
if (len > 2 && str[0] == '"' && str[len - 1] == '"')
m_output += str.substr(1, len - 2);
else
m_output += str;
}
void builder::node(string str, bool add_space) {
string::size_type n, m;
string s(str);
while (true) {
if (s.empty()) {
break;
} else if ((n = s.find("%{F-}")) == 0) {
color_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{F#")) == 0 && (m = s.find("}")) != string::npos) {
if (m - n - 4 == 2)
color_alpha(s.substr(n + 3, m - 3));
else
color(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{B-}")) == 0) {
background_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{B#")) == 0 && (m = s.find("}")) != string::npos) {
background(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{T-}")) == 0) {
font_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{T")) == 0 && (m = s.find("}")) != string::npos) {
font(std::atoi(s.substr(n + 3, m - 3).c_str()));
s.erase(n, m + 1);
} else if ((n = s.find("%{U-}")) == 0) {
line_color_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{U#")) == 0 && (m = s.find("}")) != string::npos) {
line_color(s.substr(n + 3, m - 3));
s.erase(n, m + 1);
} else if ((n = s.find("%{+u}")) == 0) {
underline();
s.erase(0, 5);
} else if ((n = s.find("%{+o}")) == 0) {
overline();
s.erase(0, 5);
} else if ((n = s.find("%{-u}")) == 0) {
underline_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{-o}")) == 0) {
overline_close(true);
s.erase(0, 5);
} else if ((n = s.find("%{A}")) == 0) {
cmd_close(true);
s.erase(0, 4);
} else if ((n = s.find("%{")) == 0 && (m = s.find("}")) != string::npos) {
append(s.substr(n, m + 1));
s.erase(n, m + 1);
} else if ((n = s.find("%{")) > 0) {
append(s.substr(0, n));
s.erase(0, n);
} else
break;
}
if (!s.empty())
append(s);
if (add_space)
space();
}
void builder::node(string str, int font_index, bool add_space) {
font(font_index);
node(str, add_space);
font_close();
}
// void builder::node(progressbar_t bar, float perc, bool add_space) {
// if (!bar)
// return;
// node(bar->get_output(math_util::cap<float>(0, 100, perc)), add_space);
// }
void builder::node(label_t label, bool add_space) {
if (!label || !*label)
return;
auto text = label->get();
if (label->m_maxlen > 0 && text.length() > label->m_maxlen) {
text = text.substr(0, label->m_maxlen) + "...";
}
if ((label->m_overline.empty() && m_counters[syntaxtag::o] > 0) ||
(m_counters[syntaxtag::o] > 0 && label->m_margin > 0))
overline_close(true);
if ((label->m_underline.empty() && m_counters[syntaxtag::u] > 0) ||
(m_counters[syntaxtag::u] > 0 && label->m_margin > 0))
underline_close(true);
if (label->m_margin > 0)
space(label->m_margin);
if (!label->m_overline.empty())
overline(label->m_overline);
if (!label->m_underline.empty())
underline(label->m_underline);
background(label->m_background);
color(label->m_foreground);
if (label->m_padding > 0)
space(label->m_padding);
node(text, label->m_font, add_space);
if (label->m_padding > 0)
space(label->m_padding);
color_close(m_lazy && label->m_margin > 0);
background_close(m_lazy && label->m_margin > 0);
if (!label->m_underline.empty() || (label->m_margin > 0 && m_counters[syntaxtag::u] > 0))
underline_close(m_lazy && label->m_margin > 0);
if (!label->m_overline.empty() || (label->m_margin > 0 && m_counters[syntaxtag::o] > 0))
overline_close(m_lazy && label->m_margin > 0);
if (label->m_margin > 0)
space(label->m_margin);
}
// void builder::node(ramp_t ramp, float perc, bool add_space) {
// if (!ramp)
// return;
// node(ramp->get_by_percentage(math_util::cap<float>(0, 100, perc)), add_space);
// }
// void builder::node(animation_t animation, bool add_space) {
// if (!animation)
// return;
// node(animation->get(), add_space);
// }
void builder::offset(int pixels) {
if (pixels != 0)
tag_open('O', std::to_string(pixels));
}
void builder::space(int width) {
if (width == DEFAULT_SPACING)
width = m_bar.spacing;
if (width <= 0)
return;
string str(width, ' ');
append(str);
}
void builder::remove_trailing_space(int width) {
if (width == DEFAULT_SPACING)
width = m_bar.spacing;
if (width <= 0)
return;
string::size_type spacing = width;
string str(spacing, ' ');
if (m_output.length() >= spacing && m_output.substr(m_output.length() - spacing) == str)
m_output = m_output.substr(0, m_output.length() - spacing);
}
void builder::invert() {
tag_open('R', "");
}
void builder::font(int index) {
if (index <= 0 && m_counters[syntaxtag::T] > 0)
font_close(true);
if (index <= 0 || index == m_fontindex)
return;
if (m_lazy && m_counters[syntaxtag::T] > 0)
font_close(true);
m_counters[syntaxtag::T]++;
m_fontindex = index;
tag_open('T', std::to_string(index));
}
void builder::font_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::T] <= 0)
return;
m_counters[syntaxtag::T]--;
m_fontindex = 1;
tag_close('T');
}
void builder::background(string color) {
if (color.length() == 2 || (color.find("#") == 0 && color.length() == 3)) {
color = "#" + color.substr(color.length() - 2);
auto bg = m_bar.background.source();
color += bg.substr(bg.length() - (bg.length() < 6 ? 3 : 6));
} else if (color.length() >= 7 && color == "#" + string(color.length() - 1, color[1])) {
color = color.substr(0, 4);
}
if (color.empty() && m_counters[syntaxtag::B] > 0)
background_close(true);
if (color.empty() || color == m_colors[syntaxtag::B])
return;
if (m_lazy && m_counters[syntaxtag::B] > 0)
background_close(true);
m_counters[syntaxtag::B]++;
m_colors[syntaxtag::B] = color;
tag_open('B', color);
}
void builder::background_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::B] <= 0)
return;
m_counters[syntaxtag::B]--;
m_colors[syntaxtag::B] = "";
tag_close('B');
}
void builder::color(string color_) {
auto color(color_);
if (color.length() == 2 || (color.find("#") == 0 && color.length() == 3)) {
color = "#" + color.substr(color.length() - 2);
auto fg = m_bar.foreground.source();
color += fg.substr(fg.length() - (fg.length() < 6 ? 3 : 6));
} else if (color.length() >= 7 && color == "#" + string(color.length() - 1, color[1])) {
color = color.substr(0, 4);
}
if (color.empty() && m_counters[syntaxtag::F] > 0)
color_close(true);
if (color.empty() || color == m_colors[syntaxtag::F])
return;
if (m_lazy && m_counters[syntaxtag::F] > 0)
color_close(true);
m_counters[syntaxtag::F]++;
m_colors[syntaxtag::F] = color;
tag_open('F', color);
}
void builder::color_alpha(string alpha_) {
auto alpha(alpha_);
string val = m_bar.foreground.source();
if (alpha.find("#") == std::string::npos) {
alpha = "#" + alpha;
}
if (alpha.size() == 4) {
color(alpha);
return;
}
if (val.size() < 6 && val.size() > 2) {
val.append(val.substr(val.size() - 3));
}
color((alpha.substr(0, 3) + val.substr(val.size() - 6)).substr(0, 9));
}
void builder::color_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::F] <= 0)
return;
m_counters[syntaxtag::F]--;
m_colors[syntaxtag::F] = "";
tag_close('F');
}
void builder::line_color(string color) {
if (color.empty() && m_counters[syntaxtag::U] > 0)
line_color_close(true);
if (color.empty() || color == m_colors[syntaxtag::U])
return;
if (m_lazy && m_counters[syntaxtag::U] > 0)
line_color_close(true);
m_counters[syntaxtag::U]++;
m_colors[syntaxtag::U] = color;
tag_open('U', color);
}
void builder::line_color_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::U] <= 0)
return;
m_counters[syntaxtag::U]--;
m_colors[syntaxtag::U] = "";
tag_close('U');
}
void builder::overline(string color) {
if (!color.empty())
line_color(color);
if (m_counters[syntaxtag::o] > 0)
return;
m_counters[syntaxtag::o]++;
append("%{+o}");
}
void builder::overline_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::o] <= 0)
return;
m_counters[syntaxtag::o]--;
append("%{-o}");
}
void builder::underline(string color) {
if (!color.empty())
line_color(color);
if (m_counters[syntaxtag::u] > 0)
return;
m_counters[syntaxtag::u]++;
append("%{+u}");
}
void builder::underline_close(bool force) {
if ((!force && m_lazy) || m_counters[syntaxtag::u] <= 0)
return;
m_counters[syntaxtag::u]--;
append("%{-u}");
}
void builder::cmd(mousebtn index, string action, bool condition) {
int button = static_cast<int>(index);
if (!condition || action.empty())
return;
action = string_util::replace_all(action, ":", "\\:");
action = string_util::replace_all(action, "$", "\\$");
action = string_util::replace_all(action, "}", "\\}");
action = string_util::replace_all(action, "{", "\\{");
action = string_util::replace_all(action, "%", "\x0025");
append("%{A" + std::to_string(button) + ":" + action + ":}");
m_counters[syntaxtag::A]++;
}
void builder::cmd_close(bool force) {
if (m_counters[syntaxtag::A] > 0 || force)
append("%{A}");
if (m_counters[syntaxtag::A] > 0)
m_counters[syntaxtag::A]--;
}
void builder::tag_open(char tag, string value) {
append("%{" + string({tag}) + value + "}");
}
void builder::tag_close(char tag) {
append("%{" + string({tag}) + "-}");
}
POLYBAR_NS_END
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cpp3ds/Audio/Sound.hpp>
#include <cpp3ds/Audio/SoundBuffer.hpp>
#include <3ds.h>
#include <string.h>
#include <cpp3ds/System/Err.hpp>
#include <cpp3ds/System/Lock.hpp>
namespace cpp3ds
{
////////////////////////////////////////////////////////////
Sound::Sound()
: m_buffer(nullptr)
, m_loop(false)
, m_isADPCM(false)
{
}
////////////////////////////////////////////////////////////
Sound::Sound(const SoundBuffer& buffer)
: m_buffer(nullptr)
, m_loop(false)
, m_isADPCM(false)
{
setBuffer(buffer);
}
////////////////////////////////////////////////////////////
Sound::Sound(const Sound& copy)
: SoundSource(copy)
, m_buffer(nullptr)
{
if (copy.m_buffer)
setBuffer(*copy.m_buffer);
setLoop(copy.getLoop());
setStateADPCM(copy.getStateADPCM());
}
////////////////////////////////////////////////////////////
Sound::~Sound()
{
stop();
if (m_buffer)
m_buffer->detachSound(this);
}
////////////////////////////////////////////////////////////
void Sound::play()
{
if (!m_buffer || m_buffer->getSampleCount() == 0)
return;
if (getStatus() == Playing)
stop();
if (getStatus() == Paused) {
ndspChnSetPaused(m_channel, false);
return;
}
{
Lock lock(g_activeNdspChannelsMutex);
m_channel = 0;
while (m_channel < 24 && ((g_activeNdspChannels >> m_channel) & 1))
m_channel++;
if (m_channel == 24) {
err() << "Failed to play audio stream: all channels are in use." << std::endl;
m_channel = -1;
return;
}
g_activeNdspChannels |= 1 << m_channel;
}
setPlayingOffset(Time::Zero);
u32 size = sizeof(Int16) * m_buffer->getSampleCount();
ndspChnReset(m_channel);
ndspChnSetInterp(m_channel, NDSP_INTERP_POLYPHASE);
ndspChnSetRate(m_channel, float(m_buffer->getSampleRate()));
ndspChnSetFormat(m_channel, (m_buffer->getChannelCount() == 1) ? NDSP_FORMAT_MONO_PCM16 : NDSP_FORMAT_STEREO_PCM16);
DSP_FlushDataCache(m_buffer->getSamples(), size);
ndspChnWaveBufAdd(m_channel, &m_ndspWaveBuf);
}
////////////////////////////////////////////////////////////
void Sound::pause()
{
if (getStatus() != Playing)
return;
ndspChnSetPaused(m_channel, true);
}
////////////////////////////////////////////////////////////
void Sound::stop()
{
if (getStatus() == Stopped)
return;
ndspChnWaveBufClear(m_channel);
{
Lock lock(g_activeNdspChannelsMutex);
g_activeNdspChannels &= ~(1 << m_channel);
m_channel = -1;
}
}
////////////////////////////////////////////////////////////
void Sound::setBuffer(const SoundBuffer& buffer)
{
// First detach from the previous buffer
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
}
memset(&m_ndspWaveBuf, 0, sizeof(ndspWaveBuf));
m_ndspWaveBuf.data_vaddr = buffer.getSamples();
m_ndspWaveBuf.nsamples = buffer.getSampleCount() / buffer.getChannelCount();
m_ndspWaveBuf.looping = m_loop; // Loop enabled
m_ndspWaveBuf.status = NDSP_WBUF_FREE;
// Assign and use the new buffer
m_buffer = &buffer;
m_buffer->attachSound(this);
}
////////////////////////////////////////////////////////////
void Sound::setStateADPCM(bool enable)
{
m_isADPCM = enable;
}
////////////////////////////////////////////////////////////
bool Sound::getStateADPCM() const
{
return m_isADPCM;
}
////////////////////////////////////////////////////////////
void Sound::setLoop(bool loop)
{
m_loop = loop;
m_ndspWaveBuf.looping = m_loop;
}
////////////////////////////////////////////////////////////
void Sound::setPlayingOffset(Time timeOffset)
{
Status status = getStatus();
stop();
m_playOffset = timeOffset;
int offset = m_buffer->getSampleRate() * m_buffer->getChannelCount() * timeOffset.asSeconds();
m_ndspWaveBuf.data_vaddr = m_buffer->getSamples() + offset;
m_ndspWaveBuf.nsamples = m_buffer->getSampleCount() / m_buffer->getChannelCount() - offset;
if (status == Playing)
ndspChnWaveBufAdd(m_channel, &m_ndspWaveBuf);
}
////////////////////////////////////////////////////////////
const SoundBuffer* Sound::getBuffer() const
{
return m_buffer;
}
////////////////////////////////////////////////////////////
bool Sound::getLoop() const
{
return m_loop;
}
////////////////////////////////////////////////////////////
Time Sound::getPlayingOffset() const
{
if (getStatus() == Stopped)
return Time::Zero;
u32 samplePos = ndspChnGetSamplePos(m_channel);
return seconds(static_cast<float>(samplePos) / m_buffer->getSampleRate()) + m_playOffset;
}
////////////////////////////////////////////////////////////
Sound::Status Sound::getStatus() const
{
return SoundSource::getStatus();
}
////////////////////////////////////////////////////////////
Sound& Sound::operator =(const Sound& right)
{
// Here we don't use the copy-and-swap idiom, because it would mess up
// the list of sound instances contained in the buffers
// Detach the sound instance from the previous buffer (if any)
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
m_buffer = NULL;
}
// Copy the sound attributes
if (right.m_buffer)
setBuffer(*right.m_buffer);
setLoop(right.getLoop());
setPitch(right.getPitch());
setVolume(right.getVolume());
setPosition(right.getPosition());
setRelativeToListener(right.isRelativeToListener());
setMinDistance(right.getMinDistance());
setAttenuation(right.getAttenuation());
return *this;
}
////////////////////////////////////////////////////////////
void Sound::resetBuffer()
{
// First stop the sound in case it is playing
stop();
// Detach the buffer
if (m_buffer)
{
m_buffer->detachSound(this);
m_buffer = NULL;
}
}
} // namespace cpp3ds
<commit_msg>Fix channel lock bug exhausting all channels<commit_after>////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cpp3ds/Audio/Sound.hpp>
#include <cpp3ds/Audio/SoundBuffer.hpp>
#include <3ds.h>
#include <string.h>
#include <cpp3ds/System/Err.hpp>
#include <cpp3ds/System/Lock.hpp>
namespace cpp3ds
{
////////////////////////////////////////////////////////////
Sound::Sound()
: m_buffer(nullptr)
, m_loop(false)
, m_isADPCM(false)
{
}
////////////////////////////////////////////////////////////
Sound::Sound(const SoundBuffer& buffer)
: m_buffer(nullptr)
, m_loop(false)
, m_isADPCM(false)
{
setBuffer(buffer);
}
////////////////////////////////////////////////////////////
Sound::Sound(const Sound& copy)
: SoundSource(copy)
, m_buffer(nullptr)
{
if (copy.m_buffer)
setBuffer(*copy.m_buffer);
setLoop(copy.getLoop());
setStateADPCM(copy.getStateADPCM());
}
////////////////////////////////////////////////////////////
Sound::~Sound()
{
stop();
if (m_buffer)
m_buffer->detachSound(this);
}
////////////////////////////////////////////////////////////
void Sound::play()
{
if (!m_buffer || m_buffer->getSampleCount() == 0)
return;
if (getStatus() == Playing)
stop();
if (getStatus() == Paused) {
ndspChnSetPaused(m_channel, false);
return;
}
if (m_channel == -1)
{
Lock lock(g_activeNdspChannelsMutex);
m_channel = 0;
while (m_channel < 24 && ((g_activeNdspChannels >> m_channel) & 1))
m_channel++;
if (m_channel == 24) {
err() << "Failed to play audio stream: all channels are in use." << std::endl;
m_channel = -1;
return;
}
g_activeNdspChannels |= 1 << m_channel;
}
setPlayingOffset(Time::Zero);
u32 size = sizeof(Int16) * m_buffer->getSampleCount();
ndspChnReset(m_channel);
ndspChnSetInterp(m_channel, NDSP_INTERP_POLYPHASE);
ndspChnSetRate(m_channel, float(m_buffer->getSampleRate()));
ndspChnSetFormat(m_channel, (m_buffer->getChannelCount() == 1) ? NDSP_FORMAT_MONO_PCM16 : NDSP_FORMAT_STEREO_PCM16);
DSP_FlushDataCache(m_buffer->getSamples(), size);
ndspChnWaveBufAdd(m_channel, &m_ndspWaveBuf);
}
////////////////////////////////////////////////////////////
void Sound::pause()
{
if (getStatus() != Playing)
return;
ndspChnSetPaused(m_channel, true);
}
////////////////////////////////////////////////////////////
void Sound::stop()
{
if (getStatus() == Stopped)
return;
ndspChnWaveBufClear(m_channel);
// TODO: set ndsp callback to make channel inactive after playback finishes
{
Lock lock(g_activeNdspChannelsMutex);
g_activeNdspChannels &= ~(1 << m_channel);
m_channel = -1;
}
}
////////////////////////////////////////////////////////////
void Sound::setBuffer(const SoundBuffer& buffer)
{
// First detach from the previous buffer
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
}
memset(&m_ndspWaveBuf, 0, sizeof(ndspWaveBuf));
m_ndspWaveBuf.data_vaddr = buffer.getSamples();
m_ndspWaveBuf.nsamples = buffer.getSampleCount() / buffer.getChannelCount();
m_ndspWaveBuf.looping = m_loop; // Loop enabled
m_ndspWaveBuf.status = NDSP_WBUF_FREE;
// Assign and use the new buffer
m_buffer = &buffer;
m_buffer->attachSound(this);
}
////////////////////////////////////////////////////////////
void Sound::setStateADPCM(bool enable)
{
m_isADPCM = enable;
}
////////////////////////////////////////////////////////////
bool Sound::getStateADPCM() const
{
return m_isADPCM;
}
////////////////////////////////////////////////////////////
void Sound::setLoop(bool loop)
{
m_loop = loop;
m_ndspWaveBuf.looping = m_loop;
}
////////////////////////////////////////////////////////////
void Sound::setPlayingOffset(Time timeOffset)
{
Status status = getStatus();
stop();
m_playOffset = timeOffset;
int offset = m_buffer->getSampleRate() * m_buffer->getChannelCount() * timeOffset.asSeconds();
m_ndspWaveBuf.data_vaddr = m_buffer->getSamples() + offset;
m_ndspWaveBuf.nsamples = m_buffer->getSampleCount() / m_buffer->getChannelCount() - offset;
if (status == Playing)
ndspChnWaveBufAdd(m_channel, &m_ndspWaveBuf);
}
////////////////////////////////////////////////////////////
const SoundBuffer* Sound::getBuffer() const
{
return m_buffer;
}
////////////////////////////////////////////////////////////
bool Sound::getLoop() const
{
return m_loop;
}
////////////////////////////////////////////////////////////
Time Sound::getPlayingOffset() const
{
if (getStatus() == Stopped)
return Time::Zero;
u32 samplePos = ndspChnGetSamplePos(m_channel);
return seconds(static_cast<float>(samplePos) / m_buffer->getSampleRate()) + m_playOffset;
}
////////////////////////////////////////////////////////////
Sound::Status Sound::getStatus() const
{
return SoundSource::getStatus();
}
////////////////////////////////////////////////////////////
Sound& Sound::operator =(const Sound& right)
{
// Here we don't use the copy-and-swap idiom, because it would mess up
// the list of sound instances contained in the buffers
// Detach the sound instance from the previous buffer (if any)
if (m_buffer)
{
stop();
m_buffer->detachSound(this);
m_buffer = NULL;
}
// Copy the sound attributes
if (right.m_buffer)
setBuffer(*right.m_buffer);
setLoop(right.getLoop());
setPitch(right.getPitch());
setVolume(right.getVolume());
setPosition(right.getPosition());
setRelativeToListener(right.isRelativeToListener());
setMinDistance(right.getMinDistance());
setAttenuation(right.getAttenuation());
return *this;
}
////////////////////////////////////////////////////////////
void Sound::resetBuffer()
{
// First stop the sound in case it is playing
stop();
// Detach the buffer
if (m_buffer)
{
m_buffer->detachSound(this);
m_buffer = NULL;
}
}
} // namespace cpp3ds
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief Contains the @ref cuda::rtc::program_t class and related code.
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
#define CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
#include <cuda/nvrtc/compilation_options.hpp>
#include <cuda/nvrtc/compilation_output.hpp>
#include <cuda/nvrtc/error.hpp>
#include <cuda/nvrtc/types.hpp>
#include <cuda/api.hpp>
#include <vector>
#include <iostream>
namespace cuda {
namespace rtc {
using const_cstrings_span = span<const char* const>;
using const_cstring_pairs_span = span<::std::pair<const char* const, const char* const>>;
class program_t;
namespace detail_ {
::std::string identify(const program_t &program);
} // namespace detail_
namespace program {
namespace detail_ {
inline program::handle_t create(
const char *program_name,
const char *program_source,
int num_headers,
const char *const *header_sources,
const char *const *header_names)
{
program::handle_t program_handle;
auto status = nvrtcCreateProgram(
&program_handle, program_source, program_name, (int) num_headers, header_sources, header_names);
throw_if_error(status, "Failed creating an NVRTC program (named " + ::std::string(program_name) + ')');
return program_handle;
}
inline void register_global(handle_t program_handle, const char *global_to_register)
{
auto status = nvrtcAddNameExpression(program_handle, global_to_register);
throw_if_error(status, "Failed registering global entity " + ::std::string(global_to_register)
+ " with " + identify(program_handle));
}
inline compilation_output_t compile(
const char * program_name,
const const_cstrings_span & raw_options,
handle_t program_handle)
{
auto status = nvrtcCompileProgram(program_handle, (int) raw_options.size(), raw_options.data());
bool succeeded = (status == status::named_t::success);
if (not (succeeded or status == status::named_t::compilation_failure)) {
throw rtc::runtime_error(status, "Failed invoking compiler for " + identify(program_handle));
}
constexpr bool do_own_handle{true};
return compilation_output::detail_::wrap(program_handle, program_name, succeeded, do_own_handle);
}
// Note: The program_source _cannot_ be nullptr; if all of your source code is preincluded headers,
// pas the address of an empty string.
inline compilation_output_t compile(
const char *program_name,
const char *program_source,
const_cstrings_span header_sources,
const_cstrings_span header_names,
const_cstrings_span raw_options,
const_cstrings_span globals_to_register)
{
assert(header_names.size() <= ::std::numeric_limits<int>::max());
if (program_name == nullptr or *program_name == '\0') {
throw ::std::invalid_argument("Attempt to compile a CUDA program without specifying a name");
}
// Note: Not rejecting empty/missing source, because we may be pre-including source files
auto num_headers = (int) header_names.size();
auto program_handle = create(
program_name, program_source, num_headers, header_sources.data(), header_names.data());
for (const auto global_to_register: globals_to_register) {
register_global(program_handle, global_to_register);
}
// Note: compilation is outside of any context
return compile(program_name, raw_options, program_handle);
}
} // namespace detail_
} // namespace program
/**
* Wrapper class for a CUDA runtime-compilable program
*
* @note This class is a "reference type", not a "value type". Therefore, making changes
* to the program is a const-respecting operation on this class.
*/
class program_t {
public: // getters
const ::std::string& name() const { return name_; }
const char* source() const { return source_; }
const compilation_options_t& options() const { return options_; }
// TODO: Think of a way to set compilation options without having
// to break the statement, e.g. if options had a reflected enum value
// or some such arrangement.
compilation_options_t& options() { return options_; }
const_cstrings_span header_names() const
{
return { headers_.names.data(), headers_.names.size()};
}
const_cstrings_span header_sources() const
{
return { headers_.sources.data(), headers_.sources.size()};
}
size_t num_headers() const { return headers_.sources.size(); }
public: // setters
program_t& set_target(device::compute_capability_t target_compute_capability)
{
options_.set_target(target_compute_capability);
return *this;
}
program_t& set_target(const device_t& device) { return set_target(device.compute_capability());}
program_t& set_target(const context_t& context) { return set_target(context.device()); }
program_t& clear_targets() { options_.targets_.clear(); return *this; }
template <typename Container>
program_t& set_targets(Container target_compute_capabilities)
{
clear_targets();
for(const auto& compute_capability : target_compute_capabilities) {
options_.add_target(compute_capability);
}
return *this;
}
program_t& add_target(device::compute_capability_t target_compute_capability)
{
options_.add_target(target_compute_capability);
return *this;
}
void add_target(const device_t& device) { add_target(device.compute_capability()); }
void add_target(const context_t& context) { add_target(context.device()); }
program_t& set_source(const char* source) { source_ = source; return *this; }
program_t& set_source(const ::std::string& source) { source_ = source.c_str(); return *this; }
program_t& set_options(compilation_options_t options)
{
options_ = ::std::move(options);
return *this;
}
template <typename HeaderNamesFwdIter, typename HeaderSourcesFwdIter>
inline program_t& add_headers(
HeaderNamesFwdIter header_names_start,
HeaderNamesFwdIter header_names_end,
HeaderSourcesFwdIter header_sources_start)
{
auto num_headers_to_add = header_names_end - header_names_start;
auto new_num_headers = headers_.names.size() + num_headers_to_add;
#ifndef NDEBUG
if (new_num_headers > ::std::numeric_limits<int>::max()) {
throw ::std::invalid_argument("Cannot use more than "
+ ::std::to_string(::std::numeric_limits<int>::max()) + " headers.");
}
#endif
headers_.names.reserve(new_num_headers);
::std::copy_n(header_names_start, new_num_headers, ::std::back_inserter(headers_.names));
headers_.sources.reserve(new_num_headers);
::std::copy_n(header_sources_start, new_num_headers, ::std::back_inserter(headers_.sources));
return *this;
}
template <typename HeaderNameAndSourceFwdIter>
inline program_t& add_headers(
HeaderNameAndSourceFwdIter named_headers_start,
HeaderNameAndSourceFwdIter named_headers_end)
{
auto num_headers_to_add = named_headers_end - named_headers_start;
auto new_num_headers = headers_.names.size() + num_headers_to_add;
#ifndef NDEBUG
if (new_num_headers > ::std::numeric_limits<int>::max()) {
throw ::std::invalid_argument("Cannot use more than "
+ ::std::to_string(::std::numeric_limits<int>::max()) + " headers.");
}
#endif
headers_.names.reserve(new_num_headers);
headers_.sources.reserve(new_num_headers);
for(auto& pair_it = named_headers_start; pair_it < named_headers_end; pair_it++) {
headers_.names.push_back(pair_it->first);
headers_.sources.push_back(pair_it->second);
}
return *this;
}
const program_t& add_headers(
const_cstrings_span header_names,
const_cstrings_span header_sources)
{
#ifndef NDEBUG
if (header_names.size() != header_sources.size()) {
throw ::std::invalid_argument(
"Got " + ::std::to_string(header_names.size()) + " header names with "
+ ::std::to_string(header_sources.size()));
}
#endif
return add_headers(header_names.cbegin(), header_names.cend(), header_sources.cbegin());
}
template <typename ContainerOfCStringPairs>
program_t& add_headers(ContainerOfCStringPairs named_header_pairs)
{
return add_headers(::std::begin(named_header_pairs), ::std::end(named_header_pairs));
}
template <typename HeaderNamesFwdIter, typename HeaderSourcesFwdIter>
program_t& set_headers(
HeaderNamesFwdIter header_names_start,
HeaderNamesFwdIter header_names_end,
HeaderSourcesFwdIter header_sources_start)
{
clear_headers();
return add_headers(header_names_start, header_names_end, header_sources_start);
}
program_t& set_headers(
const_cstrings_span header_names,
const_cstrings_span header_sources)
{
#ifndef NDEBUG
if (header_names.size() != header_sources.size()) {
throw ::std::invalid_argument(
"Got " + ::std::to_string(header_names.size()) + " header names with "
+ ::std::to_string(header_sources.size()));
}
#endif
return set_headers(header_names.cbegin(), header_names.cend(), header_sources.cbegin());
}
template <typename ContainerOfCStringPairs>
program_t& set_headers(ContainerOfCStringPairs named_header_pairs)
{
clear_headers();
return add_headers(named_header_pairs);
}
program_t& clear_headers()
{
headers_.names.clear();
headers_.sources.clear();
return *this;
}
program_t& clear_options() { options_ = {}; return *this; }
public:
// TODO: Support specifying all compilation option in a single string and parsing it
compilation_output_t compile() const
{
if ((source_ == nullptr or *source_ == '\0') and options_.preinclude_files.empty()) {
throw ::std::invalid_argument("Attempt to compile a CUDA program without any source code");
}
auto marshalled_options = marshal(options_);
::std::vector<const char*> option_ptrs = marshalled_options.option_ptrs();
return program::detail_::compile(
name_.c_str(),
source_ == nullptr ? "" : source_,
{headers_.sources.data(), headers_.sources.size()},
{headers_.names.data(), headers_.names.size()},
{option_ptrs.data(), option_ptrs.size()},
{globals_to_register_.data(), globals_to_register_.size()});
}
/**
* @brief Register a pre-mangled name of a kernel, to make available for use
* after compilation
*
* @param name The text of an expression, e.g. "my_global_func()", "f1", "N1::N2::n2",
*
*/
program_t& add_registered_global(const char* unmangled_name)
{
globals_to_register_.push_back(unmangled_name);
return *this;
}
program_t& add_registered_global(const ::std::string& unmangled_name)
{
globals_to_register_.push_back(unmangled_name.c_str());
return *this;
}
template <typename Container>
program_t& add_registered_globals(Container&& globals_to_register)
{
globals_to_register_.reserve(globals_to_register_.size() + globals_to_register.size());
::std::copy(globals_to_register.cbegin(), globals_to_register.cend(), ::std::back_inserter(globals_to_register_));
return *this;
}
public: // constructors and destructor
program_t(::std::string name) : name_(::std::move(name)) {};
program_t(const program_t&) = default;
program_t(program_t&&) = default;
~program_t() = default;
public: // operators
program_t& operator=(const program_t& other) = default;
program_t& operator=(program_t&& other) = default;
protected: // data members
const char* source_ { nullptr };
::std::string name_;
compilation_options_t options_;
struct {
::std::vector<const char*> names;
::std::vector<const char*> sources;
} headers_;
::std::vector<const char*> globals_to_register_;
}; // class program_t
namespace program {
inline program_t create(const char* program_name)
{
return program_t(program_name);
}
inline program_t create(const ::std::string program_name)
{
return program_t(program_name);
}
} // namespace program
#if CUDA_VERSION >= 11020
inline dynarray<device::compute_capability_t>
supported_targets()
{
int num_supported_archs;
auto status = nvrtcGetNumSupportedArchs(&num_supported_archs);
throw_if_error(status, "Failed obtaining the number of target NVRTC architectures");
auto raw_archs = ::std::unique_ptr<int[]>(new int[num_supported_archs]);
status = nvrtcGetSupportedArchs(raw_archs.get());
throw_if_error(status, "Failed obtaining the architectures supported by NVRTC");
dynarray<device::compute_capability_t> result;
result.reserve(num_supported_archs);
::std::transform(raw_archs.get(), raw_archs.get() + num_supported_archs, ::std::back_inserter(result),
[](int raw_arch) { return device::compute_capability_t::from_combined_number(raw_arch); });
return result;
}
#endif
} // namespace rtc
} // namespace cuda
#endif // CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
<commit_msg>Drop unnecessary inclusion of `<iostream>` for NVRTC programs.<commit_after>/**
* @file
*
* @brief Contains the @ref cuda::rtc::program_t class and related code.
*/
#pragma once
#ifndef CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
#define CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
#include <cuda/nvrtc/compilation_options.hpp>
#include <cuda/nvrtc/compilation_output.hpp>
#include <cuda/nvrtc/error.hpp>
#include <cuda/nvrtc/types.hpp>
#include <cuda/api.hpp>
#include <vector>
namespace cuda {
namespace rtc {
using const_cstrings_span = span<const char* const>;
using const_cstring_pairs_span = span<::std::pair<const char* const, const char* const>>;
class program_t;
namespace detail_ {
::std::string identify(const program_t &program);
} // namespace detail_
namespace program {
namespace detail_ {
inline program::handle_t create(
const char *program_name,
const char *program_source,
int num_headers,
const char *const *header_sources,
const char *const *header_names)
{
program::handle_t program_handle;
auto status = nvrtcCreateProgram(
&program_handle, program_source, program_name, (int) num_headers, header_sources, header_names);
throw_if_error(status, "Failed creating an NVRTC program (named " + ::std::string(program_name) + ')');
return program_handle;
}
inline void register_global(handle_t program_handle, const char *global_to_register)
{
auto status = nvrtcAddNameExpression(program_handle, global_to_register);
throw_if_error(status, "Failed registering global entity " + ::std::string(global_to_register)
+ " with " + identify(program_handle));
}
inline compilation_output_t compile(
const char * program_name,
const const_cstrings_span & raw_options,
handle_t program_handle)
{
auto status = nvrtcCompileProgram(program_handle, (int) raw_options.size(), raw_options.data());
bool succeeded = (status == status::named_t::success);
if (not (succeeded or status == status::named_t::compilation_failure)) {
throw rtc::runtime_error(status, "Failed invoking compiler for " + identify(program_handle));
}
constexpr bool do_own_handle{true};
return compilation_output::detail_::wrap(program_handle, program_name, succeeded, do_own_handle);
}
// Note: The program_source _cannot_ be nullptr; if all of your source code is preincluded headers,
// pas the address of an empty string.
inline compilation_output_t compile(
const char *program_name,
const char *program_source,
const_cstrings_span header_sources,
const_cstrings_span header_names,
const_cstrings_span raw_options,
const_cstrings_span globals_to_register)
{
assert(header_names.size() <= ::std::numeric_limits<int>::max());
if (program_name == nullptr or *program_name == '\0') {
throw ::std::invalid_argument("Attempt to compile a CUDA program without specifying a name");
}
// Note: Not rejecting empty/missing source, because we may be pre-including source files
auto num_headers = (int) header_names.size();
auto program_handle = create(
program_name, program_source, num_headers, header_sources.data(), header_names.data());
for (const auto global_to_register: globals_to_register) {
register_global(program_handle, global_to_register);
}
// Note: compilation is outside of any context
return compile(program_name, raw_options, program_handle);
}
} // namespace detail_
} // namespace program
/**
* Wrapper class for a CUDA runtime-compilable program
*
* @note This class is a "reference type", not a "value type". Therefore, making changes
* to the program is a const-respecting operation on this class.
*/
class program_t {
public: // getters
const ::std::string& name() const { return name_; }
const char* source() const { return source_; }
const compilation_options_t& options() const { return options_; }
// TODO: Think of a way to set compilation options without having
// to break the statement, e.g. if options had a reflected enum value
// or some such arrangement.
compilation_options_t& options() { return options_; }
const_cstrings_span header_names() const
{
return { headers_.names.data(), headers_.names.size()};
}
const_cstrings_span header_sources() const
{
return { headers_.sources.data(), headers_.sources.size()};
}
size_t num_headers() const { return headers_.sources.size(); }
public: // setters
program_t& set_target(device::compute_capability_t target_compute_capability)
{
options_.set_target(target_compute_capability);
return *this;
}
program_t& set_target(const device_t& device) { return set_target(device.compute_capability());}
program_t& set_target(const context_t& context) { return set_target(context.device()); }
program_t& clear_targets() { options_.targets_.clear(); return *this; }
template <typename Container>
program_t& set_targets(Container target_compute_capabilities)
{
clear_targets();
for(const auto& compute_capability : target_compute_capabilities) {
options_.add_target(compute_capability);
}
return *this;
}
program_t& add_target(device::compute_capability_t target_compute_capability)
{
options_.add_target(target_compute_capability);
return *this;
}
void add_target(const device_t& device) { add_target(device.compute_capability()); }
void add_target(const context_t& context) { add_target(context.device()); }
program_t& set_source(const char* source) { source_ = source; return *this; }
program_t& set_source(const ::std::string& source) { source_ = source.c_str(); return *this; }
program_t& set_options(compilation_options_t options)
{
options_ = ::std::move(options);
return *this;
}
template <typename HeaderNamesFwdIter, typename HeaderSourcesFwdIter>
inline program_t& add_headers(
HeaderNamesFwdIter header_names_start,
HeaderNamesFwdIter header_names_end,
HeaderSourcesFwdIter header_sources_start)
{
auto num_headers_to_add = header_names_end - header_names_start;
auto new_num_headers = headers_.names.size() + num_headers_to_add;
#ifndef NDEBUG
if (new_num_headers > ::std::numeric_limits<int>::max()) {
throw ::std::invalid_argument("Cannot use more than "
+ ::std::to_string(::std::numeric_limits<int>::max()) + " headers.");
}
#endif
headers_.names.reserve(new_num_headers);
::std::copy_n(header_names_start, new_num_headers, ::std::back_inserter(headers_.names));
headers_.sources.reserve(new_num_headers);
::std::copy_n(header_sources_start, new_num_headers, ::std::back_inserter(headers_.sources));
return *this;
}
template <typename HeaderNameAndSourceFwdIter>
inline program_t& add_headers(
HeaderNameAndSourceFwdIter named_headers_start,
HeaderNameAndSourceFwdIter named_headers_end)
{
auto num_headers_to_add = named_headers_end - named_headers_start;
auto new_num_headers = headers_.names.size() + num_headers_to_add;
#ifndef NDEBUG
if (new_num_headers > ::std::numeric_limits<int>::max()) {
throw ::std::invalid_argument("Cannot use more than "
+ ::std::to_string(::std::numeric_limits<int>::max()) + " headers.");
}
#endif
headers_.names.reserve(new_num_headers);
headers_.sources.reserve(new_num_headers);
for(auto& pair_it = named_headers_start; pair_it < named_headers_end; pair_it++) {
headers_.names.push_back(pair_it->first);
headers_.sources.push_back(pair_it->second);
}
return *this;
}
const program_t& add_headers(
const_cstrings_span header_names,
const_cstrings_span header_sources)
{
#ifndef NDEBUG
if (header_names.size() != header_sources.size()) {
throw ::std::invalid_argument(
"Got " + ::std::to_string(header_names.size()) + " header names with "
+ ::std::to_string(header_sources.size()));
}
#endif
return add_headers(header_names.cbegin(), header_names.cend(), header_sources.cbegin());
}
template <typename ContainerOfCStringPairs>
program_t& add_headers(ContainerOfCStringPairs named_header_pairs)
{
return add_headers(::std::begin(named_header_pairs), ::std::end(named_header_pairs));
}
template <typename HeaderNamesFwdIter, typename HeaderSourcesFwdIter>
program_t& set_headers(
HeaderNamesFwdIter header_names_start,
HeaderNamesFwdIter header_names_end,
HeaderSourcesFwdIter header_sources_start)
{
clear_headers();
return add_headers(header_names_start, header_names_end, header_sources_start);
}
program_t& set_headers(
const_cstrings_span header_names,
const_cstrings_span header_sources)
{
#ifndef NDEBUG
if (header_names.size() != header_sources.size()) {
throw ::std::invalid_argument(
"Got " + ::std::to_string(header_names.size()) + " header names with "
+ ::std::to_string(header_sources.size()));
}
#endif
return set_headers(header_names.cbegin(), header_names.cend(), header_sources.cbegin());
}
template <typename ContainerOfCStringPairs>
program_t& set_headers(ContainerOfCStringPairs named_header_pairs)
{
clear_headers();
return add_headers(named_header_pairs);
}
program_t& clear_headers()
{
headers_.names.clear();
headers_.sources.clear();
return *this;
}
program_t& clear_options() { options_ = {}; return *this; }
public:
// TODO: Support specifying all compilation option in a single string and parsing it
compilation_output_t compile() const
{
if ((source_ == nullptr or *source_ == '\0') and options_.preinclude_files.empty()) {
throw ::std::invalid_argument("Attempt to compile a CUDA program without any source code");
}
auto marshalled_options = marshal(options_);
::std::vector<const char*> option_ptrs = marshalled_options.option_ptrs();
return program::detail_::compile(
name_.c_str(),
source_ == nullptr ? "" : source_,
{headers_.sources.data(), headers_.sources.size()},
{headers_.names.data(), headers_.names.size()},
{option_ptrs.data(), option_ptrs.size()},
{globals_to_register_.data(), globals_to_register_.size()});
}
/**
* @brief Register a pre-mangled name of a kernel, to make available for use
* after compilation
*
* @param name The text of an expression, e.g. "my_global_func()", "f1", "N1::N2::n2",
*
*/
program_t& add_registered_global(const char* unmangled_name)
{
globals_to_register_.push_back(unmangled_name);
return *this;
}
program_t& add_registered_global(const ::std::string& unmangled_name)
{
globals_to_register_.push_back(unmangled_name.c_str());
return *this;
}
template <typename Container>
program_t& add_registered_globals(Container&& globals_to_register)
{
globals_to_register_.reserve(globals_to_register_.size() + globals_to_register.size());
::std::copy(globals_to_register.cbegin(), globals_to_register.cend(), ::std::back_inserter(globals_to_register_));
return *this;
}
public: // constructors and destructor
program_t(::std::string name) : name_(::std::move(name)) {};
program_t(const program_t&) = default;
program_t(program_t&&) = default;
~program_t() = default;
public: // operators
program_t& operator=(const program_t& other) = default;
program_t& operator=(program_t&& other) = default;
protected: // data members
const char* source_ { nullptr };
::std::string name_;
compilation_options_t options_;
struct {
::std::vector<const char*> names;
::std::vector<const char*> sources;
} headers_;
::std::vector<const char*> globals_to_register_;
}; // class program_t
namespace program {
inline program_t create(const char* program_name)
{
return program_t(program_name);
}
inline program_t create(const ::std::string program_name)
{
return program_t(program_name);
}
} // namespace program
#if CUDA_VERSION >= 11020
inline dynarray<device::compute_capability_t>
supported_targets()
{
int num_supported_archs;
auto status = nvrtcGetNumSupportedArchs(&num_supported_archs);
throw_if_error(status, "Failed obtaining the number of target NVRTC architectures");
auto raw_archs = ::std::unique_ptr<int[]>(new int[num_supported_archs]);
status = nvrtcGetSupportedArchs(raw_archs.get());
throw_if_error(status, "Failed obtaining the architectures supported by NVRTC");
dynarray<device::compute_capability_t> result;
result.reserve(num_supported_archs);
::std::transform(raw_archs.get(), raw_archs.get() + num_supported_archs, ::std::back_inserter(result),
[](int raw_arch) { return device::compute_capability_t::from_combined_number(raw_arch); });
return result;
}
#endif
} // namespace rtc
} // namespace cuda
#endif // CUDA_API_WRAPPERS_NVRTC_PROGRAM_HPP_
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdCtlr_ipl.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/** @file prdfMemTdCtlr_ipl.C
* @brief A state machine for memory Targeted Diagnostics (IPL only).
*/
#include <prdfMemTdCtlr.H>
// Platform includes
#include <prdfMemEccAnalysis.H>
#include <prdfMemMark.H>
#include <prdfMemoryMru.H>
#include <prdfMemScrubUtils.H>
#include <prdfMemUtils.H>
#include <prdfMemVcm.H>
#include <prdfP9McaDataBundle.H>
#include <prdfP9McaExtraSig.H>
#include <UtilHash.H> // for Util::hashString
using namespace TARGETING;
namespace PRDF
{
using namespace PlatServices;
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
uint32_t MemTdCtlr<T>::handleTdEvent( STEP_CODE_DATA_STRUCT & io_sc,
TdEntry * i_entry )
{
#define PRDF_FUNC "[MemTdCtlr::handleTdEvent] "
// Add this entry to the queue.
iv_queue.push( i_entry );
return SUCCESS;
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
uint32_t MemTdCtlr<T>::defaultStep( STEP_CODE_DATA_STRUCT & io_sc )
{
#define PRDF_FUNC "[MemTdCtlr::defaultStep] "
uint32_t o_rc = SUCCESS;
TdRankListEntry nextRank = iv_rankList.getNext( iv_stoppedRank,
iv_broadcastMode );
do
{
if ( nextRank <= iv_stoppedRank ) // The command made it to the end.
{
PRDF_TRAC( PRDF_FUNC "The TD command made it to the end of "
"memory on chip: 0x%08x", iv_chip->getHuid() );
// Clear all of the counters and maintenance ECC attentions. This
// must be done before telling MDIA the command is done. Otherwise,
// we may run into a race condition where MDIA may start the next
// command and it completes before PRD clears the FIR bits for this
// attention.
o_rc = prepareNextCmd<T>( iv_chip );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "prepareNextCmd<T>(0x%08x) failed",
iv_chip->getHuid() );
break;
}
// The command reached the end of memory. Send a message to MDIA.
o_rc = mdiaSendEventMsg(iv_chip->getTrgt(), MDIA::COMMAND_COMPLETE);
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "mdiaSendEventMsg(0x%08x,COMMAND_COMPLETE) "
"failed", iv_chip->getHuid() );
break;
}
}
else // There is memory left to test.
{
PRDF_TRAC( PRDF_FUNC "There is still memory left to test. "
"Calling startSfRead<T>(0x%08x, m%ds%d)",
nextRank.getChip()->getHuid(),
nextRank.getRank().getMaster(),
nextRank.getRank().getSlave() );
// Start a super fast command to the end of memory.
o_rc = startSfRead<T>( nextRank.getChip(), nextRank.getRank() );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "startSfRead<T>(0x%08x,m%ds%d) failed",
nextRank.getChip()->getHuid(),
nextRank.getRank().getMaster(),
nextRank.getRank().getSlave() );
break;
}
}
} while (0);
return o_rc;
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
template <TARGETING::TYPE T, typename D>
uint32_t __checkEcc( ExtensibleChip * i_chip, TdQueue & io_queue,
const MemAddr & i_addr, bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc )
{
#define PRDF_FUNC "[__checkEcc] "
uint32_t o_rc = SUCCESS;
o_errorsFound = true; // Assume true for unless nothing found.
TargetHandle_t trgt = i_chip->getTrgt();
HUID huid = i_chip->getHuid();
MemRank rank = i_addr.getRank();
do
{
// Check for ECC errors.
uint32_t eccAttns = 0;
o_rc = checkEccFirs<T>( i_chip, eccAttns );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "checkEccFirs<T>(0x%08x) failed", huid );
break;
}
if ( 0 != (eccAttns & MAINT_UE) )
{
// Add the signature to the multi-signature list. Also, since
// this will be a predictive callout, change the primary
// signature as well.
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintUE );
io_sc.service_data->setSignature( huid, PRDFSIG_MaintUE );
// Do memory UE handling.
o_rc = MemEcc::handleMemUe<T>( i_chip, i_addr, UE_TABLE::SCRUB_UE,
io_sc );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "handleMemUe<T>(0x%08x) failed",
i_chip->getHuid() );
break;
}
}
else if ( 0 != (eccAttns & MAINT_MPE) )
{
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintMPE );
// Read the chip mark from markstore.
MemMark chipMark;
o_rc = MarkStore::readChipMark<T>( i_chip, rank, chipMark );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "readChipMark<T>(0x%08x,%d) failed",
huid, rank.getMaster() );
break;
}
// If the chip mark is not valid, then somehow the chip mark was
// placed on a rank other than the rank in which the command
// stopped. This would most likely be a code bug.
PRDF_ASSERT( chipMark.isValid() );
// Add the mark to the callout list.
MemoryMru mm { trgt, rank, chipMark.getSymbol() };
io_sc.service_data->SetCallout( mm );
// Add a new VCM procedure to the queue.
TdEntry * e = new VcmEvent<T>{ i_chip, rank, chipMark };
io_queue.push( e );
}
else if ( isMfgCeCheckingEnabled() &&
(0 != (eccAttns & MAINT_HARD_NCE_ETE)) )
{
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintHARD_CTE );
// Query the per-symbol counters for the hard CE symbol.
MemUtils::MaintSymbols symData; MemSymbol junk;
o_rc = MemUtils::collectCeStats<T>( i_chip, rank, symData, junk );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "MemUtils::collectCeStats(0x%08x,m%ds%d) "
"failed", i_chip->GetId(), rank.getMaster(),
rank.getSlave() );
break;
}
// The command will have finished at the end of the rank so there
// may be more than one symbol. Add all to the callout list.
for ( auto & s : symData )
{
MemoryMru memmru ( trgt, rank, s.symbol );
io_sc.service_data->SetCallout( memmru );
}
// Add a TPS procedure to the queue.
TdEntry * e = new TpsEvent<T>{ i_chip, rank };
io_queue.push( e );
}
else // Nothing found.
{
o_errorsFound = false;
}
} while (0);
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t __checkEcc<TYPE_MCA, McaDataBundle *>( ExtensibleChip * i_chip,
TdQueue & io_queue,
const MemAddr & i_addr,
bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc );
/* TODO RTC 157888
template
uint32_t __checkEcc<TYPE_MBA>( ExtensibleChip * i_chip, TdQueue & io_queue,
const MemAddr & i_addr, bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc );
*/
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
void MemTdCtlr<T>::collectStateCaptureData( STEP_CODE_DATA_STRUCT & io_sc,
const char * i_startEnd )
{
#define PRDF_FUNC "[MemTdCtlr<T>::collectStateCaptureData] "
// Get the number of entries in the TD queue (limit 15)
TdQueue::Queue queue = iv_queue.getQueue();
uint8_t queueCount = queue.size();
if ( 15 < queueCount ) queueCount = 15;
// Get the buffer
uint32_t bitLen = 22 + queueCount*10; // Header + TD queue
BitStringBuffer bsb( bitLen );
uint32_t curPos = 0;
//######################################################################
// Header data (18 bits)
//######################################################################
// Specifies running at IPL. Also ensures our data is non-zero. 4-bit
bsb.setFieldJustify( curPos, 4, TD_CTLR_DATA::Version::IPL ); curPos+=4;
uint8_t mrnk = 0;
uint8_t srnk = 0;
uint8_t phase = TdEntry::Phase::TD_PHASE_0;
uint8_t type = TdEntry::TdType::INVALID_EVENT;
if ( nullptr != iv_curProcedure )
{
mrnk = iv_curProcedure->getRank().getMaster(); // 3-bit
srnk = iv_curProcedure->getRank().getSlave(); // 3-bit
phase = iv_curProcedure->getPhase(); // 4-bit
type = iv_curProcedure->getType(); // 4-bit
}
bsb.setFieldJustify( curPos, 3, mrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 3, srnk ); curPos+=3;
bsb.setFieldJustify( curPos, 4, phase ); curPos+=4;
bsb.setFieldJustify( curPos, 4, type ); curPos+=4;
//######################################################################
// TD Request Queue (min 4 bits, max 164 bits)
//######################################################################
bsb.setFieldJustify( curPos, 4, queueCount ); curPos+=4; // 4-bit
for ( uint32_t n = 0; n < queueCount; n++ )
{
uint8_t itMrnk = queue[n]->getRank().getMaster(); // 3-bit
uint8_t itSrnk = queue[n]->getRank().getSlave(); // 3-bit
uint8_t itType = queue[n]->getType(); // 4-bit
bsb.setFieldJustify( curPos, 3, itMrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 3, itSrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 4, itType ); curPos+=4;
}
//######################################################################
// Add the capture data
//######################################################################
CaptureData & cd = io_sc.service_data->GetCaptureData();
cd.Add( iv_chip->getTrgt(), Util::hashString(i_startEnd), bsb );
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
// Avoid linker errors with the template.
template class MemTdCtlr<TYPE_MCBIST>;
template class MemTdCtlr<TYPE_MBA>;
//------------------------------------------------------------------------------
} // end namespace PRDF
<commit_msg>PRD: hard CE callouts during Memory Diagnostics<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdCtlr_ipl.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
/** @file prdfMemTdCtlr_ipl.C
* @brief A state machine for memory Targeted Diagnostics (IPL only).
*/
#include <prdfMemTdCtlr.H>
// Platform includes
#include <prdfMemEccAnalysis.H>
#include <prdfMemMark.H>
#include <prdfMemoryMru.H>
#include <prdfMemScrubUtils.H>
#include <prdfMemUtils.H>
#include <prdfMemVcm.H>
#include <prdfP9McaDataBundle.H>
#include <prdfP9McaExtraSig.H>
#include <UtilHash.H> // for Util::hashString
using namespace TARGETING;
namespace PRDF
{
using namespace PlatServices;
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
uint32_t MemTdCtlr<T>::handleTdEvent( STEP_CODE_DATA_STRUCT & io_sc,
TdEntry * i_entry )
{
#define PRDF_FUNC "[MemTdCtlr::handleTdEvent] "
// Add this entry to the queue.
iv_queue.push( i_entry );
return SUCCESS;
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
uint32_t MemTdCtlr<T>::defaultStep( STEP_CODE_DATA_STRUCT & io_sc )
{
#define PRDF_FUNC "[MemTdCtlr::defaultStep] "
uint32_t o_rc = SUCCESS;
TdRankListEntry nextRank = iv_rankList.getNext( iv_stoppedRank,
iv_broadcastMode );
do
{
if ( nextRank <= iv_stoppedRank ) // The command made it to the end.
{
PRDF_TRAC( PRDF_FUNC "The TD command made it to the end of "
"memory on chip: 0x%08x", iv_chip->getHuid() );
// Clear all of the counters and maintenance ECC attentions. This
// must be done before telling MDIA the command is done. Otherwise,
// we may run into a race condition where MDIA may start the next
// command and it completes before PRD clears the FIR bits for this
// attention.
o_rc = prepareNextCmd<T>( iv_chip );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "prepareNextCmd<T>(0x%08x) failed",
iv_chip->getHuid() );
break;
}
// The command reached the end of memory. Send a message to MDIA.
o_rc = mdiaSendEventMsg(iv_chip->getTrgt(), MDIA::COMMAND_COMPLETE);
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "mdiaSendEventMsg(0x%08x,COMMAND_COMPLETE) "
"failed", iv_chip->getHuid() );
break;
}
}
else // There is memory left to test.
{
PRDF_TRAC( PRDF_FUNC "There is still memory left to test. "
"Calling startSfRead<T>(0x%08x, m%ds%d)",
nextRank.getChip()->getHuid(),
nextRank.getRank().getMaster(),
nextRank.getRank().getSlave() );
// Start a super fast command to the end of memory.
o_rc = startSfRead<T>( nextRank.getChip(), nextRank.getRank() );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "startSfRead<T>(0x%08x,m%ds%d) failed",
nextRank.getChip()->getHuid(),
nextRank.getRank().getMaster(),
nextRank.getRank().getSlave() );
break;
}
}
} while (0);
return o_rc;
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
template <TARGETING::TYPE T, typename D>
uint32_t __checkEcc( ExtensibleChip * i_chip, TdQueue & io_queue,
const MemAddr & i_addr, bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc )
{
#define PRDF_FUNC "[__checkEcc] "
uint32_t o_rc = SUCCESS;
o_errorsFound = true; // Assume true for unless nothing found.
TargetHandle_t trgt = i_chip->getTrgt();
HUID huid = i_chip->getHuid();
MemRank rank = i_addr.getRank();
do
{
// Check for ECC errors.
uint32_t eccAttns = 0;
o_rc = checkEccFirs<T>( i_chip, eccAttns );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "checkEccFirs<T>(0x%08x) failed", huid );
break;
}
if ( 0 != (eccAttns & MAINT_UE) )
{
// Add the signature to the multi-signature list. Also, since
// this will be a predictive callout, change the primary
// signature as well.
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintUE );
io_sc.service_data->setSignature( huid, PRDFSIG_MaintUE );
// Do memory UE handling.
o_rc = MemEcc::handleMemUe<T>( i_chip, i_addr, UE_TABLE::SCRUB_UE,
io_sc );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "handleMemUe<T>(0x%08x) failed",
i_chip->getHuid() );
break;
}
}
else if ( 0 != (eccAttns & MAINT_MPE) )
{
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintMPE );
// Read the chip mark from markstore.
MemMark chipMark;
o_rc = MarkStore::readChipMark<T>( i_chip, rank, chipMark );
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "readChipMark<T>(0x%08x,%d) failed",
huid, rank.getMaster() );
break;
}
// If the chip mark is not valid, then somehow the chip mark was
// placed on a rank other than the rank in which the command
// stopped. This would most likely be a code bug.
PRDF_ASSERT( chipMark.isValid() );
// Add the mark to the callout list.
MemoryMru mm { trgt, rank, chipMark.getSymbol() };
io_sc.service_data->SetCallout( mm );
// Add a new VCM procedure to the queue.
TdEntry * e = new VcmEvent<T>{ i_chip, rank, chipMark };
io_queue.push( e );
}
else if ( isMfgCeCheckingEnabled() &&
(0 != (eccAttns & MAINT_HARD_NCE_ETE)) )
{
io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintHARD_CTE );
// Query the per-symbol counters for hard CE symbols and make
// callouts for each failing DIMM. Note that this function creates
// new error logs for each DIMM with a hard CE.
D db = static_cast<D>(i_chip->getDataBundle());
o_rc = db->getIplCeStats()->calloutHardCes(rank);
if ( SUCCESS != o_rc )
{
PRDF_ERR( PRDF_FUNC "calloutHardCes(0x%02x) failed",
rank.getKey() );
break;
}
// Add a TPS procedure to the queue.
TdEntry * e = new TpsEvent<T>{ i_chip, rank };
io_queue.push( e );
}
else // Nothing found.
{
o_errorsFound = false;
}
} while (0);
return o_rc;
#undef PRDF_FUNC
}
template
uint32_t __checkEcc<TYPE_MCA, McaDataBundle *>( ExtensibleChip * i_chip,
TdQueue & io_queue,
const MemAddr & i_addr,
bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc );
/* TODO RTC 157888
template
uint32_t __checkEcc<TYPE_MBA>( ExtensibleChip * i_chip, TdQueue & io_queue,
const MemAddr & i_addr, bool & o_errorsFound,
STEP_CODE_DATA_STRUCT & io_sc );
*/
//------------------------------------------------------------------------------
template <TARGETING::TYPE T>
void MemTdCtlr<T>::collectStateCaptureData( STEP_CODE_DATA_STRUCT & io_sc,
const char * i_startEnd )
{
#define PRDF_FUNC "[MemTdCtlr<T>::collectStateCaptureData] "
// Get the number of entries in the TD queue (limit 15)
TdQueue::Queue queue = iv_queue.getQueue();
uint8_t queueCount = queue.size();
if ( 15 < queueCount ) queueCount = 15;
// Get the buffer
uint32_t bitLen = 22 + queueCount*10; // Header + TD queue
BitStringBuffer bsb( bitLen );
uint32_t curPos = 0;
//######################################################################
// Header data (18 bits)
//######################################################################
// Specifies running at IPL. Also ensures our data is non-zero. 4-bit
bsb.setFieldJustify( curPos, 4, TD_CTLR_DATA::Version::IPL ); curPos+=4;
uint8_t mrnk = 0;
uint8_t srnk = 0;
uint8_t phase = TdEntry::Phase::TD_PHASE_0;
uint8_t type = TdEntry::TdType::INVALID_EVENT;
if ( nullptr != iv_curProcedure )
{
mrnk = iv_curProcedure->getRank().getMaster(); // 3-bit
srnk = iv_curProcedure->getRank().getSlave(); // 3-bit
phase = iv_curProcedure->getPhase(); // 4-bit
type = iv_curProcedure->getType(); // 4-bit
}
bsb.setFieldJustify( curPos, 3, mrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 3, srnk ); curPos+=3;
bsb.setFieldJustify( curPos, 4, phase ); curPos+=4;
bsb.setFieldJustify( curPos, 4, type ); curPos+=4;
//######################################################################
// TD Request Queue (min 4 bits, max 164 bits)
//######################################################################
bsb.setFieldJustify( curPos, 4, queueCount ); curPos+=4; // 4-bit
for ( uint32_t n = 0; n < queueCount; n++ )
{
uint8_t itMrnk = queue[n]->getRank().getMaster(); // 3-bit
uint8_t itSrnk = queue[n]->getRank().getSlave(); // 3-bit
uint8_t itType = queue[n]->getType(); // 4-bit
bsb.setFieldJustify( curPos, 3, itMrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 3, itSrnk ); curPos+=3;
bsb.setFieldJustify( curPos, 4, itType ); curPos+=4;
}
//######################################################################
// Add the capture data
//######################################################################
CaptureData & cd = io_sc.service_data->GetCaptureData();
cd.Add( iv_chip->getTrgt(), Util::hashString(i_startEnd), bsb );
#undef PRDF_FUNC
}
//------------------------------------------------------------------------------
// Avoid linker errors with the template.
template class MemTdCtlr<TYPE_MCBIST>;
template class MemTdCtlr<TYPE_MBA>;
//------------------------------------------------------------------------------
} // end namespace PRDF
<|endoftext|>
|
<commit_before>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
#include <xercesc/framework/psvi/XSIDCDefinition.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/IC_Selector.hpp>
#include <xercesc/validators/schema/identity/XercesXPath.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/StringPool.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSIDCDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSIDCDefinition::XSIDCDefinition(IdentityConstraint* const identityConstraint,
XSIDCDefinition* const keyIC,
XSAnnotation* const headAnnot,
StringList* const stringList,
XSModel* const xsModel,
MemoryManager* const manager)
: XSObject(XSConstants::IDENTITY_CONSTRAINT, xsModel, manager)
, fIdentityConstraint(identityConstraint)
, fKey(keyIC)
, fStringList(stringList)
, fXSAnnotationList(0)
{
if (headAnnot)
{
fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
XSAnnotation* annot = headAnnot;
do
{
fXSAnnotationList->addElement(annot);
annot = annot->getNext();
} while (annot);
}
}
XSIDCDefinition::~XSIDCDefinition()
{
if (fStringList)
delete fStringList;
// don't delete fKey - deleted by XSModel
if (fXSAnnotationList)
delete fXSAnnotationList;
}
// ---------------------------------------------------------------------------
// XSIDCDefinition: XSObject virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSIDCDefinition::getName()
{
return fIdentityConstraint->getIdentityConstraintName();
}
const XMLCh *XSIDCDefinition::getNamespace()
{
return fXSModel->getURIStringPool()->getValueForId(fIdentityConstraint->getNamespaceURI());
}
XSNamespaceItem *XSIDCDefinition::getNamespaceItem()
{
return fXSModel->getNamespaceItem(getNamespace());
}
// ---------------------------------------------------------------------------
// XSIDCDefinition: access methods
// ---------------------------------------------------------------------------
XSIDCDefinition::IC_CATEGORY XSIDCDefinition::getCategory() const
{
switch(fIdentityConstraint->getType()) {
case IdentityConstraint::UNIQUE:
return IC_UNIQUE;
case IdentityConstraint::KEY:
return IC_KEY;
case IdentityConstraint::KEYREF:
return IC_KEYREF;
default:
// REVISIT:
// should never really get here... IdentityConstraint::Unknown is the other
// choice so need a default case for completeness; should issues error?
return IC_KEY;
}
}
const XMLCh *XSIDCDefinition::getSelectorStr()
{
return fIdentityConstraint->getSelector()->getXPath()->getExpression();
}
XSAnnotationList *XSIDCDefinition::getAnnotations()
{
return fXSAnnotationList;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Change uppercase enums that were conflicting with other products.<commit_after>/*
* Copyright 2003,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
#include <xercesc/framework/psvi/XSIDCDefinition.hpp>
#include <xercesc/validators/schema/identity/IC_KeyRef.hpp>
#include <xercesc/validators/schema/identity/IC_Selector.hpp>
#include <xercesc/validators/schema/identity/XercesXPath.hpp>
#include <xercesc/framework/psvi/XSModel.hpp>
#include <xercesc/framework/psvi/XSAnnotation.hpp>
#include <xercesc/util/StringPool.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// XSIDCDefinition: Constructors and Destructor
// ---------------------------------------------------------------------------
XSIDCDefinition::XSIDCDefinition(IdentityConstraint* const identityConstraint,
XSIDCDefinition* const keyIC,
XSAnnotation* const headAnnot,
StringList* const stringList,
XSModel* const xsModel,
MemoryManager* const manager)
: XSObject(XSConstants::IDENTITY_CONSTRAINT, xsModel, manager)
, fIdentityConstraint(identityConstraint)
, fKey(keyIC)
, fStringList(stringList)
, fXSAnnotationList(0)
{
if (headAnnot)
{
fXSAnnotationList = new (manager) RefVectorOf<XSAnnotation>(1, false, manager);
XSAnnotation* annot = headAnnot;
do
{
fXSAnnotationList->addElement(annot);
annot = annot->getNext();
} while (annot);
}
}
XSIDCDefinition::~XSIDCDefinition()
{
if (fStringList)
delete fStringList;
// don't delete fKey - deleted by XSModel
if (fXSAnnotationList)
delete fXSAnnotationList;
}
// ---------------------------------------------------------------------------
// XSIDCDefinition: XSObject virtual methods
// ---------------------------------------------------------------------------
const XMLCh *XSIDCDefinition::getName()
{
return fIdentityConstraint->getIdentityConstraintName();
}
const XMLCh *XSIDCDefinition::getNamespace()
{
return fXSModel->getURIStringPool()->getValueForId(fIdentityConstraint->getNamespaceURI());
}
XSNamespaceItem *XSIDCDefinition::getNamespaceItem()
{
return fXSModel->getNamespaceItem(getNamespace());
}
// ---------------------------------------------------------------------------
// XSIDCDefinition: access methods
// ---------------------------------------------------------------------------
XSIDCDefinition::IC_CATEGORY XSIDCDefinition::getCategory() const
{
switch(fIdentityConstraint->getType()) {
case IdentityConstraint::ICType_UNIQUE:
return IC_UNIQUE;
case IdentityConstraint::ICType_KEY:
return IC_KEY;
case IdentityConstraint::ICType_KEYREF:
return IC_KEYREF;
default:
// REVISIT:
// should never really get here... IdentityConstraint::Unknown is the other
// choice so need a default case for completeness; should issues error?
return IC_KEY;
}
}
const XMLCh *XSIDCDefinition::getSelectorStr()
{
return fIdentityConstraint->getSelector()->getXPath()->getExpression();
}
XSAnnotationList *XSIDCDefinition::getAnnotations()
{
return fXSAnnotationList;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) [2018] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "CommonDecred.h"
extern "C" {
#include "libsph/sph_blake.h"
}
uint256 BlockHeaderDecred::getHash() const
{
uint256 hash;
sph_blake256_context ctx;
sph_blake256_init(&ctx);
sph_blake256(&ctx, this, sizeof(BlockHeaderDecred));
sph_blake256_close(&ctx, &hash);
return hash;
}
const NetworkParamsDecred& NetworkParamsDecred::get(NetworkDecred network)
{
static NetworkParamsDecred mainnetParams{
arith_uint256{"000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
3119582664,
100,
101,
6144,
6,
3,
1,
4096,
5,
};
static NetworkParamsDecred testnetParams{
arith_uint256{"0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
2500000000,
100,
101,
2048,
6,
3,
1,
768,
5,
};
static NetworkParamsDecred simnetParams{
arith_uint256{"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
50000000000,
100,
101,
128,
6,
3,
1,
16 + (64 * 2),
5,
};
switch (network) {
case NetworkDecred::MainNet:
return mainnetParams;
case NetworkDecred::TestNet:
return testnetParams;
case NetworkDecred::SimNet:
return simnetParams;
}
return testnetParams;
}
<commit_msg>Fix DCR mainnet & testnet PoW limit<commit_after>/*
The MIT License (MIT)
Copyright (c) [2018] [BTC.COM]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "CommonDecred.h"
extern "C" {
#include "libsph/sph_blake.h"
}
uint256 BlockHeaderDecred::getHash() const
{
uint256 hash;
sph_blake256_context ctx;
sph_blake256_init(&ctx);
sph_blake256(&ctx, this, sizeof(BlockHeaderDecred));
sph_blake256_close(&ctx, &hash);
return hash;
}
const NetworkParamsDecred& NetworkParamsDecred::get(NetworkDecred network)
{
static NetworkParamsDecred mainnetParams{
arith_uint256{}.SetCompact(0x1d00ffff),
3119582664,
100,
101,
6144,
6,
3,
1,
4096,
5,
};
static NetworkParamsDecred testnetParams{
arith_uint256{}.SetCompact(0x1e00ffff),
2500000000,
100,
101,
2048,
6,
3,
1,
768,
5,
};
static NetworkParamsDecred simnetParams{
arith_uint256{}.SetCompact(0x207fffff),
50000000000,
100,
101,
128,
6,
3,
1,
16 + (64 * 2),
5,
};
switch (network) {
case NetworkDecred::MainNet:
return mainnetParams;
case NetworkDecred::TestNet:
return testnetParams;
case NetworkDecred::SimNet:
return simnetParams;
}
return testnetParams;
}
<|endoftext|>
|
<commit_before>//
// MoContentDownloader.cpp
// Chilli Source
// Created by Scott Downie on 23/01/2012.
//
// The MIT License (MIT)
//
// Copyright (c) 2012 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/Networking/ContentDownload/MoContentDownloader.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/Device.h>
#include <ChilliSource/Core/Delegate/MakeDelegate.h>
#include <ChilliSource/Networking/Http/HttpResponse.h>
#include <json/json.h>
namespace ChilliSource
{
namespace Networking
{
const f32 k_downloadProgressUpdateIntervalDefault = 1.0f / 30.0f;
//----------------------------------------------------------------
//----------------------------------------------------------------
MoContentDownloader::MoContentDownloader(HttpRequestSystem* inpRequestSystem, const std::string& instrAssetServerURL, const std::vector<std::string>& inastrTags)
: mpHttpRequestSystem(inpRequestSystem), mstrAssetServerURL(instrAssetServerURL), mastrTags(inastrTags)
{
m_downloadProgressUpdateTimer = CSCore::TimerSPtr(new CSCore::Timer());
}
//----------------------------------------------------------------
//----------------------------------------------------------------
bool MoContentDownloader::DownloadContentManifest(const Delegate& inDelegate)
{
mOnContentManifestDownloadCompleteDelegate = inDelegate;
//Request the content manifest
if(mpHttpRequestSystem->CheckReachability())
{
Core::Device* device = Core::Application::Get()->GetSystem<Core::Device>();
//Build the JSON request with the device info so the server can decide what
//assets are suitable for us
Json::Value JDeviceData(Json::objectValue);
JDeviceData["Type"] = device->GetManufacturer() + device->GetModel() + device->GetModelType();
JDeviceData["OS"] = device->GetOSVersion();
JDeviceData["Locale"] = device->GetLocale();
JDeviceData["Language"] = device->GetLanguage();
//The server uses the tags to determine which content to serve
Json::Value JTags(Json::arrayValue);
for(std::vector<std::string>::const_iterator it = mastrTags.begin(); it != mastrTags.end(); ++it)
{
JTags.append(*it);
}
JDeviceData["Tags"] = JTags;
Json::FastWriter JWriter;
mpHttpRequestSystem->MakePostRequest(mstrAssetServerURL, JWriter.write(JDeviceData), Core::MakeDelegate(this, &MoContentDownloader::OnContentManifestDownloadComplete));
return true;
}
else
{
return false;
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::DownloadPackage(const std::string& in_url, const Delegate& in_delegate, const DownloadProgressDelegate& in_progressDelegate)
{
mOnContentDownloadCompleteDelegate = in_delegate;
mpCurrentRequest = mpHttpRequestSystem->MakeGetRequest(in_url, Core::MakeDelegate(this, &MoContentDownloader::OnContentDownloadComplete));
//Reset the timer
m_downloadProgressUpdateTimer->Reset();
m_downloadProgressEventConnection = m_downloadProgressUpdateTimer->OpenConnection(k_downloadProgressUpdateIntervalDefault, [=]()
{
if(in_progressDelegate)
{
in_progressDelegate(in_url, GetDownloadProgress());
}
});
m_downloadProgressUpdateTimer->Start();
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::OnContentManifestDownloadComplete(const HttpRequest* in_request, const HttpResponse& in_response)
{
switch(in_response.GetResult())
{
case HttpResponse::Result::k_completed:
{
//Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_succeeded, in_response.GetDataAsString());
break;
}
case HttpResponseCode::k_error: //Error
case HttpResponseCode::k_unavailable://Temporary error try again later
case HttpResponseCode::k_notFound: //End point doesn't exist
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
}
break;
}
case HttpResponse::Result::k_timeout:
case HttpResponse::Result::k_failed:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
case HttpResponse::Result::k_flushed:
{
//Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_flushed, in_response.GetDataAsString());
break;
}
case HttpResponseCode::k_error: //Error
case HttpResponseCode::k_unavailable://Temporary error try again later
case HttpResponseCode::k_notFound: //End point doesn't exist
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
}
break;
}
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::OnContentDownloadComplete(const HttpRequest* in_request, const HttpResponse& in_response)
{
if(in_response.GetResult() != HttpResponse::Result::k_flushed)
{
if(mpCurrentRequest == in_request)
mpCurrentRequest = nullptr;
if(m_downloadProgressUpdateTimer)
{
m_downloadProgressEventConnection->Close();
m_downloadProgressUpdateTimer->Stop();
}
}
switch(in_response.GetResult())
{
case HttpResponse::Result::k_completed:
{
// Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
mOnContentDownloadCompleteDelegate(Result::k_succeeded, in_response.GetDataAsString());
break;
}
break;
}
case HttpResponse::Result::k_timeout:
case HttpResponse::Result::k_failed:
{
mOnContentDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
case HttpResponse::Result::k_flushed:
{
mOnContentDownloadCompleteDelegate(Result::k_flushed, in_response.GetDataAsString());
break;
}
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
f32 MoContentDownloader::GetDownloadProgress()
{
f32 progress = 0.0f;
// Check if there is an active request
if(mpCurrentRequest)
{
if(mpCurrentRequest->GetExpectedTotalSize() > 0)
{
// Calculate current scene download progress
progress = (f32)mpCurrentRequest->GetCurrentSize() / (f32)mpCurrentRequest->GetExpectedTotalSize();
CS_LOG_VERBOSE("!!!Progress = " + CSCore::ToString(progress));
}
else
{
progress = 1.0f;
}
}
return progress;
}
}
}<commit_msg>Fix for download progress glitch<commit_after>//
// MoContentDownloader.cpp
// Chilli Source
// Created by Scott Downie on 23/01/2012.
//
// The MIT License (MIT)
//
// Copyright (c) 2012 Tag Games Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <ChilliSource/Networking/ContentDownload/MoContentDownloader.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/Device.h>
#include <ChilliSource/Core/Delegate/MakeDelegate.h>
#include <ChilliSource/Networking/Http/HttpResponse.h>
#include <json/json.h>
namespace ChilliSource
{
namespace Networking
{
const f32 k_downloadProgressUpdateIntervalDefault = 1.0f / 30.0f;
//----------------------------------------------------------------
//----------------------------------------------------------------
MoContentDownloader::MoContentDownloader(HttpRequestSystem* inpRequestSystem, const std::string& instrAssetServerURL, const std::vector<std::string>& inastrTags)
: mpHttpRequestSystem(inpRequestSystem), mstrAssetServerURL(instrAssetServerURL), mastrTags(inastrTags)
{
m_downloadProgressUpdateTimer = CSCore::TimerSPtr(new CSCore::Timer());
}
//----------------------------------------------------------------
//----------------------------------------------------------------
bool MoContentDownloader::DownloadContentManifest(const Delegate& inDelegate)
{
mOnContentManifestDownloadCompleteDelegate = inDelegate;
//Request the content manifest
if(mpHttpRequestSystem->CheckReachability())
{
Core::Device* device = Core::Application::Get()->GetSystem<Core::Device>();
//Build the JSON request with the device info so the server can decide what
//assets are suitable for us
Json::Value JDeviceData(Json::objectValue);
JDeviceData["Type"] = device->GetManufacturer() + device->GetModel() + device->GetModelType();
JDeviceData["OS"] = device->GetOSVersion();
JDeviceData["Locale"] = device->GetLocale();
JDeviceData["Language"] = device->GetLanguage();
//The server uses the tags to determine which content to serve
Json::Value JTags(Json::arrayValue);
for(std::vector<std::string>::const_iterator it = mastrTags.begin(); it != mastrTags.end(); ++it)
{
JTags.append(*it);
}
JDeviceData["Tags"] = JTags;
Json::FastWriter JWriter;
mpHttpRequestSystem->MakePostRequest(mstrAssetServerURL, JWriter.write(JDeviceData), Core::MakeDelegate(this, &MoContentDownloader::OnContentManifestDownloadComplete));
return true;
}
else
{
return false;
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::DownloadPackage(const std::string& in_url, const Delegate& in_delegate, const DownloadProgressDelegate& in_progressDelegate)
{
mOnContentDownloadCompleteDelegate = in_delegate;
mpCurrentRequest = mpHttpRequestSystem->MakeGetRequest(in_url, Core::MakeDelegate(this, &MoContentDownloader::OnContentDownloadComplete));
//Reset the timer
m_downloadProgressUpdateTimer->Reset();
m_downloadProgressEventConnection = m_downloadProgressUpdateTimer->OpenConnection(k_downloadProgressUpdateIntervalDefault, [=]()
{
if(in_progressDelegate)
{
in_progressDelegate(in_url, GetDownloadProgress());
}
});
m_downloadProgressUpdateTimer->Start();
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::OnContentManifestDownloadComplete(const HttpRequest* in_request, const HttpResponse& in_response)
{
switch(in_response.GetResult())
{
case HttpResponse::Result::k_completed:
{
//Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_succeeded, in_response.GetDataAsString());
break;
}
case HttpResponseCode::k_error: //Error
case HttpResponseCode::k_unavailable://Temporary error try again later
case HttpResponseCode::k_notFound: //End point doesn't exist
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
}
break;
}
case HttpResponse::Result::k_timeout:
case HttpResponse::Result::k_failed:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
case HttpResponse::Result::k_flushed:
{
//Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
{
mOnContentManifestDownloadCompleteDelegate(Result::k_flushed, in_response.GetDataAsString());
break;
}
case HttpResponseCode::k_error: //Error
case HttpResponseCode::k_unavailable://Temporary error try again later
case HttpResponseCode::k_notFound: //End point doesn't exist
{
mOnContentManifestDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
}
break;
}
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
void MoContentDownloader::OnContentDownloadComplete(const HttpRequest* in_request, const HttpResponse& in_response)
{
if(in_response.GetResult() != HttpResponse::Result::k_flushed)
{
if(mpCurrentRequest == in_request)
mpCurrentRequest = nullptr;
if(m_downloadProgressUpdateTimer)
{
m_downloadProgressEventConnection->Close();
m_downloadProgressUpdateTimer->Stop();
}
}
switch(in_response.GetResult())
{
case HttpResponse::Result::k_completed:
{
// Check the response code for errors
switch(in_response.GetCode())
{
default: //OK
case HttpResponseCode::k_ok:
mOnContentDownloadCompleteDelegate(Result::k_succeeded, in_response.GetDataAsString());
break;
}
break;
}
case HttpResponse::Result::k_timeout:
case HttpResponse::Result::k_failed:
{
mOnContentDownloadCompleteDelegate(Result::k_failed, in_response.GetDataAsString());
break;
}
case HttpResponse::Result::k_flushed:
{
mOnContentDownloadCompleteDelegate(Result::k_flushed, in_response.GetDataAsString());
break;
}
}
}
//----------------------------------------------------------------
//----------------------------------------------------------------
f32 MoContentDownloader::GetDownloadProgress()
{
f32 progress = 0.0f;
// Check if there is an active request
if(mpCurrentRequest)
{
if(mpCurrentRequest->GetExpectedTotalSize() > 0)
{
// Calculate current scene download progress
progress = (f32)mpCurrentRequest->GetCurrentSize() / (f32)mpCurrentRequest->GetExpectedTotalSize();
CS_LOG_VERBOSE("!!!Progress = " + CSCore::ToString(progress));
}
else
{
progress = 0.0f;
}
}
return progress;
}
}
}<|endoftext|>
|
<commit_before>#include <boost/python.hpp>
namespace bp = boost::python;
#include "rcs.hh" // NML classes, nmlErrorFormat()
#include "emc.hh" // EMC NML
#include "emc_nml.hh"
extern EMC_STAT *emcStatus;
BOOST_PYTHON_MODULE(emctask) {
using namespace boost::python;
using namespace boost;
scope().attr("__doc__") =
"Task introspection\n"
;
class_<PmCartesian, noncopyable>("PmCartesian","EMC cartesian postition",no_init)
.def_readwrite("x",&PmCartesian::x)
.def_readwrite("y",&PmCartesian::y)
.def_readwrite("z",&PmCartesian::z)
;
class_<EmcPose, noncopyable>("EmcPose","EMC pose",no_init)
.def_readwrite("tran",&EmcPose::tran)
// .def_readwrite("x",&EmcPose::tran.x)
// .def_readwrite("y",&EmcPose::tran.y)
// .def_readwrite("x",&EmcPose::tran.z)
.def_readwrite("a",&EmcPose::a)
.def_readwrite("b",&EmcPose::b)
.def_readwrite("c",&EmcPose::c)
.def_readwrite("u",&EmcPose::u)
.def_readwrite("v",&EmcPose::v)
.def_readwrite("w",&EmcPose::w)
;
class_ <EMC_TRAJ_STAT, noncopyable>("EMC_TRAJ_STAT",no_init)
.def_readwrite("linearUnits", &emcStatus->motion.traj.linearUnits )
.def_readwrite("angularUnits", &emcStatus->motion.traj.angularUnits )
.def_readwrite("cycleTime", &emcStatus->motion.traj.cycleTime )
.def_readwrite("axes", &emcStatus->motion.traj.axes )
.def_readwrite("axis_mask", &emcStatus->motion.traj.axis_mask )
.def_readwrite("mode", &emcStatus->motion.traj.mode )
.def_readwrite("enabled", &emcStatus->motion.traj.enabled )
.def_readwrite("inpos", &emcStatus->motion.traj.inpos )
.def_readwrite("queue", &emcStatus->motion.traj.queue )
.def_readwrite("activeQueue", &emcStatus->motion.traj.activeQueue )
.def_readwrite("queueFull", &emcStatus->motion.traj.queueFull )
.def_readwrite("id", &emcStatus->motion.traj.id )
.def_readwrite("paused", &emcStatus->motion.traj.paused )
.def_readwrite("scale", &emcStatus->motion.traj.scale )
.def_readwrite("spindle_scale", &emcStatus->motion.traj.spindle_scale )
.def_readwrite("position", &emcStatus->motion.traj.position )
.def_readwrite("actualPosition", &emcStatus->motion.traj.actualPosition )
.def_readwrite("velocity", &emcStatus->motion.traj.velocity )
.def_readwrite("acceleration", &emcStatus->motion.traj.acceleration)
.def_readwrite("maxVelocity", &emcStatus->motion.traj.maxVelocity )
.def_readwrite("maxAcceleration", &emcStatus->motion.traj.maxAcceleration )
.def_readwrite("probedPosition", &emcStatus->motion.traj.probedPosition )
.def_readwrite("probe_tripped", &emcStatus->motion.traj.probe_tripped )
.def_readwrite("probing", &emcStatus->motion.traj.probing )
.def_readwrite("probeval", &emcStatus->motion.traj.probeval )
.def_readwrite("kinematics_type", &emcStatus->motion.traj.kinematics_type )
.def_readwrite("motion_type", &emcStatus->motion.traj.motion_type )
.def_readwrite("distance_to_go", &emcStatus->motion.traj.distance_to_go )
.def_readwrite("dtg", &emcStatus->motion.traj.dtg )
.def_readwrite("current_vel", &emcStatus->motion.traj.current_vel )
.def_readwrite("feed_override_enabled", &emcStatus->motion.traj.feed_override_enabled )
.def_readwrite("spindle_override_enabled", &emcStatus->motion.traj.spindle_override_enabled )
.def_readwrite("adaptive_feed_enabled", &emcStatus->motion.traj.adaptive_feed_enabled )
.def_readwrite("feed_hold_enabled", &emcStatus->motion.traj.feed_hold_enabled )
;
// class_ <EMC_AXIS_STAT, noncopyable>("EMC_AXIS_STAT",no_init)
// .def_readwrite("", &EmcStatus-> )
// ;
class_ <EMC_SPINDLE_STAT, noncopyable>("EMC_SPINDLE_STAT",no_init)
.def_readwrite("speed", &emcStatus->motion.spindle.speed )
.def_readwrite("direction", &emcStatus->motion.spindle.direction )
.def_readwrite("brake", &emcStatus->motion.spindle.brake )
.def_readwrite("increasing", &emcStatus->motion.spindle.increasing )
.def_readwrite("enabled", &emcStatus->motion.spindle.enabled )
;
class_ <EMC_COOLANT_STAT , noncopyable>("EMC_COOLANT_STAT ",no_init)
.def_readwrite("mist", &emcStatus->motion.coolant.mist )
.def_readwrite("flood", &emcStatus->motion.coolant.flood )
;
class_ <EMC_LUBE_STAT, noncopyable>("EMC_LUBE_STAT",no_init)
.def_readwrite("on", &emcStatus->motion.lube.on )
.def_readwrite("level", &emcStatus->motion.lube.level )
;
class_ <EMC_MOTION_STAT, noncopyable>("EMC_MOTION_STAT",no_init)
.def_readwrite("traj", &emcStatus->motion.traj)
// .def_readwrite("axis", &emcStatus->motion.axis) // FIXME wrap this
// .def_readwrite("spindle", &emcStatus->motion.spindle)
// .def_readwrite("synch_di", &emcStatus->motion.synch_di)
// .def_readwrite("analog_input", &emcStatus->motion.analog_input)
// .def_readwrite("analog_output", &emcStatus->motion.analog_output)
.def_readwrite("estop", &emcStatus->motion.estop)
.def_readwrite("coolant", &emcStatus->motion.coolant)
.def_readwrite("lube", &emcStatus->motion.lube)
.def_readwrite("debug", &emcStatus->motion.debug)
;
class_ <EMC_TASK_STAT, noncopyable>("EMC_TASK_STAT",no_init)
.def_readwrite("mode", (int *) &emcStatus->task.mode)
.def_readwrite("state", (int *) &emcStatus->task.state)
.def_readwrite("execState", (int *) &emcStatus->task.execState)
.def_readwrite("interpState", (int *) &emcStatus->task.interpState)
.def_readwrite("motionLine", &emcStatus->task.motionLine)
.def_readwrite("currentLine", &emcStatus->task.currentLine)
.def_readwrite("readLine", &emcStatus->task.readLine)
.def_readwrite("optional_stop_state", &emcStatus->task.optional_stop_state)
.def_readwrite("block_delete_state", &emcStatus->task.block_delete_state)
.def_readwrite("input_timeout", &emcStatus->task.input_timeout)
.def_readwrite("file", (char *) &emcStatus->task.file)
.def_readwrite("command", (char *) &emcStatus->task.command)
.def_readwrite("g5x_offset", &emcStatus->task.g5x_offset)
.def_readwrite("g5x_index", &emcStatus->task.g5x_index)
.def_readwrite("g92_offset", &emcStatus->task.g92_offset)
.def_readwrite("rotation_xy", &emcStatus->task.rotation_xy)
.def_readwrite("toolOffset", &emcStatus->task.toolOffset)
// int activeGCodes[ACTIVE_G_CODES]; // FIXME wrap this
// int activeMCodes[ACTIVE_M_CODES];
// double activeSettings[ACTIVE_SETTINGS];
.def_readwrite("programUnits", &emcStatus->task.programUnits)
.def_readwrite("interpreter_errcode", &emcStatus->task.interpreter_errcode)
.def_readwrite("task_paused", &emcStatus->task.task_paused)
.def_readwrite("delayLeft", &emcStatus->task.delayLeft)
;
class_ <EMC_TOOL_STAT, noncopyable>("EMC_TOOL_STAT",no_init)
.def_readwrite("pocketPrepped", &emcStatus->io.tool.pocketPrepped )
.def_readwrite("toolInSpindle", &emcStatus->io.tool.toolInSpindle )
// .def_readwrite("toolTable", &emcStatus->io.tool.toolTable ) // FIXME wrap this
;
class_ <EMC_AUX_STAT, noncopyable>("EMC_AUX_STAT",no_init)
// .def_readwrite("", &emcStatus->io.aux. ) // empty NML msg?
;
class_ <EMC_IO_STAT, noncopyable>("EMC_IO_STAT",no_init)
.def_readwrite("cycleTime", &emcStatus->io.cycleTime )
.def_readwrite("debug", &emcStatus->io.debug )
.def_readwrite("reason", &emcStatus->io.reason )
.def_readwrite("fault", &emcStatus->io.fault )
.def_readwrite("tool", &emcStatus->io.tool)
.def_readwrite("aux", &emcStatus->io.aux )
;
class_ <EMC_STAT, noncopyable>("EMC_STAT",no_init)
.def_readwrite("task",&emcStatus->task)
.def_readwrite("motion",&emcStatus->motion)
.def_readwrite("io",&emcStatus->io)
.def_readwrite("debug",&emcStatus->debug)
;
}
<commit_msg>WIP on completing taskmodule<commit_after> // EMC_AXIS_STAT axis[EMC_AXIS_MAX];
// int synch_di[EMC_MAX_DIO]; // motion inputs queried by interp
// int synch_do[EMC_MAX_DIO]; // motion outputs queried by interp
// double analog_input[EMC_MAX_AIO]; //motion analog inputs queried by interp
// double analog_output[EMC_MAX_AIO]; //motion analog outputs queried by interp
//task_stat:
// reuse interp converters
#include <boost/python.hpp>
#include "rs274ngc.hh"
#include "interp_internal.hh"
namespace bp = boost::python;
#include "array1.hh"
namespace pp = pyplusplus::containers::static_sized;
#include "interp_array_types.hh" // import activeMCodes,activeGCodes,activeSettings, toolTable
#include "rcs.hh" // NML classes, nmlErrorFormat()
#include "emc.hh" // EMC NML
#include "emc_nml.hh"
extern EMC_STAT *emcStatus;
typedef pp::array_1_t< EMC_AXIS_STAT, EMC_AXIS_MAX> axis_array, (*axis_w)( EMC_MOTION_STAT &m );
typedef pp::array_1_t< int, EMC_MAX_DIO> synch_dio_array, (*synch_dio_w)( EMC_MOTION_STAT &m );
typedef pp::array_1_t< double, EMC_MAX_AIO> analog_io_array, (*analog_io_w)( EMC_MOTION_STAT &m );
typedef pp::array_1_t< int, ACTIVE_G_CODES> active_g_codes_array, (*active_g_codes_tw)( EMC_TASK_STAT &t );
typedef pp::array_1_t< int, ACTIVE_M_CODES> active_m_codes_array, (*active_m_codes_tw)( EMC_TASK_STAT &t );
typedef pp::array_1_t< double, ACTIVE_SETTINGS> active_settings_array, (*active_settings_tw)( EMC_TASK_STAT &t );
static axis_array axis_wrapper ( EMC_MOTION_STAT & m) {
return axis_array(m.axis);
}
static synch_dio_array synch_di_wrapper ( EMC_MOTION_STAT & m) {
return synch_dio_array(m.synch_di);
}
static synch_dio_array synch_do_wrapper ( EMC_MOTION_STAT & m) {
return synch_dio_array(m.synch_do);
}
static analog_io_array analog_input_wrapper ( EMC_MOTION_STAT & m) {
return analog_io_array(m.analog_input);
}
static analog_io_array analog_output_wrapper ( EMC_MOTION_STAT & m) {
return analog_io_array(m.analog_output);
}
static active_g_codes_array activeGCodes_wrapper ( EMC_TASK_STAT & m) {
return active_g_codes_array(m.activeGCodes);
}
static active_m_codes_array activeMCodes_wrapper ( EMC_TASK_STAT & m) {
return active_m_codes_array(m.activeMCodes);
}
static active_settings_array activeSettings_wrapper ( EMC_TASK_STAT & m) {
return active_settings_array(m.activeSettings);
}
BOOST_PYTHON_MODULE(emctask) {
using namespace boost::python;
using namespace boost;
scope().attr("__doc__") =
"Task introspection\n"
;
class_<PmCartesian, noncopyable>("PmCartesian","EMC cartesian postition",no_init)
.def_readwrite("x",&PmCartesian::x)
.def_readwrite("y",&PmCartesian::y)
.def_readwrite("z",&PmCartesian::z)
;
class_<EmcPose, noncopyable>("EmcPose","EMC pose",no_init)
.def_readwrite("tran",&EmcPose::tran)
// .def_readwrite("x",&EmcPose::tran.x)
// .def_readwrite("y",&EmcPose::tran.y)
// .def_readwrite("x",&EmcPose::tran.z)
.def_readwrite("a",&EmcPose::a)
.def_readwrite("b",&EmcPose::b)
.def_readwrite("c",&EmcPose::c)
.def_readwrite("u",&EmcPose::u)
.def_readwrite("v",&EmcPose::v)
.def_readwrite("w",&EmcPose::w)
;
class_ <EMC_TRAJ_STAT, noncopyable>("EMC_TRAJ_STAT",no_init)
.def_readwrite("linearUnits", &emcStatus->motion.traj.linearUnits )
.def_readwrite("angularUnits", &emcStatus->motion.traj.angularUnits )
.def_readwrite("cycleTime", &emcStatus->motion.traj.cycleTime )
.def_readwrite("axes", &emcStatus->motion.traj.axes )
.def_readwrite("axis_mask", &emcStatus->motion.traj.axis_mask )
.def_readwrite("mode", &emcStatus->motion.traj.mode )
.def_readwrite("enabled", &emcStatus->motion.traj.enabled )
.def_readwrite("inpos", &emcStatus->motion.traj.inpos )
.def_readwrite("queue", &emcStatus->motion.traj.queue )
.def_readwrite("activeQueue", &emcStatus->motion.traj.activeQueue )
.def_readwrite("queueFull", &emcStatus->motion.traj.queueFull )
.def_readwrite("id", &emcStatus->motion.traj.id )
.def_readwrite("paused", &emcStatus->motion.traj.paused )
.def_readwrite("scale", &emcStatus->motion.traj.scale )
.def_readwrite("spindle_scale", &emcStatus->motion.traj.spindle_scale )
.def_readwrite("position", &emcStatus->motion.traj.position )
.def_readwrite("actualPosition", &emcStatus->motion.traj.actualPosition )
.def_readwrite("velocity", &emcStatus->motion.traj.velocity )
.def_readwrite("acceleration", &emcStatus->motion.traj.acceleration)
.def_readwrite("maxVelocity", &emcStatus->motion.traj.maxVelocity )
.def_readwrite("maxAcceleration", &emcStatus->motion.traj.maxAcceleration )
.def_readwrite("probedPosition", &emcStatus->motion.traj.probedPosition )
.def_readwrite("probe_tripped", &emcStatus->motion.traj.probe_tripped )
.def_readwrite("probing", &emcStatus->motion.traj.probing )
.def_readwrite("probeval", &emcStatus->motion.traj.probeval )
.def_readwrite("kinematics_type", &emcStatus->motion.traj.kinematics_type )
.def_readwrite("motion_type", &emcStatus->motion.traj.motion_type )
.def_readwrite("distance_to_go", &emcStatus->motion.traj.distance_to_go )
.def_readwrite("dtg", &emcStatus->motion.traj.dtg )
.def_readwrite("current_vel", &emcStatus->motion.traj.current_vel )
.def_readwrite("feed_override_enabled", &emcStatus->motion.traj.feed_override_enabled )
.def_readwrite("spindle_override_enabled", &emcStatus->motion.traj.spindle_override_enabled )
.def_readwrite("adaptive_feed_enabled", &emcStatus->motion.traj.adaptive_feed_enabled )
.def_readwrite("feed_hold_enabled", &emcStatus->motion.traj.feed_hold_enabled )
;
class_ <EMC_AXIS_STAT, noncopyable>("EMC_AXIS_STAT",no_init)
// // .def_readwrite("", &EmcStatus-> )
// .def("axisType", &EmcStatus-> ; // EMC_AXIS_LINEAR, EMC_AXIS_ANGULAR
// double units; // units per mm, deg for linear, angular
// double backlash;
// double minPositionLimit;
// double maxPositionLimit;
// double maxFerror;
// double minFerror;
// // dynamic status
// double ferrorCurrent; // current following error
// double ferrorHighMark; // magnitude of max following error
// /*! \todo FIXME - is this really position, or the DAC output? */
// double output; // commanded output position
// double input; // current input position
// double velocity; // current velocity
// unsigned char inpos; // non-zero means in position
// unsigned char homing; // non-zero means homing
// unsigned char homed; // non-zero means has been homed
// unsigned char fault; // non-zero means axis amp fault
// unsigned char enabled; // non-zero means enabled
// unsigned char minSoftLimit; // non-zero means min soft limit exceeded
// unsigned char maxSoftLimit; // non-zero means max soft limit exceeded
// unsigned char minHardLimit; // non-zero means min hard limit exceeded
// unsigned char maxHardLimit; // non-zero means max hard limit exceeded
// unsigned char overrideLimits; // non-zero means limits are overridden
//
;
class_ <EMC_SPINDLE_STAT, noncopyable>("EMC_SPINDLE_STAT",no_init)
.def_readwrite("speed", &emcStatus->motion.spindle.speed )
.def_readwrite("direction", &emcStatus->motion.spindle.direction )
.def_readwrite("brake", &emcStatus->motion.spindle.brake )
.def_readwrite("increasing", &emcStatus->motion.spindle.increasing )
.def_readwrite("enabled", &emcStatus->motion.spindle.enabled )
;
class_ <EMC_COOLANT_STAT , noncopyable>("EMC_COOLANT_STAT ",no_init)
.def_readwrite("mist", &emcStatus->motion.coolant.mist )
.def_readwrite("flood", &emcStatus->motion.coolant.flood )
;
class_ <EMC_LUBE_STAT, noncopyable>("EMC_LUBE_STAT",no_init)
.def_readwrite("on", &emcStatus->motion.lube.on )
.def_readwrite("level", &emcStatus->motion.lube.level )
;
class_ <EMC_MOTION_STAT, noncopyable>("EMC_MOTION_STAT",no_init)
.def_readwrite("traj", &emcStatus->motion.traj)
.add_property( "axis",
bp::make_function( axis_w(&axis_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
// .def_readwrite("spindle", &emcStatus->motion.spindle)
.add_property( "synch_di",
bp::make_function( synch_dio_w(&synch_di_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.add_property( "synch_do",
bp::make_function( synch_dio_w(&synch_do_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.add_property( "analog_input",
bp::make_function( analog_io_w(&analog_input_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.add_property( "analog_output",
bp::make_function( analog_io_w(&analog_output_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.def_readwrite("estop", &emcStatus->motion.estop)
.def_readwrite("coolant", &emcStatus->motion.coolant)
.def_readwrite("lube", &emcStatus->motion.lube)
.def_readwrite("debug", &emcStatus->motion.debug)
;
class_ <EMC_TASK_STAT, noncopyable>("EMC_TASK_STAT",no_init)
.def_readwrite("mode", (int *) &emcStatus->task.mode)
.def_readwrite("state", (int *) &emcStatus->task.state)
.def_readwrite("execState", (int *) &emcStatus->task.execState)
.def_readwrite("interpState", (int *) &emcStatus->task.interpState)
.def_readwrite("motionLine", &emcStatus->task.motionLine)
.def_readwrite("currentLine", &emcStatus->task.currentLine)
.def_readwrite("readLine", &emcStatus->task.readLine)
.def_readwrite("optional_stop_state", &emcStatus->task.optional_stop_state)
.def_readwrite("block_delete_state", &emcStatus->task.block_delete_state)
.def_readwrite("input_timeout", &emcStatus->task.input_timeout)
.def_readwrite("file", (char *) &emcStatus->task.file)
.def_readwrite("command", (char *) &emcStatus->task.command)
.def_readwrite("g5x_offset", &emcStatus->task.g5x_offset)
.def_readwrite("g5x_index", &emcStatus->task.g5x_index)
.def_readwrite("g92_offset", &emcStatus->task.g92_offset)
.def_readwrite("rotation_xy", &emcStatus->task.rotation_xy)
.def_readwrite("toolOffset", &emcStatus->task.toolOffset)
.add_property( "activeGCodes",
bp::make_function( active_g_codes_tw(&activeGCodes_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.add_property( "activeMCodes",
bp::make_function( active_m_codes_tw(&activeMCodes_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.add_property( "activeSettings",
bp::make_function( active_settings_tw(&activeSettings_wrapper),
bp::with_custodian_and_ward_postcall< 0, 1 >()))
.def_readwrite("programUnits", &emcStatus->task.programUnits)
.def_readwrite("interpreter_errcode", &emcStatus->task.interpreter_errcode)
.def_readwrite("task_paused", &emcStatus->task.task_paused)
.def_readwrite("delayLeft", &emcStatus->task.delayLeft)
;
class_ <EMC_TOOL_STAT, noncopyable>("EMC_TOOL_STAT",no_init)
.def_readwrite("pocketPrepped", &emcStatus->io.tool.pocketPrepped )
.def_readwrite("toolInSpindle", &emcStatus->io.tool.toolInSpindle )
// .def_readwrite("toolTable", &emcStatus->io.tool.toolTable ) // FIXME wrap this
;
class_ <EMC_AUX_STAT, noncopyable>("EMC_AUX_STAT",no_init)
// .def_readwrite("", &emcStatus->io.aux. ) // empty NML msg?
;
class_ <EMC_IO_STAT, noncopyable>("EMC_IO_STAT",no_init)
.def_readwrite("cycleTime", &emcStatus->io.cycleTime )
.def_readwrite("debug", &emcStatus->io.debug )
.def_readwrite("reason", &emcStatus->io.reason )
.def_readwrite("fault", &emcStatus->io.fault )
.def_readwrite("tool", &emcStatus->io.tool)
.def_readwrite("aux", &emcStatus->io.aux )
;
class_ <EMC_STAT, noncopyable>("EMC_STAT",no_init)
.def_readwrite("task",&emcStatus->task)
.def_readwrite("motion",&emcStatus->motion)
.def_readwrite("io",&emcStatus->io)
.def_readwrite("debug",&emcStatus->debug)
;
pp::register_array_1< double, EMC_MAX_AIO> ("AnalogIoArray");
pp::register_array_1< int, EMC_MAX_DIO> ("DigitalIoArray");
pp::register_array_1< EMC_AXIS_STAT,EMC_AXIS_MAX,
bp::return_internal_reference< 1, bp::default_call_policies > > ("AxisArray");
}
<|endoftext|>
|
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/file_system_helper.h"
#include <deque>
#include <string>
#include <vector>
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/str_util.h"
#include "tensorflow/core/platform/threadpool.h"
namespace tensorflow {
namespace internal {
namespace {
constexpr int kNumThreads = 8;
// Run a function in parallel using a ThreadPool, but skip the ThreadPool
// on the iOS platform due to its problems with more than a few threads.
void ForEach(int first, int last, const std::function<void(int)>& f) {
#if TARGET_OS_IPHONE
for (int i = first; i < last; i++) {
f(i);
}
#else
int num_threads = std::min(kNumThreads, last - first);
thread::ThreadPool threads(Env::Default(), "ForEach", num_threads);
for (int i = first; i < last; i++) {
threads.Schedule([f, i] { f(i); });
}
#endif
}
} // namespace
Status GetMatchingPaths(FileSystem* fs, Env* env, const string& pattern,
std::vector<string>* results) {
results->clear();
// Find the fixed prefix by looking for the first wildcard.
string fixed_prefix = pattern.substr(0, pattern.find_first_of("*?[\\"));
string eval_pattern = pattern;
std::vector<string> all_files;
string dir(io::Dirname(fixed_prefix));
// If dir is empty then we need to fix up fixed_prefix and eval_pattern to
// include . as the top level directory.
if (dir.empty()) {
dir = ".";
fixed_prefix = io::JoinPath(dir, fixed_prefix);
eval_pattern = io::JoinPath(dir, pattern);
}
// Setup a BFS to explore everything under dir.
std::deque<string> dir_q;
dir_q.push_back(dir);
Status ret; // Status to return.
// children_dir_status holds is_dir status for children. It can have three
// possible values: OK for true; FAILED_PRECONDITION for false; CANCELLED
// if we don't calculate IsDirectory (we might do that because there isn't
// any point in exploring that child path).
std::vector<Status> children_dir_status;
while (!dir_q.empty()) {
string current_dir = dir_q.front();
dir_q.pop_front();
std::vector<string> children;
Status s = fs->GetChildren(current_dir, &children);
// In case PERMISSION_DENIED is encountered, we bail here.
if (s.code() == tensorflow::error::PERMISSION_DENIED) {
continue;
}
ret.Update(s);
if (children.empty()) continue;
// This IsDirectory call can be expensive for some FS. Parallelizing it.
children_dir_status.resize(children.size());
ForEach(0, children.size(),
[fs, ¤t_dir, &children, &fixed_prefix,
&children_dir_status](int i) {
const string child_path = io::JoinPath(current_dir, children[i]);
// In case the child_path doesn't start with the fixed_prefix then
// we don't need to explore this path.
if (!absl::StartsWith(child_path, fixed_prefix)) {
children_dir_status[i] = Status(tensorflow::error::CANCELLED,
"Operation not needed");
} else {
children_dir_status[i] = fs->IsDirectory(child_path);
}
});
for (size_t i = 0; i < children.size(); ++i) {
const string child_path = io::JoinPath(current_dir, children[i]);
// If the IsDirectory call was cancelled we bail.
if (children_dir_status[i].code() == tensorflow::error::CANCELLED) {
continue;
}
// If the child is a directory add it to the queue.
if (children_dir_status[i].ok()) {
dir_q.push_back(child_path);
}
all_files.push_back(child_path);
}
}
// Match all obtained files to the input pattern.
for (const auto& f : all_files) {
if (fs->Match(f, eval_pattern)) {
results->push_back(f);
}
}
return ret;
}
} // namespace internal
} // namespace tensorflow
<commit_msg>change GetMatchingPaths to speed it up<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/platform/file_system_helper.h"
#include <deque>
#include <string>
#include <vector>
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/file_system.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/str_util.h"
#include "tensorflow/core/platform/threadpool.h"
namespace tensorflow {
namespace internal {
namespace {
constexpr int kNumThreads = 8;
// Run a function in parallel using a ThreadPool, but skip the ThreadPool
// on the iOS platform due to its problems with more than a few threads.
void ForEach(int first, int last, const std::function<void(int)>& f) {
#if TARGET_OS_IPHONE
for (int i = first; i < last; i++) {
f(i);
}
#else
int num_threads = std::min(kNumThreads, last - first);
thread::ThreadPool threads(Env::Default(), "ForEach", num_threads);
for (int i = first; i < last; i++) {
threads.Schedule([f, i] { f(i); });
}
#endif
}
} // namespace
Status GetMatchingPaths(FileSystem* fs, Env* env, const string& pattern,
std::vector<string>* results) {
results->clear();
if (pattern.empty()) {
return Status::OK();
}
string eval_pattern = pattern;
bool is_directory = pattern[pattern.size() - 1] == '/';
#ifdef PLATFORM_WINDOWS
is_directory = is_directory || pattern[pattern.size() - 1] == '\\';
#endif
if (!io::IsAbsolutePath(pattern)) {
eval_pattern = io::JoinPath(".", pattern);
}
std::vector<string> dirs;
if (!is_directory) {
dirs.push_back(eval_pattern);
}
StringPiece dir(io::Dirname(eval_pattern));
while (!dir.empty() && dir != "/") {
dirs.push_back(string(dir));
dir = io::Dirname(dir);
}
if (dir == "/") {
dirs.push_back(string(dir));
}
std::reverse(dirs.begin(), dirs.end());
// Setup a BFS to explore everything under dir.
std::deque<std::pair<string, int>> dir_q;
dir_q.push_back({dirs[0], 0});
Status ret; // Status to return.
// children_dir_status holds is_dir status for children. It can have three
// possible values: OK for true; FAILED_PRECONDITION for false; CANCELLED
// if we don't calculate IsDirectory (we might do that because there isn't
// any point in exploring that child path).
std::vector<Status> children_dir_status;
while (!dir_q.empty()) {
string current_dir = dir_q.front().first;
int dir_index = dir_q.front().second;
dir_index++;
dir_q.pop_front();
std::vector<string> children;
Status s = fs->GetChildren(current_dir, &children);
// In case PERMISSION_DENIED is encountered, we bail here.
if (s.code() == tensorflow::error::PERMISSION_DENIED) {
continue;
}
ret.Update(s);
if (children.empty()) continue;
// This IsDirectory call can be expensive for some FS. Parallelizing it.
children_dir_status.resize(children.size());
ForEach(0, children.size(),
[fs, ¤t_dir, &children, &dirs, dir_index,
is_directory, &children_dir_status](int i) {
const string child_path = io::JoinPath(current_dir, children[i]);
if (!fs->Match(child_path, dirs[dir_index])) {
children_dir_status[i] = Status(tensorflow::error::CANCELLED,
"Operation not needed");
} else if (dir_index != dirs.size() - 1){
children_dir_status[i] = fs->IsDirectory(child_path);Status::OK();
} else {
children_dir_status[i] = is_directory ?
fs->IsDirectory(child_path) : Status::OK();
}
});
for (size_t i = 0; i < children.size(); ++i) {
const string child_path = io::JoinPath(current_dir, children[i]);
// If the IsDirectory call was cancelled we bail.
if (children_dir_status[i].code() == tensorflow::error::CANCELLED) {
continue;
}
if (children_dir_status[i].ok()) {
if (dir_index != dirs.size() - 1) {
dir_q.push_back({child_path, dir_index});
} else {
results->push_back(child_path);
}
}
}
}
return ret;
}
} // namespace internal
} // namespace tensorflow
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.