text
stringlengths
54
60.6k
<commit_before>#include "Rainback.hpp" #include <iostream> #include <functional> #include <QTextStream> #include <QApplication> #include <QPushButton> #include <QLineEdit> #include <QTextEdit> #include <QRegExp> #include <QFileSystemWatcher> #include <QTcpSocket> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include <lua-cxx/QObjectObserver.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" #include "proxy/TCPServer.hpp" #include "protocol/Human.hpp" #include "protocol/Pascal.hpp" #include "proxy/QObject.hpp" #include "proxy/Socket.hpp" #include "proxy/TCPServer.hpp" #include "proxy/QWidget.hpp" #include "proxy/AbstractLine.hpp" using namespace rainback; std::shared_ptr<LuaFont> newFont(LuaStack& stack) { switch (stack.size()) { case 0: return std::make_shared<LuaFont>(); case 1: return std::make_shared<LuaFont>(stack.as<QString>(1)); default: return std::make_shared<LuaFont>( stack.as<QString>(1), stack.as<int>(2) ); } } namespace rainback { void Rainback::assertWidget() { if (!_widget) { throw LuaException("This function must not be used when no widget is available"); } } Rainback::Rainback(Lua& lua) : _widget(nullptr), _lua(lua) { if (_lua["unpack"].isNil()) { _lua["unpack"] = _lua["table"]["unpack"]; } _lua["Rainback"] = lua::value::table; _lua["error"] = lua::LuaCallable([](LuaStack& stack) { stack.error(stack.as<std::string>(-1)); }); _lua["Rainback"]["globals"] = lua::value::table; _lua["Rainback"]["AddModuleDirectory"] = std::function<void(const std::string&, const std::string&)>( [this](const std::string& root, const std::string& prefix) { auto loader = std::make_shared<DirectoryModuleLoader>(); loaders.push_back(loader); loader->setRoot(QDir(root.c_str())); loader->setPrefix(prefix); _lua.addModuleLoader(loader.get()); } ); _lua["Rainback"]["LoadDirectory"] = std::function<void(const std::string&, const bool)>( [this](const std::string& path, const bool recurse) { lua::load_dir(_lua, QDir(path.c_str()), recurse); } ); _lua["Rainback"]["Font"] = newFont; _lua["Rainback"]["Button"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QPushButton(_widget), true); } ); _lua["Rainback"]["LineEdit"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QLineEdit(_widget), true); } ); _lua["Rainback"]["TextEdit"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QTextEdit(_widget), true); } ); _lua["Rainback" ]["ScreenWidth"] = std::function<int()>([this]() { assertWidget(); return _widget->width(); }); _lua["Rainback" ]["ScreenHeight"] = std::function<int()>([this]() { assertWidget(); return _widget->height(); }); _lua["Rainback"]["GetTime"] = std::function<long()>([this]() { return elapsed.elapsed(); }); _lua["Rainback"]["StartTick"] = std::function<std::function<void()>(const int)>([this](const int framerate) { timer.start(1000 / framerate); return [this]() { timer.stop(); }; }); _lua["Rainback"]["GetCursorPosition"] = std::function<void(LuaStack&)>([this](LuaStack& stack) { assertWidget(); QPoint pos(_widget->mapFromGlobal(QCursor::pos())); stack.clear(); lua::push(stack, pos.x()); lua::push(stack, pos.y()); }); _lua["Rainback"]["Update"] = std::function<void()>([this]() { assertWidget(); _widget->update(); }); _lua["Rainback"]["Close"] = std::function<void()>([this]() { assertWidget(); qApp->closeAllWindows(); }); _lua["Rainback"]["SetBackgroundColor"] = std::function<void(const int, const int, const int)>( [this](const int r, const int g, const int b) { assertWidget(); _widget->setAutoFillBackground(true); QPalette p(_widget->palette()); p.setColor(QPalette::Background, QColor(r, g, b)); _widget->setPalette(p); } ); _lua["Rainback"]["FileExists"] = std::function<bool(const QString&)>( [this](const QString& fileName) { return QFile(fileName).exists(); } ); _lua["Rainback"]["ReadFile"] = std::function<QString(const QString&)>( [this](const QString& fileName) { QFile file(fileName); openFile(file, QIODevice::ReadOnly, true); // Using QTextStream here breaks for Unicode strings return QString(file.readAll()); } ); _lua["Rainback"]["ReadCompressedFile"] = std::function<QString(const QString&)>( [this](const QString& fileName) { QFile file(fileName); openFile(file, QIODevice::ReadOnly, true); return QString(qUncompress(file.readAll())); } ); _lua["Rainback"]["WriteFile"] = std::function<void(const QString&, const QString&)>( [this](const QString& fileName, const QString& data) { QFile file(fileName); openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false); QTextStream(&file) << data; } ); _lua["Rainback"]["WriteCompressedFile"] = std::function<void(const QString&, const QString&)>( [this](const QString& fileName, const QString& data) { QFile file(fileName); openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false); file.write(qCompress(data.toUtf8())); } ); _lua["Rainback"]["WatchFile"] = std::function<void(LuaStack&)>( [this](LuaStack& stack) { auto watcher = new QFileSystemWatcher(this); for (int i=1; i <= stack.size(); ++i) { watcher->addPath(stack.as<QString>(i)); } stack.clear(); lua::push<QObject*>(stack, watcher, true); proxy::observeToDestroy(watcher, stack.as<LuaUserdata*>(-1)); } ); _lua["string"]["grep"] = lua::LuaCallable([](LuaStack& stack) { auto str = stack.as<QString>(1); QRegExp re(stack.as<QString>(2)); stack.clear(); if (re.indexIn(str) == -1) { return; } for (int i = 0; i <= re.captureCount(); ++i) { lua::push(stack, re.cap(i)); } }); _lua["Rainback"]["Network"] = lua::value::table; auto buildSocket = [](LuaStack& stack, QAbstractSocket* socket) { proxy::observeToDestroy(socket, stack.as<LuaUserdata*>(-1)); connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater())); }; _lua["Rainback"]["Network"]["serveTCP"] = lua::LuaCallable( [this](LuaStack& stack) { if (stack.size() < 1) { throw LuaException("serverTCP requires 1 argument, but the stack has none"); } auto port = stack.as<int>(1); proxy::validatePort(port); stack.clear(); auto server = new proxy::TCPServer; auto socketServer = new QTcpServer(server); server->setServer(socketServer); lua::push<QObject*>(stack, server, true); proxy::observeToDestroy(server, stack.as<LuaUserdata*>(-1)); socketServer->listen(QHostAddress::Any, port); } ); _lua["Rainback"]["Network"]["connectTCP"] = lua::LuaCallable( [this, buildSocket](LuaStack& stack) { if (stack.size() < 2) { std::stringstream str; str << "connectTCP requires 2 arguments, but was given only " << stack.size(); throw LuaException(str.str()); } auto hostname = stack.as<QString>(1); auto port = stack.as<int>(2); proxy::validatePort(port); stack.clear(); QAbstractSocket* socket = new QTcpSocket(this); lua::push<QAbstractSocket*>(stack, socket, true); buildSocket(stack, socket); socket->connectToHost(hostname, static_cast<quint16>(port)); return socket; } ); _lua["Rainback"]["Network"]["pascalProtocol"] = std::function<std::shared_ptr<protocol::AbstractLine>(LuaStack& stack)>( [this](LuaStack& stack) { std::shared_ptr<protocol::AbstractLine> ptl(std::make_shared<protocol::Pascal>()); if (stack.size() > 0) { ptl->listen(stack.as<QAbstractSocket*>()); } return ptl; } ); _lua["Rainback"]["Network"]["humanProtocol"] = std::function<std::shared_ptr<protocol::AbstractLine>(LuaStack& stack)>( [this](LuaStack& stack) { std::shared_ptr<protocol::AbstractLine> ptl(std::make_shared<protocol::Human>()); if (stack.size() > 0) { ptl->listen(stack.as<QAbstractSocket*>()); } return ptl; } ); lua::qvariantPusher(QVariant::Size, [](LuaStack& stack, const QVariant& source) { lua::push(stack, lua::value::table); auto size = source.toSize(); stack.set("width", size.width()); stack.set("height", size.height()); }); elapsed.start(); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(close())); } void Rainback::openFile(QFile& file, const QIODevice::OpenMode& flags, const bool checkExists) { if (checkExists && !file.exists()) { throw LuaException( (QString("The specified file '") + file.fileName() + "' does not exist").toStdString() ); } if (!file.open(flags)) { throw LuaException( (QString("The specified file '") + file.fileName() + "' failed to open: " + file.error()).toStdString() ); } } void Rainback::timeout() { rainback::dispatch(_lua, "UPDATE"); } void Rainback::close() { rainback::dispatch(_lua, "CLOSE"); } } // namespace rainback // vim: set ts=4 sw=4 : <commit_msg>Removed a redundant call<commit_after>#include "Rainback.hpp" #include <iostream> #include <functional> #include <QTextStream> #include <QApplication> #include <QPushButton> #include <QLineEdit> #include <QTextEdit> #include <QRegExp> #include <QFileSystemWatcher> #include <QTcpSocket> #include <lua-cxx/LuaValue.hpp> #include <lua-cxx/loaders.hpp> #include <lua-cxx/userdata.hpp> #include <lua-cxx/QObjectObserver.hpp> #include "LuaPainter.hpp" #include "LuaFont.hpp" #include "proxy/TCPServer.hpp" #include "protocol/Human.hpp" #include "protocol/Pascal.hpp" #include "proxy/QObject.hpp" #include "proxy/Socket.hpp" #include "proxy/TCPServer.hpp" #include "proxy/QWidget.hpp" #include "proxy/AbstractLine.hpp" using namespace rainback; std::shared_ptr<LuaFont> newFont(LuaStack& stack) { switch (stack.size()) { case 0: return std::make_shared<LuaFont>(); case 1: return std::make_shared<LuaFont>(stack.as<QString>(1)); default: return std::make_shared<LuaFont>( stack.as<QString>(1), stack.as<int>(2) ); } } namespace rainback { void Rainback::assertWidget() { if (!_widget) { throw LuaException("This function must not be used when no widget is available"); } } Rainback::Rainback(Lua& lua) : _widget(nullptr), _lua(lua) { if (_lua["unpack"].isNil()) { _lua["unpack"] = _lua["table"]["unpack"]; } _lua["Rainback"] = lua::value::table; _lua["error"] = lua::LuaCallable([](LuaStack& stack) { stack.error(stack.as<std::string>(-1)); }); _lua["Rainback"]["globals"] = lua::value::table; _lua["Rainback"]["AddModuleDirectory"] = std::function<void(const std::string&, const std::string&)>( [this](const std::string& root, const std::string& prefix) { auto loader = std::make_shared<DirectoryModuleLoader>(); loaders.push_back(loader); loader->setRoot(QDir(root.c_str())); loader->setPrefix(prefix); _lua.addModuleLoader(loader.get()); } ); _lua["Rainback"]["LoadDirectory"] = std::function<void(const std::string&, const bool)>( [this](const std::string& path, const bool recurse) { lua::load_dir(_lua, QDir(path.c_str()), recurse); } ); _lua["Rainback"]["Font"] = newFont; _lua["Rainback"]["Button"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QPushButton(_widget), true); } ); _lua["Rainback"]["LineEdit"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QLineEdit(_widget), true); } ); _lua["Rainback"]["TextEdit"] = lua::LuaCallable([this](LuaStack& stack) { assertWidget(); stack.clear(); lua::push<QWidget*>(stack, new QTextEdit(_widget), true); } ); _lua["Rainback" ]["ScreenWidth"] = std::function<int()>([this]() { assertWidget(); return _widget->width(); }); _lua["Rainback" ]["ScreenHeight"] = std::function<int()>([this]() { assertWidget(); return _widget->height(); }); _lua["Rainback"]["GetTime"] = std::function<long()>([this]() { return elapsed.elapsed(); }); _lua["Rainback"]["StartTick"] = std::function<std::function<void()>(const int)>([this](const int framerate) { timer.start(1000 / framerate); return [this]() { timer.stop(); }; }); _lua["Rainback"]["GetCursorPosition"] = std::function<void(LuaStack&)>([this](LuaStack& stack) { assertWidget(); QPoint pos(_widget->mapFromGlobal(QCursor::pos())); stack.clear(); lua::push(stack, pos.x()); lua::push(stack, pos.y()); }); _lua["Rainback"]["Update"] = std::function<void()>([this]() { assertWidget(); _widget->update(); }); _lua["Rainback"]["Close"] = std::function<void()>([this]() { assertWidget(); qApp->closeAllWindows(); }); _lua["Rainback"]["SetBackgroundColor"] = std::function<void(const int, const int, const int)>( [this](const int r, const int g, const int b) { assertWidget(); _widget->setAutoFillBackground(true); QPalette p(_widget->palette()); p.setColor(QPalette::Background, QColor(r, g, b)); _widget->setPalette(p); } ); _lua["Rainback"]["FileExists"] = std::function<bool(const QString&)>( [this](const QString& fileName) { return QFile(fileName).exists(); } ); _lua["Rainback"]["ReadFile"] = std::function<QString(const QString&)>( [this](const QString& fileName) { QFile file(fileName); openFile(file, QIODevice::ReadOnly, true); // Using QTextStream here breaks for Unicode strings return QString(file.readAll()); } ); _lua["Rainback"]["ReadCompressedFile"] = std::function<QString(const QString&)>( [this](const QString& fileName) { QFile file(fileName); openFile(file, QIODevice::ReadOnly, true); return QString(qUncompress(file.readAll())); } ); _lua["Rainback"]["WriteFile"] = std::function<void(const QString&, const QString&)>( [this](const QString& fileName, const QString& data) { QFile file(fileName); openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false); QTextStream(&file) << data; } ); _lua["Rainback"]["WriteCompressedFile"] = std::function<void(const QString&, const QString&)>( [this](const QString& fileName, const QString& data) { QFile file(fileName); openFile(file, QIODevice::WriteOnly | QIODevice::Truncate, false); file.write(qCompress(data.toUtf8())); } ); _lua["Rainback"]["WatchFile"] = std::function<void(LuaStack&)>( [this](LuaStack& stack) { auto watcher = new QFileSystemWatcher(this); for (int i=1; i <= stack.size(); ++i) { watcher->addPath(stack.as<QString>(i)); } stack.clear(); lua::push<QObject*>(stack, watcher, true); proxy::observeToDestroy(watcher, stack.as<LuaUserdata*>(-1)); } ); _lua["string"]["grep"] = lua::LuaCallable([](LuaStack& stack) { auto str = stack.as<QString>(1); QRegExp re(stack.as<QString>(2)); stack.clear(); if (re.indexIn(str) == -1) { return; } for (int i = 0; i <= re.captureCount(); ++i) { lua::push(stack, re.cap(i)); } }); _lua["Rainback"]["Network"] = lua::value::table; _lua["Rainback"]["Network"]["serveTCP"] = lua::LuaCallable( [this](LuaStack& stack) { if (stack.size() < 1) { throw LuaException("serverTCP requires 1 argument, but the stack has none"); } auto port = stack.as<int>(1); proxy::validatePort(port); stack.clear(); auto server = new proxy::TCPServer; auto socketServer = new QTcpServer(server); server->setServer(socketServer); lua::push<QObject*>(stack, server, true); proxy::observeToDestroy(server, stack.as<LuaUserdata*>(-1)); socketServer->listen(QHostAddress::Any, port); } ); _lua["Rainback"]["Network"]["connectTCP"] = lua::LuaCallable( [this](LuaStack& stack) { if (stack.size() < 2) { std::stringstream str; str << "connectTCP requires 2 arguments, but was given only " << stack.size(); throw LuaException(str.str()); } auto hostname = stack.as<QString>(1); auto port = stack.as<int>(2); proxy::validatePort(port); stack.clear(); QAbstractSocket* socket = new QTcpSocket(this); lua::push<QAbstractSocket*>(stack, socket, true); socket->connectToHost(hostname, static_cast<quint16>(port)); return socket; } ); _lua["Rainback"]["Network"]["pascalProtocol"] = std::function<std::shared_ptr<protocol::AbstractLine>(LuaStack& stack)>( [this](LuaStack& stack) { std::shared_ptr<protocol::AbstractLine> ptl(std::make_shared<protocol::Pascal>()); if (stack.size() > 0) { ptl->listen(stack.as<QAbstractSocket*>()); } return ptl; } ); _lua["Rainback"]["Network"]["humanProtocol"] = std::function<std::shared_ptr<protocol::AbstractLine>(LuaStack& stack)>( [this](LuaStack& stack) { std::shared_ptr<protocol::AbstractLine> ptl(std::make_shared<protocol::Human>()); if (stack.size() > 0) { ptl->listen(stack.as<QAbstractSocket*>()); } return ptl; } ); lua::qvariantPusher(QVariant::Size, [](LuaStack& stack, const QVariant& source) { lua::push(stack, lua::value::table); auto size = source.toSize(); stack.set("width", size.width()); stack.set("height", size.height()); }); elapsed.start(); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(close())); } void Rainback::openFile(QFile& file, const QIODevice::OpenMode& flags, const bool checkExists) { if (checkExists && !file.exists()) { throw LuaException( (QString("The specified file '") + file.fileName() + "' does not exist").toStdString() ); } if (!file.open(flags)) { throw LuaException( (QString("The specified file '") + file.fileName() + "' failed to open: " + file.error()).toStdString() ); } } void Rainback::timeout() { rainback::dispatch(_lua, "UPDATE"); } void Rainback::close() { rainback::dispatch(_lua, "CLOSE"); } } // namespace rainback // vim: set ts=4 sw=4 : <|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/. */ #ifndef DATASERIES_HXX #define DATASERIES_HXX #include <rtl/ustring.hxx> #include <mdds/multi_type_vector.hpp> #include <mdds/multi_type_vector_trait.hpp> #include <vector> #include <map> #include <com/sun/star/uno/Any.h> namespace chart { class DataSeries { public: typedef mdds::multi_type_vector<mdds::mtv::element_block_func> DataSeriesType; DataSeriesType getDataSeries(); size_t size(); double getValue(size_t nIndex); private: OUString maLabel; DataSeriesType maDataSeries; }; /** * point properties overwrite series properties */ struct DataSeriesProperties { typedef std::map< OUString, com::sun::star::uno::Any > PropertyMap; PropertyMap aSeriesProps; std::vector< PropertyMap > aPointProps; }; struct Axis { double nMin; double nMax; bool bLog; bool bInverseDirection; }; struct DataSeriesState { DataSeries aXValue; DataSeries aYValue; DataSeriesProperties aProperties; std::map<OUString, DataSeries> aMapProperties; Axis aXAxis; Axis aYAxis; }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>some small cosmetic changes<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/. */ #ifndef DATASERIES_HXX #define DATASERIES_HXX #include <rtl/ustring.hxx> #include <mdds/multi_type_vector.hpp> #include <mdds/multi_type_vector_trait.hpp> #include <vector> #include <map> #include <com/sun/star/uno/Any.h> namespace chart { class DataSequence { public: typedef mdds::multi_type_vector<mdds::mtv::element_block_func> DataSeriesType; // used for fast iteration through data series // allows to easily skip empty data ranges DataSeriesType getDataSeries(); size_t size(); double getValue(size_t nIndex); private: OUString maLabel; DataSeriesType maDataSeries; }; /** * point properties overwrite series properties */ struct DataSeriesProperties { typedef std::map< OUString, com::sun::star::uno::Any > PropertyMap; PropertyMap aSeriesProps; // we might want to switch to multi_type_vector for better memory usage // hopefully this vector is empty most of the time std::vector< PropertyMap > aPointProps; com::sun::star::chart::MissingValueTreatment eMissingValueTreatment; }; struct Axis { double nMin; double nMax; bool bLog; bool bInverseDirection; }; struct DataSeriesState { // length of the data series is min(aXValue.size(), aYValue.size()); DataSequence aXValue; DataSequence aYValue; DataSeriesProperties aProperties; // also contains bubble chart bubble size // apply values to properties with functor std::map<OUString, DataSeries> aMappedProperties; Axis aXAxis; Axis aYAxis; }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <malloc.h> #include <stdarg.h> #include <string.h> #include <io.h> #include "Resource.h" #define USE_NAMETREES #define filesize(fileptr) (filelength(fileno(fileptr))) CResource::CResource() { drs=NULL; Init(); } CResource::~CResource() { ShutDown(); } bool CResource::Init() { ShutDown(); return true; } void CResource::ShutDown() { CloseResource(); } void CResource::DestroyNameTree() { nametree.Destroy(); } bool CResource::BuildNameTree() { int i; for (i=0;i<NUM_RES_ENTRIES;i++) { if (drstable[i].foffset!=0) { if (!nametree.AddLeaf(drstable[i].fname,i)) { nametree.Destroy(); return false; } } } return true; } int CResource::SearchNameTree(char *name) { return nametree.FindLeaf(name); } int CResource::FindEntryBrutal(char *entryname) { int i; if (drs!=NULL) { for (i=0;i<NUM_RES_ENTRIES;i++) { if (!stricmp(entryname,drstable[i].fname)) return i; } } return -1; } bool CResource::OpenResource(const char *filename) { int i; uint32_t size,drssize; const int hdrlen=8; char cmphdr[hdrlen]; char idhdr[hdrlen]={'v','s',' ','d','2',0,0,0}; if (filename==NULL || filename[0]==0) return false; if (strcmp(filename, path)==0) return true; memset(cmphdr, 0, sizeof(cmphdr)); CloseResource(); drs=fopen((const char *)filename, "rb"); if (drs==NULL) return false; size=fread(cmphdr,1,hdrlen,drs); if (size==hdrlen) { size=memcmp(cmphdr,idhdr, hdrlen); if (size==0) { for (i=0,size=0,drssize=0;i<NUM_RES_ENTRIES;i++) { memset(drstable[i].fname,0,sizeof(drstable[i].fname)); size+=fread(&drstable[i].fname,1,sizeof(drstable[i].fname),drs); size+=fread(&drstable[i].foffset,1,sizeof(drstable[i].foffset),drs); size+=fread(&drstable[i].fsize,1,sizeof(drstable[i].fname)-1,drs); strupr(drstable[i].fname); drssize+=drstable[i].fsize; } drssize+=size+hdrlen; if (drssize==filesize(drs) && size==NUM_RES_ENTRIES*((sizeof(drstable[0].fname)-1)+sizeof(drstable[0].fsize)+sizeof(drstable[0].foffset))) { #ifdef USE_NAMETREES if (BuildNameTree()) #endif { strncpy(path, filename, sizeof(path)); path[sizeof(path)-1]=0; return true; } } } } CloseResource(); return false; } void CResource::CloseResource() { if (drs!=NULL) { fclose(drs); } drs=NULL; memset(drstable,0,sizeof(drstable)); path[0]=0; #ifdef USE_NAMETREES DestroyNameTree(); #endif } int CResource::FindEntry(const char *entryname) { char uprname[16]; if (entryname==NULL) return -1; strncpy(uprname,entryname,sizeof(uprname)); uprname[sizeof(uprname)-1]=0; strupr(uprname); #ifdef USE_NAMETREES return SearchNameTree(uprname); #else return FindEntryBrutal(uprname); #endif } bool CResource::ReadEntry(void *buffer, int entrynum) { if (drs!=NULL && buffer!=NULL && entrynum<NUM_RES_ENTRIES && entrynum>=0) { if (!fseek(drs,drstable[entrynum].foffset,SEEK_SET)) { if (fread(buffer,1,drstable[entrynum].fsize,drs)==drstable[entrynum].fsize) return true; } } return false; } bool CResource::ReadEntryEx(void *buffer, int entrynum, int offset, int size) { if (drs!=NULL && buffer!=NULL && entrynum<NUM_RES_ENTRIES && entrynum>=0) { if (size==0) size=drstable[entrynum].fsize; if ((offset+size)<=(int)drstable[entrynum].fsize) { if (!fseek(drs,drstable[entrynum].foffset+offset,SEEK_SET)) { if ((int)fread(buffer,1,size,drs)==size) return true; } } } return false; } char *CResource::GetEntryName(int entrynum) { if (drs==NULL || entrynum>=NUM_RES_ENTRIES || entrynum<0) return NULL; return drstable[entrynum].fname; } int CResource::GetEntrySize(int entrynum) { if (drs==NULL || entrynum>=NUM_RES_ENTRIES || entrynum<0) return -1; return (int)drstable[entrynum].fsize; } <commit_msg>Fixed a bug in the resource loader.<commit_after>#include <malloc.h> #include <stdarg.h> #include <string.h> #include <io.h> #include "Resource.h" #define USE_NAMETREES #define filesize(fileptr) (filelength(fileno(fileptr))) CResource::CResource() { drs=NULL; Init(); } CResource::~CResource() { ShutDown(); } bool CResource::Init() { ShutDown(); return true; } void CResource::ShutDown() { CloseResource(); } void CResource::DestroyNameTree() { nametree.Destroy(); } bool CResource::BuildNameTree() { int i; for (i=0;i<NUM_RES_ENTRIES;i++) { if (drstable[i].foffset!=0) { if (!nametree.AddLeaf(drstable[i].fname,i)) { nametree.Destroy(); return false; } } } return true; } int CResource::SearchNameTree(char *name) { return nametree.FindLeaf(name); } int CResource::FindEntryBrutal(char *entryname) { int i; if (drs!=NULL) { for (i=0;i<NUM_RES_ENTRIES;i++) { if (!stricmp(entryname,drstable[i].fname)) return i; } } return -1; } bool CResource::OpenResource(const char *filename) { int i; uint32_t size,drssize; const int hdrlen=8; char cmphdr[hdrlen]; char idhdr[hdrlen]={'v','s',' ','d','2',0,0,0}; if (filename==NULL || filename[0]==0) return false; if (strcmp(filename, path)==0) return true; memset(cmphdr, 0, sizeof(cmphdr)); CloseResource(); drs=fopen((const char *)filename, "rb"); if (drs==NULL) return false; size=fread(cmphdr,1,hdrlen,drs); if (size==hdrlen) { size=memcmp(cmphdr,idhdr, hdrlen); if (size==0) { for (i=0,size=0,drssize=0;i<NUM_RES_ENTRIES;i++) { memset(drstable[i].fname,0,sizeof(drstable[i].fname)); size+=fread(&drstable[i].fname,1,sizeof(drstable[i].fname)-1,drs); size+=fread(&drstable[i].foffset,1,sizeof(drstable[i].foffset),drs); size+=fread(&drstable[i].fsize,1,sizeof(drstable[i].fsize),drs); strupr(drstable[i].fname); drssize+=drstable[i].fsize; } drssize+=size+hdrlen; if (drssize==filesize(drs) && size==NUM_RES_ENTRIES*((sizeof(drstable[0].fname)-1)+sizeof(drstable[0].fsize)+sizeof(drstable[0].foffset))) { #ifdef USE_NAMETREES if (BuildNameTree()) #endif { strncpy(path, filename, sizeof(path)); path[sizeof(path)-1]=0; return true; } } } } CloseResource(); return false; } void CResource::CloseResource() { if (drs!=NULL) { fclose(drs); } drs=NULL; memset(drstable,0,sizeof(drstable)); path[0]=0; #ifdef USE_NAMETREES DestroyNameTree(); #endif } int CResource::FindEntry(const char *entryname) { char uprname[16]; if (entryname==NULL) return -1; strncpy(uprname,entryname,sizeof(uprname)); uprname[sizeof(uprname)-1]=0; strupr(uprname); #ifdef USE_NAMETREES return SearchNameTree(uprname); #else return FindEntryBrutal(uprname); #endif } bool CResource::ReadEntry(void *buffer, int entrynum) { if (drs!=NULL && buffer!=NULL && entrynum<NUM_RES_ENTRIES && entrynum>=0) { if (!fseek(drs,drstable[entrynum].foffset,SEEK_SET)) { if (fread(buffer,1,drstable[entrynum].fsize,drs)==drstable[entrynum].fsize) return true; } } return false; } bool CResource::ReadEntryEx(void *buffer, int entrynum, int offset, int size) { if (drs!=NULL && buffer!=NULL && entrynum<NUM_RES_ENTRIES && entrynum>=0) { if (size==0) size=drstable[entrynum].fsize; if ((offset+size)<=(int)drstable[entrynum].fsize) { if (!fseek(drs,drstable[entrynum].foffset+offset,SEEK_SET)) { if ((int)fread(buffer,1,size,drs)==size) return true; } } } return false; } char *CResource::GetEntryName(int entrynum) { if (drs==NULL || entrynum>=NUM_RES_ENTRIES || entrynum<0) return NULL; return drstable[entrynum].fname; } int CResource::GetEntrySize(int entrynum) { if (drs==NULL || entrynum>=NUM_RES_ENTRIES || entrynum<0) return -1; return (int)drstable[entrynum].fsize; } <|endoftext|>
<commit_before>#include "Course.h" #include "CourseCont.h" #include "Options.h" #include "Scheduler.h" #include <iostream> CourseSched Scheduler::generateSchedule(CourseCont& courseList, Options &opts){ CourseSched schedule; courseList.sort(); courseList.begin(); bool reachEnd = false; for(int i = 0; i < opts.getNumCourses() && !reachEnd;){ reachEnd = courseList.getCourse().equal(courseList.last()); try{ courseList.getCourse().addPadding(opts.getBreakPadding()); schedule.addCourse(courseList.getCourse()); courseList.next(); i++; }catch(const TimeConflict &expt){ courseList.next(); }catch(const EmptyContainer &epct){ break; } } return schedule; }<commit_msg>fixes #12 - uses functions available to check for conflicts with padding without changing the course times that are added to the schedule<commit_after>#include "Course.h" #include "CourseCont.h" #include "Options.h" #include "Scheduler.h" #include <iostream> CourseSched Scheduler::generateSchedule(CourseCont& courseList, Options &opts){ CourseSched schedule; courseList.sort(); courseList.begin(); bool reachEnd = false; for(int i = 0; i < opts.getNumCourses() && !reachEnd;){ reachEnd = courseList.getCourse().equal(courseList.last()); try{ Course add, comp; add = comp = courseList.getCourse(); //.addPadding(opts.getBreakPadding()); comp.addPadding(opts.getBreakPadding()); schedule.findCourseConflict(comp); //will throw and skip if conflict schedule.addCourse(add); courseList.next(); i++; }catch(const TimeConflict &expt){ courseList.next(); }catch(const EmptyContainer &epct){ break; } } return schedule; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dsEntriesNoExp.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: pjunck $ $Date: 2004-10-22 12:03:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SBA_UNODATBR_HXX_ #include "unodatbr.hxx" #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef _DBAUI_LISTVIEWITEMS_HXX_ #include "listviewitems.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif #ifndef _DBU_BRW_HRC_ #include "dbu_brw.hrc" #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif using namespace ::dbtools; using namespace ::svx; // ......................................................................... namespace dbaui { // ......................................................................... // ----------------------------------------------------------------------------- SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const { DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!"); switch (getEntryType(_pEntry)) { case etTableContainer: return etTable; case etQueryContainer: return etQuery; } return etUnknown; } // ----------------------------------------------------------------------------- String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const { return m_pTreeView->getListBox()->GetEntryText(_pEntry); } // ----------------------------------------------------------------------------- SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const { if (!_pEntry) return etUnknown; SvLBoxEntry* pRootEntry = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry); SvLBoxEntry* pEntryParent = m_pTreeView->getListBox()->GetParent(_pEntry); SvLBoxEntry* pTables = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES); SvLBoxEntry* pQueries = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES); #ifdef DBG_UTIL String sTest; if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables); if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries); #endif if (pRootEntry == _pEntry) return etDatasource; if (pTables == _pEntry) return etTableContainer; if (pQueries == _pEntry) return etQueryContainer; if (pTables == pEntryParent) return etTable; if (pQueries == pEntryParent) return etQuery; return etUnknown; } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect) { SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL; if (pTextItem) { static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect); m_pTreeModel->InvalidateEntry(_pEntry); } else DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!"); } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect) { while (_pEntry) { select(_pEntry, _bSelect); _pEntry = m_pTreeModel->GetParent(_pEntry); } } //------------------------------------------------------------------------------ sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const { SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL; if (pTextItem) return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized(); else DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!"); return sal_False; } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::AddSupportedFeatures() { SbaXDataBrowserController::AddSupportedFeatures(); m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:Title")] = ID_BROWSER_TITLE; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DSBrowserExplorer")] = ID_BROWSER_EXPLORER; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DSBFormLetter")] = ID_BROWSER_FORMLETTER; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DSBInsertColumns")] = ID_BROWSER_INSERTCOLUMNS; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DSBInsertContent")] = ID_BROWSER_INSERTCONTENT; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DSBDocumentDataSource")] = ID_BROWSER_DOCUMENT_DATASOURCE; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:CloseWin")] = ID_BROWSER_CLOSE; m_aSupportedFeatures[ ::rtl::OUString::createFromAscii(".uno:DBRebuildData")] = ID_BROWSER_REFRESH_REBUILD; } // ------------------------------------------------------------------------- String SbaTableQueryBrowser::getURL() const { return String(); } // ----------------------------------------------------------------------------- void SbaTableQueryBrowser::notifyHiContrastChanged() { if ( m_pTreeView ) { sal_Bool bHiContrast = isHiContrast(); if ( m_bHiContrast != bHiContrast ) { m_bHiContrast = bHiContrast; // change all bitmap entries DBTreeListBox* pListBox = m_pTreeView->getListBox(); SvLBoxEntry* pEntryLoop = m_pTreeModel->First(); while ( pEntryLoop ) { DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData()); if ( pData ) { ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast())); Image aImage(aResId); USHORT nCount = pEntryLoop->ItemCount(); for (USHORT i=0;i<nCount;++i) { SvLBoxItem* pItem = pEntryLoop->GetItem(i); if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP) { static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage); static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage); break; } } } pEntryLoop = m_pTreeModel->Next(pEntryLoop); } } } } // ----------------------------------------------------------------------------- // ......................................................................... } // namespace dbaui // ......................................................................... <commit_msg>INTEGRATION: CWS dba19 (1.10.8); FILE MERGED 2004/11/09 08:09:14 oj 1.10.8.1: #i36540# add forma letter again to supported features<commit_after>/************************************************************************* * * $RCSfile: dsEntriesNoExp.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2004-11-16 09:29:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SBA_UNODATBR_HXX_ #include "unodatbr.hxx" #endif #ifndef DBACCESS_UI_BROWSER_ID_HXX #include "browserids.hxx" #endif #ifndef _DBAUI_LISTVIEWITEMS_HXX_ #include "listviewitems.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef DBACCESS_UI_DBTREEVIEW_HXX #include "dbtreeview.hxx" #endif #ifndef DBAUI_DBTREELISTBOX_HXX #include "dbtreelistbox.hxx" #endif #ifndef _DBU_BRW_HRC_ #include "dbu_brw.hrc" #endif #ifndef DBAUI_DBTREEMODEL_HXX #include "dbtreemodel.hxx" #endif using namespace ::dbtools; using namespace ::svx; // ......................................................................... namespace dbaui { // ......................................................................... // ----------------------------------------------------------------------------- SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getChildType( SvLBoxEntry* _pEntry ) const { DBG_ASSERT(isContainer(_pEntry), "SbaTableQueryBrowser::getChildType: invalid entry!"); switch (getEntryType(_pEntry)) { case etTableContainer: return etTable; case etQueryContainer: return etQuery; } return etUnknown; } // ----------------------------------------------------------------------------- String SbaTableQueryBrowser::GetEntryText( SvLBoxEntry* _pEntry ) const { return m_pTreeView->getListBox()->GetEntryText(_pEntry); } // ----------------------------------------------------------------------------- SbaTableQueryBrowser::EntryType SbaTableQueryBrowser::getEntryType( SvLBoxEntry* _pEntry ) const { if (!_pEntry) return etUnknown; SvLBoxEntry* pRootEntry = m_pTreeView->getListBox()->GetRootLevelParent(_pEntry); SvLBoxEntry* pEntryParent = m_pTreeView->getListBox()->GetParent(_pEntry); SvLBoxEntry* pTables = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_TABLES); SvLBoxEntry* pQueries = m_pTreeView->getListBox()->GetEntry(pRootEntry, CONTAINER_QUERIES); #ifdef DBG_UTIL String sTest; if (pTables) sTest = m_pTreeView->getListBox()->GetEntryText(pTables); if (pQueries) sTest = m_pTreeView->getListBox()->GetEntryText(pQueries); #endif if (pRootEntry == _pEntry) return etDatasource; if (pTables == _pEntry) return etTableContainer; if (pQueries == _pEntry) return etQueryContainer; if (pTables == pEntryParent) return etTable; if (pQueries == pEntryParent) return etQuery; return etUnknown; } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::select(SvLBoxEntry* _pEntry, sal_Bool _bSelect) { SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL; if (pTextItem) { static_cast<OBoldListboxString*>(pTextItem)->emphasize(_bSelect); m_pTreeModel->InvalidateEntry(_pEntry); } else DBG_ERROR("SbaTableQueryBrowser::select: invalid entry!"); } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::selectPath(SvLBoxEntry* _pEntry, sal_Bool _bSelect) { while (_pEntry) { select(_pEntry, _bSelect); _pEntry = m_pTreeModel->GetParent(_pEntry); } } //------------------------------------------------------------------------------ sal_Bool SbaTableQueryBrowser::isSelected(SvLBoxEntry* _pEntry) const { SvLBoxItem* pTextItem = _pEntry ? _pEntry->GetFirstItem(SV_ITEM_ID_BOLDLBSTRING) : NULL; if (pTextItem) return static_cast<OBoldListboxString*>(pTextItem)->isEmphasized(); else DBG_ERROR("SbaTableQueryBrowser::isSelected: invalid entry!"); return sal_False; } //------------------------------------------------------------------------------ void SbaTableQueryBrowser::AddSupportedFeatures() { SbaXDataBrowserController::AddSupportedFeatures(); m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:Title"))] = ID_BROWSER_TITLE; if ( !m_bShowMenu ) { m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DSBrowserExplorer"))] = ID_BROWSER_EXPLORER; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DSBFormLetter"))] = ID_BROWSER_FORMLETTER; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DSBInsertColumns"))] = ID_BROWSER_INSERTCOLUMNS; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DSBInsertContent"))] = ID_BROWSER_INSERTCONTENT; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DSBDocumentDataSource"))] = ID_BROWSER_DOCUMENT_DATASOURCE; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DataSourceBrowser/FormLetter"))] = ID_BROWSER_FORMLETTER; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DataSourceBrowser/InsertColumns"))] = ID_BROWSER_INSERTCOLUMNS; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DataSourceBrowser/InsertContent"))] = ID_BROWSER_INSERTCONTENT; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DataSourceBrowser/DocumentDataSource"))]= ID_BROWSER_DOCUMENT_DATASOURCE; } m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseWin"))] = ID_BROWSER_CLOSE; m_aSupportedFeatures[ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:DBRebuildData"))] = ID_BROWSER_REFRESH_REBUILD; } // ------------------------------------------------------------------------- String SbaTableQueryBrowser::getURL() const { return String(); } // ----------------------------------------------------------------------------- void SbaTableQueryBrowser::notifyHiContrastChanged() { if ( m_pTreeView ) { sal_Bool bHiContrast = isHiContrast(); if ( m_bHiContrast != bHiContrast ) { m_bHiContrast = bHiContrast; // change all bitmap entries DBTreeListBox* pListBox = m_pTreeView->getListBox(); SvLBoxEntry* pEntryLoop = m_pTreeModel->First(); while ( pEntryLoop ) { DBTreeListModel::DBTreeListUserData* pData = static_cast<DBTreeListModel::DBTreeListUserData*>(pEntryLoop->GetUserData()); if ( pData ) { ModuleRes aResId(DBTreeListModel::getImageResId(pData->eType,isHiContrast())); Image aImage(aResId); USHORT nCount = pEntryLoop->ItemCount(); for (USHORT i=0;i<nCount;++i) { SvLBoxItem* pItem = pEntryLoop->GetItem(i); if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXCONTEXTBMP) { static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap1(pEntryLoop,aImage); static_cast<SvLBoxContextBmp*>(pItem)->SetBitmap2(pEntryLoop,aImage); break; } } } pEntryLoop = m_pTreeModel->Next(pEntryLoop); } } } } // ----------------------------------------------------------------------------- // ......................................................................... } // namespace dbaui // ......................................................................... <|endoftext|>
<commit_before>/* Copyright (c) 2014 Ableton AG, Berlin 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. */ // clang-format off #pragma once #if defined(__clang__) #if __has_warning("-Wreserved-id-macro") #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \ _Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") #else #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO #endif #if __has_warning("-Wunused-local-typedef") #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF \ _Pragma("clang diagnostic ignored \"-Wunused-local-typedef\"") #else #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF #endif #define SUPPRESS_WARNINGS \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"") \ _Pragma("clang diagnostic ignored \"-Wconversion\"") \ _Pragma("clang diagnostic ignored \"-Wcovered-switch-default\"") \ _Pragma("clang diagnostic ignored \"-Wdeprecated\"") \ _Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"") \ _Pragma("clang diagnostic ignored \"-Wdocumentation-unknown-command\"") \ _Pragma("clang diagnostic ignored \"-Wdocumentation\"") \ _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \ _Pragma("clang diagnostic ignored \"-Wextra-semi\"") \ _Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \ _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") \ _Pragma("clang diagnostic ignored \"-Wheader-hygiene\"") \ _Pragma("clang diagnostic ignored \"-Wmissing-noreturn\"") \ _Pragma("clang diagnostic ignored \"-Wmissing-prototypes\"") \ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ _Pragma("clang diagnostic ignored \"-Wpadded\"") \ _Pragma("clang diagnostic ignored \"-Wshadow\"") \ _Pragma("clang diagnostic ignored \"-Wshift-sign-overflow\"") \ _Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \ _Pragma("clang diagnostic ignored \"-Wsign-compare\"") \ _Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \ _Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \ _Pragma("clang diagnostic ignored \"-Wundef\"") \ _Pragma("clang diagnostic ignored \"-Wundefined-reinterpret-cast\"") \ _Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \ _Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \ _Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \ _Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \ ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \ ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF #define RESTORE_WARNINGS \ _Pragma("clang diagnostic pop") #elif defined(_MSC_VER) #if _MSC_VER < 1900 #define ABL_PRAGMA_MSVC_DISABLE_4459 #else #define ABL_PRAGMA_MSVC_DISABLE_4459 \ __pragma(warning(disable: 4459)) #endif /** * C4100: 'identifier' : unreferenced formal parameter * C4127: conditional expression is constant * C4191: 'type cast' : unsafe conversion from 'function pointer type' to 'function pointer type' * Calling this function through the result pointer may cause your program to fail * C4244: 'conversion' conversion from 'type1' to 'type2', possible loss of data * C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' * C4365: 'action' : conversion from 'type_1' to 'type_2', signed/unsigned mismatch * C4388: signed/unsigned mismatch * C4459: declaration of 'identifier' hides global declaration * C4555: expression has no effect; expected expression with side-effect * C4619: #pragma warning : there is no warning number 'number' * C4628: digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char' * C4640: 'instance' : construction of local static object is not thread-safe * C4668: 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' * C4714: function 'function' marked as __forceinline not inlined * C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning) * C4826: Conversion from 'type1 ' to 'type_2' is sign-extended. This may cause unexpected runtime behavior. */ #define SUPPRESS_WARNINGS \ __pragma(warning(push)) \ __pragma(warning(disable: 4100)) \ __pragma(warning(disable: 4127)) \ __pragma(warning(disable: 4191)) \ __pragma(warning(disable: 4244)) \ __pragma(warning(disable: 4251)) \ __pragma(warning(disable: 4365)) \ __pragma(warning(disable: 4388)) \ __pragma(warning(disable: 4555)) \ __pragma(warning(disable: 4619)) \ __pragma(warning(disable: 4628)) \ __pragma(warning(disable: 4640)) \ __pragma(warning(disable: 4668)) \ __pragma(warning(disable: 4714)) \ __pragma(warning(disable: 4800)) \ __pragma(warning(disable: 4826)) \ ABL_PRAGMA_MSVC_DISABLE_4459 #define RESTORE_WARNINGS \ __pragma(warning(pop)) #else #define SUPPRESS_WARNINGS #define RESTORE_WARNINGS #endif <commit_msg>Disable MSVC warning C4242 produced by Qt5.6 headers<commit_after>/* Copyright (c) 2014 Ableton AG, Berlin 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. */ // clang-format off #pragma once #if defined(__clang__) #if __has_warning("-Wreserved-id-macro") #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \ _Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") #else #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO #endif #if __has_warning("-Wunused-local-typedef") #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF \ _Pragma("clang diagnostic ignored \"-Wunused-local-typedef\"") #else #define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF #endif #define SUPPRESS_WARNINGS \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"") \ _Pragma("clang diagnostic ignored \"-Wconversion\"") \ _Pragma("clang diagnostic ignored \"-Wcovered-switch-default\"") \ _Pragma("clang diagnostic ignored \"-Wdeprecated\"") \ _Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"") \ _Pragma("clang diagnostic ignored \"-Wdocumentation-unknown-command\"") \ _Pragma("clang diagnostic ignored \"-Wdocumentation\"") \ _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \ _Pragma("clang diagnostic ignored \"-Wextra-semi\"") \ _Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \ _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") \ _Pragma("clang diagnostic ignored \"-Wheader-hygiene\"") \ _Pragma("clang diagnostic ignored \"-Wmissing-noreturn\"") \ _Pragma("clang diagnostic ignored \"-Wmissing-prototypes\"") \ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ _Pragma("clang diagnostic ignored \"-Wpadded\"") \ _Pragma("clang diagnostic ignored \"-Wshadow\"") \ _Pragma("clang diagnostic ignored \"-Wshift-sign-overflow\"") \ _Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \ _Pragma("clang diagnostic ignored \"-Wsign-compare\"") \ _Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \ _Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \ _Pragma("clang diagnostic ignored \"-Wundef\"") \ _Pragma("clang diagnostic ignored \"-Wundefined-reinterpret-cast\"") \ _Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \ _Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \ _Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \ _Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \ ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \ ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF #define RESTORE_WARNINGS \ _Pragma("clang diagnostic pop") #elif defined(_MSC_VER) #if _MSC_VER < 1900 #define ABL_PRAGMA_MSVC_DISABLE_4459 #else #define ABL_PRAGMA_MSVC_DISABLE_4459 \ __pragma(warning(disable: 4459)) #endif /** * C4100: 'identifier' : unreferenced formal parameter * C4127: conditional expression is constant * C4191: 'type cast' : unsafe conversion from 'function pointer type' to 'function pointer type' * Calling this function through the result pointer may cause your program to fail * C4242: 'identifier' : conversion from 'type1' to 'type2', possible loss of data * C4244: 'conversion' conversion from 'type1' to 'type2', possible loss of data * C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' * C4365: 'action' : conversion from 'type_1' to 'type_2', signed/unsigned mismatch * C4388: signed/unsigned mismatch * C4459: declaration of 'identifier' hides global declaration * C4555: expression has no effect; expected expression with side-effect * C4619: #pragma warning : there is no warning number 'number' * C4628: digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char' * C4640: 'instance' : construction of local static object is not thread-safe * C4668: 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' * C4714: function 'function' marked as __forceinline not inlined * C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning) * C4826: Conversion from 'type1 ' to 'type_2' is sign-extended. This may cause unexpected runtime behavior. */ #define SUPPRESS_WARNINGS \ __pragma(warning(push)) \ __pragma(warning(disable: 4100)) \ __pragma(warning(disable: 4127)) \ __pragma(warning(disable: 4191)) \ __pragma(warning(disable: 4242)) \ __pragma(warning(disable: 4244)) \ __pragma(warning(disable: 4251)) \ __pragma(warning(disable: 4365)) \ __pragma(warning(disable: 4388)) \ __pragma(warning(disable: 4555)) \ __pragma(warning(disable: 4619)) \ __pragma(warning(disable: 4628)) \ __pragma(warning(disable: 4640)) \ __pragma(warning(disable: 4668)) \ __pragma(warning(disable: 4714)) \ __pragma(warning(disable: 4800)) \ __pragma(warning(disable: 4826)) \ ABL_PRAGMA_MSVC_DISABLE_4459 #define RESTORE_WARNINGS \ __pragma(warning(pop)) #else #define SUPPRESS_WARNINGS #define RESTORE_WARNINGS #endif <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2014 Johannes Hggqvist 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 "WaveFile.h" #include <fstream> #include <iostream> #include <cstdint> #include <cassert> #include <cstring> namespace { struct RIFFChunk { std::uint32_t chunkID; std::uint32_t chunkSize; std::uint32_t format; }; struct fmtChunk { std::uint32_t chunkID; std::uint32_t chunkSize; std::uint16_t audioFormat; std::uint16_t numChannels; std::uint32_t sampleRate; std::uint32_t byteRate; std::uint16_t blockAlign; std::uint16_t bitsPerSample; }; struct WaveHeader { RIFFChunk riff; fmtChunk fmt; }; } WaveFile::WaveFile() : data(nullptr), size(0) { } WaveFile::WaveFile(const std::string &filename) : data(nullptr), size(0) { Load(filename); } WaveFile::~WaveFile() { Unload(); } bool WaveFile::Load(const std::string &filename) { if (IsLoaded()) { Unload(); } std::fstream file(filename, std::ios::in | std::ios::binary); if (!file.is_open()) { std::cerr << "Error: Could not open file." << std::endl; return false; } WaveHeader header; std::memset(&header, 0, sizeof(WaveHeader)); while (file.peek() != std::char_traits<char>::eof()) { std::uint32_t chunkID; std::uint32_t chunkSize; file.read(reinterpret_cast<char*>(&chunkID), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&chunkSize), sizeof(std::uint32_t)); switch (chunkID) { case 'FFIR': { header.riff.chunkID = chunkID; header.riff.chunkSize = chunkSize; file.read(reinterpret_cast<char*>(&header.riff.format), sizeof(std::uint32_t)); if (header.riff.format != 'EVAW') { std::cerr << "Error: Not a valid WAVE file." << std::endl; return false; } break; } case ' tmf': { header.fmt.chunkID = chunkID; header.fmt.chunkSize = chunkSize; file.read(reinterpret_cast<char*>(&header.fmt.audioFormat), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.numChannels), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.sampleRate), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&header.fmt.byteRate), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&header.fmt.blockAlign), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.bitsPerSample), sizeof(std::uint16_t)); if (header.fmt.bitsPerSample % 2 != 0) { std::cerr << "Error: Invalid number of bits per sample" << std::endl; return false; } if (header.fmt.byteRate != (header.fmt.sampleRate * header.fmt.numChannels * header.fmt.bitsPerSample / 8)) { std::cerr << "Error: Invalid byte rate" << std::endl; return false; } if (header.fmt.blockAlign != (header.fmt.numChannels * header.fmt.bitsPerSample / 8)) { std::cerr << "Error: Invalid block align" << std::endl; return false; } break; } case 'atad': { assert(data == nullptr); size = chunkSize; data = new char[size]; file.read(data, chunkSize); break; } default: { file.ignore(chunkSize); break; } } } // Check that we got all chunks if (header.riff.chunkID != 'FFIR') { std::cerr << "Error: Missing RIFF chunk." << std::endl; return false; } if (header.fmt.chunkID != ' tmf') { std::cerr << "Error: Missing fmt chunk." << std::endl; return false; } if (data == nullptr) { std::cerr << "Error: Missing data chunk." << std::endl; return false; } // Fill meta struct meta.audioFormat = static_cast<AudioFormat>(header.fmt.audioFormat); meta.numChannels = header.fmt.numChannels; meta.sampleRate = header.fmt.sampleRate; meta.bitsPerSample = header.fmt.bitsPerSample; return true; } void WaveFile::Unload() { delete[] data; data = nullptr; size = 0; } std::string WaveFile::GetAudioFormatString() const { switch (meta.audioFormat) { case WaveFile::PCM: return "PCM"; case WaveFile::IEEE_FLOAT: return "IEEE float"; default: return "Unknown"; } } <commit_msg>Replaced all magic numbers with static const's<commit_after>/* The MIT License (MIT) Copyright (c) 2014 Johannes Hggqvist 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 "WaveFile.h" #include <fstream> #include <iostream> #include <cstdint> #include <cassert> #include <cstring> namespace { static const std::uint32_t RIFF_ID = 'FFIR'; static const std::uint32_t FMT_ID = ' tmf'; static const std::uint32_t DATA_ID = 'atad'; struct RIFFChunk { static const std::uint32_t FORMAT_WAVE = 'EVAW'; std::uint32_t chunkID; std::uint32_t chunkSize; std::uint32_t format; }; struct fmtChunk { std::uint32_t chunkID; std::uint32_t chunkSize; std::uint16_t audioFormat; std::uint16_t numChannels; std::uint32_t sampleRate; std::uint32_t byteRate; std::uint16_t blockAlign; std::uint16_t bitsPerSample; }; struct WaveHeader { RIFFChunk riff; fmtChunk fmt; }; } WaveFile::WaveFile() : data(nullptr), size(0) { } WaveFile::WaveFile(const std::string &filename) : data(nullptr), size(0) { Load(filename); } WaveFile::~WaveFile() { Unload(); } bool WaveFile::Load(const std::string &filename) { if (IsLoaded()) { Unload(); } std::fstream file(filename, std::ios::in | std::ios::binary); if (!file.is_open()) { std::cerr << "Error: Could not open file." << std::endl; return false; } WaveHeader header; std::memset(&header, 0, sizeof(WaveHeader)); while (file.peek() != std::char_traits<char>::eof()) { std::uint32_t chunkID; std::uint32_t chunkSize; file.read(reinterpret_cast<char*>(&chunkID), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&chunkSize), sizeof(std::uint32_t)); switch (chunkID) { case RIFF_ID: { header.riff.chunkID = chunkID; header.riff.chunkSize = chunkSize; file.read(reinterpret_cast<char*>(&header.riff.format), sizeof(std::uint32_t)); if (header.riff.format != RIFFChunk::FORMAT_WAVE) { std::cerr << "Error: Not a valid WAVE file." << std::endl; return false; } break; } case FMT_ID: { header.fmt.chunkID = chunkID; header.fmt.chunkSize = chunkSize; file.read(reinterpret_cast<char*>(&header.fmt.audioFormat), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.numChannels), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.sampleRate), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&header.fmt.byteRate), sizeof(std::uint32_t)); file.read(reinterpret_cast<char*>(&header.fmt.blockAlign), sizeof(std::uint16_t)); file.read(reinterpret_cast<char*>(&header.fmt.bitsPerSample), sizeof(std::uint16_t)); if (header.fmt.bitsPerSample % 2 != 0) { std::cerr << "Error: Invalid number of bits per sample" << std::endl; return false; } if (header.fmt.byteRate != (header.fmt.sampleRate * header.fmt.numChannels * header.fmt.bitsPerSample / 8)) { std::cerr << "Error: Invalid byte rate" << std::endl; return false; } if (header.fmt.blockAlign != (header.fmt.numChannels * header.fmt.bitsPerSample / 8)) { std::cerr << "Error: Invalid block align" << std::endl; return false; } break; } case DATA_ID: { assert(data == nullptr); size = chunkSize; data = new char[size]; file.read(data, chunkSize); break; } default: { file.ignore(chunkSize); break; } } } // Check that we got all chunks if (header.riff.chunkID != RIFF_ID) { std::cerr << "Error: Missing RIFF chunk." << std::endl; return false; } if (header.fmt.chunkID != FMT_ID) { std::cerr << "Error: Missing fmt chunk." << std::endl; return false; } if (data == nullptr) { std::cerr << "Error: Missing data chunk." << std::endl; return false; } // Fill meta struct meta.audioFormat = static_cast<AudioFormat>(header.fmt.audioFormat); meta.numChannels = header.fmt.numChannels; meta.sampleRate = header.fmt.sampleRate; meta.bitsPerSample = header.fmt.bitsPerSample; return true; } void WaveFile::Unload() { delete[] data; data = nullptr; size = 0; } std::string WaveFile::GetAudioFormatString() const { switch (meta.audioFormat) { case WaveFile::PCM: return "PCM"; case WaveFile::IEEE_FLOAT: return "IEEE float"; default: return "Unknown"; } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "AVT.hpp" #include <algorithm> #include <Include/STLHelper.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVTPartSimple.hpp" #include "AVTPartXPath.hpp" #include "StylesheetConstructionContext.hpp" static const XalanDOMChar theTokenDelimiterCharacters[] = { XalanUnicode::charLeftCurlyBracket, XalanUnicode::charRightCurlyBracket, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, 0 }; static const XalanDOMChar theLeftCurlyBracketString[] = { XalanUnicode::charLeftCurlyBracket, 0 }; static const XalanDOMChar theRightCurlyBracketString[] = { XalanUnicode::charRightCurlyBracket, 0 }; /** * Construct an AVT by parsing the string, and either * constructing a vector of AVTParts, or simply hold * on to the string if the AVT is simple. */ AVT::AVT( const XalanDOMChar* name, const XalanDOMChar* type, const XalanDOMChar* stringedValue, const PrefixResolver& resolver, StylesheetConstructionContext& constructionContext) : m_parts(), m_simpleString(), // $$$ ToDo: Explicit XalanDOMString constructor m_name(XalanDOMString(name)), m_prefix(getPrefix(name)), m_pcType(type) { StringTokenizer tokenizer(stringedValue, theTokenDelimiterCharacters, true); const unsigned int nTokens = tokenizer.countTokens(); if(nTokens < 2) { m_simpleString = stringedValue; // then do the simple thing } else { m_parts.reserve(nTokens + 1); XalanDOMString buffer; XalanDOMString exprBuffer; XalanDOMString t; // base token XalanDOMString lookahead; // next token XalanDOMString error; // if non-null, break from loop while(tokenizer.hasMoreTokens()) { if(length(lookahead)) { t = lookahead; clear(lookahead); } else { t = tokenizer.nextToken(); } if(length(t) == 1) { const XalanDOMChar theChar = charAt(t, 0); switch(theChar) { case(XalanUnicode::charLeftCurlyBracket): { // Attribute Value Template start lookahead = tokenizer.nextToken(); if(equals(lookahead, theLeftCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); break; // from switch } else { if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } clear(exprBuffer); while(length(lookahead) > 0 && !equals(lookahead, theRightCurlyBracketString)) { if(length(lookahead) == 1) { switch(charAt(lookahead, 0)) { case XalanUnicode::charApostrophe: case XalanUnicode::charQuoteMark: { // String start append(exprBuffer, lookahead); const XalanDOMString quote = lookahead; // Consume stuff 'till next quote lookahead = tokenizer.nextToken(); while(!equals(lookahead, quote)) { append(exprBuffer, lookahead); lookahead = tokenizer.nextToken(); } append(exprBuffer,lookahead); break; } case XalanUnicode::charLeftCurlyBracket: { // What's another curly doing here? error = TranscodeFromLocalCodePage("Error: Can not have \"{\" within expression."); break; } default: { // part of the template stuff, just add it. append(exprBuffer, lookahead); } } // end inner switch } // end if lookahead length == 1 else { // part of the template stuff, just add it. append(exprBuffer,lookahead); } lookahead = tokenizer.nextToken(); } // end while(!equals(lookahead, "}")) assert(equals(lookahead, theRightCurlyBracketString)); // Proper close of attribute template. Evaluate the // expression. clear(buffer); const XPath* const xpath = constructionContext.createXPath(exprBuffer, resolver); assert(xpath != 0); m_parts.push_back(new AVTPartXPath(xpath)); clear(lookahead); // breaks out of inner while loop if(length(error) > 0) { break; // from inner while loop } } break; } case(XalanUnicode::charRightCurlyBracket): { lookahead = tokenizer.nextToken(); if(equals(lookahead, theRightCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); // swallow } else { // Illegal, I think... constructionContext.warn("Found \"}\" but no attribute template open!"); append(buffer, theRightCurlyBracketString); // leave the lookahead to be processed by the next round. } break; } default: { const XalanDOMString s(&theChar, 1); // Anything else just add to string. append(buffer, s); } } // end switch t } // end if length == 1 else { // Anything else just add to string. append(buffer,t); } if(length(error) > 0) { constructionContext.warn("Attr Template, " + error); break; } } // end while(tokenizer.hasMoreTokens()) if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } } // end else nTokens > 1 if(m_parts.empty() && length(m_simpleString) == 0) { // Error? clear(m_simpleString); } else if (m_parts.size() < m_parts.capacity()) { AVTPartPtrVectorType(m_parts).swap(m_parts); } } AVT::~AVT() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_parts.begin(), m_parts.end(), DeleteFunctor<AVTPart>()); } void AVT::evaluate( XalanDOMString& buf, XalanNode* contextNode, const PrefixResolver& prefixResolver, XPathExecutionContext& executionContext) const { if(length(m_simpleString) > 0) { buf = m_simpleString; } else { clear(buf); if(m_parts.empty() == false) { const AVTPartPtrVectorType::size_type n = m_parts.size(); for(AVTPartPtrVectorType::size_type i = 0; i < n; i++) { assert(m_parts[i] != 0); m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext); } } } } XalanDOMString AVT::getPrefix(const XalanDOMChar* theName) { if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { return substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } else { return XalanDOMString(); } } <commit_msg>Use new StringTokenizer overload.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "AVT.hpp" #include <algorithm> #include <Include/STLHelper.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/StringTokenizer.hpp> #include <PlatformSupport/XalanUnicode.hpp> #include <DOMSupport/DOMServices.hpp> #include "AVTPartSimple.hpp" #include "AVTPartXPath.hpp" #include "StylesheetConstructionContext.hpp" static const XalanDOMChar theTokenDelimiterCharacters[] = { XalanUnicode::charLeftCurlyBracket, XalanUnicode::charRightCurlyBracket, XalanUnicode::charApostrophe, XalanUnicode::charQuoteMark, 0 }; static const XalanDOMChar theLeftCurlyBracketString[] = { XalanUnicode::charLeftCurlyBracket, 0 }; static const XalanDOMChar theRightCurlyBracketString[] = { XalanUnicode::charRightCurlyBracket, 0 }; /** * Construct an AVT by parsing the string, and either * constructing a vector of AVTParts, or simply hold * on to the string if the AVT is simple. */ AVT::AVT( const XalanDOMChar* name, const XalanDOMChar* type, const XalanDOMChar* stringedValue, const PrefixResolver& resolver, StylesheetConstructionContext& constructionContext) : m_parts(), m_simpleString(), // $$$ ToDo: Explicit XalanDOMString constructor m_name(XalanDOMString(name)), m_prefix(getPrefix(name)), m_pcType(type) { StringTokenizer tokenizer(stringedValue, theTokenDelimiterCharacters, true); const unsigned int nTokens = tokenizer.countTokens(); if(nTokens < 2) { m_simpleString = stringedValue; // then do the simple thing } else { m_parts.reserve(nTokens + 1); XalanDOMString buffer; XalanDOMString exprBuffer; XalanDOMString t; // base token XalanDOMString lookahead; // next token XalanDOMString error; // if non-null, break from loop while(tokenizer.hasMoreTokens()) { if(length(lookahead)) { t = lookahead; clear(lookahead); } else { tokenizer.nextToken(t); } if(length(t) == 1) { const XalanDOMChar theChar = charAt(t, 0); switch(theChar) { case(XalanUnicode::charLeftCurlyBracket): { // Attribute Value Template start tokenizer.nextToken(lookahead); if(equals(lookahead, theLeftCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); break; // from switch } else { if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } clear(exprBuffer); while(length(lookahead) > 0 && !equals(lookahead, theRightCurlyBracketString)) { if(length(lookahead) == 1) { switch(charAt(lookahead, 0)) { case XalanUnicode::charApostrophe: case XalanUnicode::charQuoteMark: { // String start append(exprBuffer, lookahead); const XalanDOMString quote = lookahead; // Consume stuff 'till next quote tokenizer.nextToken(lookahead); while(!equals(lookahead, quote)) { append(exprBuffer, lookahead); tokenizer.nextToken(lookahead); } append(exprBuffer,lookahead); break; } case XalanUnicode::charLeftCurlyBracket: { // What's another curly doing here? error = TranscodeFromLocalCodePage("Error: Can not have \"{\" within expression."); break; } default: { // part of the template stuff, just add it. append(exprBuffer, lookahead); } } // end inner switch } // end if lookahead length == 1 else { // part of the template stuff, just add it. append(exprBuffer,lookahead); } tokenizer.nextToken(lookahead); } // end while(!equals(lookahead, "}")) assert(equals(lookahead, theRightCurlyBracketString)); // Proper close of attribute template. Evaluate the // expression. clear(buffer); const XPath* const xpath = constructionContext.createXPath(exprBuffer, resolver); assert(xpath != 0); m_parts.push_back(new AVTPartXPath(xpath)); clear(lookahead); // breaks out of inner while loop if(length(error) > 0) { break; // from inner while loop } } break; } case(XalanUnicode::charRightCurlyBracket): { tokenizer.nextToken(lookahead); if(equals(lookahead, theRightCurlyBracketString)) { // Double curlys mean escape to show curly append(buffer, lookahead); clear(lookahead); // swallow } else { // Illegal, I think... constructionContext.warn("Found \"}\" but no attribute template open!"); append(buffer, theRightCurlyBracketString); // leave the lookahead to be processed by the next round. } break; } default: { const XalanDOMString s(&theChar, 1); // Anything else just add to string. append(buffer, s); } } // end switch t } // end if length == 1 else { // Anything else just add to string. append(buffer,t); } if(length(error) > 0) { constructionContext.warn("Attr Template, " + error); break; } } // end while(tokenizer.hasMoreTokens()) if(length(buffer) > 0) { m_parts.push_back(new AVTPartSimple(buffer)); clear(buffer); } } // end else nTokens > 1 if(m_parts.empty() && length(m_simpleString) == 0) { // Error? clear(m_simpleString); } else if (m_parts.size() < m_parts.capacity()) { AVTPartPtrVectorType(m_parts).swap(m_parts); } } AVT::~AVT() { #if !defined(XALAN_NO_NAMESPACES) using std::for_each; #endif // Clean up all entries in the vector. for_each(m_parts.begin(), m_parts.end(), DeleteFunctor<AVTPart>()); } void AVT::evaluate( XalanDOMString& buf, XalanNode* contextNode, const PrefixResolver& prefixResolver, XPathExecutionContext& executionContext) const { if(length(m_simpleString) > 0) { buf = m_simpleString; } else { clear(buf); if(m_parts.empty() == false) { const AVTPartPtrVectorType::size_type n = m_parts.size(); for(AVTPartPtrVectorType::size_type i = 0; i < n; i++) { assert(m_parts[i] != 0); m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext); } } } } XalanDOMString AVT::getPrefix(const XalanDOMChar* theName) { if (startsWith(theName, DOMServices::s_XMLNamespaceWithSeparator) == true) { return substring(theName, DOMServices::s_XMLNamespaceWithSeparatorLength); } else { return XalanDOMString(); } } <|endoftext|>
<commit_before>/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "ecclesia/lib/redfish/testing/grpc_dynamic_mockup_server.h" #include <memory> #include <string> #include <string_view> #include "google/protobuf/struct.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "ecclesia/lib/file/test_filesystem.h" #include "ecclesia/lib/http/codes.h" #include "ecclesia/lib/network/testing.h" #include "ecclesia/lib/protobuf/parse.h" #include "ecclesia/lib/redfish/interface.h" #include "ecclesia/lib/redfish/proto/redfish_v1.grpc.pb.h" #include "ecclesia/lib/redfish/proto/redfish_v1.pb.h" #include "ecclesia/lib/redfish/transport/grpc.h" #include "ecclesia/lib/redfish/transport/grpc_dynamic_impl.h" #include "ecclesia/lib/redfish/transport/grpc_dynamic_options.h" #include "ecclesia/lib/status/rpc.h" #include "ecclesia/lib/testing/proto.h" #include "ecclesia/lib/testing/status.h" #include "grpcpp/channel.h" #include "grpcpp/client_context.h" #include "grpcpp/create_channel.h" #include "grpcpp/security/credentials.h" #include "grpcpp/server_context.h" #include "grpcpp/support/status.h" namespace ecclesia { namespace { using ::google::protobuf::Struct; using ::redfish::v1::Request; using ::redfish::v1::Response; using ::testing::Eq; using ::testing::Test; class GrpcRedfishMockUpServerTest : public Test { protected: GrpcRedfishMockUpServerTest() { GrpcDynamicImplOptions options; options.SetToInsecure(); int port = FindUnusedPortOrDie(); mockup_server_ = absl::make_unique<GrpcDynamicMockupServer>( "barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport::Params params; client_ = absl::make_unique<GrpcRedfishTransport>( absl::StrCat("[::1]:", port), params); std::shared_ptr<grpc::Channel> channel = CreateChannel( absl::StrCat("[::1]:", port), grpc::InsecureChannelCredentials()); stub_ = ::redfish::v1::RedfishV1::NewStub(channel); } std::unique_ptr<GrpcDynamicMockupServer> mockup_server_; std::unique_ptr<GrpcRedfishTransport> client_; std::unique_ptr<::redfish::v1::RedfishV1::Stub> stub_; }; // Testing Post, Patch and Get requests. The Patch request can verify the // resource has been Posted. And The Get Request can verify that the // resource has been Patched. TEST_F(GrpcRedfishMockUpServerTest, TestPostPatchAndGetRequest) { // Test Post request std::string_view data_post = R"json({ "ChassisType": "RackMount", "Name": "MyChassis" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_EQ(result_post->code, ecclesia::HttpResponseCode::HTTP_CODE_NO_CONTENT); // Test Patch request std::string_view data_patch = R"json({ "Name": "MyNewName" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1/Chassis/Member1", data_patch); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_EQ(result_patch->code, ecclesia::HttpResponseCode::HTTP_CODE_NO_CONTENT); // Test Get Request absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1/Chassis/Member1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name; name = (result_get->body)["Name"]; EXPECT_EQ(name, "MyNewName"); EXPECT_EQ(result_get->code, ecclesia::HttpResponseCode::HTTP_CODE_REQUEST_OK); } TEST_F(GrpcRedfishMockUpServerTest, TestPutRequests) { grpc::ClientContext context; Request request; Response response; EXPECT_THAT(AsAbslStatus(stub_->Put(&context, request, &response)), IsStatusUnimplemented()); } TEST_F(GrpcRedfishMockUpServerTest, TestDeleteRequests) { grpc::ClientContext context; Request request; Response response; EXPECT_THAT(AsAbslStatus(stub_->Delete(&context, request, &response)), IsStatusUnimplemented()); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomGet) { const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Name" value: { string_value: "MyResource" } } )pb"); mockup_server_->AddHttpGetHandler( "/redfish/v1/MyResource", [&kResponse](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { *response->mutable_message() = kResponse; return grpc::Status::OK; }); absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1/MyResource"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name = (result_get->body)["Name"]; EXPECT_THAT(name, Eq("MyResource")); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomPost) { const ::redfish::v1::Request kRequest = ParseTextProtoOrDie(R"pb( url: "/redfish/v1/MyResource" message { fields { key: "num" value: { number_value: 1 } } fields { key: "str" value: { string_value: "hi" } } } )pb"); const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Result" value: { string_value: "OK" } } )pb"); bool called = false; mockup_server_->AddHttpPostHandler( "/redfish/v1/MyResource", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; EXPECT_THAT(*request, EqualsProto(kRequest)); *response->mutable_message() = kResponse; return grpc::Status::OK; }); std::string_view data_post = R"json({ "num": 1, "str": "hi" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/MyResource", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); ASSERT_TRUE(called); std::string name = (result_post->body)["Result"]; EXPECT_THAT(name, Eq("OK")); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomPatch) { const ::redfish::v1::Request kRequest = ParseTextProtoOrDie(R"pb( url: "/redfish/v1/MyResource" message { fields { key: "num" value: { number_value: 1 } } fields { key: "str" value: { string_value: "hi" } } } )pb"); const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Result" value: { string_value: "OK" } } )pb"); bool called = false; mockup_server_->AddHttpPatchHandler( "/redfish/v1/MyResource", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; EXPECT_THAT(*request, EqualsProto(kRequest)); *response->mutable_message() = kResponse; return grpc::Status::OK; }); std::string_view data_patch = R"json({ "num": 1, "str": "hi" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1/MyResource", data_patch); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_TRUE(called); std::string name = (result_patch->body)["Result"]; EXPECT_THAT(name, Eq("OK")); } TEST_F(GrpcRedfishMockUpServerTest, TestPostReset) { bool called = false; // Register the handler. mockup_server_->AddHttpPostHandler( "/redfish/v1/Chassis", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); std::string_view data_post = R"json({ "Id": "id", "Name": "MyChassis" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_FALSE(called); } TEST_F(GrpcRedfishMockUpServerTest, TestPatchReset) { bool called = false; // Register the handler. mockup_server_->AddHttpPatchHandler( "/redfish/v1", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); std::string_view data = R"json({ "Name": "Test Name" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1", data); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_patch = client_->Patch("/redfish/v1", data); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_FALSE(called); } TEST_F(GrpcRedfishMockUpServerTest, TestGetReset) { bool called = false; // Register the handler. mockup_server_->AddHttpGetHandler( "/redfish/v1", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_get = client_->Get("/redfish/v1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name = (result_get->body)["Name"]; EXPECT_THAT(name, Eq("Root Service")); EXPECT_FALSE(called); } TEST(GrpcRedfishMockUpServerUdsTest, TestUds) { absl::flat_hash_map<std::string, std::string> headers; std::string mockup_uds = absl::StrCat(GetTestTempUdsDirectory(), "/mockup.socket"); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", mockup_uds); GrpcRedfishTransport transport(absl::StrCat("unix://", mockup_uds), {}); std::string_view expexted_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expexted_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); } } // namespace } // namespace ecclesia <commit_msg>Internal change<commit_after>/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 "ecclesia/lib/redfish/testing/grpc_dynamic_mockup_server.h" #include <memory> #include <string> #include "google/protobuf/struct.pb.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" #include "ecclesia/lib/file/test_filesystem.h" #include "ecclesia/lib/http/codes.h" #include "ecclesia/lib/network/testing.h" #include "ecclesia/lib/protobuf/parse.h" #include "ecclesia/lib/redfish/interface.h" #include "ecclesia/lib/redfish/proto/redfish_v1.grpc.pb.h" #include "ecclesia/lib/redfish/proto/redfish_v1.pb.h" #include "ecclesia/lib/redfish/transport/grpc.h" #include "ecclesia/lib/redfish/transport/grpc_dynamic_impl.h" #include "ecclesia/lib/redfish/transport/grpc_dynamic_options.h" #include "ecclesia/lib/status/rpc.h" #include "ecclesia/lib/testing/proto.h" #include "ecclesia/lib/testing/status.h" #include "grpcpp/channel.h" #include "grpcpp/client_context.h" #include "grpcpp/create_channel.h" #include "grpcpp/security/credentials.h" #include "grpcpp/server_context.h" #include "grpcpp/support/status.h" namespace ecclesia { namespace { using ::google::protobuf::Struct; using ::redfish::v1::Request; using ::redfish::v1::Response; using ::testing::Eq; using ::testing::Test; class GrpcRedfishMockUpServerTest : public Test { protected: GrpcRedfishMockUpServerTest() { GrpcDynamicImplOptions options; options.SetToInsecure(); int port = FindUnusedPortOrDie(); mockup_server_ = absl::make_unique<GrpcDynamicMockupServer>( "barebones_session_auth/mockup.shar", "[::1]", port); GrpcRedfishTransport::Params params; client_ = absl::make_unique<GrpcRedfishTransport>( absl::StrCat("[::1]:", port), params); std::shared_ptr<grpc::Channel> channel = CreateChannel( absl::StrCat("[::1]:", port), grpc::InsecureChannelCredentials()); stub_ = ::redfish::v1::RedfishV1::NewStub(channel); } std::unique_ptr<GrpcDynamicMockupServer> mockup_server_; std::unique_ptr<GrpcRedfishTransport> client_; std::unique_ptr<::redfish::v1::RedfishV1::Stub> stub_; }; // Testing Post, Patch and Get requests. The Patch request can verify the // resource has been Posted. And The Get Request can verify that the // resource has been Patched. TEST_F(GrpcRedfishMockUpServerTest, TestPostPatchAndGetRequest) { // Test Post request std::string_view data_post = R"json({ "ChassisType": "RackMount", "Name": "MyChassis" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_EQ(result_post->code, ecclesia::HttpResponseCode::HTTP_CODE_NO_CONTENT); // Test Patch request std::string_view data_patch = R"json({ "Name": "MyNewName" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1/Chassis/Member1", data_patch); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_EQ(result_patch->code, ecclesia::HttpResponseCode::HTTP_CODE_NO_CONTENT); // Test Get Request absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1/Chassis/Member1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name; name = (result_get->body)["Name"]; EXPECT_EQ(name, "MyNewName"); EXPECT_EQ(result_get->code, ecclesia::HttpResponseCode::HTTP_CODE_REQUEST_OK); } TEST_F(GrpcRedfishMockUpServerTest, TestPutRequests) { grpc::ClientContext context; Request request; Response response; EXPECT_THAT(AsAbslStatus(stub_->Put(&context, request, &response)), IsStatusUnimplemented()); } TEST_F(GrpcRedfishMockUpServerTest, TestDeleteRequests) { grpc::ClientContext context; Request request; Response response; EXPECT_THAT(AsAbslStatus(stub_->Delete(&context, request, &response)), IsStatusUnimplemented()); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomGet) { const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Name" value: { string_value: "MyResource" } } )pb"); mockup_server_->AddHttpGetHandler( "/redfish/v1/MyResource", [&kResponse](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { *response->mutable_message() = kResponse; return grpc::Status::OK; }); absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1/MyResource"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name = (result_get->body)["Name"]; EXPECT_THAT(name, Eq("MyResource")); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomPost) { const ::redfish::v1::Request kRequest = ParseTextProtoOrDie(R"pb( url: "/redfish/v1/MyResource" message { fields { key: "num" value: { number_value: 1 } } fields { key: "str" value: { string_value: "hi" } } } )pb"); const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Result" value: { string_value: "OK" } } )pb"); bool called = false; mockup_server_->AddHttpPostHandler( "/redfish/v1/MyResource", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; EXPECT_THAT(*request, EqualsProto(kRequest)); *response->mutable_message() = kResponse; return grpc::Status::OK; }); std::string_view data_post = R"json({ "num": 1, "str": "hi" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/MyResource", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); ASSERT_TRUE(called); std::string name = (result_post->body)["Result"]; EXPECT_THAT(name, Eq("OK")); } TEST_F(GrpcRedfishMockUpServerTest, TestCustomPatch) { const ::redfish::v1::Request kRequest = ParseTextProtoOrDie(R"pb( url: "/redfish/v1/MyResource" message { fields { key: "num" value: { number_value: 1 } } fields { key: "str" value: { string_value: "hi" } } } )pb"); const google::protobuf::Struct kResponse = ParseTextProtoOrDie(R"pb( fields { key: "Result" value: { string_value: "OK" } } )pb"); bool called = false; mockup_server_->AddHttpPatchHandler( "/redfish/v1/MyResource", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; EXPECT_THAT(*request, EqualsProto(kRequest)); *response->mutable_message() = kResponse; return grpc::Status::OK; }); std::string_view data_patch = R"json({ "num": 1, "str": "hi" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1/MyResource", data_patch); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_TRUE(called); std::string name = (result_patch->body)["Result"]; EXPECT_THAT(name, Eq("OK")); } TEST_F(GrpcRedfishMockUpServerTest, TestPostReset) { bool called = false; // Register the handler. mockup_server_->AddHttpPostHandler( "/redfish/v1/Chassis", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); std::string_view data_post = R"json({ "Id": "id", "Name": "MyChassis" })json"; absl::StatusOr<RedfishTransport::Result> result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_post = client_->Post("/redfish/v1/Chassis", data_post); ASSERT_TRUE(result_post.status().ok()) << result_post.status().message(); EXPECT_FALSE(called); } TEST_F(GrpcRedfishMockUpServerTest, TestPatchReset) { bool called = false; // Register the handler. mockup_server_->AddHttpPatchHandler( "/redfish/v1", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); std::string_view data = R"json({ "Name": "Test Name" })json"; absl::StatusOr<RedfishTransport::Result> result_patch = client_->Patch("/redfish/v1", data); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_patch = client_->Patch("/redfish/v1", data); ASSERT_TRUE(result_patch.status().ok()) << result_patch.status().message(); EXPECT_FALSE(called); } TEST_F(GrpcRedfishMockUpServerTest, TestGetReset) { bool called = false; // Register the handler. mockup_server_->AddHttpGetHandler( "/redfish/v1", [&](grpc::ServerContext *context, const ::redfish::v1::Request *request, Response *response) { called = true; return grpc::Status::OK; }); absl::StatusOr<RedfishTransport::Result> result_get = client_->Get("/redfish/v1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); EXPECT_TRUE(called); // Clear the registered handler. called = false; mockup_server_->ClearHandlers(); result_get = client_->Get("/redfish/v1"); ASSERT_TRUE(result_get.status().ok()) << result_get.status().message(); std::string name = (result_get->body)["Name"]; EXPECT_THAT(name, Eq("Root Service")); EXPECT_FALSE(called); } TEST(GrpcRedfishMockUpServerUdsTest, TestUds) { absl::flat_hash_map<std::string, std::string> headers; std::string mockup_uds = absl::StrCat(GetTestTempUdsDirectory(), "/mockup.socket"); GrpcDynamicMockupServer mockup_server("barebones_session_auth/mockup.shar", mockup_uds); GrpcRedfishTransport transport(absl::StrCat("unix://", mockup_uds), {}); std::string_view expexted_str = R"json({ "@odata.context": "/redfish/v1/$metadata#ServiceRoot.ServiceRoot", "@odata.id": "/redfish/v1", "@odata.type": "#ServiceRoot.v1_5_0.ServiceRoot", "Chassis": { "@odata.id": "/redfish/v1/Chassis" }, "Id": "RootService", "Links": { "Sessions": { "@odata.id": "/redfish/v1/SessionService/Sessions" } }, "Name": "Root Service", "RedfishVersion": "1.6.1" })json"; nlohmann::json expected = nlohmann::json::parse(expexted_str, nullptr, false); absl::StatusOr<GrpcRedfishTransport::Result> res_get = transport.Get("/redfish/v1"); ASSERT_THAT(res_get, IsOk()); EXPECT_THAT(res_get->body, Eq(expected)); } } // namespace } // namespace ecclesia <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2017-2017 ARM Limited * * 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 "mbed.h" #include "us_ticker_api.h" #include "BLE.h" #include "wsf_types.h" #include "wsf_msg.h" #include "wsf_os.h" #include "wsf_buf.h" #include "wsf_timer.h" #include "hci_handler.h" #include "dm_handler.h" #include "l2c_handler.h" #include "att_handler.h" #include "smp_handler.h" #include "l2c_api.h" #include "att_api.h" #include "smp_api.h" #include "hci_drv.h" #include "CordioBLE.h" #include "mbed_assert.h" #include "CordioPalAttClient.h" #include "CordioPalSecurityManager.h" /*! WSF handler ID */ wsfHandlerId_t stack_handler_id; /** * Weak definition of ble_cordio_get_hci_driver. * A runtime error is generated if the user does not define any * ble_cordio_get_hci_driver. */ MBED_WEAK ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() { error("Please provide an implementation for the HCI driver"); ble::vendor::cordio::CordioHCIDriver* bad_instance = NULL; return *bad_instance; } /** * Low level HCI interface between Cordio stack and the port. */ extern "C" uint16_t hci_mbed_os_drv_write(uint8_t type, uint16_t len, uint8_t *pData) { return ble_cordio_get_hci_driver().write(type, len, pData); } extern "C" void hci_mbed_os_start_reset_sequence(void) { ble_cordio_get_hci_driver().start_reset_sequence(); } extern "C" void hci_mbed_os_handle_reset_sequence(uint8_t* msg) { ble_cordio_get_hci_driver().handle_reset_sequence(msg); } /* * This function will signal to the user code by calling signalEventsToProcess. * It is registered and called into the Wsf Stack. */ extern "C" void wsf_mbed_ble_signal_event(void) { ble::vendor::cordio::BLE::deviceInstance().signalEventsToProcess(::BLE::DEFAULT_INSTANCE); } /** * BLE-API requires an implementation of the following function in order to * obtain its transport handle. */ BLEInstanceBase *createBLEInstance() { return (&(ble::vendor::cordio::BLE::deviceInstance())); } namespace ble { namespace vendor { namespace cordio { BLE::BLE(CordioHCIDriver& hci_driver) : initialization_status(NOT_INITIALIZED), instanceID(::BLE::DEFAULT_INSTANCE), _event_queue() { _hci_driver = &hci_driver; stack_setup(); } BLE::~BLE() { } /** * The singleton which represents the BLE transport for the BLE. */ BLE& BLE::deviceInstance() { static BLE instance( ble_cordio_get_hci_driver() ); return instance; } ble_error_t BLE::init( ::BLE::InstanceID_t instanceID, FunctionPointerWithContext< ::BLE::InitializationCompleteCallbackContext *> initCallback) { switch (initialization_status) { case NOT_INITIALIZED: _event_queue.initialize(this, instanceID); _init_callback = initCallback; start_stack_reset(); return BLE_ERROR_NONE; case INITIALIZING: return BLE_ERROR_INITIALIZATION_INCOMPLETE; case INITIALIZED: return BLE_ERROR_NONE; default: return BLE_ERROR_UNSPECIFIED; } } bool BLE::hasInitialized() const { return initialization_status == INITIALIZED; } ble_error_t BLE::shutdown() { if (initialization_status != INITIALIZED) { return BLE_ERROR_INITIALIZATION_INCOMPLETE; } initialization_status = NOT_INITIALIZED; _hci_driver->terminate(); getGattServer().reset(); getGattClient().reset(); getGap().reset(); _event_queue.clear(); return BLE_ERROR_NONE; } const char* BLE::getVersion() { static const char version[] = "generic-cordio"; return version; } generic::GenericGap& BLE::getGap() { static pal::vendor::cordio::GenericAccessService cordio_gap_service; static ble::generic::GenericGap gap( _event_queue, pal::vendor::cordio::Gap::get_gap(), cordio_gap_service ); return gap; } const generic::GenericGap& BLE::getGap() const { BLE &self = const_cast<BLE&>(*this); return const_cast<const generic::GenericGap&>(self.getGap()); }; GattServer& BLE::getGattServer() { return cordio::GattServer::getInstance(); } const GattServer& BLE::getGattServer() const { return cordio::GattServer::getInstance(); } generic::GenericGattClient& BLE::getGattClient() { static pal::AttClientToGattClientAdapter pal_client( pal::vendor::cordio::CordioAttClient::get_client() ); static generic::GenericGattClient client(&pal_client); return client; } SecurityManager& BLE::getSecurityManager() { static pal::MemorySecurityDb m_db; static SigningEventMonitorProxy signing_event_monitor(*this); static generic::GenericSecurityManager m_instance( pal::vendor::cordio::CordioSecurityManager::get_security_manager(), m_db, getGap(), signing_event_monitor ); return m_instance; } const SecurityManager& BLE::getSecurityManager() const { const BLE &self = const_cast<BLE&>(*this); return const_cast<const SecurityManager&>(self.getSecurityManager()); } void BLE::waitForEvent() { static Timeout nextTimeout; timestamp_t nextTimestamp; bool_t pTimerRunning; callDispatcher(); if (wsfOsReadyToSleep()) { // setup an mbed timer for the next cordio timeout nextTimestamp = (timestamp_t)(WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } } void BLE::processEvents() { callDispatcher(); } void BLE::stack_handler(wsfEventMask_t event, wsfMsgHdr_t* msg) { if (msg == NULL) { return; } if (ble::pal::vendor::cordio::CordioSecurityManager::get_security_manager().sm_handler(msg)) { return; } switch(msg->event) { case DM_RESET_CMPL_IND: { ::BLE::InitializationCompleteCallbackContext context = { ::BLE::Instance(::BLE::DEFAULT_INSTANCE), BLE_ERROR_NONE }; deviceInstance().getGattServer().initialize(); deviceInstance().initialization_status = INITIALIZED; _init_callback.call(&context); } break; default: ble::pal::vendor::cordio::Gap::gap_handler(msg); break; } } void BLE::device_manager_cb(dmEvt_t* dm_event) { BLE::deviceInstance().stack_handler(0, &dm_event->hdr); } /* * AttServerInitDeInitCback callback is used to Initialize/Deinitialize * the CCC Table of the ATT Server when a remote peer requests to Open * or Close the connection. */ void BLE::connection_handler(dmEvt_t* dm_event) { dmConnId_t connId = (dmConnId_t)dm_event->hdr.param; switch (dm_event->hdr.event) { case DM_CONN_OPEN_IND: /* set up CCC table with uninitialized (all zero) values */ AttsCccInitTable(connId, NULL); break; case DM_CONN_CLOSE_IND: /* clear CCC table on connection close */ AttsCccClearTable(connId); break; default: break; } } void BLE::timeoutCallback() { wsf_mbed_ble_signal_event(); } void BLE::stack_setup() { MBED_ASSERT(_hci_driver != NULL); wsfHandlerId_t handlerId; buf_pool_desc_t buf_pool_desc = _hci_driver->get_buffer_pool_description(); // Initialize buffers with the ones provided by the HCI driver uint16_t bytes_used = WsfBufInit( buf_pool_desc.buffer_size, buf_pool_desc.buffer_memory, buf_pool_desc.pool_count, buf_pool_desc.pool_description ); MBED_ASSERT(bytes_used != 0); WsfTimerInit(); SecInit(); // Note: enable once security is supported SecRandInit(); SecAesInit(); SecCmacInit(); SecEccInit(); handlerId = WsfOsSetNextHandler(HciHandler); HciHandlerInit(handlerId); handlerId = WsfOsSetNextHandler(DmHandler); DmAdvInit(); DmScanInit(); DmConnInit(); DmConnMasterInit(); DmConnSlaveInit(); DmSecInit(); // Note: enable once security is supported DmSecLescInit(); DmPrivInit(); DmHandlerInit(handlerId); handlerId = WsfOsSetNextHandler(L2cSlaveHandler); L2cSlaveHandlerInit(handlerId); L2cInit(); L2cSlaveInit(); L2cMasterInit(); handlerId = WsfOsSetNextHandler(AttHandler); AttHandlerInit(handlerId); AttsInit(); AttsIndInit(); AttcInit(); handlerId = WsfOsSetNextHandler(SmpHandler); SmpHandlerInit(handlerId); SmprInit(); SmprScInit(); SmpiInit(); SmpiScInit(); stack_handler_id = WsfOsSetNextHandler(&BLE::stack_handler); HciSetMaxRxAclLen(100); DmRegister(BLE::device_manager_cb); DmConnRegister(DM_CLIENT_ID_APP, BLE::device_manager_cb); AttConnRegister(BLE::connection_handler); AttRegister((attCback_t) ble::pal::vendor::cordio::CordioAttClient::att_client_handler); } void BLE::start_stack_reset() { _hci_driver->initialize(); DmDevReset(); } void BLE::callDispatcher() { // process the external event queue _event_queue.process(); // follow by stack events static uint32_t lastTimeUs = us_ticker_read(); uint32_t currTimeUs, deltaTimeMs; // Update the current cordio time currTimeUs = us_ticker_read(); deltaTimeMs = (currTimeUs - lastTimeUs) / 1000; if (deltaTimeMs > 0) { WsfTimerUpdate(deltaTimeMs / WSF_MS_PER_TICK); lastTimeUs += deltaTimeMs * 1000; } wsfOsDispatcher(); if (wsfOsReadyToSleep()) { static Timeout nextTimeout; // setup an mbed timer for the next Cordio timeout bool_t pTimerRunning; timestamp_t nextTimestamp = (timestamp_t) (WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } } CordioHCIDriver* BLE::_hci_driver = NULL; FunctionPointerWithContext< ::BLE::InitializationCompleteCallbackContext*> BLE::_init_callback; } // namespace cordio } // namespace vendor } // namespace ble <commit_msg>Cordio: Enable client and server signing<commit_after>/* mbed Microcontroller Library * Copyright (c) 2017-2017 ARM Limited * * 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 "mbed.h" #include "us_ticker_api.h" #include "BLE.h" #include "wsf_types.h" #include "wsf_msg.h" #include "wsf_os.h" #include "wsf_buf.h" #include "wsf_timer.h" #include "hci_handler.h" #include "dm_handler.h" #include "l2c_handler.h" #include "att_handler.h" #include "smp_handler.h" #include "l2c_api.h" #include "att_api.h" #include "smp_api.h" #include "hci_drv.h" #include "CordioBLE.h" #include "mbed_assert.h" #include "CordioPalAttClient.h" #include "CordioPalSecurityManager.h" /*! WSF handler ID */ wsfHandlerId_t stack_handler_id; /** * Weak definition of ble_cordio_get_hci_driver. * A runtime error is generated if the user does not define any * ble_cordio_get_hci_driver. */ MBED_WEAK ble::vendor::cordio::CordioHCIDriver& ble_cordio_get_hci_driver() { error("Please provide an implementation for the HCI driver"); ble::vendor::cordio::CordioHCIDriver* bad_instance = NULL; return *bad_instance; } /** * Low level HCI interface between Cordio stack and the port. */ extern "C" uint16_t hci_mbed_os_drv_write(uint8_t type, uint16_t len, uint8_t *pData) { return ble_cordio_get_hci_driver().write(type, len, pData); } extern "C" void hci_mbed_os_start_reset_sequence(void) { ble_cordio_get_hci_driver().start_reset_sequence(); } extern "C" void hci_mbed_os_handle_reset_sequence(uint8_t* msg) { ble_cordio_get_hci_driver().handle_reset_sequence(msg); } /* * This function will signal to the user code by calling signalEventsToProcess. * It is registered and called into the Wsf Stack. */ extern "C" void wsf_mbed_ble_signal_event(void) { ble::vendor::cordio::BLE::deviceInstance().signalEventsToProcess(::BLE::DEFAULT_INSTANCE); } /** * BLE-API requires an implementation of the following function in order to * obtain its transport handle. */ BLEInstanceBase *createBLEInstance() { return (&(ble::vendor::cordio::BLE::deviceInstance())); } namespace ble { namespace vendor { namespace cordio { BLE::BLE(CordioHCIDriver& hci_driver) : initialization_status(NOT_INITIALIZED), instanceID(::BLE::DEFAULT_INSTANCE), _event_queue() { _hci_driver = &hci_driver; stack_setup(); } BLE::~BLE() { } /** * The singleton which represents the BLE transport for the BLE. */ BLE& BLE::deviceInstance() { static BLE instance( ble_cordio_get_hci_driver() ); return instance; } ble_error_t BLE::init( ::BLE::InstanceID_t instanceID, FunctionPointerWithContext< ::BLE::InitializationCompleteCallbackContext *> initCallback) { switch (initialization_status) { case NOT_INITIALIZED: _event_queue.initialize(this, instanceID); _init_callback = initCallback; start_stack_reset(); return BLE_ERROR_NONE; case INITIALIZING: return BLE_ERROR_INITIALIZATION_INCOMPLETE; case INITIALIZED: return BLE_ERROR_NONE; default: return BLE_ERROR_UNSPECIFIED; } } bool BLE::hasInitialized() const { return initialization_status == INITIALIZED; } ble_error_t BLE::shutdown() { if (initialization_status != INITIALIZED) { return BLE_ERROR_INITIALIZATION_INCOMPLETE; } initialization_status = NOT_INITIALIZED; _hci_driver->terminate(); getGattServer().reset(); getGattClient().reset(); getGap().reset(); _event_queue.clear(); return BLE_ERROR_NONE; } const char* BLE::getVersion() { static const char version[] = "generic-cordio"; return version; } generic::GenericGap& BLE::getGap() { static pal::vendor::cordio::GenericAccessService cordio_gap_service; static ble::generic::GenericGap gap( _event_queue, pal::vendor::cordio::Gap::get_gap(), cordio_gap_service ); return gap; } const generic::GenericGap& BLE::getGap() const { BLE &self = const_cast<BLE&>(*this); return const_cast<const generic::GenericGap&>(self.getGap()); }; GattServer& BLE::getGattServer() { return cordio::GattServer::getInstance(); } const GattServer& BLE::getGattServer() const { return cordio::GattServer::getInstance(); } generic::GenericGattClient& BLE::getGattClient() { static pal::AttClientToGattClientAdapter pal_client( pal::vendor::cordio::CordioAttClient::get_client() ); static generic::GenericGattClient client(&pal_client); return client; } SecurityManager& BLE::getSecurityManager() { static pal::MemorySecurityDb m_db; static SigningEventMonitorProxy signing_event_monitor(*this); static generic::GenericSecurityManager m_instance( pal::vendor::cordio::CordioSecurityManager::get_security_manager(), m_db, getGap(), signing_event_monitor ); return m_instance; } const SecurityManager& BLE::getSecurityManager() const { const BLE &self = const_cast<BLE&>(*this); return const_cast<const SecurityManager&>(self.getSecurityManager()); } void BLE::waitForEvent() { static Timeout nextTimeout; timestamp_t nextTimestamp; bool_t pTimerRunning; callDispatcher(); if (wsfOsReadyToSleep()) { // setup an mbed timer for the next cordio timeout nextTimestamp = (timestamp_t)(WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } } void BLE::processEvents() { callDispatcher(); } void BLE::stack_handler(wsfEventMask_t event, wsfMsgHdr_t* msg) { if (msg == NULL) { return; } if (ble::pal::vendor::cordio::CordioSecurityManager::get_security_manager().sm_handler(msg)) { return; } switch(msg->event) { case DM_RESET_CMPL_IND: { ::BLE::InitializationCompleteCallbackContext context = { ::BLE::Instance(::BLE::DEFAULT_INSTANCE), BLE_ERROR_NONE }; deviceInstance().getGattServer().initialize(); deviceInstance().initialization_status = INITIALIZED; _init_callback.call(&context); } break; default: ble::pal::vendor::cordio::Gap::gap_handler(msg); break; } } void BLE::device_manager_cb(dmEvt_t* dm_event) { BLE::deviceInstance().stack_handler(0, &dm_event->hdr); } /* * AttServerInitDeInitCback callback is used to Initialize/Deinitialize * the CCC Table of the ATT Server when a remote peer requests to Open * or Close the connection. */ void BLE::connection_handler(dmEvt_t* dm_event) { dmConnId_t connId = (dmConnId_t)dm_event->hdr.param; switch (dm_event->hdr.event) { case DM_CONN_OPEN_IND: /* set up CCC table with uninitialized (all zero) values */ AttsCccInitTable(connId, NULL); break; case DM_CONN_CLOSE_IND: /* clear CCC table on connection close */ AttsCccClearTable(connId); break; default: break; } } void BLE::timeoutCallback() { wsf_mbed_ble_signal_event(); } void BLE::stack_setup() { MBED_ASSERT(_hci_driver != NULL); wsfHandlerId_t handlerId; buf_pool_desc_t buf_pool_desc = _hci_driver->get_buffer_pool_description(); // Initialize buffers with the ones provided by the HCI driver uint16_t bytes_used = WsfBufInit( buf_pool_desc.buffer_size, buf_pool_desc.buffer_memory, buf_pool_desc.pool_count, buf_pool_desc.pool_description ); MBED_ASSERT(bytes_used != 0); WsfTimerInit(); SecInit(); // Note: enable once security is supported SecRandInit(); SecAesInit(); SecCmacInit(); SecEccInit(); handlerId = WsfOsSetNextHandler(HciHandler); HciHandlerInit(handlerId); handlerId = WsfOsSetNextHandler(DmHandler); DmAdvInit(); DmScanInit(); DmConnInit(); DmConnMasterInit(); DmConnSlaveInit(); DmSecInit(); // Note: enable once security is supported DmSecLescInit(); DmPrivInit(); DmHandlerInit(handlerId); handlerId = WsfOsSetNextHandler(L2cSlaveHandler); L2cSlaveHandlerInit(handlerId); L2cInit(); L2cSlaveInit(); L2cMasterInit(); handlerId = WsfOsSetNextHandler(AttHandler); AttHandlerInit(handlerId); AttsInit(); AttsIndInit(); AttsSignInit(); AttcInit(); AttcSignInit(); handlerId = WsfOsSetNextHandler(SmpHandler); SmpHandlerInit(handlerId); SmprInit(); SmprScInit(); SmpiInit(); SmpiScInit(); stack_handler_id = WsfOsSetNextHandler(&BLE::stack_handler); HciSetMaxRxAclLen(100); DmRegister(BLE::device_manager_cb); DmConnRegister(DM_CLIENT_ID_APP, BLE::device_manager_cb); AttConnRegister(BLE::connection_handler); AttRegister((attCback_t) ble::pal::vendor::cordio::CordioAttClient::att_client_handler); } void BLE::start_stack_reset() { _hci_driver->initialize(); DmDevReset(); } void BLE::callDispatcher() { // process the external event queue _event_queue.process(); // follow by stack events static uint32_t lastTimeUs = us_ticker_read(); uint32_t currTimeUs, deltaTimeMs; // Update the current cordio time currTimeUs = us_ticker_read(); deltaTimeMs = (currTimeUs - lastTimeUs) / 1000; if (deltaTimeMs > 0) { WsfTimerUpdate(deltaTimeMs / WSF_MS_PER_TICK); lastTimeUs += deltaTimeMs * 1000; } wsfOsDispatcher(); if (wsfOsReadyToSleep()) { static Timeout nextTimeout; // setup an mbed timer for the next Cordio timeout bool_t pTimerRunning; timestamp_t nextTimestamp = (timestamp_t) (WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK) * 1000; if (pTimerRunning) { nextTimeout.attach_us(timeoutCallback, nextTimestamp); } } } CordioHCIDriver* BLE::_hci_driver = NULL; FunctionPointerWithContext< ::BLE::InitializationCompleteCallbackContext*> BLE::_init_callback; } // namespace cordio } // namespace vendor } // namespace ble <|endoftext|>
<commit_before>Matrix3i m = Matrix3i::Random(); cout << "Here is the matrix m:" << endl << m << endl; cout << "Here is m.minor(1,1):" << endl << m.minor(1,1) << endl; <commit_msg>Remove doc/snippets/MatrixBase_minor.cpp because minor() was removed.<commit_after><|endoftext|>
<commit_before>/* * TemplateComponent.cpp * * Created on: Jan 23, 2014 * Author: gwue */ #include "TemplateSoundComponent.hpp" // include the concrete implementation headers. #include "impl/TemplateSoundComponent_SW.hpp" // #include "impl/TemplateSoundComponent_HW.hpp" // Macro to define the Component name. This will be the name that will later appear in the TGF files DEFINE_COMPONENTNAME(TemplateSoundComponent, "template") // Export the sound compononent such that it can be compiled as a shared object // Different possibilities here: // EXPORT_SOUNDCOMPONENT_MIXED_IMPL(CLASSNAME) --> both HW and SW implementations exist // EXPORT_SOUNDCOMPONENT_SW_ONLY(CLASSNAME) // EXPORT_SOUNDCOMPONENT_HW_ONLY(CLASSNAME) // EXPORT_SOUNDCOMPONENT_NO_IMPL(CLASSNAME) --> no impl/ subclass, processing is done right here. // can be used for very simple stuff like constants. // preferably use SW_ONLY instead EXPORT_SOUNDCOMPONENT_SW_ONLY(TemplateSoundComponent); TemplateSoundComponent::TemplateSoundComponent(std::vector<std::string> params) : SoundComponentImpl(params) { // Read some value from the first parameter std::stringstream str; str << params[0]; int someValue; str >> someValue; // Register ports (that you have declared in the header file) // CREATE_AND_REGISTER_PORT3(<ComponentClass>, In|Out, SoundPort|ControlPort, <Name>, <Portumber> // <ComponentClass> is the name of this component // Either In or Out to specify the direction of this port // Type of the Port // <Name> as defined in the header // <Portnumber> as defined in the header // For: DECLARE_PORT3(ControlPort, TemplateControlIn, 1); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, In, ControlPort, TemplateControlIn, 1); // For: DECLARE_PORT3(ControlPort, TemplateControlOut, 1); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, In, ControlPort, TemplateControlOut, 1); // For: DECLARE_PORT3(SoundPort, TemplateSoundIn, 2); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, In, SoundPort, TemplateSoundIn, 2); // For: DECLARE_PORT3(SoundPort, TemplateSoundOut, 2); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, Out, SoundPort, TemplateSoundOut, 2); } TemplateSoundComponent::~TemplateSoundComponent(){} void TemplateSoundComponent::init() { // You can init() sound output ports to clear their buffers m_TemplateSoundOut_2_Port->init(); } // ::process is not implemented here but in the SW subclass! <commit_msg>Fixed a small error in the template (Out Port that was declared as In)<commit_after>/* * TemplateComponent.cpp * * Created on: Jan 23, 2014 * Author: gwue */ #include "TemplateSoundComponent.hpp" // include the concrete implementation headers. #include "impl/TemplateSoundComponent_SW.hpp" // #include "impl/TemplateSoundComponent_HW.hpp" // Macro to define the Component name. This will be the name that will later appear in the TGF files DEFINE_COMPONENTNAME(TemplateSoundComponent, "template") // Export the sound compononent such that it can be compiled as a shared object // Different possibilities here: // EXPORT_SOUNDCOMPONENT_MIXED_IMPL(CLASSNAME) --> both HW and SW implementations exist // EXPORT_SOUNDCOMPONENT_SW_ONLY(CLASSNAME) // EXPORT_SOUNDCOMPONENT_HW_ONLY(CLASSNAME) // EXPORT_SOUNDCOMPONENT_NO_IMPL(CLASSNAME) --> no impl/ subclass, processing is done right here. // can be used for very simple stuff like constants. // preferably use SW_ONLY instead EXPORT_SOUNDCOMPONENT_SW_ONLY(TemplateSoundComponent); TemplateSoundComponent::TemplateSoundComponent(std::vector<std::string> params) : SoundComponentImpl(params) { // Read some value from the first parameter std::stringstream str; str << params[0]; int someValue; str >> someValue; // Register ports (that you have declared in the header file) // CREATE_AND_REGISTER_PORT3(<ComponentClass>, In|Out, SoundPort|ControlPort, <Name>, <Portumber> // <ComponentClass> is the name of this component // Either In or Out to specify the direction of this port // Type of the Port // <Name> as defined in the header // <Portnumber> as defined in the header // For: DECLARE_PORT3(ControlPort, TemplateControlIn, 1); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, In, ControlPort, TemplateControlIn, 1); // For: DECLARE_PORT3(ControlPort, TemplateControlOut, 1); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, Out, ControlPort, TemplateControlOut, 1); // For: DECLARE_PORT3(SoundPort, TemplateSoundIn, 2); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, In, SoundPort, TemplateSoundIn, 2); // For: DECLARE_PORT3(SoundPort, TemplateSoundOut, 2); CREATE_AND_REGISTER_PORT3(TemplateSoundComponent, Out, SoundPort, TemplateSoundOut, 2); } TemplateSoundComponent::~TemplateSoundComponent(){} void TemplateSoundComponent::init() { // You can init() sound output ports to clear their buffers m_TemplateSoundOut_2_Port->init(); } // ::process is not implemented here but in the SW subclass! <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/menu_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "chrome/browser/gtk/standard_menus.h" #include "chrome/common/gtk_util.h" #include "third_party/skia/include/core/SkBitmap.h" using gtk_util::ConvertAcceleratorsFromWindowsStyle; bool MenuGtk::block_activation_ = false; MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) : delegate_(delegate), dummy_accel_group_(gtk_accel_group_new()), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); BuildMenuIn(menu_.get(), menu_data, accel_group); } MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load) : delegate_(delegate), dummy_accel_group_(NULL), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); if (load) BuildMenuFromDelegate(); } MenuGtk::~MenuGtk() { menu_.Destroy(); STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end()); if (dummy_accel_group_) g_object_unref(dummy_accel_group_); } void MenuGtk::ConnectSignalHandlers() { // We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may // take a long time or even start a nested message loop. g_signal_connect(menu_.get(), "show", G_CALLBACK(OnMenuShow), this); g_signal_connect(menu_.get(), "hide", G_CALLBACK(OnMenuHidden), this); } void MenuGtk::AppendMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendMenuItemWithIcon(int command_id, const std::string& label, const SkBitmap& icon) { GtkWidget* menu_item = BuildMenuItemWithImage(label, icon); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendCheckMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_check_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendSeparator() { GtkWidget* menu_item = gtk_separator_menu_item_new(); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) { g_object_set_data(G_OBJECT(menu_item), "menu-id", reinterpret_cast<void*>(command_id)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) { DCHECK(event->type == GDK_BUTTON_PRESS) << "Non-button press event sent to RunMenuAt"; GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event); Popup(widget, event_button->button, event_button->time); } void MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, WidgetMenuPositionFunc, widget, button_type, timestamp); } void MenuGtk::PopupAsContext(guint32 event_time) { // TODO(estade): |button| value of 3 (6th argument) is not strictly true, // but does it matter? gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time); } void MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, PointMenuPositionFunc, &point, 3, event_time); } void MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) { Popup(widget, 0, gtk_get_current_event_time()); gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE); } void MenuGtk::Cancel() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void MenuGtk::BuildMenuIn(GtkWidget* menu, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) { // We keep track of the last menu item in order to group radio items. GtkWidget* last_menu_item = NULL; for (; menu_data->type != MENU_END; ++menu_data) { GtkWidget* menu_item = NULL; std::string label; if (menu_data->label_argument) { label = l10n_util::GetStringFUTF8( menu_data->label_id, l10n_util::GetStringUTF16(menu_data->label_argument)); } else if (menu_data->label_id) { label = l10n_util::GetStringUTF8(menu_data->label_id); } else if (menu_data->type != MENU_SEPARATOR) { label = delegate_->GetLabel(menu_data->id); DCHECK(!label.empty()); } label = ConvertAcceleratorsFromWindowsStyle(label); switch (menu_data->type) { case MENU_RADIO: if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) { menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget( GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str()); } else { menu_item = gtk_radio_menu_item_new_with_mnemonic( NULL, label.c_str()); } break; case MENU_CHECKBOX: menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str()); break; case MENU_SEPARATOR: menu_item = gtk_separator_menu_item_new(); break; case MENU_NORMAL: default: menu_item = gtk_menu_item_new_with_mnemonic(label.c_str()); break; } if (menu_data->submenu) { GtkWidget* submenu = gtk_menu_new(); BuildMenuIn(submenu, menu_data->submenu, accel_group); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else if (menu_data->custom_submenu) { gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu_data->custom_submenu->menu_.get()); submenus_we_own_.push_back(menu_data->custom_submenu); } if (menu_data->accel_key) { // If we ever want to let the user do any key remaping, we'll need to // change the following so we make a gtk_accel_map which keeps the actual // keys. gtk_widget_add_accelerator(menu_item, "activate", menu_data->only_show || !accel_group ? dummy_accel_group_ : accel_group, menu_data->accel_key, GdkModifierType(menu_data->accel_modifiers), GTK_ACCEL_VISIBLE); } g_object_set_data(G_OBJECT(menu_item), "menu-data", const_cast<MenuCreateMaterial*>(menu_data)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_append(menu, menu_item); last_menu_item = menu_item; } } GtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label, const SkBitmap& icon) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_image_menu_item_new_with_mnemonic(converted_label.c_str()); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); if (delegate_->AlwaysShowImages()) gtk_util::SetAlwaysShowImage(menu_item); return menu_item; } void MenuGtk::BuildMenuFromDelegate() { // Note that the menu IDs start at 1, not 0. for (int i = 1; i <= delegate_->GetItemCount(); ++i) { GtkWidget* menu_item = NULL; if (delegate_->IsItemSeparator(i)) { menu_item = gtk_separator_menu_item_new(); } else if (delegate_->HasIcon(i)) { const SkBitmap* icon = delegate_->GetIcon(i); menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon); } else { menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str()); } AppendMenuItem(i, menu_item); } } // static void MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) { if (block_activation_) return; // We receive activation messages when highlighting a menu that has a // submenu. Ignore them. if (gtk_menu_item_get_submenu(menuitem)) return; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(menuitem), "menu-data")); int id; if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(menuitem), "menu-id")); } // The menu item can still be activated by hotkeys even if it is disabled. if (menu->delegate_->IsCommandEnabled(id)) menu->delegate_->ExecuteCommand(id); } // static void MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, void* void_widget) { GtkWidget* widget = GTK_WIDGET(void_widget); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); gdk_window_get_origin(widget->window, x, y); GdkScreen *screen = gtk_widget_get_screen(widget); gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y); GdkRectangle screen_rect; gdk_screen_get_monitor_geometry(screen, monitor, &screen_rect); if (GTK_WIDGET_NO_WINDOW(widget)) { *x += widget->allocation.x; *y += widget->allocation.y; } *y += widget->allocation.height; bool start_align = !!g_object_get_data(G_OBJECT(widget), "left-align-popup"); if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) start_align = !start_align; if (!start_align) *x += widget->allocation.width - menu_req.width; // If the menu would run off the bottom of the screen, and there is more // screen space up than down, then pop upwards. if (*y + menu_req.height >= screen_rect.height && *y > screen_rect.height / 2) { *y -= menu_req.height; } *push_in = FALSE; } // static void MenuGtk::PointMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, gpointer userdata) { *push_in = TRUE; gfx::Point* point = reinterpret_cast<gfx::Point*>(userdata); *x = point->x(); *y = point->y(); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); GdkScreen* screen = gdk_screen_get_default(); gint screen_height = gdk_screen_get_height(screen); if (*y + menu_req.height >= screen_height) *y -= menu_req.height; } void MenuGtk::UpdateMenu() { gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this); } // static void MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) { MessageLoop::current()->PostTask(FROM_HERE, menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu)); } // static void MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) { menu->delegate_->StoppedShowing(); } // static void MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) { if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) { // We need to explicitly handle this case because otherwise we'll ask the // menu delegate about something with an invalid id. return; } MenuGtk* menu = reinterpret_cast<MenuGtk*>(userdata); int id; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(widget), "menu-data")); if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(widget), "menu-id")); } if (GTK_IS_CHECK_MENU_ITEM(widget)) { GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget); // gtk_check_menu_item_set_active() will send the activate signal. Touching // the underlying "active" property will also call the "activate" handler // for this menu item. So we prevent the "activate" handler from // being called while we set the checkbox. // Why not use one of the glib signal-blocking functions? Because when we // toggle a radio button, it will deactivate one of the other radio buttons, // which we don't have a pointer to. // Wny not make this a member variable? Because "menu" is a pointer to the // root of the MenuGtk and we want to disable *all* MenuGtks, including // submenus. block_activation_ = true; gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id)); block_activation_ = false; } if (GTK_IS_MENU_ITEM(widget)) { gtk_widget_set_sensitive( widget, menu->delegate_->IsCommandEnabled(id)); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)); if (submenu) { gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo, userdata); } } } <commit_msg>Fix radio items in MenuGtk.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/menu_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/stl_util-inl.h" #include "base/string_util.h" #include "chrome/browser/gtk/standard_menus.h" #include "chrome/common/gtk_util.h" #include "third_party/skia/include/core/SkBitmap.h" using gtk_util::ConvertAcceleratorsFromWindowsStyle; bool MenuGtk::block_activation_ = false; MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) : delegate_(delegate), dummy_accel_group_(gtk_accel_group_new()), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); BuildMenuIn(menu_.get(), menu_data, accel_group); } MenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load) : delegate_(delegate), dummy_accel_group_(NULL), menu_(gtk_menu_new()), factory_(this) { ConnectSignalHandlers(); if (load) BuildMenuFromDelegate(); } MenuGtk::~MenuGtk() { menu_.Destroy(); STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end()); if (dummy_accel_group_) g_object_unref(dummy_accel_group_); } void MenuGtk::ConnectSignalHandlers() { // We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may // take a long time or even start a nested message loop. g_signal_connect(menu_.get(), "show", G_CALLBACK(OnMenuShow), this); g_signal_connect(menu_.get(), "hide", G_CALLBACK(OnMenuHidden), this); } void MenuGtk::AppendMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendMenuItemWithIcon(int command_id, const std::string& label, const SkBitmap& icon) { GtkWidget* menu_item = BuildMenuItemWithImage(label, icon); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendCheckMenuItemWithLabel(int command_id, const std::string& label) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_check_menu_item_new_with_mnemonic(converted_label.c_str()); AppendMenuItem(command_id, menu_item); } void MenuGtk::AppendSeparator() { GtkWidget* menu_item = gtk_separator_menu_item_new(); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) { g_object_set_data(G_OBJECT(menu_item), "menu-id", reinterpret_cast<void*>(command_id)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item); } void MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) { DCHECK(event->type == GDK_BUTTON_PRESS) << "Non-button press event sent to RunMenuAt"; GdkEventButton* event_button = reinterpret_cast<GdkEventButton*>(event); Popup(widget, event_button->button, event_button->time); } void MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, WidgetMenuPositionFunc, widget, button_type, timestamp); } void MenuGtk::PopupAsContext(guint32 event_time) { // TODO(estade): |button| value of 3 (6th argument) is not strictly true, // but does it matter? gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time); } void MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) { gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, PointMenuPositionFunc, &point, 3, event_time); } void MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) { Popup(widget, 0, gtk_get_current_event_time()); gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE); } void MenuGtk::Cancel() { gtk_menu_popdown(GTK_MENU(menu_.get())); } void MenuGtk::BuildMenuIn(GtkWidget* menu, const MenuCreateMaterial* menu_data, GtkAccelGroup* accel_group) { // We keep track of the last menu item in order to group radio items. GtkWidget* last_menu_item = NULL; for (; menu_data->type != MENU_END; ++menu_data) { GtkWidget* menu_item = NULL; std::string label; if (menu_data->label_argument) { label = l10n_util::GetStringFUTF8( menu_data->label_id, l10n_util::GetStringUTF16(menu_data->label_argument)); } else if (menu_data->label_id) { label = l10n_util::GetStringUTF8(menu_data->label_id); } else if (menu_data->type != MENU_SEPARATOR) { label = delegate_->GetLabel(menu_data->id); DCHECK(!label.empty()); } label = ConvertAcceleratorsFromWindowsStyle(label); switch (menu_data->type) { case MENU_RADIO: if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) { menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget( GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str()); } else { menu_item = gtk_radio_menu_item_new_with_mnemonic( NULL, label.c_str()); } break; case MENU_CHECKBOX: menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str()); break; case MENU_SEPARATOR: menu_item = gtk_separator_menu_item_new(); break; case MENU_NORMAL: default: menu_item = gtk_menu_item_new_with_mnemonic(label.c_str()); break; } if (menu_data->submenu) { GtkWidget* submenu = gtk_menu_new(); BuildMenuIn(submenu, menu_data->submenu, accel_group); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else if (menu_data->custom_submenu) { gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), menu_data->custom_submenu->menu_.get()); submenus_we_own_.push_back(menu_data->custom_submenu); } if (menu_data->accel_key) { // If we ever want to let the user do any key remaping, we'll need to // change the following so we make a gtk_accel_map which keeps the actual // keys. gtk_widget_add_accelerator(menu_item, "activate", menu_data->only_show || !accel_group ? dummy_accel_group_ : accel_group, menu_data->accel_key, GdkModifierType(menu_data->accel_modifiers), GTK_ACCEL_VISIBLE); } g_object_set_data(G_OBJECT(menu_item), "menu-data", const_cast<MenuCreateMaterial*>(menu_data)); g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(OnMenuItemActivated), this); gtk_widget_show(menu_item); gtk_menu_append(menu, menu_item); last_menu_item = menu_item; } } GtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label, const SkBitmap& icon) { std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label); GtkWidget* menu_item = gtk_image_menu_item_new_with_mnemonic(converted_label.c_str()); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); if (delegate_->AlwaysShowImages()) gtk_util::SetAlwaysShowImage(menu_item); return menu_item; } void MenuGtk::BuildMenuFromDelegate() { // Note that the menu IDs start at 1, not 0. for (int i = 1; i <= delegate_->GetItemCount(); ++i) { GtkWidget* menu_item = NULL; if (delegate_->IsItemSeparator(i)) { menu_item = gtk_separator_menu_item_new(); } else if (delegate_->HasIcon(i)) { const SkBitmap* icon = delegate_->GetIcon(i); menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon); } else { menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str()); } AppendMenuItem(i, menu_item); } } // static void MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) { if (block_activation_) return; // We receive activation messages when highlighting a menu that has a // submenu. Ignore them. if (gtk_menu_item_get_submenu(menuitem)) return; // The activate signal is sent to radio items as they get deselected; // ignore it in this case. if (GTK_IS_RADIO_MENU_ITEM(menuitem) && !gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(menuitem))) { return; } const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(menuitem), "menu-data")); int id; if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(menuitem), "menu-id")); } // The menu item can still be activated by hotkeys even if it is disabled. if (menu->delegate_->IsCommandEnabled(id)) menu->delegate_->ExecuteCommand(id); } // static void MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, void* void_widget) { GtkWidget* widget = GTK_WIDGET(void_widget); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); gdk_window_get_origin(widget->window, x, y); GdkScreen *screen = gtk_widget_get_screen(widget); gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y); GdkRectangle screen_rect; gdk_screen_get_monitor_geometry(screen, monitor, &screen_rect); if (GTK_WIDGET_NO_WINDOW(widget)) { *x += widget->allocation.x; *y += widget->allocation.y; } *y += widget->allocation.height; bool start_align = !!g_object_get_data(G_OBJECT(widget), "left-align-popup"); if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) start_align = !start_align; if (!start_align) *x += widget->allocation.width - menu_req.width; // If the menu would run off the bottom of the screen, and there is more // screen space up than down, then pop upwards. if (*y + menu_req.height >= screen_rect.height && *y > screen_rect.height / 2) { *y -= menu_req.height; } *push_in = FALSE; } // static void MenuGtk::PointMenuPositionFunc(GtkMenu* menu, int* x, int* y, gboolean* push_in, gpointer userdata) { *push_in = TRUE; gfx::Point* point = reinterpret_cast<gfx::Point*>(userdata); *x = point->x(); *y = point->y(); GtkRequisition menu_req; gtk_widget_size_request(GTK_WIDGET(menu), &menu_req); GdkScreen* screen = gdk_screen_get_default(); gint screen_height = gdk_screen_get_height(screen); if (*y + menu_req.height >= screen_height) *y -= menu_req.height; } void MenuGtk::UpdateMenu() { gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this); } // static void MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) { MessageLoop::current()->PostTask(FROM_HERE, menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu)); } // static void MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) { menu->delegate_->StoppedShowing(); } // static void MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) { if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) { // We need to explicitly handle this case because otherwise we'll ask the // menu delegate about something with an invalid id. return; } MenuGtk* menu = reinterpret_cast<MenuGtk*>(userdata); int id; const MenuCreateMaterial* data = reinterpret_cast<const MenuCreateMaterial*>( g_object_get_data(G_OBJECT(widget), "menu-data")); if (data) { id = data->id; } else { id = reinterpret_cast<intptr_t>(g_object_get_data(G_OBJECT(widget), "menu-id")); } if (GTK_IS_CHECK_MENU_ITEM(widget)) { GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget); // gtk_check_menu_item_set_active() will send the activate signal. Touching // the underlying "active" property will also call the "activate" handler // for this menu item. So we prevent the "activate" handler from // being called while we set the checkbox. // Why not use one of the glib signal-blocking functions? Because when we // toggle a radio button, it will deactivate one of the other radio buttons, // which we don't have a pointer to. // Wny not make this a member variable? Because "menu" is a pointer to the // root of the MenuGtk and we want to disable *all* MenuGtks, including // submenus. block_activation_ = true; gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id)); block_activation_ = false; } if (GTK_IS_MENU_ITEM(widget)) { gtk_widget_set_sensitive( widget, menu->delegate_->IsCommandEnabled(id)); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)); if (submenu) { gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo, userdata); } } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); } void RunTest(const FilePath::StringType& test_file_name) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(test_file_name); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL test_url = net::FilePathToFileURL(test_path); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_WIN) TEST_F(PPAPITest, DeviceContext2D) { #else // TODO(brettw) currently fails on Mac & Linux 64 for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #endif RunTest(FILE_PATH_LITERAL("test_device_context_2d.html")); } TEST_F(PPAPITest, ImageData) { RunTest(FILE_PATH_LITERAL("test_image_data.html")); } <commit_msg>Disable the ImageData test on Mac which is failing.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); #if defined(OS_WIN) std::wstring pepper_plugin = plugin_lib.value(); #else std::wstring pepper_plugin = UTF8ToWide(plugin_lib.value()); #endif pepper_plugin.append(L";application/x-ppapi-tests"); launch_arguments_.AppendSwitchWithValue(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); } void RunTest(const FilePath::StringType& test_file_name) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("third_party")); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(test_file_name); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL test_url = net::FilePathToFileURL(test_path); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); std::string escaped_value = WaitUntilCookieNonEmpty(tab.get(), test_url, "COMPLETION_COOKIE", action_max_timeout_ms()); EXPECT_STREQ("PASS", escaped_value.c_str()); } }; #if defined(OS_WIN) TEST_F(PPAPITest, DeviceContext2D) { #else // TODO(brettw) currently fails on Mac & Linux 64 for unknown reasons. TEST_F(PPAPITest, DISABLED_DeviceContext2D) { #endif RunTest(FILE_PATH_LITERAL("test_device_context_2d.html")); } #if defined(OS_MACOSX) // TODO(brettw) this fails on Mac for unknown reasons. TEST_F(PPAPITest, DISABLED_ImageData) { #else TEST_F(PPAPITest, ImageData) { #endif RunTest(FILE_PATH_LITERAL("test_image_data.html")); } <|endoftext|>
<commit_before>#ifndef CONFIGMGR_LOCALBE_LOCALFILEHELPER_HXX_ #include "localfilehelper.hxx" #endif #ifndef _CONFIGMGR_FILEHELPER_HXX_ #include "filehelper.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif // _RTL_USTRBUF_HXX_ #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #include <vector> namespace configmgr { namespace localbe { //------------------------------------------------------------------------------ bool isValidFileURL (rtl::OUString const& _sFileURL) { using osl::File; rtl::OUString sSystemPath; return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath)); } //------------------------------------------------------------------------------ void validateFileURL(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw(css::configuration::InvalidBootstrapFileException) { if (!isValidFileURL( _sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" Not a Valid File URL: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw com::sun::star::configuration::InvalidBootstrapFileException( sMsg.makeStringAndClear(),pContext, rtl::OUString() ) ; } } //------------------------------------------------------------------------------ void checkFileExists(const rtl::OUString& _sFileURL,const uno::Reference<uno::XInterface>& pContext) throw (backend::CannotConnectException) { if (!FileHelper::fileExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" No Such File or Directory: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw backend::CannotConnectException(sMsg.makeStringAndClear(), pContext, uno::Any()) ; } } //------------------------------------------------------------------------------ void checkIfDirectory(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw (backend::BackendSetupException) { if (!FileHelper::dirExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" File:\""); sMsg.append(_sFileURL); sMsg.appendAscii("\" Must be a Directory\""); throw backend::BackendSetupException(sMsg.makeStringAndClear(),pContext, uno::Any()) ; } } // --------------------------------------------------------------------------------------- bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc. { using osl::File; rtl::OUString sBasePath = _rsURL; OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData)); rtl::OUString sAbsolute; if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) { _rsURL = sAbsolute; return true; } else { OSL_ENSURE(false, "Could not get absolute file URL for valid URL"); return false; } } // --------------------------------------------------------------------------------------- osl::DirectoryItem::RC implNormalizeURL(rtl::OUString & _sURL, osl::DirectoryItem& aDirItem) { using namespace osl; OSL_PRECOND(aDirItem.is(), "Opened DirItem required"); static const sal_uInt32 cFileStatusMask = FileStatusMask_FileURL; FileStatus aFileStatus(cFileStatusMask); DirectoryItem::RC rc = aDirItem.getFileStatus(aFileStatus); if (rc == DirectoryItem::E_None) { rtl::OUString aNormalizedURL = aFileStatus.getFileURL(); if (aNormalizedURL.getLength() != 0) _sURL = aNormalizedURL; else rc = DirectoryItem::E_INVAL; } return rc; } // --------------------------------------------------------------------------------------- bool normalizeURL(rtl::OUString & _sURL, const uno::Reference<uno::XInterface>& pContext, bool bNothrow ) throw (backend::InsufficientAccessRightsException, backend::BackendAccessException) { using namespace osl; if (_sURL.getLength() == 0) return false; DirectoryItem aDirItem; DirectoryItem::RC rc = DirectoryItem::get(_sURL, aDirItem); if (rc == DirectoryItem::E_None) rc = implNormalizeURL(_sURL,aDirItem); switch (rc) { case DirectoryItem::E_None: return true; case DirectoryItem::E_NOENT: return true; case DirectoryItem::E_ACCES: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - InsufficientAccess"); throw backend::InsufficientAccessRightsException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; default: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - ").append(FileHelper::createOSLErrorString(rc)); throw backend::BackendAccessException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; } } // --------------------------------------------------------------------------------------- static sal_Unicode kComponentSeparator = '.' ; static sal_Unicode kPathSeparator = '/' ; rtl::OUString componentToPath(const rtl::OUString& aComponent) { rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ bool checkOptionalArg(rtl::OUString& aArg) { if (aArg.getLength() && aArg[0] == sal_Unicode('?')) { aArg = aArg.copy(1); return true; } else { return false; } } //------------------------------------------------------------------------------ void fillFromBlankSeparated(const rtl::OUString& aList, uno::Sequence<rtl::OUString>& aTarget) { std::vector<rtl::OUString> tokens ; sal_Int32 nextToken = 0 ; do { tokens.push_back(aList.getToken(0, ' ', nextToken)) ; } while (nextToken >= 0) ; if (tokens.size() > 0) { aTarget.realloc(tokens.size()) ; std::vector<rtl::OUString>::const_iterator token ; sal_Int32 i = 0 ; for (token = tokens.begin() ; token != tokens.end() ; ++ token) { aTarget [i ++] = *token ; } } } //------------------------------------------------------------------------------ } } // namespace configmgr <commit_msg>INTEGRATION: CWS adabas13 (1.2.58); FILE MERGED 2005/01/25 13:13:29 jb 1.2.58.1: #119211# Improve entity handling to support multi-stratum sublayers which have dots in their names<commit_after>#ifndef CONFIGMGR_LOCALBE_LOCALFILEHELPER_HXX_ #include "localfilehelper.hxx" #endif #ifndef _CONFIGMGR_FILEHELPER_HXX_ #include "filehelper.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif // _RTL_USTRBUF_HXX_ #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #include <vector> namespace configmgr { namespace localbe { //------------------------------------------------------------------------------ bool isValidFileURL (rtl::OUString const& _sFileURL) { using osl::File; rtl::OUString sSystemPath; return _sFileURL.getLength() && (File::E_None == File::getSystemPathFromFileURL(_sFileURL, sSystemPath)); } //------------------------------------------------------------------------------ void validateFileURL(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw(css::configuration::InvalidBootstrapFileException) { if (!isValidFileURL( _sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" Not a Valid File URL: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw com::sun::star::configuration::InvalidBootstrapFileException( sMsg.makeStringAndClear(),pContext, rtl::OUString() ) ; } } //------------------------------------------------------------------------------ void checkFileExists(const rtl::OUString& _sFileURL,const uno::Reference<uno::XInterface>& pContext) throw (backend::CannotConnectException) { if (!FileHelper::fileExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" No Such File or Directory: \""); sMsg.append(_sFileURL); sMsg.appendAscii("\""); throw backend::CannotConnectException(sMsg.makeStringAndClear(), pContext, uno::Any()) ; } } //------------------------------------------------------------------------------ void checkIfDirectory(const rtl::OUString& _sFileURL, const uno::Reference<uno::XInterface>& pContext) throw (backend::BackendSetupException) { if (!FileHelper::dirExists(_sFileURL)) { rtl::OUStringBuffer sMsg; sMsg.appendAscii(" File:\""); sMsg.append(_sFileURL); sMsg.appendAscii("\" Must be a Directory\""); throw backend::BackendSetupException(sMsg.makeStringAndClear(),pContext, uno::Any()) ; } } // --------------------------------------------------------------------------------------- bool implEnsureAbsoluteURL(rtl::OUString & _rsURL) // also strips embedded dots etc. { using osl::File; rtl::OUString sBasePath = _rsURL; OSL_VERIFY(osl_Process_E_None == osl_getProcessWorkingDir(&sBasePath.pData)); rtl::OUString sAbsolute; if ( File::E_None == File::getAbsoluteFileURL(sBasePath, _rsURL, sAbsolute)) { _rsURL = sAbsolute; return true; } else { OSL_ENSURE(false, "Could not get absolute file URL for valid URL"); return false; } } // --------------------------------------------------------------------------------------- osl::DirectoryItem::RC implNormalizeURL(rtl::OUString & _sURL, osl::DirectoryItem& aDirItem) { using namespace osl; OSL_PRECOND(aDirItem.is(), "Opened DirItem required"); static const sal_uInt32 cFileStatusMask = FileStatusMask_FileURL; FileStatus aFileStatus(cFileStatusMask); DirectoryItem::RC rc = aDirItem.getFileStatus(aFileStatus); if (rc == DirectoryItem::E_None) { rtl::OUString aNormalizedURL = aFileStatus.getFileURL(); if (aNormalizedURL.getLength() != 0) _sURL = aNormalizedURL; else rc = DirectoryItem::E_INVAL; } return rc; } // --------------------------------------------------------------------------------------- bool normalizeURL(rtl::OUString & _sURL, const uno::Reference<uno::XInterface>& pContext, bool bNothrow ) throw (backend::InsufficientAccessRightsException, backend::BackendAccessException) { using namespace osl; if (_sURL.getLength() == 0) return false; DirectoryItem aDirItem; DirectoryItem::RC rc = DirectoryItem::get(_sURL, aDirItem); if (rc == DirectoryItem::E_None) rc = implNormalizeURL(_sURL,aDirItem); switch (rc) { case DirectoryItem::E_None: return true; case DirectoryItem::E_NOENT: return true; case DirectoryItem::E_ACCES: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - InsufficientAccess"); throw backend::InsufficientAccessRightsException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; default: if (!bNothrow) { rtl::OUStringBuffer msg; msg.appendAscii("LocalBackend: Cannot normalize URL \"" ); msg.append(_sURL); msg.appendAscii("\" - ").append(FileHelper::createOSLErrorString(rc)); throw backend::BackendAccessException(msg.makeStringAndClear(),pContext,uno::Any()); } return false; } } // --------------------------------------------------------------------------------------- static const sal_Unicode kComponentSeparator = '.' ; static const sal_Unicode kPathSeparator = '/' ; rtl::OUString componentToPath(const rtl::OUString& aComponent) { rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ rtl::OUString layeridToPath(const rtl::OUString& aLayerId) { sal_Int32 const nSplit = aLayerId.indexOf(k_cLayerIdSeparator); if (nSplit < 0) return componentToPath(aLayerId); rtl::OUString const aComponent= aLayerId.copy(0,nSplit); rtl::OUString const aSubid = aLayerId.copy(nSplit+1); rtl::OUStringBuffer retCode ; retCode.append(kPathSeparator) ; retCode.append(aComponent.replace(kComponentSeparator, kPathSeparator)) ; retCode.append(kPathSeparator) ; retCode.append(aSubid) ; return retCode.makeStringAndClear() ; } //------------------------------------------------------------------------------ bool checkOptionalArg(rtl::OUString& aArg) { if (aArg.getLength() && aArg[0] == sal_Unicode('?')) { aArg = aArg.copy(1); return true; } else { return false; } } //------------------------------------------------------------------------------ void fillFromBlankSeparated(const rtl::OUString& aList, uno::Sequence<rtl::OUString>& aTarget) { std::vector<rtl::OUString> tokens ; sal_Int32 nextToken = 0 ; do { tokens.push_back(aList.getToken(0, ' ', nextToken)) ; } while (nextToken >= 0) ; if (tokens.size() > 0) { aTarget.realloc(tokens.size()) ; std::vector<rtl::OUString>::const_iterator token ; sal_Int32 i = 0 ; for (token = tokens.begin() ; token != tokens.end() ; ++ token) { aTarget [i ++] = *token ; } } } //------------------------------------------------------------------------------ } } // namespace configmgr <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "camerabinvideoencoder.h" #include "camerabinsession.h" #include "camerabincontainer.h" #include <QtCore/qdebug.h> CameraBinVideoEncoder::CameraBinVideoEncoder(CameraBinSession *session) :QVideoEncoderControl(session), m_session(session) { QList<QByteArray> codecCandidates; #if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6) codecCandidates << "video/mpeg4" << "video/h264" << "video/h263" << "video/theora" << "video/mpeg2" << "video/mpeg1" << "video/mjpeg" << "video/VP8" << "video/h261"; m_elementNames["video/h264"] = "dsph264enc"; m_elementNames["video/mpeg4"] = "dspmp4venc"; m_elementNames["video/h263"] = "dsph263enc"; m_elementNames["video/theora"] = "theoraenc"; m_elementNames["video/mpeg2"] = "ffenc_mpeg2video"; m_elementNames["video/mpeg1"] = "ffenc_mpeg1video"; m_elementNames["video/mjpeg"] = "ffenc_mjpeg"; m_elementNames["video/VP8"] = "vp8enc"; m_elementNames["video/h261"] = "ffenc_h261"; m_codecOptions["video/mpeg4"] = QStringList() << "mode" << "keyframe-interval"; #else codecCandidates << "video/h264" << "video/xvid" << "video/mpeg4" << "video/mpeg1" << "video/mpeg2" << "video/theora" << "video/VP8" << "video/h261" << "video/mjpeg"; m_elementNames["video/h264"] = "x264enc"; m_elementNames["video/xvid"] = "xvidenc"; m_elementNames["video/mpeg4"] = "ffenc_mpeg4"; m_elementNames["video/mpeg1"] = "ffenc_mpeg1video"; m_elementNames["video/mpeg2"] = "ffenc_mpeg2video"; m_elementNames["video/theora"] = "theoraenc"; m_elementNames["video/mjpeg"] = "ffenc_mjpeg"; m_elementNames["video/VP8"] = "vp8enc"; m_elementNames["video/h261"] = "ffenc_h261"; m_codecOptions["video/h264"] = QStringList() << "quantizer"; m_codecOptions["video/xvid"] = QStringList() << "quantizer" << "profile"; m_codecOptions["video/mpeg4"] = QStringList() << "quantizer"; m_codecOptions["video/mpeg1"] = QStringList() << "quantizer"; m_codecOptions["video/mpeg2"] = QStringList() << "quantizer"; m_codecOptions["video/theora"] = QStringList(); #endif foreach( const QByteArray& codecName, codecCandidates ) { QByteArray elementName = m_elementNames[codecName]; GstElementFactory *factory = gst_element_factory_find(elementName.constData()); if (factory) { m_codecs.append(codecName); const gchar *descr = gst_element_factory_get_description(factory); m_codecDescriptions.insert(codecName, QString::fromUtf8(descr)); m_streamTypes.insert(codecName, CameraBinContainer::supportedStreamTypes(factory, GST_PAD_SRC)); gst_object_unref(GST_OBJECT(factory)); } } } CameraBinVideoEncoder::~CameraBinVideoEncoder() { } QList<QSize> CameraBinVideoEncoder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; QPair<int,int> rate = rateAsRational(settings.frameRate()); //select the closest supported rational rate to settings.frameRate() return m_session->supportedResolutions(rate, continuous); } QList< qreal > CameraBinVideoEncoder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; QList< qreal > res; QPair<int,int> rate; foreach(rate, m_session->supportedFrameRates(settings.resolution(), continuous)) { if (rate.second > 0) res << qreal(rate.first)/rate.second; } return res; } QStringList CameraBinVideoEncoder::supportedVideoCodecs() const { return m_codecs; } QString CameraBinVideoEncoder::videoCodecDescription(const QString &codecName) const { return m_codecDescriptions.value(codecName); } QStringList CameraBinVideoEncoder::supportedEncodingOptions(const QString &codec) const { return m_codecOptions.value(codec); } QVariant CameraBinVideoEncoder::encodingOption(const QString &codec, const QString &name) const { return m_options[codec].value(name); } void CameraBinVideoEncoder::setEncodingOption( const QString &codec, const QString &name, const QVariant &value) { m_options[codec][name] = value; } QVideoEncoderSettings CameraBinVideoEncoder::videoSettings() const { return m_videoSettings; } void CameraBinVideoEncoder::setVideoSettings(const QVideoEncoderSettings &settings) { m_videoSettings = settings; m_userSettings = settings; emit settingsChanged(); } void CameraBinVideoEncoder::setActualVideoSettings(const QVideoEncoderSettings &settings) { m_videoSettings = settings; } void CameraBinVideoEncoder::resetActualSettings() { m_videoSettings = m_userSettings; } GstElement *CameraBinVideoEncoder::createEncoder() { QString codec = m_videoSettings.codec(); QByteArray elementName = m_elementNames.value(codec); GstElement *encoderElement = gst_element_factory_make( elementName.constData(), "video-encoder"); if (encoderElement) { if (m_videoSettings.encodingMode() == QtMultimediaKit::ConstantQualityEncoding) { QtMultimediaKit::EncodingQuality qualityValue = m_videoSettings.quality(); if (elementName == "x264enc") { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 4, NULL); int qualityTable[] = { 50, //VeryLow 35, //Low 21, //Normal 15, //High 8 //VeryHigh }; g_object_set(G_OBJECT(encoderElement), "quantizer", qualityTable[qualityValue], NULL); } else if (elementName == "xvidenc") { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 3, NULL); int qualityTable[] = { 32, //VeryLow 12, //Low 5, //Normal 3, //High 2 //VeryHigh }; int quant = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL); } else if (elementName == "ffenc_mpeg4" || elementName == "ffenc_mpeg1video" || elementName == "ffenc_mpeg2video" ) { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 2, NULL); //quant from 1 to 30, default ~3 double qualityTable[] = { 20, //VeryLow 8.0, //Low 3.0, //Normal 2.5, //High 2.0 //VeryHigh }; double quant = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL); } else if (elementName == "theoraenc") { int qualityTable[] = { 8, //VeryLow 16, //Low 32, //Normal 45, //High 60 //VeryHigh }; //quality from 0 to 63 int quality = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quality", quality, NULL); } else if (elementName == "dsph264enc" || elementName == "dspmp4venc" || elementName == "dsph263enc") { //only bitrate parameter is supported int qualityTable[] = { 1000000, //VeryLow 2000000, //Low 4000000, //Normal 8000000, //High 16000000 //VeryHigh }; //quality from 0 to 63 int bitrate = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL); } } else { int bitrate = m_videoSettings.bitRate(); if (bitrate > 0) { g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL); } } QMap<QString,QVariant> options = m_options.value(codec); QMapIterator<QString,QVariant> it(options); while (it.hasNext()) { it.next(); QString option = it.key(); QVariant value = it.value(); switch (value.type()) { case QVariant::Int: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toInt(), NULL); break; case QVariant::Bool: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toBool(), NULL); break; case QVariant::Double: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toDouble(), NULL); break; case QVariant::String: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toString().toUtf8().constData(), NULL); break; default: qWarning() << "unsupported option type:" << option << value; break; } } } return encoderElement; } QPair<int,int> CameraBinVideoEncoder::rateAsRational(qreal frameRate) const { if (frameRate > 0.001) { //convert to rational number QList<int> denumCandidates; denumCandidates << 1 << 2 << 3 << 5 << 10 << 25 << 30 << 50 << 100 << 1001 << 1000; qreal error = 1.0; int num = 1; int denum = 1; foreach (int curDenum, denumCandidates) { int curNum = qRound(frameRate*curDenum); qreal curError = qAbs(qreal(curNum)/curDenum - frameRate); if (curError < error) { error = curError; num = curNum; denum = curDenum; } if (curError < 1e-8) break; } return QPair<int,int>(num,denum); } return QPair<int,int>(); } QSet<QString> CameraBinVideoEncoder::supportedStreamTypes(const QString &codecName) const { return m_streamTypes.value(codecName); } <commit_msg>Camerabin backend: removed invalid comment.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "camerabinvideoencoder.h" #include "camerabinsession.h" #include "camerabincontainer.h" #include <QtCore/qdebug.h> CameraBinVideoEncoder::CameraBinVideoEncoder(CameraBinSession *session) :QVideoEncoderControl(session), m_session(session) { QList<QByteArray> codecCandidates; #if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6) codecCandidates << "video/mpeg4" << "video/h264" << "video/h263" << "video/theora" << "video/mpeg2" << "video/mpeg1" << "video/mjpeg" << "video/VP8" << "video/h261"; m_elementNames["video/h264"] = "dsph264enc"; m_elementNames["video/mpeg4"] = "dspmp4venc"; m_elementNames["video/h263"] = "dsph263enc"; m_elementNames["video/theora"] = "theoraenc"; m_elementNames["video/mpeg2"] = "ffenc_mpeg2video"; m_elementNames["video/mpeg1"] = "ffenc_mpeg1video"; m_elementNames["video/mjpeg"] = "ffenc_mjpeg"; m_elementNames["video/VP8"] = "vp8enc"; m_elementNames["video/h261"] = "ffenc_h261"; m_codecOptions["video/mpeg4"] = QStringList() << "mode" << "keyframe-interval"; #else codecCandidates << "video/h264" << "video/xvid" << "video/mpeg4" << "video/mpeg1" << "video/mpeg2" << "video/theora" << "video/VP8" << "video/h261" << "video/mjpeg"; m_elementNames["video/h264"] = "x264enc"; m_elementNames["video/xvid"] = "xvidenc"; m_elementNames["video/mpeg4"] = "ffenc_mpeg4"; m_elementNames["video/mpeg1"] = "ffenc_mpeg1video"; m_elementNames["video/mpeg2"] = "ffenc_mpeg2video"; m_elementNames["video/theora"] = "theoraenc"; m_elementNames["video/mjpeg"] = "ffenc_mjpeg"; m_elementNames["video/VP8"] = "vp8enc"; m_elementNames["video/h261"] = "ffenc_h261"; m_codecOptions["video/h264"] = QStringList() << "quantizer"; m_codecOptions["video/xvid"] = QStringList() << "quantizer" << "profile"; m_codecOptions["video/mpeg4"] = QStringList() << "quantizer"; m_codecOptions["video/mpeg1"] = QStringList() << "quantizer"; m_codecOptions["video/mpeg2"] = QStringList() << "quantizer"; m_codecOptions["video/theora"] = QStringList(); #endif foreach( const QByteArray& codecName, codecCandidates ) { QByteArray elementName = m_elementNames[codecName]; GstElementFactory *factory = gst_element_factory_find(elementName.constData()); if (factory) { m_codecs.append(codecName); const gchar *descr = gst_element_factory_get_description(factory); m_codecDescriptions.insert(codecName, QString::fromUtf8(descr)); m_streamTypes.insert(codecName, CameraBinContainer::supportedStreamTypes(factory, GST_PAD_SRC)); gst_object_unref(GST_OBJECT(factory)); } } } CameraBinVideoEncoder::~CameraBinVideoEncoder() { } QList<QSize> CameraBinVideoEncoder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; QPair<int,int> rate = rateAsRational(settings.frameRate()); //select the closest supported rational rate to settings.frameRate() return m_session->supportedResolutions(rate, continuous); } QList< qreal > CameraBinVideoEncoder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; QList< qreal > res; QPair<int,int> rate; foreach(rate, m_session->supportedFrameRates(settings.resolution(), continuous)) { if (rate.second > 0) res << qreal(rate.first)/rate.second; } return res; } QStringList CameraBinVideoEncoder::supportedVideoCodecs() const { return m_codecs; } QString CameraBinVideoEncoder::videoCodecDescription(const QString &codecName) const { return m_codecDescriptions.value(codecName); } QStringList CameraBinVideoEncoder::supportedEncodingOptions(const QString &codec) const { return m_codecOptions.value(codec); } QVariant CameraBinVideoEncoder::encodingOption(const QString &codec, const QString &name) const { return m_options[codec].value(name); } void CameraBinVideoEncoder::setEncodingOption( const QString &codec, const QString &name, const QVariant &value) { m_options[codec][name] = value; } QVideoEncoderSettings CameraBinVideoEncoder::videoSettings() const { return m_videoSettings; } void CameraBinVideoEncoder::setVideoSettings(const QVideoEncoderSettings &settings) { m_videoSettings = settings; m_userSettings = settings; emit settingsChanged(); } void CameraBinVideoEncoder::setActualVideoSettings(const QVideoEncoderSettings &settings) { m_videoSettings = settings; } void CameraBinVideoEncoder::resetActualSettings() { m_videoSettings = m_userSettings; } GstElement *CameraBinVideoEncoder::createEncoder() { QString codec = m_videoSettings.codec(); QByteArray elementName = m_elementNames.value(codec); GstElement *encoderElement = gst_element_factory_make( elementName.constData(), "video-encoder"); if (encoderElement) { if (m_videoSettings.encodingMode() == QtMultimediaKit::ConstantQualityEncoding) { QtMultimediaKit::EncodingQuality qualityValue = m_videoSettings.quality(); if (elementName == "x264enc") { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 4, NULL); int qualityTable[] = { 50, //VeryLow 35, //Low 21, //Normal 15, //High 8 //VeryHigh }; g_object_set(G_OBJECT(encoderElement), "quantizer", qualityTable[qualityValue], NULL); } else if (elementName == "xvidenc") { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 3, NULL); int qualityTable[] = { 32, //VeryLow 12, //Low 5, //Normal 3, //High 2 //VeryHigh }; int quant = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL); } else if (elementName == "ffenc_mpeg4" || elementName == "ffenc_mpeg1video" || elementName == "ffenc_mpeg2video" ) { //constant quantizer mode g_object_set(G_OBJECT(encoderElement), "pass", 2, NULL); //quant from 1 to 30, default ~3 double qualityTable[] = { 20, //VeryLow 8.0, //Low 3.0, //Normal 2.5, //High 2.0 //VeryHigh }; double quant = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL); } else if (elementName == "theoraenc") { int qualityTable[] = { 8, //VeryLow 16, //Low 32, //Normal 45, //High 60 //VeryHigh }; //quality from 0 to 63 int quality = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "quality", quality, NULL); } else if (elementName == "dsph264enc" || elementName == "dspmp4venc" || elementName == "dsph263enc") { //only bitrate parameter is supported int qualityTable[] = { 1000000, //VeryLow 2000000, //Low 4000000, //Normal 8000000, //High 16000000 //VeryHigh }; int bitrate = qualityTable[qualityValue]; g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL); } } else { int bitrate = m_videoSettings.bitRate(); if (bitrate > 0) { g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL); } } QMap<QString,QVariant> options = m_options.value(codec); QMapIterator<QString,QVariant> it(options); while (it.hasNext()) { it.next(); QString option = it.key(); QVariant value = it.value(); switch (value.type()) { case QVariant::Int: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toInt(), NULL); break; case QVariant::Bool: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toBool(), NULL); break; case QVariant::Double: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toDouble(), NULL); break; case QVariant::String: g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toString().toUtf8().constData(), NULL); break; default: qWarning() << "unsupported option type:" << option << value; break; } } } return encoderElement; } QPair<int,int> CameraBinVideoEncoder::rateAsRational(qreal frameRate) const { if (frameRate > 0.001) { //convert to rational number QList<int> denumCandidates; denumCandidates << 1 << 2 << 3 << 5 << 10 << 25 << 30 << 50 << 100 << 1001 << 1000; qreal error = 1.0; int num = 1; int denum = 1; foreach (int curDenum, denumCandidates) { int curNum = qRound(frameRate*curDenum); qreal curError = qAbs(qreal(curNum)/curDenum - frameRate); if (curError < error) { error = curError; num = curNum; denum = curDenum; } if (curError < 1e-8) break; } return QPair<int,int>(num,denum); } return QPair<int,int>(); } QSet<QString> CameraBinVideoEncoder::supportedStreamTypes(const QString &codecName) const { return m_streamTypes.value(codecName); } <|endoftext|>
<commit_before>#include "kernel.h" #include "raster.h" #include "linerasterizer.h" #include "pixeliterator.h" using namespace Ilwis; bool PixelIterator::isValid() const { return _isValid; } PixelIterator::PixelIterator() : _grid(0), _x(0), _y(0), _z(0), _localOffset(0), _currentBlock(0), _flow(fXYZ), _isValid(true), _endx(0), _endy(0), _endz(0), _linearposition(0), _endposition(0), _xChanged(false), _yChanged(false), _zChanged(false) { } PixelIterator::PixelIterator(const IRasterCoverage &raster, const Box3D<>& box) : _raster(raster), _box(box), _localOffset(0), _currentBlock(0), _flow(fXYZ), _isValid(false) { init(); } PixelIterator::PixelIterator(PixelIterator&& iter) : _raster(std::move(iter._raster)), _grid(std::move(iter._grid)), _box(std::move(iter._box)), _x(iter._x), _y(iter._y), _z(iter._z), _localOffset(iter._localOffset), _currentBlock(iter._currentBlock), _flow(iter._flow), _isValid(iter._isValid), _endx(iter._endx), _endy(iter._endy), _endz(iter._endz), _linearposition(iter._linearposition), _endposition(iter._endposition), _xChanged(iter._xChanged), _yChanged(iter._yChanged), _zChanged(iter._zChanged) { // _raster = IRasterCoverage(); // _box = Box3D<>(); // _localOffset = 0; // _currentBlock = 0; // _flow = fXYZ; // _isValid = false; } PixelIterator::PixelIterator(const PixelIterator& iter) { copy(iter); } void PixelIterator::copy(const PixelIterator &iter) { _raster = iter._raster; if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future _grid = _raster->_grid.data(); _box = iter._box; _isValid = iter._isValid; _flow = iter._flow; _x = iter._x; _y = iter._y; _z = iter._z; _endx = iter._endx; _endy = iter._endy; _endz = iter._endz; _linearposition = iter._linearposition; _endposition = iter._endposition; _localOffset = iter._localOffset; _currentBlock = iter._currentBlock; } void PixelIterator::init() { const Size& sz = _raster->size(); if ( _box.isNull()) { _box = Box3D<>(sz); } _box.ensure(sz); _x = _box.min_corner().x(); _y = _box.min_corner().y(); _z = _box.min_corner().z(); _endx = _box.max_corner().x(); _endy = _box.max_corner().y(); _endz = _box.max_corner().z(); bool inside = contains(Pixel(_x,_y)); if ( inside) { _grid = _raster->grid(); } if ( _grid == 0) { _isValid = false; ERROR1(ERR_NO_INITIALIZED_1,_raster->name()); return; } initPosition(); _isValid = inside; _xChanged = _yChanged = _zChanged = false; } inline bool PixelIterator::moveXYZ(int delta) { _x += delta; _linearposition += delta; _localOffset += delta; _xChanged = true; _yChanged = _zChanged = false; if ( _x > _endx) { _xChanged = (_x - delta) % _box.xlength() != 0; qint32 tempy = _y + (_x - _box.min_corner().x()) / _box.xlength(); _x = _box.min_corner().x() + (_x - _box.min_corner().x()) % _box.xlength(); _yChanged = tempy != _y; std::swap(_y,tempy); qint32 ylocal = _y % _grid->maxLines(); quint32 localblock = _y / _grid->maxLines(); quint32 bandblocks = _grid->blocksPerBand() * _z; _localOffset = _x + ylocal * _grid->size().xsize(); if ( bandblocks + localblock != _currentBlock) { _currentBlock = bandblocks + localblock;; _localOffset = _x; } if ( _y > _endy) { quint32 newz = _z + (_y - _box.min_corner().y()) / _box.ylength(); _currentBlock = newz * _grid->blocksPerBand() + _y / _grid->maxLines(); _zChanged = newz != _z; _z = newz; _y = _box.min_corner().y() + (_y - _box.min_corner().y()) % _box.ylength(); _yChanged = _y != tempy; localblock = _y / _grid->maxLines(); _localOffset = _y * _grid->size().xsize() + _x - localblock * _grid->maxLines() * _grid->size().xsize(); if ( _z > _endz) { // done with this iteration block _linearposition = _endposition; return false; } } } return true; } inline bool PixelIterator::isAtEnd() const { return _x == _box.max_corner().x() && _y == _box.max_corner().y() && _z == _box.max_corner().z(); } Voxel PixelIterator::position() const { return Voxel(_x, _y, _z); } const Box3D<> &PixelIterator::box() const { return _box; } quint32 PixelIterator::linearPosition() const { // return sz.xsize() * sz.ysize() * _z + sz.xsize() * _y + _x; return _linearposition; } bool PixelIterator::move(int n) { bool ok; if (isAtEnd()) { _linearposition = _endposition; return false; } if ( _flow == fXYZ) { ok = moveXYZ(n); } else if ( _flow == fYXZ){ } return ok; } PixelIterator& PixelIterator::operator=(const PixelIterator& iter) { copy(iter); return *this; } PixelIterator& PixelIterator::operator=(const PixelIterator&& iter) { copy(iter); return *this; } inline PixelIterator PixelIterator::operator++(int) { PixelIterator temp(*this); if(!move(1)) return end(); return temp; } inline PixelIterator PixelIterator::operator--(int) { PixelIterator temp(*this); move(-1); return temp; } bool PixelIterator::operator==(const PixelIterator& iter) const{ return _linearposition == iter._linearposition; } bool PixelIterator::operator!=(const PixelIterator& iter) const{ return ! operator ==(iter); } bool PixelIterator::operator<(const PixelIterator &iter) const { return _linearposition < iter._linearposition; } bool PixelIterator::operator>(const PixelIterator &iter) const { return _linearposition > iter._linearposition; } bool PixelIterator::operator<=(const PixelIterator &iter) const { return _linearposition <= iter._linearposition; } bool PixelIterator::operator>=(const PixelIterator &iter) const { return _linearposition >= iter._linearposition; } PixelIterator PixelIterator::end() const { PixelIterator iter(*this); iter += _endposition; return iter; } void PixelIterator::setFlow(Flow flw) { _flow = flw; } bool PixelIterator::contains(const Pixel& pix) { return pix.x() >= _box.min_corner().x() && pix.x() < _box.max_corner().x() && pix.y() >= _box.min_corner().y() && pix.y() < _box.max_corner().y(); } bool PixelIterator::xchanged() const { return _xChanged; } bool PixelIterator::ychanged() const { return _yChanged; } bool PixelIterator::zchanged() const { return _zChanged; } void PixelIterator::initPosition() { const Size& sz = _raster->size(); quint64 linpos = _y * sz.xsize() + _x; _currentBlock = _y / _grid->maxLines(); _localOffset = linpos - _currentBlock * _grid->maxLines() * sz.xsize(); _currentBlock += _z * _grid->blocksPerBand(); _linearposition = sz.xsize() * sz.ysize() * _z + linpos; _endposition = sz.xsize() * sz.ysize() * sz.zsize(); } int PixelIterator:: operator-(const PixelIterator& iter) { return linearPosition() - iter.linearPosition(); } <commit_msg>added initialization<commit_after>#include "kernel.h" #include "raster.h" #include "linerasterizer.h" #include "pixeliterator.h" using namespace Ilwis; bool PixelIterator::isValid() const { return _isValid; } PixelIterator::PixelIterator() : _grid(0), _x(0), _y(0), _z(0), _localOffset(0), _currentBlock(0), _flow(fXYZ), _isValid(true), _endx(0), _endy(0), _endz(0), _linearposition(0), _endposition(0), _xChanged(false), _yChanged(false), _zChanged(false) { } PixelIterator::PixelIterator(const IRasterCoverage &raster, const Box3D<>& box) : _raster(raster), _box(box), _localOffset(0), _currentBlock(0), _flow(fXYZ), _isValid(false) { init(); } PixelIterator::PixelIterator(PixelIterator&& iter) : _raster(std::move(iter._raster)), _grid(std::move(iter._grid)), _box(std::move(iter._box)), _x(iter._x), _y(iter._y), _z(iter._z), _localOffset(iter._localOffset), _currentBlock(iter._currentBlock), _flow(iter._flow), _isValid(iter._isValid), _endx(iter._endx), _endy(iter._endy), _endz(iter._endz), _linearposition(iter._linearposition), _endposition(iter._endposition), _xChanged(iter._xChanged), _yChanged(iter._yChanged), _zChanged(iter._zChanged) { // _raster = IRasterCoverage(); // _box = Box3D<>(); // _localOffset = 0; // _currentBlock = 0; // _flow = fXYZ; // _isValid = false; } PixelIterator::PixelIterator(const PixelIterator& iter) { copy(iter); } void PixelIterator::copy(const PixelIterator &iter) { _raster = iter._raster; if ( _raster.isValid()) // TODO beyond end marker(end()) dont have a valid raster, no problem just yet but it maybe needed in the future _grid = _raster->_grid.data(); _box = iter._box; _isValid = iter._isValid; _flow = iter._flow; _x = iter._x; _y = iter._y; _z = iter._z; _endx = iter._endx; _endy = iter._endy; _endz = iter._endz; _linearposition = iter._linearposition; _endposition = iter._endposition; _localOffset = iter._localOffset; _currentBlock = iter._currentBlock; } void PixelIterator::init() { const Size& sz = _raster->size(); if ( _box.isNull()) { _box = Box3D<>(sz); } _box.ensure(sz); _x = _box.min_corner().x(); _y = _box.min_corner().y(); _z = _box.min_corner().z(); _endx = _box.max_corner().x(); _endy = _box.max_corner().y(); _endz = _box.max_corner().z(); bool inside = contains(Pixel(_x,_y)); if ( inside) { _grid = _raster->grid(); } if ( _grid == 0) { _isValid = false; ERROR1(ERR_NO_INITIALIZED_1,_raster->name()); return; } initPosition(); _isValid = inside; _xChanged = _yChanged = _zChanged = false; } inline bool PixelIterator::moveXYZ(int delta) { _x += delta; _linearposition += delta; _localOffset += delta; _xChanged = true; _yChanged = _zChanged = false; if ( _x > _endx) { _xChanged = (_x - delta) % _box.xlength() != 0; qint32 tempy = _y + (_x - _box.min_corner().x()) / _box.xlength(); _x = _box.min_corner().x() + (_x - _box.min_corner().x()) % _box.xlength(); _yChanged = tempy != _y; std::swap(_y,tempy); qint32 ylocal = _y % _grid->maxLines(); quint32 localblock = _y / _grid->maxLines(); quint32 bandblocks = _grid->blocksPerBand() * _z; _localOffset = _x + ylocal * _grid->size().xsize(); if ( bandblocks + localblock != _currentBlock) { _currentBlock = bandblocks + localblock;; _localOffset = _x; } if ( _y > _endy) { quint32 newz = _z + (_y - _box.min_corner().y()) / _box.ylength(); _currentBlock = newz * _grid->blocksPerBand() + _y / _grid->maxLines(); _zChanged = newz != _z; _z = newz; _y = _box.min_corner().y() + (_y - _box.min_corner().y()) % _box.ylength(); _yChanged = _y != tempy; localblock = _y / _grid->maxLines(); _localOffset = _y * _grid->size().xsize() + _x - localblock * _grid->maxLines() * _grid->size().xsize(); if ( _z > _endz) { // done with this iteration block _linearposition = _endposition; return false; } } } return true; } inline bool PixelIterator::isAtEnd() const { return _x == _box.max_corner().x() && _y == _box.max_corner().y() && _z == _box.max_corner().z(); } Voxel PixelIterator::position() const { return Voxel(_x, _y, _z); } const Box3D<> &PixelIterator::box() const { return _box; } quint32 PixelIterator::linearPosition() const { // return sz.xsize() * sz.ysize() * _z + sz.xsize() * _y + _x; return _linearposition; } bool PixelIterator::move(int n) { bool ok = false; if (isAtEnd()) { _linearposition = _endposition; return false; } if ( _flow == fXYZ) { ok = moveXYZ(n); } else if ( _flow == fYXZ){ } return ok; } PixelIterator& PixelIterator::operator=(const PixelIterator& iter) { copy(iter); return *this; } PixelIterator& PixelIterator::operator=(const PixelIterator&& iter) { copy(iter); return *this; } inline PixelIterator PixelIterator::operator++(int) { PixelIterator temp(*this); if(!move(1)) return end(); return temp; } inline PixelIterator PixelIterator::operator--(int) { PixelIterator temp(*this); move(-1); return temp; } bool PixelIterator::operator==(const PixelIterator& iter) const{ return _linearposition == iter._linearposition; } bool PixelIterator::operator!=(const PixelIterator& iter) const{ return ! operator ==(iter); } bool PixelIterator::operator<(const PixelIterator &iter) const { return _linearposition < iter._linearposition; } bool PixelIterator::operator>(const PixelIterator &iter) const { return _linearposition > iter._linearposition; } bool PixelIterator::operator<=(const PixelIterator &iter) const { return _linearposition <= iter._linearposition; } bool PixelIterator::operator>=(const PixelIterator &iter) const { return _linearposition >= iter._linearposition; } PixelIterator PixelIterator::end() const { PixelIterator iter(*this); iter += _endposition; return iter; } void PixelIterator::setFlow(Flow flw) { _flow = flw; } bool PixelIterator::contains(const Pixel& pix) { return pix.x() >= _box.min_corner().x() && pix.x() < _box.max_corner().x() && pix.y() >= _box.min_corner().y() && pix.y() < _box.max_corner().y(); } bool PixelIterator::xchanged() const { return _xChanged; } bool PixelIterator::ychanged() const { return _yChanged; } bool PixelIterator::zchanged() const { return _zChanged; } void PixelIterator::initPosition() { const Size& sz = _raster->size(); quint64 linpos = _y * sz.xsize() + _x; _currentBlock = _y / _grid->maxLines(); _localOffset = linpos - _currentBlock * _grid->maxLines() * sz.xsize(); _currentBlock += _z * _grid->blocksPerBand(); _linearposition = sz.xsize() * sz.ysize() * _z + linpos; _endposition = sz.xsize() * sz.ysize() * sz.zsize(); } int PixelIterator:: operator-(const PixelIterator& iter) { return linearPosition() - iter.linearPosition(); } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <sys/syscall.h> #include <unistd.h> #include "../TPlatform.h" namespace tyr { namespace basic { pid_t kern_getpid(void) { return getpid(); } int kern_mutex_init(KernMutex* mtx) { return pthread_mutex_init(mtx, nullptr); } int kern_mutex_destroy(KernMutex* mtx) { return pthread_mutex_destroy(mtx); } int kern_mutex_lock(KernMutex* mtx) { return pthread_mutex_lock(mtx); } int kern_mutex_unlock(KernMutex* mtx) { return pthread_mutex_unlock(mtx); } int kern_cond_init(KernCond* cond) { return pthread_cond_init(cond, nullptr); } int kern_cond_destroy(KernCond* cond) { return pthread_cond_destroy(cond); } int kern_cond_signal(KernCond* cond) { return pthread_cond_signal(cond); } int kern_cond_broadcast(KernCond* cond) { return pthread_cond_broadcast(cond); } int kern_cond_wait(KernCond* cond, KernMutex* mtx) { return pthread_cond_wait(cond, mtx); } int kern_cond_timedwait(KernCond* cond, KernMutex* mtx, uint64_t nanosec) { struct timespec ts; kern_gettime(&ts); ts.tv_sec += nanosec / NANOSEC; ts.tv_nsec = nanosec % NANOSEC; return pthread_cond_timedwait(cond, mtx, &ts); } int kern_thread_create(KernThread* thread, void* (*start_routine)(void*), void* arg) { return pthread_create(thread, nullptr, start_routine, arg); } int kern_thread_join(KernThread thread) { return pthread_join(thread, nullptr); } int kern_thread_detach(KernThread thread) { return pthread_detach(thread); } int kern_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) { return pthread_atfork(prepare, parent, child); } int kern_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) { return 0; } int kern_threadkey_create(KernThreadKey* key, void (*destructor)(void*)) { return pthread_key_create(key, destructor); } int kern_threadkey_delete(KernThreadKey key) { return pthread_key_delete(key); } int kern_setspecific(KernThreadKey key, const void* value) { return pthread_setspecific(key, value); } void* kern_getspecific(KernThreadKey key) { return pthread_getspecific(key); } }} <commit_msg>fix(platform): fixed bug of *_atfork for posix<commit_after>// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <sys/syscall.h> #include <unistd.h> #include "../TPlatform.h" namespace tyr { namespace basic { pid_t kern_getpid(void) { return getpid(); } int kern_mutex_init(KernMutex* mtx) { return pthread_mutex_init(mtx, nullptr); } int kern_mutex_destroy(KernMutex* mtx) { return pthread_mutex_destroy(mtx); } int kern_mutex_lock(KernMutex* mtx) { return pthread_mutex_lock(mtx); } int kern_mutex_unlock(KernMutex* mtx) { return pthread_mutex_unlock(mtx); } int kern_cond_init(KernCond* cond) { return pthread_cond_init(cond, nullptr); } int kern_cond_destroy(KernCond* cond) { return pthread_cond_destroy(cond); } int kern_cond_signal(KernCond* cond) { return pthread_cond_signal(cond); } int kern_cond_broadcast(KernCond* cond) { return pthread_cond_broadcast(cond); } int kern_cond_wait(KernCond* cond, KernMutex* mtx) { return pthread_cond_wait(cond, mtx); } int kern_cond_timedwait(KernCond* cond, KernMutex* mtx, uint64_t nanosec) { struct timespec ts; kern_gettime(&ts); ts.tv_sec += nanosec / NANOSEC; ts.tv_nsec = nanosec % NANOSEC; return pthread_cond_timedwait(cond, mtx, &ts); } int kern_thread_create(KernThread* thread, void* (*start_routine)(void*), void* arg) { return pthread_create(thread, nullptr, start_routine, arg); } int kern_thread_join(KernThread thread) { return pthread_join(thread, nullptr); } int kern_thread_detach(KernThread thread) { return pthread_detach(thread); } int kern_thread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)) { return pthread_atfork(prepare, parent, child); } int kern_threadkey_create(KernThreadKey* key, void (*destructor)(void*)) { return pthread_key_create(key, destructor); } int kern_threadkey_delete(KernThreadKey key) { return pthread_key_delete(key); } int kern_setspecific(KernThreadKey key, const void* value) { return pthread_setspecific(key, value); } void* kern_getspecific(KernThreadKey key) { return pthread_getspecific(key); } }} <|endoftext|>
<commit_before><commit_msg>308. Range Sum Query 2D - Mutable<commit_after><|endoftext|>
<commit_before>/* Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LGPL. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Alternatively, this file is available under the Mozilla Public License Version 1.1. You may obtain a copy of the License at http://www.mozilla.org/MPL/ */ #include "localsocket.h" #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include "sys/uio.h" #include <sys/un.h> #include <unistd.h> #include <cassert> #include <climits> #include <cstdlib> #include <cstring> // HACK, put this somewhere else (get the value from original d-bus? or is it infinite?) static const int maxFds = 12; using namespace std; LocalSocket::LocalSocket(const string &socketFilePath) : m_fd(-1) { const int fd = socket(PF_UNIX, SOCK_STREAM, 0); if (fd < 0) { return; } // don't let forks inherit the file descriptor - that can cause confusion... fcntl(fd, F_SETFD, FD_CLOEXEC); struct sockaddr_un addr; addr.sun_family = PF_UNIX; bool ok = socketFilePath.length() < sizeof(addr.sun_path); if (ok) { memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length()); } ok = ok && (connect(fd, (struct sockaddr *)&addr, sizeof(sa_family_t) + socketFilePath.length()) == 0); if (ok) { m_fd = fd; } else { ::close(fd); } } LocalSocket::LocalSocket(int fd) : m_fd(fd) { } LocalSocket::~LocalSocket() { close(); } void LocalSocket::close() { setEventDispatcher(nullptr); if (m_fd >= 0) { ::close(m_fd); } m_fd = -1; } int LocalSocket::write(chunk a) { if (m_fd < 0) { return 0; // TODO -1? } // sendmsg boilerplate struct msghdr send_msg; struct iovec iov; send_msg.msg_name = 0; send_msg.msg_namelen = 0; send_msg.msg_flags = 0; send_msg.msg_iov = &iov; send_msg.msg_iovlen = 1; iov.iov_base = a.ptr; iov.iov_len = a.length; // we can only send a fixed number of fds anyway due to the non-flexible size of the control message // receive buffer, so we set an arbitrary limit. const int numFds = 0; // TODO - how many should we get? do we need to know? assert(numFds <= maxFds); char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)]; if (numFds) { // fill in a control message send_msg.msg_control = cmsgBuf; send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds); struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg); c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds); c_msg->cmsg_level = SOL_SOCKET; c_msg->cmsg_type = SCM_RIGHTS; // set the control data to pass - this is why we don't use the simpler write() for (int i = 0; i < numFds; i++) { // TODO // reinterpret_cast<int *>(CMSG_DATA(c_msg))[i] = message.m_fileDescriptors[i]; } } else { // no file descriptor to send, no control message send_msg.msg_control = 0; send_msg.msg_controllen = 0; } while (iov.iov_len > 0) { int nbytes = sendmsg(m_fd, &send_msg, MSG_DONTWAIT); if (nbytes < 0) { if (errno == EINTR) { continue; } // if we were notified for writing, we must have written at least one byte before getting // EAGAIN aka EWOULDBLOCK if (errno == EAGAIN && iov.iov_len < a.length) { break; } close(); return false; } iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes; iov.iov_len -= nbytes; // sendmsg() should always send the number of bytes asked for or block, so... if (nbytes != 0) { assert(iov.iov_len == 0); } } return a.length - iov.iov_len; // "- iov.iov_len" is for later, TODO revisit } int LocalSocket::availableBytesForReading() { int available = 0; if (ioctl(m_fd, FIONREAD, &available) < 0) { available = 0; } return available; } chunk LocalSocket::read(byte *buffer, int maxSize) { chunk ret; if (maxSize <= 0) { return ret; } // recvmsg-with-control-message boilerplate struct msghdr recv_msg; char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)]; memset(cmsgBuf, 0, sizeof(cmsgBuf)); recv_msg.msg_control = cmsgBuf; recv_msg.msg_controllen = sizeof(cmsgBuf); recv_msg.msg_name = 0; recv_msg.msg_namelen = 0; recv_msg.msg_flags = 0; struct iovec iov; recv_msg.msg_iov = &iov; recv_msg.msg_iovlen = 1; // end boilerplate ret.ptr = buffer; ret.length = 0; iov.iov_base = ret.ptr; iov.iov_len = maxSize; while (iov.iov_len > 0) { int nbytes = recvmsg(m_fd, &recv_msg, MSG_DONTWAIT); if (nbytes < 0) { if (errno == EINTR) { continue; } // If we were notified for reading directly by the event dispatcher, we must be able to read at // least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify // something that is very eager to read everything (like Message::notifyRead()...) by reading // multiple times and in that case, we may be called in an attempt to read more when there is // currently no more data. // Just return zero bytes and no error in that case. if (errno == EAGAIN /* && iov.iov_len < maxSize */) { break; } close(); return ret; } ret.length += nbytes; iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes; iov.iov_len -= nbytes; } // done reading "regular data", now read any file descriptors passed via control messages struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg); if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) { const int len = c_msg->cmsg_len / sizeof(int); int *data = reinterpret_cast<int *>(CMSG_DATA(c_msg)); for (int i = 0; i < len; i++) { // TODO // message.appendFileDescriptor(data[i]); } } return ret; } bool LocalSocket::isOpen() { return m_fd != -1; } int LocalSocket::fileDescriptor() const { return m_fd; } void LocalSocket::notifyRead() { if (availableBytesForReading()) { IConnection::notifyRead(); } else { // This should really only happen in error cases! ### TODO test? close(); } } <commit_msg>LocalSocket write: don't fail on short writes.<commit_after>/* Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LGPL. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Alternatively, this file is available under the Mozilla Public License Version 1.1. You may obtain a copy of the License at http://www.mozilla.org/MPL/ */ #include "localsocket.h" #include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/socket.h> #include "sys/uio.h" #include <sys/un.h> #include <unistd.h> #include <cassert> #include <climits> #include <cstdlib> #include <cstring> // HACK, put this somewhere else (get the value from original d-bus? or is it infinite?) static const int maxFds = 12; using namespace std; LocalSocket::LocalSocket(const string &socketFilePath) : m_fd(-1) { const int fd = socket(PF_UNIX, SOCK_STREAM, 0); if (fd < 0) { return; } // don't let forks inherit the file descriptor - that can cause confusion... fcntl(fd, F_SETFD, FD_CLOEXEC); struct sockaddr_un addr; addr.sun_family = PF_UNIX; bool ok = socketFilePath.length() < sizeof(addr.sun_path); if (ok) { memcpy(addr.sun_path, socketFilePath.c_str(), socketFilePath.length()); } ok = ok && (connect(fd, (struct sockaddr *)&addr, sizeof(sa_family_t) + socketFilePath.length()) == 0); if (ok) { m_fd = fd; } else { ::close(fd); } } LocalSocket::LocalSocket(int fd) : m_fd(fd) { } LocalSocket::~LocalSocket() { close(); } void LocalSocket::close() { setEventDispatcher(nullptr); if (m_fd >= 0) { ::close(m_fd); } m_fd = -1; } int LocalSocket::write(chunk a) { if (m_fd < 0) { return 0; // TODO -1? } // sendmsg boilerplate struct msghdr send_msg; struct iovec iov; send_msg.msg_name = 0; send_msg.msg_namelen = 0; send_msg.msg_flags = 0; send_msg.msg_iov = &iov; send_msg.msg_iovlen = 1; iov.iov_base = a.ptr; iov.iov_len = a.length; // we can only send a fixed number of fds anyway due to the non-flexible size of the control message // receive buffer, so we set an arbitrary limit. const int numFds = 0; // TODO - how many should we get? do we need to know? assert(numFds <= maxFds); char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)]; if (numFds) { // fill in a control message send_msg.msg_control = cmsgBuf; send_msg.msg_controllen = CMSG_SPACE(sizeof(int) * numFds); struct cmsghdr *c_msg = CMSG_FIRSTHDR(&send_msg); c_msg->cmsg_len = CMSG_LEN(sizeof(int) * numFds); c_msg->cmsg_level = SOL_SOCKET; c_msg->cmsg_type = SCM_RIGHTS; // set the control data to pass - this is why we don't use the simpler write() for (int i = 0; i < numFds; i++) { // TODO // reinterpret_cast<int *>(CMSG_DATA(c_msg))[i] = message.m_fileDescriptors[i]; } } else { // no file descriptor to send, no control message send_msg.msg_control = 0; send_msg.msg_controllen = 0; } while (iov.iov_len > 0) { int nbytes = sendmsg(m_fd, &send_msg, MSG_DONTWAIT); if (nbytes < 0) { if (errno == EINTR) { continue; } // if we were notified for writing, we must have written at least one byte before getting // EAGAIN aka EWOULDBLOCK if (errno == EAGAIN && iov.iov_len < a.length) { break; } close(); return false; } iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes; iov.iov_len -= nbytes; } return a.length - iov.iov_len; } int LocalSocket::availableBytesForReading() { int available = 0; if (ioctl(m_fd, FIONREAD, &available) < 0) { available = 0; } return available; } chunk LocalSocket::read(byte *buffer, int maxSize) { chunk ret; if (maxSize <= 0) { return ret; } // recvmsg-with-control-message boilerplate struct msghdr recv_msg; char cmsgBuf[CMSG_SPACE(sizeof(int) * maxFds)]; memset(cmsgBuf, 0, sizeof(cmsgBuf)); recv_msg.msg_control = cmsgBuf; recv_msg.msg_controllen = sizeof(cmsgBuf); recv_msg.msg_name = 0; recv_msg.msg_namelen = 0; recv_msg.msg_flags = 0; struct iovec iov; recv_msg.msg_iov = &iov; recv_msg.msg_iovlen = 1; // end boilerplate ret.ptr = buffer; ret.length = 0; iov.iov_base = ret.ptr; iov.iov_len = maxSize; while (iov.iov_len > 0) { int nbytes = recvmsg(m_fd, &recv_msg, MSG_DONTWAIT); if (nbytes < 0) { if (errno == EINTR) { continue; } // If we were notified for reading directly by the event dispatcher, we must be able to read at // least one byte before getting AGAIN aka EWOULDBLOCK - *however* the event loop might notify // something that is very eager to read everything (like Message::notifyRead()...) by reading // multiple times and in that case, we may be called in an attempt to read more when there is // currently no more data. // Just return zero bytes and no error in that case. if (errno == EAGAIN /* && iov.iov_len < maxSize */) { break; } close(); return ret; } ret.length += nbytes; iov.iov_base = static_cast<char *>(iov.iov_base) + nbytes; iov.iov_len -= nbytes; } // done reading "regular data", now read any file descriptors passed via control messages struct cmsghdr *c_msg = CMSG_FIRSTHDR(&recv_msg); if (c_msg && c_msg->cmsg_level == SOL_SOCKET && c_msg->cmsg_type == SCM_RIGHTS) { const int len = c_msg->cmsg_len / sizeof(int); int *data = reinterpret_cast<int *>(CMSG_DATA(c_msg)); for (int i = 0; i < len; i++) { // TODO // message.appendFileDescriptor(data[i]); } } return ret; } bool LocalSocket::isOpen() { return m_fd != -1; } int LocalSocket::fileDescriptor() const { return m_fd; } void LocalSocket::notifyRead() { if (availableBytesForReading()) { IConnection::notifyRead(); } else { // This should really only happen in error cases! ### TODO test? close(); } } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eoslib/print.h> #include <eoslib/types.hpp> #include <eoslib/math.hpp> namespace eosio { static_assert( sizeof(long) == sizeof(int), "unexpected size difference" ); /** * Prints string * @brief Prints string * @param cstr - a null terminated string */ inline void print( const char* ptr ) { prints(ptr); } /** * Prints 64 bit unsigned integer as a 64 bit unsigned integer * @brief Prints integer 64 bit unsigned integer * @param Value to be printed */ inline void print( uint64_t num ) { printi(num); } /** * Prints 32 bit unsigned integer as a 64 bit unsigned integer * @brief Prints integer 32 bit unsigned integer * @param Value to be printed */ inline void print( uint32_t num ) { printi(num); } /** * Prints integer as a 64 bit unsigned integer * @brief Prints integer * @param Value to be printed */ inline void print( int num ) { printi(num); } /** * Prints unsigned integer as a 64 bit unsigned integer * @brief Prints unsigned integer * @param Value to be printed */ inline void print( unsigned int num ) { printi(num); } /** * Prints uint128 struct as 128 bit unsigned integer * @brief Prints uint128 struct * @param Value to be printed */ inline void print( uint128 num ) { printi128((uint128_t*)&num); } /** * Prints 128 bit unsigned integer * @brief Prints 128 bit unsigned integer * @param Value to be printed */ inline void print( uint128_t num ) { printi128((uint128_t*)&num); } /** * Prints a 64 bit names as base32 encoded string * @brief Prints a 64 bit names as base32 encoded string * @param Value of 64 bit names to be printed */ inline void print( name name ) { printn(name.value); } inline void print( bool val ) { prints(val?"true":"false"); } template<typename T> inline void print( T&& t ) { t.print(); } /** * @defgroup consoleCppapi Console C++ API * @ingroup consoleapi * @brief C++ wrapper for Console C API * * This API uses C++ variadic templates and type detection to * make it easy to print any native type. You can even overload * the `print()` method for your own custom types. * * **Example:** * ``` * print( "hello world, this is a number: ", 5 ); * ``` * * @section override Overriding Print for your Types * * There are two ways to overload print: * 1. implement void print( const T& ) * 2. implement T::print()const * * @{ */ /** * Print out value / list of values (except double) * @brief Print out value / list of values * @param a Value to be printed * @param args Other values to be printed * * Example: * @code * char *s = "Hello World!"; * uint64_t unsigned_64_bit_int = 1e+18; * uint128_t unsigned_128_bit_int (87654323456); * uint64_t string_as_unsigned_64_bit = N(abcde); * print(s , unsigned_64_bit_int, unsigned_128_bit_int, string_as_unsigned_64_bit); * // Ouput: Hello World!100000000000000000087654323456abcde * @endcode */ template<typename Arg, typename... Args> void print( Arg a, Args... args ) { print(a); print(args...); } /** * Simulate C++ style streams */ class iostream {}; /** * Overload c++ iostream * @brief Overload c++ iostream * @param out Output strem * @param v Value to be printed * * Example: * @code * const char *s = "Hello World!"; * uint64_t unsigned_64_bit_int = 1e+18; * uint128_t unsigned_128_bit_int (87654323456); * uint64_t string_as_unsigned_64_bit = N(abcde); * std::out << s << " " << unsigned_64_bit_int << " " << unsigned_128_bit_int << " " << string_as_unsigned_64_bit); * // Output: Hello World! 1000000000000000000 87654323456 abcde * @endcode */ template<typename T> inline iostream& operator<<( iostream& out, const T& v ) { print( v ); return out; } static iostream cout; /// @} consoleCppapi } <commit_msg>Fix for comments. (cherry-picked from fd9582a1a57d557aff5efcfe99b7e72a4ef5ad80)<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eoslib/print.h> #include <eoslib/types.hpp> #include <eoslib/math.hpp> namespace eosio { static_assert( sizeof(long) == sizeof(int), "unexpected size difference" ); /** * Prints string * @brief Prints string * @param cstr - a null terminated string */ inline void print( const char* ptr ) { prints(ptr); } /** * Prints 64 bit unsigned integer as a 64 bit unsigned integer * @brief Prints integer 64 bit unsigned integer * @param Value to be printed */ inline void print( uint64_t num ) { printi(num); } /** * Prints 32 bit unsigned integer as a 64 bit unsigned integer * @brief Prints integer 32 bit unsigned integer * @param Value to be printed */ inline void print( uint32_t num ) { printi(num); } /** * Prints integer as a 64 bit unsigned integer * @brief Prints integer * @param Value to be printed */ inline void print( int num ) { printi(num); } /** * Prints unsigned integer as a 64 bit unsigned integer * @brief Prints unsigned integer * @param Value to be printed */ inline void print( unsigned int num ) { printi(num); } /** * Prints uint128 struct as 128 bit unsigned integer * @brief Prints uint128 struct * @param Value to be printed */ inline void print( uint128 num ) { printi128((uint128_t*)&num); } /** * Prints 128 bit unsigned integer * @brief Prints 128 bit unsigned integer * @param Value to be printed */ inline void print( uint128_t num ) { printi128((uint128_t*)&num); } /** * Prints a 64 bit names as base32 encoded string * @brief Prints a 64 bit names as base32 encoded string * @param Value of 64 bit names to be printed */ inline void print( name name ) { printn(name.value); } inline void print( bool val ) { prints(val?"true":"false"); } template<typename T> inline void print( T&& t ) { t.print(); } /** * @defgroup consoleCppapi Console C++ API * @ingroup consoleapi * @brief C++ wrapper for Console C API * * This API uses C++ variadic templates and type detection to * make it easy to print any native type. You can even overload * the `print()` method for your own custom types. * * **Example:** * ``` * print( "hello world, this is a number: ", 5 ); * ``` * * @section override Overriding Print for your Types * * There are two ways to overload print: * 1. implement void print( const T& ) * 2. implement T::print()const * * @{ */ /** * Print out value / list of values (except double) * @brief Print out value / list of values * @param a Value to be printed * @param args Other values to be printed * * Example: * @code * const char *s = "Hello World!"; * uint64_t unsigned_64_bit_int = 1e+18; * uint128_t unsigned_128_bit_int (87654323456); * uint64_t string_as_unsigned_64_bit = N(abcde); * print(s , unsigned_64_bit_int, unsigned_128_bit_int, string_as_unsigned_64_bit); * // Ouput: Hello World!100000000000000000087654323456abcde * @endcode */ template<typename Arg, typename... Args> void print( Arg a, Args... args ) { print(a); print(args...); } /** * Simulate C++ style streams */ class iostream {}; /** * Overload c++ iostream * @brief Overload c++ iostream * @param out Output strem * @param v Value to be printed * * Example: * @code * const char *s = "Hello World!"; * uint64_t unsigned_64_bit_int = 1e+18; * uint128_t unsigned_128_bit_int (87654323456); * uint64_t string_as_unsigned_64_bit = N(abcde); * std::out << s << " " << unsigned_64_bit_int << " " << unsigned_128_bit_int << " " << string_as_unsigned_64_bit; * // Output: Hello World! 1000000000000000000 87654323456 abcde * @endcode */ template<typename T> inline iostream& operator<<( iostream& out, const T& v ) { print( v ); return out; } static iostream cout; /// @} consoleCppapi } <|endoftext|>
<commit_before>/* This file is part of the KDE project * * Copyright 2004-2007 Torsten Rahn <tackat@kde.org> * Copyright 2007 Inge Wallin <ingwa@kde.org> * Copyright 2007 Thomas Zander <zander@kde.org> * Copyright 2010 Bastian Holst <bastianholst@gmx.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ // Self #include "MarbleControlBox.h" // Tabs #include "CurrentLocationWidget.h" #include "NavigationWidget.h" #include "FileViewWidget.h" #include "LegendWidget.h" #include "MapViewWidget.h" #include "RoutingWidget.h" // Marble #include "global.h" #include "MarbleWidget.h" #include "MarbleModel.h" #include "GeoSceneDocument.h" #include "GeoSceneHead.h" #include "HttpDownloadManager.h" #include "MarbleDebug.h" namespace Marble { class MarbleControlBoxPrivate { public: MarbleControlBoxPrivate(); MarbleWidget *m_widget; NavigationWidget *m_navigationWidget; LegendWidget *m_legendWidget; MapViewWidget *m_mapViewWidget; CurrentLocationWidget *m_currentLocationWidget; FileViewWidget *m_fileViewWidget; RoutingWidget *m_routingWidget; }; MarbleControlBoxPrivate::MarbleControlBoxPrivate() : m_routingWidget(0) { } // ================================================================ MarbleControlBox::MarbleControlBox(QWidget *parent) : QToolBox( parent ), d( new MarbleControlBoxPrivate ) { d->m_widget = 0; setFocusPolicy( Qt::NoFocus ); // setFocusProxy( d->uiWidget.searchLineEdit ); // Iterate through all of the Side Widget values // d->m_navigationWidget = new NavigationWidget( this ); addItem( d->m_navigationWidget, d->m_navigationWidget->windowTitle() ); d->m_legendWidget = new LegendWidget( this ); addItem( d->m_legendWidget, d->m_legendWidget->windowTitle() ); d->m_mapViewWidget = new MapViewWidget( this ); addItem( d->m_mapViewWidget, d->m_mapViewWidget->windowTitle() ); d->m_fileViewWidget = new FileViewWidget( this ); addItem( d->m_fileViewWidget, d->m_fileViewWidget->windowTitle() ); d->m_currentLocationWidget = new CurrentLocationWidget( this ); addItem( d->m_currentLocationWidget, d->m_currentLocationWidget->windowTitle() ); setCurrentIndex(0); //default setCurrentLocationTabShown( true ); setFileViewTabShown( false ); connect( d->m_mapViewWidget, SIGNAL( showMapWizard() ), this, SIGNAL( showMapWizard() ) ); connect( d->m_mapViewWidget, SIGNAL( showUploadDialog() ), this, SIGNAL( showUploadDialog() ) ); } MarbleControlBox::~MarbleControlBox() { delete d; } void MarbleControlBox::addMarbleWidget(MarbleWidget *widget) { d->m_widget = widget; bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen; if ( !smallScreen ) { d->m_routingWidget = new RoutingWidget( widget, this ); addItem( d->m_routingWidget, tr( "Routing" ) ); } d->m_fileViewWidget->setMarbleWidget( widget ); d->m_legendWidget->setMarbleWidget( widget ); d->m_navigationWidget->setMarbleWidget( widget ); d->m_mapViewWidget->setMarbleWidget( widget ); d->m_currentLocationWidget->setMarbleWidget( widget ); connect( d->m_widget, SIGNAL( themeChanged( QString ) ), this, SLOT( selectTheme( QString ) ) ); } void MarbleControlBox::setWidgetTabShown( QWidget * widget, int insertIndex, bool show, QString &text ) { int index = indexOf( widget ); if( show ) { if ( !(index >= 0) ){ if ( insertIndex < count() ) { insertItem( insertIndex, widget, text ); } else { insertItem( 3 ,widget, text ); } widget->show(); } } else { if ( index >= 0 ) { widget->hide(); removeItem( index ); } } } void MarbleControlBox::setNavigationTabShown( bool show ) { QString title = tr( "Navigation" ); setWidgetTabShown( d->m_navigationWidget, 0, show, title); } void MarbleControlBox::setLegendTabShown( bool show ) { QString title = tr( "Legend" ); setWidgetTabShown( d->m_legendWidget, 1, show, title ); } void MarbleControlBox::setMapViewTabShown( bool show ) { QString title = tr( "Map View" ); setWidgetTabShown( d->m_mapViewWidget, 2, show, title ); } void MarbleControlBox::setFileViewTabShown( bool show ) { QString title = tr( "File View" ); setWidgetTabShown( d->m_fileViewWidget, 3, show, title ); } void MarbleControlBox::setCurrentLocationTabShown( bool show ) { QString title = tr( "Current Location" ); setWidgetTabShown( d->m_currentLocationWidget, 4, show, title ); if ( d->m_widget && d->m_widget->mapTheme() ) { bool enabled = d->m_widget->mapTheme()->head()->target() == "earth"; int locationIndex = indexOf( d->m_currentLocationWidget ); if ( locationIndex >= 0 ) { setItemEnabled( locationIndex, enabled ); } if ( !enabled ) { d->m_widget->setShowGps( false ); } } } void MarbleControlBox::setRoutingTabShown( bool show ) { if ( d->m_routingWidget ) { QString title = tr( "Routing" ); setWidgetTabShown( d->m_routingWidget, 5, show, title ); } } void MarbleControlBox::selectTheme( const QString &theme ) { Q_UNUSED( theme ) if ( !d->m_widget ) return; QString selectedId = d->m_widget->mapTheme()->head()->target(); if ( d->m_routingWidget ) { int routingIndex = indexOf( d->m_routingWidget ); setItemEnabled( routingIndex, selectedId == "earth" ); } int locationIndex = indexOf( d->m_currentLocationWidget ); if ( locationIndex >= 0 ) { setItemEnabled( locationIndex, selectedId == "earth" ); } } void MarbleControlBox::setWorkOffline(bool offline) { HttpDownloadManager * const downloadManager = d->m_widget->model()->downloadManager(); downloadManager->setDownloadEnabled( !offline ); d->m_navigationWidget->setWorkOffline( offline ); if ( d->m_routingWidget ) { d->m_routingWidget->setWorkOffline( offline ); } } void MarbleControlBox::updateMapThemeView() { d->m_mapViewWidget->updateMapThemeView(); } } #include "MarbleControlBox.moc" <commit_msg>Fix routing manager not always being aware of offline mode on Maemo.<commit_after>/* This file is part of the KDE project * * Copyright 2004-2007 Torsten Rahn <tackat@kde.org> * Copyright 2007 Inge Wallin <ingwa@kde.org> * Copyright 2007 Thomas Zander <zander@kde.org> * Copyright 2010 Bastian Holst <bastianholst@gmx.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ // Self #include "MarbleControlBox.h" // Tabs #include "CurrentLocationWidget.h" #include "NavigationWidget.h" #include "FileViewWidget.h" #include "LegendWidget.h" #include "MapViewWidget.h" #include "RoutingWidget.h" // Marble #include "global.h" #include "MarbleWidget.h" #include "MarbleModel.h" #include "GeoSceneDocument.h" #include "GeoSceneHead.h" #include "HttpDownloadManager.h" #include "MarbleDebug.h" namespace Marble { class MarbleControlBoxPrivate { public: MarbleControlBoxPrivate(); MarbleWidget *m_widget; NavigationWidget *m_navigationWidget; LegendWidget *m_legendWidget; MapViewWidget *m_mapViewWidget; CurrentLocationWidget *m_currentLocationWidget; FileViewWidget *m_fileViewWidget; RoutingWidget *m_routingWidget; }; MarbleControlBoxPrivate::MarbleControlBoxPrivate() : m_routingWidget(0) { } // ================================================================ MarbleControlBox::MarbleControlBox(QWidget *parent) : QToolBox( parent ), d( new MarbleControlBoxPrivate ) { d->m_widget = 0; setFocusPolicy( Qt::NoFocus ); // setFocusProxy( d->uiWidget.searchLineEdit ); // Iterate through all of the Side Widget values // d->m_navigationWidget = new NavigationWidget( this ); addItem( d->m_navigationWidget, d->m_navigationWidget->windowTitle() ); d->m_legendWidget = new LegendWidget( this ); addItem( d->m_legendWidget, d->m_legendWidget->windowTitle() ); d->m_mapViewWidget = new MapViewWidget( this ); addItem( d->m_mapViewWidget, d->m_mapViewWidget->windowTitle() ); d->m_fileViewWidget = new FileViewWidget( this ); addItem( d->m_fileViewWidget, d->m_fileViewWidget->windowTitle() ); d->m_currentLocationWidget = new CurrentLocationWidget( this ); addItem( d->m_currentLocationWidget, d->m_currentLocationWidget->windowTitle() ); setCurrentIndex(0); //default setCurrentLocationTabShown( true ); setFileViewTabShown( false ); connect( d->m_mapViewWidget, SIGNAL( showMapWizard() ), this, SIGNAL( showMapWizard() ) ); connect( d->m_mapViewWidget, SIGNAL( showUploadDialog() ), this, SIGNAL( showUploadDialog() ) ); } MarbleControlBox::~MarbleControlBox() { delete d; } void MarbleControlBox::addMarbleWidget(MarbleWidget *widget) { d->m_widget = widget; bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen; if ( !smallScreen ) { d->m_routingWidget = new RoutingWidget( widget, this ); addItem( d->m_routingWidget, tr( "Routing" ) ); } d->m_fileViewWidget->setMarbleWidget( widget ); d->m_legendWidget->setMarbleWidget( widget ); d->m_navigationWidget->setMarbleWidget( widget ); d->m_mapViewWidget->setMarbleWidget( widget ); d->m_currentLocationWidget->setMarbleWidget( widget ); connect( d->m_widget, SIGNAL( themeChanged( QString ) ), this, SLOT( selectTheme( QString ) ) ); } void MarbleControlBox::setWidgetTabShown( QWidget * widget, int insertIndex, bool show, QString &text ) { int index = indexOf( widget ); if( show ) { if ( !(index >= 0) ){ if ( insertIndex < count() ) { insertItem( insertIndex, widget, text ); } else { insertItem( 3 ,widget, text ); } widget->show(); } } else { if ( index >= 0 ) { widget->hide(); removeItem( index ); } } } void MarbleControlBox::setNavigationTabShown( bool show ) { QString title = tr( "Navigation" ); setWidgetTabShown( d->m_navigationWidget, 0, show, title); } void MarbleControlBox::setLegendTabShown( bool show ) { QString title = tr( "Legend" ); setWidgetTabShown( d->m_legendWidget, 1, show, title ); } void MarbleControlBox::setMapViewTabShown( bool show ) { QString title = tr( "Map View" ); setWidgetTabShown( d->m_mapViewWidget, 2, show, title ); } void MarbleControlBox::setFileViewTabShown( bool show ) { QString title = tr( "File View" ); setWidgetTabShown( d->m_fileViewWidget, 3, show, title ); } void MarbleControlBox::setCurrentLocationTabShown( bool show ) { QString title = tr( "Current Location" ); setWidgetTabShown( d->m_currentLocationWidget, 4, show, title ); if ( d->m_widget && d->m_widget->mapTheme() ) { bool enabled = d->m_widget->mapTheme()->head()->target() == "earth"; int locationIndex = indexOf( d->m_currentLocationWidget ); if ( locationIndex >= 0 ) { setItemEnabled( locationIndex, enabled ); } if ( !enabled ) { d->m_widget->setShowGps( false ); } } } void MarbleControlBox::setRoutingTabShown( bool show ) { if ( d->m_routingWidget ) { QString title = tr( "Routing" ); setWidgetTabShown( d->m_routingWidget, 5, show, title ); } } void MarbleControlBox::selectTheme( const QString &theme ) { Q_UNUSED( theme ) if ( !d->m_widget ) return; QString selectedId = d->m_widget->mapTheme()->head()->target(); if ( d->m_routingWidget ) { int routingIndex = indexOf( d->m_routingWidget ); setItemEnabled( routingIndex, selectedId == "earth" ); } int locationIndex = indexOf( d->m_currentLocationWidget ); if ( locationIndex >= 0 ) { setItemEnabled( locationIndex, selectedId == "earth" ); } } void MarbleControlBox::setWorkOffline(bool offline) { HttpDownloadManager * const downloadManager = d->m_widget->model()->downloadManager(); downloadManager->setDownloadEnabled( !offline ); d->m_navigationWidget->setWorkOffline( offline ); d->m_widget->model()->routingManager()->setWorkOffline( offline ); if ( d->m_routingWidget ) { d->m_routingWidget->setWorkOffline( offline ); } } void MarbleControlBox::updateMapThemeView() { d->m_mapViewWidget->updateMapThemeView(); } } #include "MarbleControlBox.moc" <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/trajectory/CTrajectoryTask.cpp,v $ $Revision: 1.74 $ $Name: $ $Author: shoops $ $Date: 2006/04/27 01:32:17 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CTrajectoryTask class. * * This class implements a trajectory task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CTrajectoryTask.h" #include "CTrajectoryProblem.h" #include "CTrajectoryMethod.h" #include "model/CModel.h" #include "model/CState.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/CProcessReport.h" #include "utilities/CCopasiException.h" #include "CopasiDataModel/CCopasiDataModel.h" #define XXXX_Reporting bool fle(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 <= d2);} bool fl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 < d2);} bool ble(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 >= d2);} bool bl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 > d2);} CTrajectoryTask::CTrajectoryTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mTimeSeriesRequested(true), mTimeSeries(), mpTrajectoryProblem(NULL), mpTrajectoryMethod(NULL), mpCurrentState(NULL), mpCurrentTime(NULL) { mpProblem = new CTrajectoryProblem(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(CCopasiMethod::deterministic, (CTrajectoryProblem *) mpProblem); this->add(mpMethod, true); //mpMethod->setObjectParent(this); } /*CTrajectoryTask::CTrajectoryTask(const CTrajectoryTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent), mpCurrentState(src.mpCurrentState), mTimeSeriesRequested(src.mTimeSeriesRequested) {fatalError();}*/ CTrajectoryTask::~CTrajectoryTask() { cleanup(); } void CTrajectoryTask::cleanup() { pdelete(mpCurrentState); } void CTrajectoryTask::load(CReadConfig & configBuffer) { configBuffer.getVariable("Dynamics", "bool", &mScheduled, CReadConfig::LOOP); pdelete(mpProblem); mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->load(configBuffer); pdelete(mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(); this->add(mpMethod, true); //mpMethod->setObjectParent(this); ((CTrajectoryMethod *)mpMethod)->setProblem((CTrajectoryProblem *) mpProblem); } bool CTrajectoryTask::initialize(const OutputFlag & of, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpTrajectoryProblem = dynamic_cast<CTrajectoryProblem *>(mpProblem); assert(mpTrajectoryProblem); mpTrajectoryMethod = dynamic_cast<CTrajectoryMethod *>(mpMethod); assert(mpTrajectoryMethod); mpTrajectoryMethod->setProblem(mpTrajectoryProblem); bool success = mpMethod->isValidProblem(mpProblem); pdelete(mpCurrentState); mpCurrentState = new CState(mpTrajectoryProblem->getModel()->getState()); mpCurrentTime = &mpCurrentState->getTime(); if (!CCopasiTask::initialize(of, pOstream)) success = false; mTimeSeriesRequested = mpTrajectoryProblem->timeSeriesRequested(); return success; } bool CTrajectoryTask::process(const bool & useInitialValues) { //***** processStart(useInitialValues); //***** unsigned C_INT32 FailCounter = 0; C_FLOAT64 StepSize = mpTrajectoryProblem->getStepSize(); C_FLOAT64 NextTimeToReport; const C_FLOAT64 EndTime = *mpCurrentTime + mpTrajectoryProblem->getDuration(); const C_FLOAT64 StartTime = *mpCurrentTime; C_FLOAT64 StepNumber = (mpTrajectoryProblem->getDuration()) / StepSize; bool (*LE)(const C_FLOAT64 &, const C_FLOAT64 &); bool (*L)(const C_FLOAT64 &, const C_FLOAT64 &); if (StepSize < 0.0) { LE = &ble; L = &bl; } else { LE = &fle; L = &fl; } unsigned C_INT32 StepCounter = 1; C_FLOAT64 outputStartTime = mpTrajectoryProblem->getOutputStartTime(); if (StepSize == 0.0 && mpTrajectoryProblem->getDuration() != 0.0) { CCopasiMessage(CCopasiMessage::ERROR, MCTrajectoryProblem + 1, StepSize); return false; } output(COutputInterface::BEFORE); bool flagProceed = true; C_FLOAT64 handlerFactor = 100.0 / mpTrajectoryProblem->getDuration(); C_FLOAT64 Percentage = 0; unsigned C_INT32 hProcess; if (mpCallBack) { mpCallBack->setName("performing simulation..."); C_FLOAT64 hundred = 100; hProcess = mpCallBack->addItem("Completion", CCopasiParameter::DOUBLE, &Percentage, &hundred); } if ((*LE)(outputStartTime, *mpCurrentTime)) output(COutputInterface::DURING); try { do { // This is numerically more stable then adding // mpTrajectoryProblem->getStepSize(). NextTimeToReport = StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber; flagProceed &= processStep(NextTimeToReport); if (mpCallBack) { Percentage = (*mpCurrentTime - StartTime) * handlerFactor; flagProceed &= mpCallBack->progress(hProcess); } if ((*LE)(outputStartTime, *mpCurrentTime)) { output(COutputInterface::DURING); } } while ((*L)(*mpCurrentTime, EndTime) && flagProceed); } catch (CCopasiException Exception) { mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); if ((*LE)(outputStartTime, *mpCurrentTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finish(hProcess); output(COutputInterface::AFTER); throw CCopasiException(Exception.getMessage()); } if (mpCallBack) mpCallBack->finish(hProcess); output(COutputInterface::AFTER); return true; } void CTrajectoryTask::processStart(const bool & useInitialValues) { if (useInitialValues) mpTrajectoryProblem->getModel()->applyInitialValues(); *mpCurrentState = mpTrajectoryProblem->getModel()->getState(); mpTrajectoryMethod->setCurrentState(mpCurrentState); mpTrajectoryMethod->start(mpCurrentState); return; } bool CTrajectoryTask::processStep(const C_FLOAT64 & nextTime) { C_FLOAT64 CompareTime = nextTime - 100 * fabs(nextTime) * DBL_EPSILON; if (*mpCurrentTime <= CompareTime) { do { mpTrajectoryMethod->step(nextTime - *mpCurrentTime); if (*mpCurrentTime > CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12); } while (true); mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); return true; } CompareTime = nextTime + 100 * fabs(nextTime) * DBL_EPSILON; if (*mpCurrentTime >= CompareTime) { do { mpTrajectoryMethod->step(nextTime - *mpCurrentTime); if (*mpCurrentTime < CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12); } while (true); mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); return true; } // Current time is approximately nextTime; return false; } bool CTrajectoryTask::restore() { bool success = CCopasiTask::restore(); if (mUpdateModel) { CModel * pModel = mpProblem->getModel(); pModel->setState(*mpCurrentState); pModel->applyAssignments(); pModel->setInitialState(pModel->getState()); } return success; } bool CTrajectoryTask::setMethodType(const int & type) { CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type; if (!CTrajectoryMethod::isValidSubType(Type)) return false; if (mpMethod->getSubType() == Type) return true; pdelete (mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(Type, (CTrajectoryProblem *) mpProblem); this->add(mpMethod, true); //mpMethod->setObjectParent(this); return true; } CState * CTrajectoryTask::getState() {return mpCurrentState;} const CTimeSeries & CTrajectoryTask::getTimeSeries() const {return mTimeSeries;} void CTrajectoryTask::output(const COutputInterface::Activity & activity) { CCopasiDataModel::Global->output(activity); if (mTimeSeriesRequested && mDoOutput == OUTPUT_COMPLETE) switch (activity) { case COutputInterface::BEFORE: mTimeSeries.init(mpTrajectoryProblem->getStepNumber(), mpProblem->getModel()); break; case COutputInterface::DURING: mTimeSeries.add(); break; case COutputInterface::AFTER: mTimeSeries.finish(); break; } } <commit_msg>Fixed output to call CCopasiTask::output instead of the global output handler.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/trajectory/CTrajectoryTask.cpp,v $ $Revision: 1.75 $ $Name: $ $Author: shoops $ $Date: 2006/05/02 20:20:22 $ End CVS Header */ // Copyright 2005 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. /** * CTrajectoryTask class. * * This class implements a trajectory task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CTrajectoryTask.h" #include "CTrajectoryProblem.h" #include "CTrajectoryMethod.h" #include "model/CModel.h" #include "model/CState.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/CProcessReport.h" #include "utilities/CCopasiException.h" #include "CopasiDataModel/CCopasiDataModel.h" #define XXXX_Reporting bool fle(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 <= d2);} bool fl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 < d2);} bool ble(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 >= d2);} bool bl(const C_FLOAT64 & d1, const C_FLOAT64 & d2) {return (d1 > d2);} CTrajectoryTask::CTrajectoryTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mTimeSeriesRequested(true), mTimeSeries(), mpTrajectoryProblem(NULL), mpTrajectoryMethod(NULL), mpCurrentState(NULL), mpCurrentTime(NULL) { mpProblem = new CTrajectoryProblem(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(CCopasiMethod::deterministic, (CTrajectoryProblem *) mpProblem); this->add(mpMethod, true); //mpMethod->setObjectParent(this); } /*CTrajectoryTask::CTrajectoryTask(const CTrajectoryTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent), mpCurrentState(src.mpCurrentState), mTimeSeriesRequested(src.mTimeSeriesRequested) {fatalError();}*/ CTrajectoryTask::~CTrajectoryTask() { cleanup(); } void CTrajectoryTask::cleanup() { pdelete(mpCurrentState); } void CTrajectoryTask::load(CReadConfig & configBuffer) { configBuffer.getVariable("Dynamics", "bool", &mScheduled, CReadConfig::LOOP); pdelete(mpProblem); mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->load(configBuffer); pdelete(mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(); this->add(mpMethod, true); //mpMethod->setObjectParent(this); ((CTrajectoryMethod *)mpMethod)->setProblem((CTrajectoryProblem *) mpProblem); } bool CTrajectoryTask::initialize(const OutputFlag & of, std::ostream * pOstream) { assert(mpProblem && mpMethod); mpTrajectoryProblem = dynamic_cast<CTrajectoryProblem *>(mpProblem); assert(mpTrajectoryProblem); mpTrajectoryMethod = dynamic_cast<CTrajectoryMethod *>(mpMethod); assert(mpTrajectoryMethod); mpTrajectoryMethod->setProblem(mpTrajectoryProblem); bool success = mpMethod->isValidProblem(mpProblem); pdelete(mpCurrentState); mpCurrentState = new CState(mpTrajectoryProblem->getModel()->getState()); mpCurrentTime = &mpCurrentState->getTime(); if (!CCopasiTask::initialize(of, pOstream)) success = false; mTimeSeriesRequested = mpTrajectoryProblem->timeSeriesRequested(); return success; } bool CTrajectoryTask::process(const bool & useInitialValues) { //***** processStart(useInitialValues); //***** unsigned C_INT32 FailCounter = 0; C_FLOAT64 StepSize = mpTrajectoryProblem->getStepSize(); C_FLOAT64 NextTimeToReport; const C_FLOAT64 EndTime = *mpCurrentTime + mpTrajectoryProblem->getDuration(); const C_FLOAT64 StartTime = *mpCurrentTime; C_FLOAT64 StepNumber = (mpTrajectoryProblem->getDuration()) / StepSize; bool (*LE)(const C_FLOAT64 &, const C_FLOAT64 &); bool (*L)(const C_FLOAT64 &, const C_FLOAT64 &); if (StepSize < 0.0) { LE = &ble; L = &bl; } else { LE = &fle; L = &fl; } unsigned C_INT32 StepCounter = 1; C_FLOAT64 outputStartTime = mpTrajectoryProblem->getOutputStartTime(); if (StepSize == 0.0 && mpTrajectoryProblem->getDuration() != 0.0) { CCopasiMessage(CCopasiMessage::ERROR, MCTrajectoryProblem + 1, StepSize); return false; } output(COutputInterface::BEFORE); bool flagProceed = true; C_FLOAT64 handlerFactor = 100.0 / mpTrajectoryProblem->getDuration(); C_FLOAT64 Percentage = 0; unsigned C_INT32 hProcess; if (mpCallBack) { mpCallBack->setName("performing simulation..."); C_FLOAT64 hundred = 100; hProcess = mpCallBack->addItem("Completion", CCopasiParameter::DOUBLE, &Percentage, &hundred); } if ((*LE)(outputStartTime, *mpCurrentTime)) output(COutputInterface::DURING); try { do { // This is numerically more stable then adding // mpTrajectoryProblem->getStepSize(). NextTimeToReport = StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber; flagProceed &= processStep(NextTimeToReport); if (mpCallBack) { Percentage = (*mpCurrentTime - StartTime) * handlerFactor; flagProceed &= mpCallBack->progress(hProcess); } if ((*LE)(outputStartTime, *mpCurrentTime)) { output(COutputInterface::DURING); } } while ((*L)(*mpCurrentTime, EndTime) && flagProceed); } catch (CCopasiException Exception) { mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); if ((*LE)(outputStartTime, *mpCurrentTime)) { output(COutputInterface::DURING); } if (mpCallBack) mpCallBack->finish(hProcess); output(COutputInterface::AFTER); throw CCopasiException(Exception.getMessage()); } if (mpCallBack) mpCallBack->finish(hProcess); output(COutputInterface::AFTER); return true; } void CTrajectoryTask::processStart(const bool & useInitialValues) { if (useInitialValues) mpTrajectoryProblem->getModel()->applyInitialValues(); *mpCurrentState = mpTrajectoryProblem->getModel()->getState(); mpTrajectoryMethod->setCurrentState(mpCurrentState); mpTrajectoryMethod->start(mpCurrentState); return; } bool CTrajectoryTask::processStep(const C_FLOAT64 & nextTime) { C_FLOAT64 CompareTime = nextTime - 100 * fabs(nextTime) * DBL_EPSILON; if (*mpCurrentTime <= CompareTime) { do { mpTrajectoryMethod->step(nextTime - *mpCurrentTime); if (*mpCurrentTime > CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12); } while (true); mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); return true; } CompareTime = nextTime + 100 * fabs(nextTime) * DBL_EPSILON; if (*mpCurrentTime >= CompareTime) { do { mpTrajectoryMethod->step(nextTime - *mpCurrentTime); if (*mpCurrentTime < CompareTime) break; /* Here we will do conditional event processing */ /* Currently this is correct since no events are processed. */ CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12); } while (true); mpTrajectoryProblem->getModel()->setState(*mpCurrentState); mpTrajectoryProblem->getModel()->refreshConcentrations(); return true; } // Current time is approximately nextTime; return false; } bool CTrajectoryTask::restore() { bool success = CCopasiTask::restore(); if (mUpdateModel) { CModel * pModel = mpProblem->getModel(); pModel->setState(*mpCurrentState); pModel->applyAssignments(); pModel->setInitialState(pModel->getState()); } return success; } bool CTrajectoryTask::setMethodType(const int & type) { CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type; if (!CTrajectoryMethod::isValidSubType(Type)) return false; if (mpMethod->getSubType() == Type) return true; pdelete (mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(Type, (CTrajectoryProblem *) mpProblem); this->add(mpMethod, true); //mpMethod->setObjectParent(this); return true; } CState * CTrajectoryTask::getState() {return mpCurrentState;} const CTimeSeries & CTrajectoryTask::getTimeSeries() const {return mTimeSeries;} void CTrajectoryTask::output(const COutputInterface::Activity & activity) { CCopasiTask::output(activity); if (mTimeSeriesRequested && mDoOutput == OUTPUT_COMPLETE) switch (activity) { case COutputInterface::BEFORE: mTimeSeries.init(mpTrajectoryProblem->getStepNumber(), mpProblem->getModel()); break; case COutputInterface::DURING: mTimeSeries.add(); break; case COutputInterface::AFTER: mTimeSeries.finish(); break; } } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION 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. */ #include "Glue.hxx" #include "Client.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "header_writer.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "strmap.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "abort_close.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "pool.hxx" #include "util/Cancellable.hxx" #include "util/Compiler.h" #include <string.h> #include <sys/socket.h> struct AjpRequest final : public StockGetHandler, Lease { struct pool &pool; EventLoop &event_loop; StockItem *stock_item; const char *const protocol; const char *const remote_addr; const char *const remote_host; const char *const server_name; const unsigned server_port; const bool is_ssl; const http_method_t method; const char *const uri; StringMap headers; Istream *body; HttpResponseHandler &handler; CancellablePointer &cancel_ptr; AjpRequest(struct pool &_pool, EventLoop &_event_loop, const char *_protocol, const char *_remote_addr, const char *_remote_host, const char *_server_name, unsigned _server_port, bool _is_ssl, http_method_t _method, const char *_uri, StringMap &&_headers, HttpResponseHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), event_loop(_event_loop), protocol(_protocol), remote_addr(_remote_addr), remote_host(_remote_host), server_name(_server_name), server_port(_server_port), is_ssl(_is_ssl), method(_method), uri(_uri), headers(std::move(_headers)), handler(_handler), cancel_ptr(_cancel_ptr) { } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock_item->Put(!reuse); } }; /* * stock callback * */ void AjpRequest::OnStockItemReady(StockItem &item) { stock_item = &item; ajp_client_request(pool, event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uri, headers, body, handler, cancel_ptr); } void AjpRequest::OnStockItemError(std::exception_ptr ep) { handler.InvokeError(ep); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void ajp_stock_request(struct pool &pool, EventLoop &event_loop, TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const char *protocol, const char *remote_addr, const char *remote_host, const char *server_name, unsigned server_port, bool is_ssl, http_method_t method, const HttpAddress &uwa, StringMap &&headers, Istream *body, HttpResponseHandler &handler, CancellablePointer &_cancel_ptr) { assert(uwa.path != nullptr); assert(body == nullptr || !body->HasHandler()); auto hr = NewFromPool<AjpRequest>(pool, pool, event_loop, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uwa.path, std::move(headers), handler, _cancel_ptr); auto *cancel_ptr = &_cancel_ptr; if (body != nullptr) { hr->body = istream_hold_new(pool, *body); cancel_ptr = &async_close_on_abort(pool, *hr->body, *cancel_ptr); } else hr->body = nullptr; tcp_balancer.Get(pool, false, SocketAddress::Null(), session_sticky, uwa.addresses, 20, *hr, *cancel_ptr); } <commit_msg>ajp/Glue: move code to method BeginConnect()<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION 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. */ #include "Glue.hxx" #include "Client.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "header_writer.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "strmap.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "abort_close.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "pool.hxx" #include "util/Cancellable.hxx" #include "util/Compiler.h" #include <string.h> #include <sys/socket.h> struct AjpRequest final : StockGetHandler, Lease { struct pool &pool; EventLoop &event_loop; StockItem *stock_item; const char *const protocol; const char *const remote_addr; const char *const remote_host; const char *const server_name; const unsigned server_port; const bool is_ssl; const http_method_t method; const char *const uri; StringMap headers; Istream *body; HttpResponseHandler &handler; CancellablePointer &cancel_ptr; AjpRequest(struct pool &_pool, EventLoop &_event_loop, const char *_protocol, const char *_remote_addr, const char *_remote_host, const char *_server_name, unsigned _server_port, bool _is_ssl, http_method_t _method, const char *_uri, StringMap &&_headers, HttpResponseHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), event_loop(_event_loop), protocol(_protocol), remote_addr(_remote_addr), remote_host(_remote_host), server_name(_server_name), server_port(_server_port), is_ssl(_is_ssl), method(_method), uri(_uri), headers(std::move(_headers)), handler(_handler), cancel_ptr(_cancel_ptr) { } void BeginConnect(TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const HttpAddress &address, CancellablePointer &_cancel_ptr) { tcp_balancer.Get(pool, false, SocketAddress::Null(), session_sticky, address.addresses, 20, *this, _cancel_ptr); } private: /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock_item->Put(!reuse); } }; /* * stock callback * */ void AjpRequest::OnStockItemReady(StockItem &item) { stock_item = &item; ajp_client_request(pool, event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uri, headers, body, handler, cancel_ptr); } void AjpRequest::OnStockItemError(std::exception_ptr ep) { handler.InvokeError(ep); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void ajp_stock_request(struct pool &pool, EventLoop &event_loop, TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const char *protocol, const char *remote_addr, const char *remote_host, const char *server_name, unsigned server_port, bool is_ssl, http_method_t method, const HttpAddress &uwa, StringMap &&headers, Istream *body, HttpResponseHandler &handler, CancellablePointer &_cancel_ptr) { assert(uwa.path != nullptr); assert(body == nullptr || !body->HasHandler()); auto hr = NewFromPool<AjpRequest>(pool, pool, event_loop, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uwa.path, std::move(headers), handler, _cancel_ptr); auto *cancel_ptr = &_cancel_ptr; if (body != nullptr) { hr->body = istream_hold_new(pool, *body); cancel_ptr = &async_close_on_abort(pool, *hr->body, *cancel_ptr); } else hr->body = nullptr; hr->BeginConnect(tcp_balancer, session_sticky, uwa, *cancel_ptr); } <|endoftext|>
<commit_before>#include "allocator.h" #include <cstring> namespace nvds { void Allocator::Format() { ModificationList modifications; set_modifications(&modifications); memset(flm_, 0, kSize); uint32_t blk = sizeof(FreeListManager); Write(GetLastFreeList(), blk); // 'The block before first block' is not free // The last 4 bytes is kept for the free tag uint32_t blk_size = (kSize - blk - sizeof(uint32_t)) & ~static_cast<uint32_t>(0x0f); Write(blk, blk_size & ~BlockHeader::kFreeMask); Write(blk + blk_size - sizeof(uint32_t), blk_size); SetTheFreeTag(blk, blk_size); // TODO(wgtdkp): setting `next` and `prev` nullptr(unnecessary if called `memset`)p } uint32_t Allocator::AllocBlock(uint32_t blk_size) { auto free_list = GetFreeListByBlockSize(blk_size); uint32_t head; while (free_list < kNumFreeLists * sizeof(uint32_t) && (head = Read<uint32_t>(free_list)) == 0) { free_list += sizeof(uint32_t); } if (head == 0) { return 0; } auto head_size = ReadTheSizeTag(head); assert(ReadTheFreeTag(head, head_size) != 0); assert(head_size >= blk_size); if (head_size == blk_size) { auto next_blk = Read<uint32_t>(head + offsetof(BlockHeader, next)); ResetTheFreeTag(head, head_size); Write(free_list, next_blk); Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); return head; } return SplitBlock(head, head_size, blk_size); } void Allocator::FreeBlock(uint32_t blk) { auto blk_size = ReadTheSizeTag(blk); auto blk_size_old = blk_size; auto prev_blk_size = Read<uint32_t>(blk - sizeof(uint32_t)); auto prev_blk = blk - prev_blk_size; auto next_blk = blk + blk_size; auto next_blk_size = ReadTheSizeTag(next_blk); if (ReadThePrevFreeTag(blk) && blk_size <= kMaxBlockSize && prev_blk_size <= kMaxBlockSize) { RemoveBlock(prev_blk, prev_blk_size); blk = prev_blk; blk_size += prev_blk_size; } if (ReadTheFreeTag(next_blk, next_blk_size) && blk_size <= kMaxBlockSize && next_blk_size <= kMaxBlockSize) { RemoveBlock(next_blk, next_blk_size); blk_size += next_blk_size; } // If the blk_size changed, write it. if (blk_size != blk_size_old) { Write(blk, ReadThePrevFreeTag(blk) | blk_size); Write(blk + blk_size - sizeof(uint32_t), blk_size); } SetTheFreeTag(blk, blk_size); auto free_list = GetFreeListByBlockSize(blk_size); auto head = Read<uint32_t>(free_list); Write(free_list, blk); Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); Write(blk + offsetof(BlockHeader, next), head); if (head != 0) { Write(head + offsetof(BlockHeader, prev), blk); } } void Allocator::RemoveBlock(uint32_t blk, uint32_t blk_size) { assert(ReadTheFreeTag(blk, blk_size) != 0); auto prev_blk = Read<uint32_t>(blk + offsetof(BlockHeader, prev)); auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next)); if (prev_blk != 0) { Write(prev_blk + offsetof(BlockHeader, next), Read<uint32_t>(blk + offsetof(BlockHeader, next))); } else { auto free_list = GetFreeListByBlockSize(blk_size); Write(free_list, Read<uint32_t>(blk + offsetof(BlockHeader, next))); } if (next_blk != 0) { Write(next_blk + offsetof(BlockHeader, prev), Read<uint32_t>(blk + offsetof(BlockHeader, prev))); } } uint32_t Allocator::SplitBlock(uint32_t blk, uint32_t blk_size, uint32_t needed_size) { auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next)); auto free_list = GetFreeListByBlockSize(blk_size); assert(blk_size > needed_size); auto new_size = blk_size - needed_size; Write(free_list, next_blk); if (next_blk != 0) { Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); } // Update size Write(blk, ReadThePrevFreeTag(blk) | new_size); Write(blk + new_size - sizeof(uint32_t), new_size); free_list = GetFreeListByBlockSize(new_size); auto head = Read<uint32_t>(free_list); Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); Write(blk + offsetof(BlockHeader, next), head); Write(free_list, blk); if (head != 0) { Write(head + offsetof(BlockHeader, prev), blk); } // The rest smaller block is still free Write(blk + new_size, BlockHeader::kFreeMask | needed_size); Write(blk + blk_size - sizeof(uint32_t), needed_size); // Piece splitted is not free now. ResetTheFreeTag(blk + new_size, needed_size); return blk + new_size; } } // namespace nvds <commit_msg>fix typo in comment<commit_after>#include "allocator.h" #include <cstring> namespace nvds { void Allocator::Format() { ModificationList modifications; set_modifications(&modifications); memset(flm_, 0, kSize); uint32_t blk = sizeof(FreeListManager); Write(GetLastFreeList(), blk); // 'The block before first block' is not free // The last 4 bytes is kept for the free tag uint32_t blk_size = (kSize - blk - sizeof(uint32_t)) & ~static_cast<uint32_t>(0x0f); Write(blk, blk_size & ~BlockHeader::kFreeMask); Write(blk + blk_size - sizeof(uint32_t), blk_size); SetTheFreeTag(blk, blk_size); // TODO(wgtdkp): setting `next` and `prev` nullptr.(unnecessary if called `memset`) } uint32_t Allocator::AllocBlock(uint32_t blk_size) { auto free_list = GetFreeListByBlockSize(blk_size); uint32_t head; while (free_list < kNumFreeLists * sizeof(uint32_t) && (head = Read<uint32_t>(free_list)) == 0) { free_list += sizeof(uint32_t); } if (head == 0) { return 0; } auto head_size = ReadTheSizeTag(head); assert(ReadTheFreeTag(head, head_size) != 0); assert(head_size >= blk_size); if (head_size == blk_size) { auto next_blk = Read<uint32_t>(head + offsetof(BlockHeader, next)); ResetTheFreeTag(head, head_size); Write(free_list, next_blk); Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); return head; } return SplitBlock(head, head_size, blk_size); } void Allocator::FreeBlock(uint32_t blk) { auto blk_size = ReadTheSizeTag(blk); auto blk_size_old = blk_size; auto prev_blk_size = Read<uint32_t>(blk - sizeof(uint32_t)); auto prev_blk = blk - prev_blk_size; auto next_blk = blk + blk_size; auto next_blk_size = ReadTheSizeTag(next_blk); if (ReadThePrevFreeTag(blk) && blk_size <= kMaxBlockSize && prev_blk_size <= kMaxBlockSize) { RemoveBlock(prev_blk, prev_blk_size); blk = prev_blk; blk_size += prev_blk_size; } if (ReadTheFreeTag(next_blk, next_blk_size) && blk_size <= kMaxBlockSize && next_blk_size <= kMaxBlockSize) { RemoveBlock(next_blk, next_blk_size); blk_size += next_blk_size; } // If the blk_size changed, write it. if (blk_size != blk_size_old) { Write(blk, ReadThePrevFreeTag(blk) | blk_size); Write(blk + blk_size - sizeof(uint32_t), blk_size); } SetTheFreeTag(blk, blk_size); auto free_list = GetFreeListByBlockSize(blk_size); auto head = Read<uint32_t>(free_list); Write(free_list, blk); Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); Write(blk + offsetof(BlockHeader, next), head); if (head != 0) { Write(head + offsetof(BlockHeader, prev), blk); } } void Allocator::RemoveBlock(uint32_t blk, uint32_t blk_size) { assert(ReadTheFreeTag(blk, blk_size) != 0); auto prev_blk = Read<uint32_t>(blk + offsetof(BlockHeader, prev)); auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next)); if (prev_blk != 0) { Write(prev_blk + offsetof(BlockHeader, next), Read<uint32_t>(blk + offsetof(BlockHeader, next))); } else { auto free_list = GetFreeListByBlockSize(blk_size); Write(free_list, Read<uint32_t>(blk + offsetof(BlockHeader, next))); } if (next_blk != 0) { Write(next_blk + offsetof(BlockHeader, prev), Read<uint32_t>(blk + offsetof(BlockHeader, prev))); } } uint32_t Allocator::SplitBlock(uint32_t blk, uint32_t blk_size, uint32_t needed_size) { auto next_blk = Read<uint32_t>(blk + offsetof(BlockHeader, next)); auto free_list = GetFreeListByBlockSize(blk_size); assert(blk_size > needed_size); auto new_size = blk_size - needed_size; Write(free_list, next_blk); if (next_blk != 0) { Write(next_blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); } // Update size Write(blk, ReadThePrevFreeTag(blk) | new_size); Write(blk + new_size - sizeof(uint32_t), new_size); free_list = GetFreeListByBlockSize(new_size); auto head = Read<uint32_t>(free_list); Write(blk + offsetof(BlockHeader, prev), static_cast<uint32_t>(0)); Write(blk + offsetof(BlockHeader, next), head); Write(free_list, blk); if (head != 0) { Write(head + offsetof(BlockHeader, prev), blk); } // The rest smaller block is still free Write(blk + new_size, BlockHeader::kFreeMask | needed_size); Write(blk + blk_size - sizeof(uint32_t), needed_size); // Piece splitted is not free now. ResetTheFreeTag(blk + new_size, needed_size); return blk + new_size; } } // namespace nvds <|endoftext|>
<commit_before>/* * Copyright (c) 2002 - present, H. Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder 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 COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_ #define CRIMILD_ #include "Animation/Animation.hpp" #include "Animation/ChannelImpl.hpp" #include "Animation/Clip.hpp" #include "Animation/Skeleton.hpp" #include "Audio/AudioListener.hpp" #include "Audio/AudioSource.hpp" #include "Behaviors/Actions/AnimateContextValue.hpp" #include "Behaviors/Actions/AnimateParticleSystem.hpp" #include "Behaviors/Actions/AnimateSettingValue.hpp" #include "Behaviors/Actions/ClearTargets.hpp" #include "Behaviors/Actions/CopyTransformFromTarget.hpp" #include "Behaviors/Actions/EnableNode.hpp" #include "Behaviors/Actions/ExecuteBehavior.hpp" #include "Behaviors/Actions/ExecuteBehaviorOnTarget.hpp" #include "Behaviors/Actions/FindTarget.hpp" #include "Behaviors/Actions/LoadScene.hpp" #include "Behaviors/Actions/LookAt.hpp" #include "Behaviors/Actions/MotionApply.hpp" #include "Behaviors/Actions/MotionAvoidOthers.hpp" #include "Behaviors/Actions/MotionAvoidWalls.hpp" #include "Behaviors/Actions/MotionComputePathToTarget.hpp" #include "Behaviors/Actions/MotionReset.hpp" #include "Behaviors/Actions/MotionSeek.hpp" #include "Behaviors/Actions/PrintMessage.hpp" #include "Behaviors/Actions/ResetNavigation.hpp" #include "Behaviors/Actions/Rotate.hpp" #include "Behaviors/Actions/SetContextValue.hpp" #include "Behaviors/Actions/SetSettingValue.hpp" #include "Behaviors/Actions/Success.hpp" #include "Behaviors/Actions/Transform.hpp" #include "Behaviors/Actions/Trigger.hpp" #include "Behaviors/Actions/Wait.hpp" #include "Behaviors/Behavior.hpp" #include "Behaviors/BehaviorContext.hpp" #include "Behaviors/BehaviorController.hpp" #include "Behaviors/BehaviorTree.hpp" #include "Behaviors/Composites/Composite.hpp" #include "Behaviors/Composites/Parallel.hpp" #include "Behaviors/Composites/Selector.hpp" #include "Behaviors/Composites/Sequence.hpp" #include "Behaviors/Conditions/DistanceToTarget.hpp" #include "Behaviors/Conditions/HasTargets.hpp" #include "Behaviors/Conditions/IsAtTarget.hpp" #include "Behaviors/Conditions/TestContextValue.hpp" #include "Behaviors/Conditions/TestInputAxis.hpp" #include "Behaviors/Conditions/TestSettingValue.hpp" #include "Behaviors/Decorators/Decorator.hpp" #include "Behaviors/Decorators/Inverter.hpp" #include "Behaviors/Decorators/Repeat.hpp" #include "Behaviors/Decorators/RepeatUntilFail.hpp" #include "Behaviors/Decorators/RepeatUntilSuccess.hpp" #include "Behaviors/Decorators/Succeeder.hpp" #include "Behaviors/Decorators/Throttle.hpp" #include "Behaviors/withBehavior.hpp" #include "Boundings/AABBBoundingVolume.hpp" #include "Boundings/BoundingVolume.hpp" #include "Boundings/PlaneBoundingVolume.hpp" #include "Boundings/SphereBoundingVolume.hpp" #include "Coding/Codable.hpp" #include "Coding/Decoder.hpp" #include "Coding/EncodedData.hpp" #include "Coding/Encoder.hpp" #include "Coding/FileDecoder.hpp" #include "Coding/FileEncoder.hpp" #include "Coding/MemoryDecoder.hpp" #include "Coding/MemoryEncoder.hpp" #include "Coding/Tags.hpp" #include "Components/AnimatorComponent.hpp" #include "Components/AudioListenerComponent.hpp" #include "Components/AudioSourceComponent.hpp" #include "Components/BillboardComponent.hpp" #include "Components/FreeLookCameraComponent.hpp" #include "Components/LambdaComponent.hpp" #include "Components/MaterialComponent.hpp" #include "Components/NodeComponent.hpp" #include "Components/NodeComponentCatalog.hpp" #include "Components/OrbitComponent.hpp" #include "Components/RenderStateComponent.hpp" #include "Components/RotationComponent.hpp" #include "Components/SingleValueComponent.hpp" #include "Components/SkinnedMeshComponent.hpp" #include "Components/TimerComponent.hpp" #include "Components/UIResponder.hpp" #include "Concurrency/Async.hpp" #include "Concurrency/Job.hpp" #include "Concurrency/JobScheduler.hpp" #include "Concurrency/WorkStealingDeque.hpp" #include "Debug/DebugRenderComponent.hpp" #include "Debug/DebugRenderHelper.hpp" #include "Debug/SceneDebugDump.hpp" #include "Exceptions/Exception.hpp" #include "Exceptions/FileNotFoundException.hpp" #include "Exceptions/HasParentException.hpp" #include "Exceptions/RuntimeException.hpp" #include "Foundation/Containers/Array.hpp" #include "Foundation/Containers/Map.hpp" #include "Foundation/Containers/PriorityQueue.hpp" #include "Foundation/Containers/Queue.hpp" #include "Foundation/Containers/Stack.hpp" #include "Foundation/FilePath.hpp" #include "Foundation/Log.hpp" #include "Foundation/Macros.hpp" #include "Foundation/Memory.hpp" #include "Foundation/NamedObject.hpp" #include "Foundation/ObjectFactory.hpp" #include "Foundation/Policies/ThreadingPolicy.hpp" #include "Foundation/Profiler.hpp" #include "Foundation/SharedObject.hpp" #include "Foundation/Singleton.hpp" #include "Foundation/StringUtils.hpp" #include "Foundation/Version.hpp" #include "Loaders/OBJLoader.hpp" #include "Mathematics/Clock.hpp" #include "Mathematics/ColorRGB.hpp" #include "Mathematics/ColorRGBA.hpp" #include "Mathematics/ColorRGBAOps.hpp" #include "Mathematics/ColorRGBOps.hpp" #include "Mathematics/Frustum.hpp" #include "Mathematics/Interpolation.hpp" #include "Mathematics/Intersection.hpp" #include "Mathematics/Matrix3.hpp" #include "Mathematics/Matrix3_equality.hpp" #include "Mathematics/Matrix4.hpp" #include "Mathematics/Matrix4_equality.hpp" #include "Mathematics/Numeric.hpp" #include "Mathematics/Plane3.hpp" #include "Mathematics/Quaternion.hpp" #include "Mathematics/Random.hpp" #include "Mathematics/Ray3.hpp" #include "Mathematics/Rect.hpp" #include "Mathematics/Root.hpp" #include "Mathematics/Series.hpp" #include "Mathematics/Sphere.hpp" #include "Mathematics/Transformation.hpp" #include "Mathematics/Transformation_apply.hpp" #include "Mathematics/Transformation_inverse.hpp" #include "Mathematics/Transformation_lookAt.hpp" #include "Mathematics/Transformation_operators.hpp" #include "Mathematics/Transformation_rotation.hpp" #include "Mathematics/Transformation_scale.hpp" #include "Mathematics/Transformation_translation.hpp" #include "Mathematics/Vector2.hpp" #include "Mathematics/Vector2Ops.hpp" #include "Mathematics/Vector3.hpp" #include "Mathematics/Vector3Ops.hpp" #include "Mathematics/Vector4.hpp" #include "Mathematics/Vector_equality.hpp" #include "Mathematics/io.hpp" #include "Mathematics/ortho.hpp" #include "Mathematics/perspective.hpp" #include "Mathematics/trigonometry.hpp" #include "Messaging/MessageQueue.hpp" #include "Navigation/NavigationCell.hpp" #include "Navigation/NavigationCellEdge.hpp" #include "Navigation/NavigationController.hpp" #include "Navigation/NavigationMesh.hpp" #include "Navigation/NavigationMeshContainer.hpp" #include "Navigation/NavigationMeshOBJ.hpp" #include "ParticleSystem/Generators/AccelerationParticleGenerator.hpp" #include "ParticleSystem/Generators/BoxPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/ColorParticleGenerator.hpp" #include "ParticleSystem/Generators/DefaultValueParticleGenerator.hpp" #include "ParticleSystem/Generators/EulerAnglesParticleGenerator.hpp" #include "ParticleSystem/Generators/GridPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/NodePositionParticleGenerator.hpp" #include "ParticleSystem/Generators/OrbitPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/RandomValueParticleGenerator.hpp" #include "ParticleSystem/Generators/SpherePositionParticleGenerator.hpp" #include "ParticleSystem/Generators/SphereVelocityParticleGenerator.hpp" #include "ParticleSystem/Generators/TimeParticleGenerator.hpp" #include "ParticleSystem/Generators/UniformScaleParticleGenerator.hpp" #include "ParticleSystem/Generators/VelocityParticleGenerator.hpp" #include "ParticleSystem/ParticleData.hpp" #include "ParticleSystem/ParticleSystemComponent.hpp" #include "ParticleSystem/Renderers/AnimatedSpriteParticleRenderer.hpp" #include "ParticleSystem/Renderers/InstancedParticleRenderer.hpp" #include "ParticleSystem/Renderers/NodeParticleRenderer.hpp" #include "ParticleSystem/Renderers/OrientedQuadParticleRenderer.hpp" #include "ParticleSystem/Renderers/PointSpriteParticleRenderer.hpp" #include "ParticleSystem/Updaters/AttractorParticleUpdater.hpp" #include "ParticleSystem/Updaters/CameraSortParticleUpdater.hpp" #include "ParticleSystem/Updaters/ColorParticleUpdater.hpp" #include "ParticleSystem/Updaters/EulerParticleUpdater.hpp" #include "ParticleSystem/Updaters/FloorParticleUpdater.hpp" #include "ParticleSystem/Updaters/PositionVelocityParticleUpdater.hpp" #include "ParticleSystem/Updaters/SetAttribValueParticleUpdater.hpp" #include "ParticleSystem/Updaters/TimeParticleUpdater.hpp" #include "ParticleSystem/Updaters/UniformScaleParticleUpdater.hpp" #include "ParticleSystem/Updaters/ZSortParticleUpdater.hpp" #include "Primitives/ArcPrimitive.hpp" #include "Primitives/ArrowPrimitive.hpp" #include "Primitives/BoxPrimitive.hpp" #include "Primitives/ConePrimitive.hpp" #include "Primitives/CylinderPrimitive.hpp" #include "Primitives/KleinBottlePrimitive.hpp" #include "Primitives/MobiusStripPrimitive.hpp" #include "Primitives/NewellTeapotPrimitive.hpp" #include "Primitives/ParametricPrimitive.hpp" #include "Primitives/ParametricSpherePrimitive.hpp" #include "Primitives/Primitive.hpp" #include "Primitives/QuadPrimitive.hpp" #include "Primitives/SpherePrimitive.hpp" #include "Primitives/TorusPrimitive.hpp" #include "Primitives/TrefoilKnotPrimitive.hpp" #include "Rendering/Buffer.hpp" #include "Rendering/Catalog.hpp" #include "Rendering/ColorMaskState.hpp" #include "Rendering/CommandBuffer.hpp" #include "Rendering/ComputePass.hpp" #include "Rendering/DescriptorSet.hpp" #include "Rendering/Font.hpp" #include "Rendering/Image.hpp" #include "Rendering/ImageManager.hpp" #include "Rendering/ImageTGA.hpp" #include "Rendering/IndexBuffer.hpp" #include "Rendering/Material.hpp" #include "Rendering/Materials/LitMaterial.hpp" #include "Rendering/Materials/PrincipledBSDFMaterial.hpp" #include "Rendering/Materials/SkyboxMaterial.hpp" #include "Rendering/Materials/UnlitMaterial.hpp" #include "Rendering/Operations/OperationUtils.hpp" #include "Rendering/Operations/Operations.hpp" #include "Rendering/Operations/Operations_softRT.hpp" #include "Rendering/Pipeline.hpp" #include "Rendering/Programs/UnlitShaderProgram.hpp" #include "Rendering/RenderPass.hpp" #include "Rendering/RenderResource.hpp" #include "Rendering/RenderState.hpp" #include "Rendering/Renderer.hpp" #include "Rendering/Sampler.hpp" #include "Rendering/Shader.hpp" #include "Rendering/ShaderLibrary.hpp" #include "Rendering/ShaderLocation.hpp" #include "Rendering/ShaderProgram.hpp" #include "Rendering/ShaderProgramLibrary.hpp" #include "Rendering/ShaderUniform.hpp" #include "Rendering/ShaderUniformImpl.hpp" #include "Rendering/ShadowMap.hpp" #include "Rendering/SkinnedMesh.hpp" #include "Rendering/Swapchain.hpp" #include "Rendering/Texture.hpp" #include "Rendering/UniformBuffer.hpp" #include "Rendering/Uniforms/CallbackUniformBuffer.hpp" #include "Rendering/Uniforms/CameraViewProjectionUniformBuffer.hpp" #include "Rendering/Uniforms/LightingUniform.hpp" #include "Rendering/Uniforms/ModelUniformBuffer.hpp" #include "Rendering/Uniforms/ModelViewProjectionUniformBuffer.hpp" #include "Rendering/VertexBuffer.hpp" #include "SceneGraph/Camera.hpp" #include "SceneGraph/Geometry.hpp" #include "SceneGraph/Group.hpp" #include "SceneGraph/Light.hpp" #include "SceneGraph/Node.hpp" #include "SceneGraph/Skybox.hpp" #include "SceneGraph/Switch.hpp" #include "SceneGraph/Text.hpp" #include "Simulation/Console/Console.hpp" #include "Simulation/FileSystem.hpp" #include "Simulation/Input.hpp" #include "Simulation/Simulation.hpp" #include "Simulation/Systems/AudioSystem.hpp" #include "Simulation/Systems/DebugSystem.hpp" #include "Simulation/Systems/RenderSystem.hpp" #include "Simulation/Systems/StreamingSystem.hpp" #include "Simulation/Systems/UISystem.hpp" #include "Simulation/Systems/UpdateSystem.hpp" #include "UI/UIBackground.hpp" #include "UI/UIButton.hpp" #include "UI/UICanvas.hpp" #include "UI/UIFrame.hpp" #include "UI/UIFrameConstraint.hpp" #include "UI/UIFrameConstraintMaker.hpp" #include "UI/UILabel.hpp" #include "Visitors/Apply.hpp" #include "Visitors/ApplyToGeometries.hpp" #include "Visitors/ComputeRenderQueue.hpp" #include "Visitors/FetchCameras.hpp" #include "Visitors/FetchLights.hpp" #include "Visitors/NodeVisitor.hpp" #include "Visitors/Picking.hpp" #include "Visitors/SelectNodes.hpp" #include "Visitors/ShallowCopy.hpp" #include "Visitors/StartComponents.hpp" #include "Visitors/UpdateComponents.hpp" #include "Visitors/UpdateRenderState.hpp" #include "Visitors/UpdateWorldState.hpp" namespace crimild { void init( void ); } #endif <commit_msg>Add missing header<commit_after>/* * Copyright (c) 2002 - present, H. Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder 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 COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_ #define CRIMILD_ #include "Animation/Animation.hpp" #include "Animation/ChannelImpl.hpp" #include "Animation/Clip.hpp" #include "Animation/Skeleton.hpp" #include "Audio/AudioListener.hpp" #include "Audio/AudioSource.hpp" #include "Behaviors/Actions/AnimateContextValue.hpp" #include "Behaviors/Actions/AnimateParticleSystem.hpp" #include "Behaviors/Actions/AnimateSettingValue.hpp" #include "Behaviors/Actions/ClearTargets.hpp" #include "Behaviors/Actions/CopyTransformFromTarget.hpp" #include "Behaviors/Actions/EnableNode.hpp" #include "Behaviors/Actions/ExecuteBehavior.hpp" #include "Behaviors/Actions/ExecuteBehaviorOnTarget.hpp" #include "Behaviors/Actions/FindTarget.hpp" #include "Behaviors/Actions/LoadScene.hpp" #include "Behaviors/Actions/LookAt.hpp" #include "Behaviors/Actions/MotionApply.hpp" #include "Behaviors/Actions/MotionAvoidOthers.hpp" #include "Behaviors/Actions/MotionAvoidWalls.hpp" #include "Behaviors/Actions/MotionComputePathToTarget.hpp" #include "Behaviors/Actions/MotionReset.hpp" #include "Behaviors/Actions/MotionSeek.hpp" #include "Behaviors/Actions/PrintMessage.hpp" #include "Behaviors/Actions/ResetNavigation.hpp" #include "Behaviors/Actions/Rotate.hpp" #include "Behaviors/Actions/SetContextValue.hpp" #include "Behaviors/Actions/SetSettingValue.hpp" #include "Behaviors/Actions/Success.hpp" #include "Behaviors/Actions/Transform.hpp" #include "Behaviors/Actions/Trigger.hpp" #include "Behaviors/Actions/Wait.hpp" #include "Behaviors/Behavior.hpp" #include "Behaviors/BehaviorContext.hpp" #include "Behaviors/BehaviorController.hpp" #include "Behaviors/BehaviorTree.hpp" #include "Behaviors/Composites/Composite.hpp" #include "Behaviors/Composites/Parallel.hpp" #include "Behaviors/Composites/Selector.hpp" #include "Behaviors/Composites/Sequence.hpp" #include "Behaviors/Conditions/DistanceToTarget.hpp" #include "Behaviors/Conditions/HasTargets.hpp" #include "Behaviors/Conditions/IsAtTarget.hpp" #include "Behaviors/Conditions/TestContextValue.hpp" #include "Behaviors/Conditions/TestInputAxis.hpp" #include "Behaviors/Conditions/TestSettingValue.hpp" #include "Behaviors/Decorators/Decorator.hpp" #include "Behaviors/Decorators/Inverter.hpp" #include "Behaviors/Decorators/Repeat.hpp" #include "Behaviors/Decorators/RepeatUntilFail.hpp" #include "Behaviors/Decorators/RepeatUntilSuccess.hpp" #include "Behaviors/Decorators/Succeeder.hpp" #include "Behaviors/Decorators/Throttle.hpp" #include "Behaviors/withBehavior.hpp" #include "Boundings/AABBBoundingVolume.hpp" #include "Boundings/BoundingVolume.hpp" #include "Boundings/PlaneBoundingVolume.hpp" #include "Boundings/SphereBoundingVolume.hpp" #include "Coding/Codable.hpp" #include "Coding/Decoder.hpp" #include "Coding/EncodedData.hpp" #include "Coding/Encoder.hpp" #include "Coding/FileDecoder.hpp" #include "Coding/FileEncoder.hpp" #include "Coding/MemoryDecoder.hpp" #include "Coding/MemoryEncoder.hpp" #include "Coding/Tags.hpp" #include "Components/AnimatorComponent.hpp" #include "Components/AudioListenerComponent.hpp" #include "Components/AudioSourceComponent.hpp" #include "Components/BillboardComponent.hpp" #include "Components/FreeLookCameraComponent.hpp" #include "Components/LambdaComponent.hpp" #include "Components/MaterialComponent.hpp" #include "Components/NodeComponent.hpp" #include "Components/NodeComponentCatalog.hpp" #include "Components/OrbitComponent.hpp" #include "Components/RenderStateComponent.hpp" #include "Components/RotationComponent.hpp" #include "Components/SingleValueComponent.hpp" #include "Components/SkinnedMeshComponent.hpp" #include "Components/TimerComponent.hpp" #include "Components/UIResponder.hpp" #include "Concurrency/Async.hpp" #include "Concurrency/Job.hpp" #include "Concurrency/JobScheduler.hpp" #include "Concurrency/WorkStealingDeque.hpp" #include "Debug/DebugRenderComponent.hpp" #include "Debug/DebugRenderHelper.hpp" #include "Debug/SceneDebugDump.hpp" #include "Exceptions/Exception.hpp" #include "Exceptions/FileNotFoundException.hpp" #include "Exceptions/HasParentException.hpp" #include "Exceptions/RuntimeException.hpp" #include "Foundation/Containers/Array.hpp" #include "Foundation/Containers/Map.hpp" #include "Foundation/Containers/PriorityQueue.hpp" #include "Foundation/Containers/Queue.hpp" #include "Foundation/Containers/Stack.hpp" #include "Foundation/FilePath.hpp" #include "Foundation/Log.hpp" #include "Foundation/Macros.hpp" #include "Foundation/Memory.hpp" #include "Foundation/NamedObject.hpp" #include "Foundation/ObjectFactory.hpp" #include "Foundation/Policies/ThreadingPolicy.hpp" #include "Foundation/Profiler.hpp" #include "Foundation/SharedObject.hpp" #include "Foundation/Singleton.hpp" #include "Foundation/StringUtils.hpp" #include "Foundation/Version.hpp" #include "Loaders/OBJLoader.hpp" #include "Mathematics/Clock.hpp" #include "Mathematics/ColorRGB.hpp" #include "Mathematics/ColorRGBA.hpp" #include "Mathematics/ColorRGBAOps.hpp" #include "Mathematics/ColorRGBOps.hpp" #include "Mathematics/Frustum.hpp" #include "Mathematics/Interpolation.hpp" #include "Mathematics/Intersection.hpp" #include "Mathematics/Matrix3.hpp" #include "Mathematics/Matrix3_equality.hpp" #include "Mathematics/Matrix4.hpp" #include "Mathematics/Matrix4_equality.hpp" #include "Mathematics/Numeric.hpp" #include "Mathematics/Plane3.hpp" #include "Mathematics/Quaternion.hpp" #include "Mathematics/Random.hpp" #include "Mathematics/Ray3.hpp" #include "Mathematics/Rect.hpp" #include "Mathematics/Root.hpp" #include "Mathematics/Series.hpp" #include "Mathematics/Sphere.hpp" #include "Mathematics/Transformation.hpp" #include "Mathematics/Transformation_apply.hpp" #include "Mathematics/Transformation_inverse.hpp" #include "Mathematics/Transformation_lookAt.hpp" #include "Mathematics/Transformation_operators.hpp" #include "Mathematics/Transformation_rotation.hpp" #include "Mathematics/Transformation_scale.hpp" #include "Mathematics/Transformation_translation.hpp" #include "Mathematics/Vector2.hpp" #include "Mathematics/Vector2Ops.hpp" #include "Mathematics/Vector3.hpp" #include "Mathematics/Vector3Ops.hpp" #include "Mathematics/Vector4.hpp" #include "Mathematics/Vector_equality.hpp" #include "Mathematics/easing.hpp" #include "Mathematics/io.hpp" #include "Mathematics/ortho.hpp" #include "Mathematics/perspective.hpp" #include "Mathematics/trigonometry.hpp" #include "Messaging/MessageQueue.hpp" #include "Navigation/NavigationCell.hpp" #include "Navigation/NavigationCellEdge.hpp" #include "Navigation/NavigationController.hpp" #include "Navigation/NavigationMesh.hpp" #include "Navigation/NavigationMeshContainer.hpp" #include "Navigation/NavigationMeshOBJ.hpp" #include "ParticleSystem/Generators/AccelerationParticleGenerator.hpp" #include "ParticleSystem/Generators/BoxPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/ColorParticleGenerator.hpp" #include "ParticleSystem/Generators/DefaultValueParticleGenerator.hpp" #include "ParticleSystem/Generators/EulerAnglesParticleGenerator.hpp" #include "ParticleSystem/Generators/GridPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/NodePositionParticleGenerator.hpp" #include "ParticleSystem/Generators/OrbitPositionParticleGenerator.hpp" #include "ParticleSystem/Generators/RandomValueParticleGenerator.hpp" #include "ParticleSystem/Generators/SpherePositionParticleGenerator.hpp" #include "ParticleSystem/Generators/SphereVelocityParticleGenerator.hpp" #include "ParticleSystem/Generators/TimeParticleGenerator.hpp" #include "ParticleSystem/Generators/UniformScaleParticleGenerator.hpp" #include "ParticleSystem/Generators/VelocityParticleGenerator.hpp" #include "ParticleSystem/ParticleData.hpp" #include "ParticleSystem/ParticleSystemComponent.hpp" #include "ParticleSystem/Renderers/AnimatedSpriteParticleRenderer.hpp" #include "ParticleSystem/Renderers/InstancedParticleRenderer.hpp" #include "ParticleSystem/Renderers/NodeParticleRenderer.hpp" #include "ParticleSystem/Renderers/OrientedQuadParticleRenderer.hpp" #include "ParticleSystem/Renderers/PointSpriteParticleRenderer.hpp" #include "ParticleSystem/Updaters/AttractorParticleUpdater.hpp" #include "ParticleSystem/Updaters/CameraSortParticleUpdater.hpp" #include "ParticleSystem/Updaters/ColorParticleUpdater.hpp" #include "ParticleSystem/Updaters/EulerParticleUpdater.hpp" #include "ParticleSystem/Updaters/FloorParticleUpdater.hpp" #include "ParticleSystem/Updaters/PositionVelocityParticleUpdater.hpp" #include "ParticleSystem/Updaters/SetAttribValueParticleUpdater.hpp" #include "ParticleSystem/Updaters/TimeParticleUpdater.hpp" #include "ParticleSystem/Updaters/UniformScaleParticleUpdater.hpp" #include "ParticleSystem/Updaters/ZSortParticleUpdater.hpp" #include "Primitives/ArcPrimitive.hpp" #include "Primitives/ArrowPrimitive.hpp" #include "Primitives/BoxPrimitive.hpp" #include "Primitives/ConePrimitive.hpp" #include "Primitives/CylinderPrimitive.hpp" #include "Primitives/KleinBottlePrimitive.hpp" #include "Primitives/MobiusStripPrimitive.hpp" #include "Primitives/NewellTeapotPrimitive.hpp" #include "Primitives/ParametricPrimitive.hpp" #include "Primitives/ParametricSpherePrimitive.hpp" #include "Primitives/Primitive.hpp" #include "Primitives/QuadPrimitive.hpp" #include "Primitives/SpherePrimitive.hpp" #include "Primitives/TorusPrimitive.hpp" #include "Primitives/TrefoilKnotPrimitive.hpp" #include "Rendering/Buffer.hpp" #include "Rendering/Catalog.hpp" #include "Rendering/ColorMaskState.hpp" #include "Rendering/CommandBuffer.hpp" #include "Rendering/ComputePass.hpp" #include "Rendering/DescriptorSet.hpp" #include "Rendering/Font.hpp" #include "Rendering/Image.hpp" #include "Rendering/ImageManager.hpp" #include "Rendering/ImageTGA.hpp" #include "Rendering/IndexBuffer.hpp" #include "Rendering/Material.hpp" #include "Rendering/Materials/LitMaterial.hpp" #include "Rendering/Materials/PrincipledBSDFMaterial.hpp" #include "Rendering/Materials/SkyboxMaterial.hpp" #include "Rendering/Materials/UnlitMaterial.hpp" #include "Rendering/Operations/OperationUtils.hpp" #include "Rendering/Operations/Operations.hpp" #include "Rendering/Operations/Operations_softRT.hpp" #include "Rendering/Pipeline.hpp" #include "Rendering/Programs/UnlitShaderProgram.hpp" #include "Rendering/RenderPass.hpp" #include "Rendering/RenderResource.hpp" #include "Rendering/RenderState.hpp" #include "Rendering/Renderer.hpp" #include "Rendering/Sampler.hpp" #include "Rendering/Shader.hpp" #include "Rendering/ShaderLibrary.hpp" #include "Rendering/ShaderLocation.hpp" #include "Rendering/ShaderProgram.hpp" #include "Rendering/ShaderProgramLibrary.hpp" #include "Rendering/ShaderUniform.hpp" #include "Rendering/ShaderUniformImpl.hpp" #include "Rendering/ShadowMap.hpp" #include "Rendering/SkinnedMesh.hpp" #include "Rendering/Swapchain.hpp" #include "Rendering/Texture.hpp" #include "Rendering/UniformBuffer.hpp" #include "Rendering/Uniforms/CallbackUniformBuffer.hpp" #include "Rendering/Uniforms/CameraViewProjectionUniformBuffer.hpp" #include "Rendering/Uniforms/LightingUniform.hpp" #include "Rendering/Uniforms/ModelUniformBuffer.hpp" #include "Rendering/Uniforms/ModelViewProjectionUniformBuffer.hpp" #include "Rendering/VertexBuffer.hpp" #include "SceneGraph/Camera.hpp" #include "SceneGraph/Geometry.hpp" #include "SceneGraph/Group.hpp" #include "SceneGraph/Light.hpp" #include "SceneGraph/Node.hpp" #include "SceneGraph/Skybox.hpp" #include "SceneGraph/Switch.hpp" #include "SceneGraph/Text.hpp" #include "Simulation/Console/Console.hpp" #include "Simulation/FileSystem.hpp" #include "Simulation/Input.hpp" #include "Simulation/Simulation.hpp" #include "Simulation/Systems/AudioSystem.hpp" #include "Simulation/Systems/DebugSystem.hpp" #include "Simulation/Systems/RenderSystem.hpp" #include "Simulation/Systems/StreamingSystem.hpp" #include "Simulation/Systems/UISystem.hpp" #include "Simulation/Systems/UpdateSystem.hpp" #include "UI/UIBackground.hpp" #include "UI/UIButton.hpp" #include "UI/UICanvas.hpp" #include "UI/UIFrame.hpp" #include "UI/UIFrameConstraint.hpp" #include "UI/UIFrameConstraintMaker.hpp" #include "UI/UILabel.hpp" #include "Visitors/Apply.hpp" #include "Visitors/ApplyToGeometries.hpp" #include "Visitors/ComputeRenderQueue.hpp" #include "Visitors/FetchCameras.hpp" #include "Visitors/FetchLights.hpp" #include "Visitors/NodeVisitor.hpp" #include "Visitors/Picking.hpp" #include "Visitors/SelectNodes.hpp" #include "Visitors/ShallowCopy.hpp" #include "Visitors/StartComponents.hpp" #include "Visitors/UpdateComponents.hpp" #include "Visitors/UpdateRenderState.hpp" #include "Visitors/UpdateWorldState.hpp" namespace crimild { void init( void ); } #endif <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/Devices/DriverConfig.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/joystick.h> // Get the joystick abilities #include <vpr/Util/Debug.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Type/DeviceConstructor.h> #include <gadget/Util/Debug.h> #include <gadget/gadgetParam.h> #include <drivers/Open/LinuxJoydev/LinuxJoydev.h> extern "C" { GADGET_DRIVER_EXPORT(vpr::Uint32) getGadgeteerVersion() { return __GADGET_version; } GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr) { new gadget::DeviceConstructor<gadget::LinuxJoydev>(inputMgr); } } namespace gadget { // Constructor. LinuxJoydev::LinuxJoydev() { /* Do nothing. */ ; } // Destructor. LinuxJoydev::~LinuxJoydev() throw () { /* Do nothing. */ ; } std::string LinuxJoydev::getElementType() { return "linux_joydev"; } bool LinuxJoydev::config(jccl::ConfigElementPtr e) { if(! (Input::config(e) && Digital::config(e) && Analog::config(e))) { return false; } // The joydev driver returns axis values in the range [-32767, 32767]. // Hence, we ignore whatever the user provided through the config element. setMin(-32767.0f); setMax(32767.0f); mJsLabel = e->getName(); mPortName = e->getProperty<std::string>("port_name"); unsigned int num_axis_buttons = e->getNum("axis_buttons"); for ( unsigned int i = 0; i < num_axis_buttons; ++i ) { unsigned int idx = e->getProperty<unsigned int>("axis_buttons", i); mAxisButtonIndices.push_back(idx); } return true; } // Begins sampling. Connects to the joystick and prepares to read. bool LinuxJoydev::startSampling() { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "Opening Linux Joystick driver on port: " << mPortName << std::endl << vprDEBUG_FLUSH; // Open the joystick non-blocking. mJsFD = open(mPortName.c_str(), O_RDONLY | O_NONBLOCK); if(mJsFD < 0) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Failed to open Linux Joystick: " << mPortName << std::endl << vprDEBUG_FLUSH; return false; } // Read in the settings int version; unsigned char num_axes, num_buttons; char js_name[255]; ioctl(mJsFD, JSIOCGVERSION, &version); const unsigned int version_major(version >> 16); const unsigned int version_minor((version >> 8) & 0xff); const unsigned int version_patch(version & 0xff); char version_str[256]; snprintf(version_str, sizeof(version_str), "%d.%d.%d", version_major, version_minor, version_patch); // Verify that the version is new enough. if ( version_major < 1 ) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Linux Joystick API Version is too old. The LinuxJoydev " << "driver requires version 1.0 or greater, but found version " << version_str << std::endl << vprDEBUG_FLUSH; return false; } ioctl(mJsFD, JSIOCGAXES, &num_axes); ioctl(mJsFD, JSIOCGBUTTONS, &num_buttons); mNumAxes = num_axes; mNumButtons = num_buttons; // Get joystick name if ( ioctl(mJsFD, JSIOCGNAME(sizeof(js_name)), js_name) < 0 ) { mPhysicalJsName = std::string("Unknown"); } else { mPhysicalJsName = js_name; } // Output joystick description vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << " Joystick Label: " << mJsLabel << std::endl << " Joystick Name: " << mPhysicalJsName << std::endl << " Axes: " << mNumAxes << std::endl << " Buttons: " << mNumButtons << std::endl << " Driver version: " << version_str << std::endl << " Axis buttons: "; for ( unsigned int i = 0; i < mAxisButtonIndices.size(); ++i ) { vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << mAxisButtonIndices[i] << " "; } vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << std::endl << vprDEBUG_FLUSH; // Allocate initial device data // - By default this will clear them out mCurAxes.resize(mNumAxes); mCurAxesRanges.resize(mNumAxes, axis_range_t(getMin(), getMax())); mCurButtons.resize(mNumButtons + mAxisButtonIndices.size()); // Setup axis as button stuff mAxisToButtonIndexLookup.clear(); mAxisToButtonIndexLookup.resize(mNumAxes, -1); // Default to -1, meaning no axis button for ( unsigned int i = 0; i < mAxisButtonIndices.size(); ++i ) // For each configured axis index { unsigned int virtual_btn_index = (mNumButtons + i); // Index of the virtual button from the axis vprASSERT(virtual_btn_index < mCurButtons.size() && "Virtual button index out of range"); unsigned int axis_index = mAxisButtonIndices[i]; // Index of the axis we are mapping mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); // Setup the mapping } return true; } // Stops sampling. Drops the connection to joystick and clears everything. bool LinuxJoydev::stopSampling() { if(mJsFD > 0) { close(mJsFD); // Close the joystick device } return true; } // Updates to the sampled data. void LinuxJoydev::updateData() { // -- Read in any new pending events js_event cur_event; // While events pending while (read(mJsFD, &cur_event, sizeof(struct js_event)) > 0) { if(cur_event.type & JS_EVENT_BUTTON) { //std::cout << "ljs: btn: " << unsigned(cur_event.number) << " val:" // << cur_event.value << std::endl; const unsigned int btn_number(cur_event.number); vprASSERT(btn_number < mCurButtons.size() && "Button out of range"); mCurButtons[btn_number] = cur_event.value; // Assign the new button value (0,1) mCurButtons[btn_number].setTime(); // Set timestamp to now } else if(cur_event.type & JS_EVENT_AXIS) { //std::cout << "ljs: axis: " << unsigned(cur_event.number) << " val:" // << cur_event.value << std::endl; const unsigned int axis_number(cur_event.number); vprASSERT(axis_number < mCurAxes.size() && "Axis out of range"); vprASSERT(axis_number < mCurAxesRanges.size() && "Axis out of range"); float norm_value(0.0f); normalizeMinToMax(cur_event.value, norm_value); mCurAxes[axis_number] = norm_value; mCurAxes[axis_number].setTime(); // Check for axis buttons // - If we have a mapping // - If axis is gt 0.5, then btn is down if(mAxisToButtonIndexLookup[axis_number] != -1) // If we map to a virtual button { unsigned vir_btn_index = mAxisToButtonIndexLookup[axis_number]; vprASSERT(vir_btn_index < mCurButtons.size() && "Virtual button index out of range"); mCurButtons[vir_btn_index] = ( (norm_value > 0.5f) ? 1 : 0); mCurButtons[vir_btn_index].setTime(); } } } // Check to make sure error was just no-pending events if(errno != EAGAIN) { vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << "ERROR: Error reading linux joystick.\n" << vprDEBUG_FLUSH; return; } addDigitalSample(mCurButtons); swapDigitalBuffers(); addAnalogSample(mCurAxes); swapAnalogBuffers(); } } // End of gadget namespace <commit_msg>Bug fixed: Axis buttons now provide two digital data sources: one for the axis' low value and one for its high value. Prior to this change, only one digital data source per analog axis was available.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2005 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/Devices/DriverConfig.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <sys/ioctl.h> #include <fcntl.h> #include <linux/joystick.h> // Get the joystick abilities #include <vpr/Util/Debug.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Type/DeviceConstructor.h> #include <gadget/Util/Debug.h> #include <gadget/gadgetParam.h> #include <drivers/Open/LinuxJoydev/LinuxJoydev.h> extern "C" { GADGET_DRIVER_EXPORT(vpr::Uint32) getGadgeteerVersion() { return __GADGET_version; } GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr) { new gadget::DeviceConstructor<gadget::LinuxJoydev>(inputMgr); } } namespace gadget { // Constructor. LinuxJoydev::LinuxJoydev() { /* Do nothing. */ ; } // Destructor. LinuxJoydev::~LinuxJoydev() throw () { /* Do nothing. */ ; } std::string LinuxJoydev::getElementType() { return "linux_joydev"; } bool LinuxJoydev::config(jccl::ConfigElementPtr e) { if(! (Input::config(e) && Digital::config(e) && Analog::config(e))) { return false; } // The joydev driver returns axis values in the range [-32767, 32767]. // Hence, we ignore whatever the user provided through the config element. setMin(-32767.0f); setMax(32767.0f); mJsLabel = e->getName(); mPortName = e->getProperty<std::string>("port_name"); unsigned int num_axis_buttons = e->getNum("axis_buttons"); for ( unsigned int i = 0; i < num_axis_buttons; ++i ) { unsigned int idx = e->getProperty<unsigned int>("axis_buttons", i); mAxisButtonIndices.push_back(idx); } return true; } // Begins sampling. Connects to the joystick and prepares to read. bool LinuxJoydev::startSampling() { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL) << "Opening Linux Joystick driver on port: " << mPortName << std::endl << vprDEBUG_FLUSH; // Open the joystick non-blocking. mJsFD = open(mPortName.c_str(), O_RDONLY | O_NONBLOCK); if(mJsFD < 0) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Failed to open Linux Joystick: " << mPortName << std::endl << vprDEBUG_FLUSH; return false; } // Read in the settings int version; unsigned char num_axes, num_buttons; char js_name[255]; ioctl(mJsFD, JSIOCGVERSION, &version); const unsigned int version_major(version >> 16); const unsigned int version_minor((version >> 8) & 0xff); const unsigned int version_patch(version & 0xff); char version_str[256]; snprintf(version_str, sizeof(version_str), "%d.%d.%d", version_major, version_minor, version_patch); // Verify that the version is new enough. if ( version_major < 1 ) { vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL) << "ERROR: Linux Joystick API Version is too old. The LinuxJoydev " << "driver requires version 1.0 or greater, but found version " << version_str << std::endl << vprDEBUG_FLUSH; return false; } ioctl(mJsFD, JSIOCGAXES, &num_axes); ioctl(mJsFD, JSIOCGBUTTONS, &num_buttons); mNumAxes = num_axes; mNumButtons = num_buttons; // Get joystick name if ( ioctl(mJsFD, JSIOCGNAME(sizeof(js_name)), js_name) < 0 ) { mPhysicalJsName = std::string("Unknown"); } else { mPhysicalJsName = js_name; } // Output joystick description vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << " Joystick Label: " << mJsLabel << std::endl << " Joystick Name: " << mPhysicalJsName << std::endl << " Axes: " << mNumAxes << std::endl << " Buttons: " << mNumButtons << std::endl << " Driver version: " << version_str << std::endl << " Axis buttons: "; for ( unsigned int i = 0; i < mAxisButtonIndices.size(); ++i ) { vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << mAxisButtonIndices[i] << " "; } vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL) << std::endl << vprDEBUG_FLUSH; // Allocate initial device data // - By default this will clear them out mCurAxes.resize(mNumAxes); mCurAxesRanges.resize(mNumAxes, axis_range_t(getMin(), getMax())); // We use double the number of axis button indices because each axis has // to map to two buttons (high and low). mCurButtons.resize(mNumButtons + mAxisButtonIndices.size() * 2); // Setup axis as button stuff mAxisToButtonIndexLookup.clear(); mAxisToButtonIndexLookup.resize(mNumAxes, -1); // Default to -1, meaning no axis button for ( unsigned int i = 0; i < mAxisButtonIndices.size(); ++i ) // For each configured axis index { // Define the index of the virtual button from the axis. Each axis // provides two virtual buttons: one for its low value and one for its // high value. These virtual buttons are paired up in the digital // sample buffers as [low0, high0, low1, high1, ..., lowN, highN] for // axes 0 through N. const unsigned int virtual_btn_index = mNumButtons + i * 2; vprASSERT(virtual_btn_index < mCurButtons.size() && "Virtual button index out of range"); unsigned int axis_index = mAxisButtonIndices[i]; // Index of the axis we are mapping mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); // Setup the mapping } return true; } // Stops sampling. Drops the connection to joystick and clears everything. bool LinuxJoydev::stopSampling() { if(mJsFD > 0) { close(mJsFD); // Close the joystick device } return true; } // Updates to the sampled data. void LinuxJoydev::updateData() { // -- Read in any new pending events js_event cur_event; // While events pending while (read(mJsFD, &cur_event, sizeof(struct js_event)) > 0) { if(cur_event.type & JS_EVENT_BUTTON) { //std::cout << "ljs: btn: " << unsigned(cur_event.number) << " val:" // << cur_event.value << std::endl; const unsigned int btn_number(cur_event.number); vprASSERT(btn_number < mCurButtons.size() && "Button out of range"); mCurButtons[btn_number] = cur_event.value; // Assign the new button value (0,1) mCurButtons[btn_number].setTime(); // Set timestamp to now } else if(cur_event.type & JS_EVENT_AXIS) { //std::cout << "ljs: axis: " << unsigned(cur_event.number) << " val:" // << cur_event.value << std::endl; const unsigned int axis_number(cur_event.number); vprASSERT(axis_number < mCurAxes.size() && "Axis out of range"); vprASSERT(axis_number < mCurAxesRanges.size() && "Axis out of range"); float norm_value(0.0f); normalizeMinToMax(cur_event.value, norm_value); mCurAxes[axis_number] = norm_value; mCurAxes[axis_number].setTime(); // Check for axis buttons. If we have a mapping for axis_number, // then we map the value of the analog axis to two buttons (high and // low). If the analog value is greater than 0.5, then we map the // high button to 1 and the low button to 0. If the analog value is // less than 0.5, then we map the high button to 0 and the low button // to 0. Otherwise, both buttons are 0. if ( mAxisToButtonIndexLookup[axis_number] != -1 ) // If we map to a virtual button { const unsigned int low_btn_index = mAxisToButtonIndexLookup[axis_number]; const unsigned int high_btn_index = low_btn_index + 1; vprASSERT(high_btn_index < mCurButtons.size() && "Virtual high button index out of range"); vprASSERT(low_btn_index < mCurButtons.size() && "Virtual low button index out of range"); // Record the high button as pressed and the low button as not // pressed. if ( norm_value > 0.5f ) { mCurButtons[low_btn_index] = 0; mCurButtons[high_btn_index] = 1; } // Record the high button as not pressed and the low button as // pressed. else if ( norm_value < 0.5f ) { mCurButtons[low_btn_index] = 1; mCurButtons[high_btn_index] = 0; } // Record both buttons as not pressed. else { mCurButtons[low_btn_index] = 0; mCurButtons[high_btn_index] = 0; } mCurButtons[low_btn_index].setTime(); mCurButtons[high_btn_index].setTime(); } } } // Check to make sure error was just no-pending events if(errno != EAGAIN) { vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << "ERROR: Error reading linux joystick.\n" << vprDEBUG_FLUSH; return; } addDigitalSample(mCurButtons); swapDigitalBuffers(); addAnalogSample(mCurAxes); swapAnalogBuffers(); } } // End of gadget namespace <|endoftext|>
<commit_before>#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QComboBox> #include <QApplication> #include <qmath.h> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); amount->setSingleStep(0.001); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); qApp->sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } <commit_msg>Removed restricting stretching of nebls units as it doesn't necessarily fit its combo box in high dpi screens.<commit_after>#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QComboBox> #include <QApplication> #include <qmath.h> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); amount->setSingleStep(0.001); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); // layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); qApp->sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); } <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <bh_component.hpp> #include <bh_extmethod.hpp> #include <bh_idmap.hpp> #include "kernel.hpp" #include "block.hpp" #include "instruction.hpp" #include "type.hpp" #include "store.hpp" using namespace bohrium; using namespace component; using namespace std; namespace { class Impl : public ComponentImpl { private: Store _store; map<bh_opcode, extmethod::ExtmethodFace> extmethods; public: Impl(int stack_level) : ComponentImpl(stack_level), _store(config) {} ~Impl() {}; // NB: a destructor implementation must exist void execute(bh_ir *bhir); void extmethod(const string &name, bh_opcode opcode) { // ExtmethodFace does not have a default or copy constructor thus // we have to use its move constructor. extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name))); } }; } extern "C" ComponentImpl* create(int stack_level) { return new Impl(stack_level); } extern "C" void destroy(ComponentImpl* self) { delete self; } namespace { void spaces(stringstream &out, int num) { for (int i = 0; i < num; ++i) { out << " "; } } } void write_block(const IdMap<bh_base*> &base_ids, const Block &block, stringstream &out) { if (block.isInstr()) { if (block._instr != NULL) { spaces(out, 4 + block.rank*4); write_instr(base_ids, *block._instr, out); } } else { spaces(out, 4 + block.rank*4); // If this block is sweeped, we will "peel" the for-loop such that the // sweep instruction is replaced with BH_IDENTITY in the first iteration if (block._sweeps.size() > 0) { Block peeled_block(block); vector<bh_instruction> sweep_instr_list(block._sweeps.size()); { size_t i = 0; for (const bh_instruction *instr: block._sweeps) { Block *sweep_instr_block = peeled_block.findInstrBlock(instr); assert(sweep_instr_block != NULL); bh_instruction *sweep_instr = &sweep_instr_list[i++]; sweep_instr->opcode = BH_IDENTITY; sweep_instr->operand[1] = instr->operand[1]; // The input is the same as in the sweep sweep_instr->operand[0] = instr->operand[0]; // But the output needs an extra dimension when we are reducing to a non-scalar if (bh_opcode_is_reduction(instr->opcode) and instr->operand[1].ndim > 1) { sweep_instr->operand[0].insert_dim(instr->constant.get_int64(), 1, 0); } sweep_instr_block->_instr = sweep_instr; } } string itername; {stringstream t; t << "i" << block.rank; itername = t.str();} out << "{ // Peeled loop, 1. iteration" << endl; spaces(out, 8 + block.rank*4); out << "uint64_t " << itername << " = 0;" << endl; for (const Block &b: peeled_block._block_list) { write_block(base_ids, b, out); } spaces(out, 4 + block.rank*4); out << "}" << endl; spaces(out, 4 + block.rank*4); } string itername; {stringstream t; t << "i" << block.rank; itername = t.str();} out << "for(uint64_t " << itername; if (block._sweeps.size() > 0) // If the for-loop has been peeled, we should that at 1 out << "=1; "; else out << "=0; "; out << itername << " < " << block.size << "; ++" << itername << ") {" << endl; for (const Block &b: block._block_list) { write_block(base_ids, b, out); } spaces(out, 4 + block.rank*4); out << "}" << endl; } } vector<Block> fuser_singleton(vector<bh_instruction> &instr_list) { set<bh_base*> bases; // Set of all known bases set<bh_base*> syncs; // Set of all sync'ed bases // Creates the block_list based on the instr_list vector<Block> block_list; for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) { int nop = bh_noperands(instr->opcode); if (nop == 0) continue; // Ignore noop instructions such as BH_NONE or BH_TALLY bh_base *created_array = NULL; // Is this instruction creating a new array? bh_base *destroyed_array = NULL;// Is this instruction destroying an array? // Add inputs to 'bases' for (int i=1; i<nop; ++i) { bh_view &v = instr->operand[i]; if (not bh_is_constant(&v)) { bases.insert(v.base); } } // Add output to 'bases' and check if 'instr' creates a new array { bh_view &v = instr->operand[0]; if (bases.find(v.base) == bases.end()) { // TODO: check if writing to whole array created_array = v.base; } bases.insert(v.base); } if (instr->opcode == BH_SYNC) { assert(nop == 1); syncs.insert(instr->operand[0].base); } else if (instr->opcode == BH_FREE) { assert(nop == 1); if (syncs.find(instr->operand[0].base) == syncs.end()) { // If the array is free'ed and not sync'ed, it can be destroyed destroyed_array = instr->operand[0].base; } } set<bh_base*> news, frees, tmps; if (created_array != NULL) news.insert(created_array); if (destroyed_array != NULL) frees.insert(destroyed_array); // Now that we have the news, frees, and tmps, we can create the single instruction block vector<bh_instruction*> single_instr = {&instr[0]}; block_list.push_back(create_nested_block(single_instr, 0, news, frees, tmps)); } return block_list; } // Check if 'a' and 'b' supports data-parallelism when merged static bool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b) { if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode)) return true; const int a_nop = bh_noperands(a->opcode); for(int i=0; i<a_nop; ++i) { if(not bh_view_disjoint(&b->operand[0], &a->operand[i]) && not bh_view_aligned(&b->operand[0], &a->operand[i])) return false; } const int b_nop = bh_noperands(b->opcode); for(int i=0; i<b_nop; ++i) { if(not bh_view_disjoint(&a->operand[0], &b->operand[i]) && not bh_view_aligned(&a->operand[0], &b->operand[i])) return false; } return true; } // Check if 'b1' and 'b2' supports data-parallelism when merged static bool data_parallel_compatible(const Block &b1, const Block &b2) { for (const bh_instruction *i1 : b1.getAllInstr()) { for (const bh_instruction *i2 : b2.getAllInstr()) { if (not data_parallel_compatible(i1, i2)) return false; } } return true; } // Check if 'b1' and 'b2' is fusible. static bool fusible(const Block &b1, const Block &b2) { if (not data_parallel_compatible(b1, b2)) return false; if (b1.rank != b2.rank or b1.size != b2.size) return false; if (b1._sweeps.size() > 0) return false; return true; } vector<Block> fuser_serial(vector<Block> &block_list) { vector<Block> ret; for (auto it = block_list.begin(); it != block_list.end(); ) { ret.push_back(*it); Block &cur = ret.back(); ++it; if (cur.isInstr()) { continue; // We should never fuse instruction blocks } for (; it != block_list.end(); ++it) { if ((not it->isInstr()) and fusible(cur, *it)) { cur.merge(*it); } else { break; } } // Let's fuse at the next rank level cur._block_list = fuser_serial(cur._block_list); } return ret; } vector<Block> remove_empty_blocks(vector<Block> &block_list) { vector<Block> ret; for (Block &b: block_list) { if (b.getAllInstr().size() > 0) ret.push_back(b); } return ret; } void Impl::execute(bh_ir *bhir) { // Assign IDs to all base arrays IdMap<bh_base *> base_ids; // NB: by assigning the IDs in the order they appear in the 'instr_list', // the kernels can better be reused for(const bh_instruction &instr: bhir->instr_list) { const int nop = bh_noperands(instr.opcode); for(int i=0; i<nop; ++i) { const bh_view &v = instr.operand[i]; if (not bh_is_constant(&v)) { base_ids.insert(v.base); } } } // Do we have anything to do? if (base_ids.size() == 0) return; //Let's create a kernel Kernel kernel; { // Let's fuse the 'instr_list' into blocks kernel.block_list = fuser_singleton(bhir->instr_list); kernel.block_list = fuser_serial(kernel.block_list); kernel.block_list = remove_empty_blocks(kernel.block_list); // And fill kernel attributes for (bh_instruction &instr: bhir->instr_list) { if (instr.opcode == BH_RANDOM) { kernel.useRandom = true; } else if (instr.opcode == BH_FREE) { kernel.frees.insert(instr.operand[0].base); } } } // Do we even have any "real" operations to perform? if (kernel.block_list.size() == 0) { // Finally, let's cleanup for(bh_base *base: kernel.frees) { bh_data_free(base); } return; } // Debug print //cout << kernel.block_list; // Code generation stringstream ss; // Make sure all arrays are allocated for(bh_base *base: base_ids.getKeys()) { bh_data_malloc(base); } // Write the need includes ss << "#include <stdint.h>" << endl; ss << "#include <stdlib.h>" << endl; ss << "#include <stdbool.h>" << endl; ss << "#include <complex.h>" << endl; ss << "#include <tgmath.h>" << endl; ss << "#include <math.h>" << endl; ss << "#include <bh_memory.h>" << endl; ss << "#include <bh_type.h>" << endl; ss << endl; if (kernel.useRandom) { // Write the random function ss << "#include <Random123/philox.h>" << endl; ss << "uint64_t random123(uint64_t start, uint64_t key, uint64_t index) {" << endl; ss << " union {philox2x32_ctr_t c; uint64_t ul;} ctr, res; " << endl; ss << " ctr.ul = start + index; " << endl; ss << " res.c = philox2x32(ctr.c, (philox2x32_key_t){{key}}); " << endl; ss << " return res.ul; " << endl; ss << "} " << endl; } ss << endl; // Write the header of the execute function ss << "void execute("; for(size_t id=0; id < base_ids.size(); ++id) { const bh_base *b = base_ids.getKeys()[id]; ss << write_type(b->type) << " a" << id << "[]"; if (id+1 < base_ids.size()) { ss << ", "; } } ss << ") {" << endl; // Write the blocks that makes up the body of 'execute()' for(const Block &block: kernel.block_list) { write_block(base_ids, block, ss); } ss << "}" << endl << endl; // Write the launcher function, which will convert the data_list of void pointers // to typed arrays and call the execute function { ss << "void launcher(void* data_list[]) {" << endl; size_t i=0; for (bh_base *b: base_ids.getKeys()) { spaces(ss, 4); ss << write_type(b->type) << " *a" << base_ids[b]; ss << " = data_list[" << i << "];" << endl; ++i; } spaces(ss, 4); ss << "execute("; for(size_t id=0; id < base_ids.size(); ++id) { ss << "a" << id; if (id+1 < base_ids.size()) { ss << ", "; } } ss << ");" << endl; ss << "}" << endl; } // cout << ss.str(); KernelFunction func = _store.getFunction(ss.str()); assert(func != NULL); // Create a 'data_list' of data pointers vector<void*> data_list; data_list.reserve(base_ids.size()); for(bh_base *base: base_ids.getKeys()) { assert(base->data != NULL); data_list.push_back(base->data); } // Call the launcher function with the 'data_list', which will execute the kernel func(&data_list[0]); // Finally, let's cleanup for(bh_base *base: kernel.frees) { bh_data_free(base); } } <commit_msg>uni: cleanup<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <bh_component.hpp> #include <bh_extmethod.hpp> #include <bh_idmap.hpp> #include "kernel.hpp" #include "block.hpp" #include "instruction.hpp" #include "type.hpp" #include "store.hpp" using namespace bohrium; using namespace component; using namespace std; namespace { class Impl : public ComponentImpl { private: Store _store; map<bh_opcode, extmethod::ExtmethodFace> extmethods; public: Impl(int stack_level) : ComponentImpl(stack_level), _store(config) {} ~Impl() {}; // NB: a destructor implementation must exist void execute(bh_ir *bhir); void extmethod(const string &name, bh_opcode opcode) { // ExtmethodFace does not have a default or copy constructor thus // we have to use its move constructor. extmethods.insert(make_pair(opcode, extmethod::ExtmethodFace(config, name))); } }; } extern "C" ComponentImpl* create(int stack_level) { return new Impl(stack_level); } extern "C" void destroy(ComponentImpl* self) { delete self; } namespace { void spaces(stringstream &out, int num) { for (int i = 0; i < num; ++i) { out << " "; } } } void write_block(const IdMap<bh_base*> &base_ids, const Block &block, stringstream &out) { if (block.isInstr()) { if (block._instr != NULL) { spaces(out, 4 + block.rank*4); write_instr(base_ids, *block._instr, out); } } else { spaces(out, 4 + block.rank*4); // If this block is sweeped, we will "peel" the for-loop such that the // sweep instruction is replaced with BH_IDENTITY in the first iteration if (block._sweeps.size() > 0) { Block peeled_block(block); vector<bh_instruction> sweep_instr_list(block._sweeps.size()); { size_t i = 0; for (const bh_instruction *instr: block._sweeps) { Block *sweep_instr_block = peeled_block.findInstrBlock(instr); assert(sweep_instr_block != NULL); bh_instruction *sweep_instr = &sweep_instr_list[i++]; sweep_instr->opcode = BH_IDENTITY; sweep_instr->operand[1] = instr->operand[1]; // The input is the same as in the sweep sweep_instr->operand[0] = instr->operand[0]; // But the output needs an extra dimension when we are reducing to a non-scalar if (bh_opcode_is_reduction(instr->opcode) and instr->operand[1].ndim > 1) { sweep_instr->operand[0].insert_dim(instr->constant.get_int64(), 1, 0); } sweep_instr_block->_instr = sweep_instr; } } string itername; {stringstream t; t << "i" << block.rank; itername = t.str();} out << "{ // Peeled loop, 1. iteration" << endl; spaces(out, 8 + block.rank*4); out << "uint64_t " << itername << " = 0;" << endl; for (const Block &b: peeled_block._block_list) { write_block(base_ids, b, out); } spaces(out, 4 + block.rank*4); out << "}" << endl; spaces(out, 4 + block.rank*4); } string itername; {stringstream t; t << "i" << block.rank; itername = t.str();} out << "for(uint64_t " << itername; if (block._sweeps.size() > 0) // If the for-loop has been peeled, we should that at 1 out << "=1; "; else out << "=0; "; out << itername << " < " << block.size << "; ++" << itername << ") {" << endl; for (const Block &b: block._block_list) { write_block(base_ids, b, out); } spaces(out, 4 + block.rank*4); out << "}" << endl; } } vector<Block> fuser_singleton(vector<bh_instruction> &instr_list) { set<bh_base*> bases; // Set of all known bases set<bh_base*> syncs; // Set of all sync'ed bases // Creates the block_list based on the instr_list vector<Block> block_list; for (auto instr=instr_list.begin(); instr != instr_list.end(); ++instr) { int nop = bh_noperands(instr->opcode); if (nop == 0) continue; // Ignore noop instructions such as BH_NONE or BH_TALLY bh_base *created_array = NULL; // Is this instruction creating a new array? bh_base *destroyed_array = NULL;// Is this instruction destroying an array? // Add inputs to 'bases' for (int i=1; i<nop; ++i) { bh_view &v = instr->operand[i]; if (not bh_is_constant(&v)) { bases.insert(v.base); } } // Add output to 'bases' and check if 'instr' creates a new array { bh_view &v = instr->operand[0]; if (bases.find(v.base) == bases.end()) { // TODO: check if writing to whole array created_array = v.base; } bases.insert(v.base); } if (instr->opcode == BH_SYNC) { assert(nop == 1); syncs.insert(instr->operand[0].base); } else if (instr->opcode == BH_FREE) { assert(nop == 1); if (syncs.find(instr->operand[0].base) == syncs.end()) { // If the array is free'ed and not sync'ed, it can be destroyed destroyed_array = instr->operand[0].base; } } set<bh_base*> news, frees, tmps; if (created_array != NULL) news.insert(created_array); if (destroyed_array != NULL) frees.insert(destroyed_array); // Now that we have the news, frees, and tmps, we can create the single instruction block vector<bh_instruction*> single_instr = {&instr[0]}; block_list.push_back(create_nested_block(single_instr, 0, news, frees, tmps)); } return block_list; } // Check if 'a' and 'b' supports data-parallelism when merged static bool data_parallel_compatible(const bh_instruction *a, const bh_instruction *b) { if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode)) return true; const int a_nop = bh_noperands(a->opcode); for(int i=0; i<a_nop; ++i) { if(not bh_view_disjoint(&b->operand[0], &a->operand[i]) && not bh_view_aligned(&b->operand[0], &a->operand[i])) return false; } const int b_nop = bh_noperands(b->opcode); for(int i=0; i<b_nop; ++i) { if(not bh_view_disjoint(&a->operand[0], &b->operand[i]) && not bh_view_aligned(&a->operand[0], &b->operand[i])) return false; } return true; } // Check if 'b1' and 'b2' supports data-parallelism when merged static bool data_parallel_compatible(const Block &b1, const Block &b2) { for (const bh_instruction *i1 : b1.getAllInstr()) { for (const bh_instruction *i2 : b2.getAllInstr()) { if (not data_parallel_compatible(i1, i2)) return false; } } return true; } vector<Block> fuser_serial(vector<Block> &block_list) { vector<Block> ret; for (auto it = block_list.begin(); it != block_list.end(); ) { ret.push_back(*it); Block &cur = ret.back(); ++it; if (cur.isInstr()) { continue; // We should never fuse instruction blocks } for (; it != block_list.end(); ++it) { // We start with general checks of fusibility if (it->isInstr()) break; if (not data_parallel_compatible(cur, *it)) break; if (cur._sweeps.size() > 0) //TODO: support merge of reduction break; assert(cur.rank == it->rank); // And then we check for shape match if (cur.size == it->size) { // Perfect match, directly mergeable cur.merge(*it); } else { break; // We couldn't find any shape match } } // Let's fuse at the next rank level cur._block_list = fuser_serial(cur._block_list); } return ret; } vector<Block> remove_empty_blocks(vector<Block> &block_list) { vector<Block> ret; for (Block &b: block_list) { if (b.getAllInstr().size() > 0) ret.push_back(b); } return ret; } void Impl::execute(bh_ir *bhir) { // Assign IDs to all base arrays IdMap<bh_base *> base_ids; // NB: by assigning the IDs in the order they appear in the 'instr_list', // the kernels can better be reused for(const bh_instruction &instr: bhir->instr_list) { const int nop = bh_noperands(instr.opcode); for(int i=0; i<nop; ++i) { const bh_view &v = instr.operand[i]; if (not bh_is_constant(&v)) { base_ids.insert(v.base); } } } // Do we have anything to do? if (base_ids.size() == 0) return; //Let's create a kernel Kernel kernel; { // Let's fuse the 'instr_list' into blocks kernel.block_list = fuser_singleton(bhir->instr_list); kernel.block_list = fuser_serial(kernel.block_list); kernel.block_list = remove_empty_blocks(kernel.block_list); // And fill kernel attributes for (bh_instruction &instr: bhir->instr_list) { if (instr.opcode == BH_RANDOM) { kernel.useRandom = true; } else if (instr.opcode == BH_FREE) { kernel.frees.insert(instr.operand[0].base); } } } // Do we even have any "real" operations to perform? if (kernel.block_list.size() == 0) { // Finally, let's cleanup for(bh_base *base: kernel.frees) { bh_data_free(base); } return; } // Debug print //cout << kernel.block_list; // Code generation stringstream ss; // Make sure all arrays are allocated for(bh_base *base: base_ids.getKeys()) { bh_data_malloc(base); } // Write the need includes ss << "#include <stdint.h>" << endl; ss << "#include <stdlib.h>" << endl; ss << "#include <stdbool.h>" << endl; ss << "#include <complex.h>" << endl; ss << "#include <tgmath.h>" << endl; ss << "#include <math.h>" << endl; ss << "#include <bh_memory.h>" << endl; ss << "#include <bh_type.h>" << endl; ss << endl; if (kernel.useRandom) { // Write the random function ss << "#include <Random123/philox.h>" << endl; ss << "uint64_t random123(uint64_t start, uint64_t key, uint64_t index) {" << endl; ss << " union {philox2x32_ctr_t c; uint64_t ul;} ctr, res; " << endl; ss << " ctr.ul = start + index; " << endl; ss << " res.c = philox2x32(ctr.c, (philox2x32_key_t){{key}}); " << endl; ss << " return res.ul; " << endl; ss << "} " << endl; } ss << endl; // Write the header of the execute function ss << "void execute("; for(size_t id=0; id < base_ids.size(); ++id) { const bh_base *b = base_ids.getKeys()[id]; ss << write_type(b->type) << " a" << id << "[]"; if (id+1 < base_ids.size()) { ss << ", "; } } ss << ") {" << endl; // Write the blocks that makes up the body of 'execute()' for(const Block &block: kernel.block_list) { write_block(base_ids, block, ss); } ss << "}" << endl << endl; // Write the launcher function, which will convert the data_list of void pointers // to typed arrays and call the execute function { ss << "void launcher(void* data_list[]) {" << endl; size_t i=0; for (bh_base *b: base_ids.getKeys()) { spaces(ss, 4); ss << write_type(b->type) << " *a" << base_ids[b]; ss << " = data_list[" << i << "];" << endl; ++i; } spaces(ss, 4); ss << "execute("; for(size_t id=0; id < base_ids.size(); ++id) { ss << "a" << id; if (id+1 < base_ids.size()) { ss << ", "; } } ss << ");" << endl; ss << "}" << endl; } // cout << ss.str(); KernelFunction func = _store.getFunction(ss.str()); assert(func != NULL); // Create a 'data_list' of data pointers vector<void*> data_list; data_list.reserve(base_ids.size()); for(bh_base *base: base_ids.getKeys()) { assert(base->data != NULL); data_list.push_back(base->data); } // Call the launcher function with the 'data_list', which will execute the kernel func(&data_list[0]); // Finally, let's cleanup for(bh_base *base: kernel.frees) { bh_data_free(base); } } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) // DP with rolling window. class Solution { public: /** * @param values: a vector of integers * @return: a boolean which equals to true if the first player will win */ bool firstWillWin(vector<int> &values) { // For boundary case. if (values.size() < 2) { return values.size() % 2 == 1; } vector<int> P(5, 0); int sum = 0; // P[i] = max(values[i] + min(P[i + 2], P[i + 3]), // values[i] + values[i + 1] + min(P[i + 3], P[i + 4])) for (int i = values.size() - 1; i >= 0; --i) { sum += values[i]; int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0; int a = i + 2 < values.size() ? P[(i + 2) % 5] : 0; int b = i + 3 < values.size() ? P[(i + 3) % 5] : 0; int c = i + 4 < values.size() ? P[(i + 4) % 5] : 0; P[i % 5] = max(values[i] + min(a, b), values[i] + values_i_plus_1 + min(b, c)); } return P[0] > sum - P[0]; } }; // Time: O(n) // Space: O(n) class Solution2 { public: /** * @param values: a vector of integers * @return: a boolean which equals to true if the first player will win */ bool firstWillWin(vector<int> &values) { // For boundary case. if (values.size() < 2) { return values.size() % 2 == 1; } vector<int> P(values.size(), 0); int sum = 0; // P[i] = max(values[i] + min(P[i + 2], P[i + 3]), // values[i] + values[i + 1] + min(P[i + 3], P[i + 4])) for (int i = values.size() - 1; i >= 0; --i) { sum += values[i]; int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0; int a = i + 2 < values.size() ? P[i + 2] : 0; int b = i + 3 < values.size() ? P[i + 3] : 0; int c = i + 4 < values.size() ? P[i + 4] : 0; P[i] = max(values[i] + min(a, b), values[i] + values_i_plus_1 + min(b, c)); } return P[0] > sum - P[0]; } }; <commit_msg>Update coins-in-a-line-ii.cpp<commit_after>// Time: O(n) // Space: O(1) // DP with rolling window. class Solution { public: /** * @param values: a vector of integers * @return: a boolean which equals to true if the first player will win */ bool firstWillWin(vector<int> &values) { // For boundary case. if (values.size() < 2) { return values.size() % 2 == 1; } vector<int> P(5, 0); int sum = 0; for (int i = values.size() - 1; i >= 0; --i) { sum += values[i]; int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0; int a = i + 2 < values.size() ? P[(i + 2) % 5] : 0; int b = i + 3 < values.size() ? P[(i + 3) % 5] : 0; int c = i + 4 < values.size() ? P[(i + 4) % 5] : 0; // P[i] = max(values[i] + min(P[i + 2], P[i + 3]), // values[i] + values[i + 1] + min(P[i + 3], P[i + 4])) P[i % 5] = max(values[i] + min(a, b), values[i] + values_i_plus_1 + min(b, c)); } return P[0] > sum - P[0]; } }; // Time: O(n) // Space: O(n) class Solution2 { public: /** * @param values: a vector of integers * @return: a boolean which equals to true if the first player will win */ bool firstWillWin(vector<int> &values) { // For boundary case. if (values.size() < 2) { return values.size() % 2 == 1; } vector<int> P(values.size(), 0); int sum = 0; for (int i = values.size() - 1; i >= 0; --i) { sum += values[i]; int values_i_plus_1 = i + 1 < values.size() ? values[i + 1]: 0; int a = i + 2 < values.size() ? P[i + 2] : 0; int b = i + 3 < values.size() ? P[i + 3] : 0; int c = i + 4 < values.size() ? P[i + 4] : 0; // P[i] = max(values[i] + min(P[i + 2], P[i + 3]), // values[i] + values[i + 1] + min(P[i + 3], P[i + 4])) P[i] = max(values[i] + min(a, b), values[i] + values_i_plus_1 + min(b, c)); } return P[0] > sum - P[0]; } }; <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/prediction/predictor/vehicle/lane_sequence_predictor.h" #include <cmath> #include <utility> #include <limits> #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::math::KalmanFilter; using ::apollo::common::adapter::AdapterConfig; void LaneSequencePredictor::Clear() { trajectories_.clear(); adc_lane_id_.clear(); adc_lane_s_ = 0.0; } void LaneSequencePredictor::Predict(Obstacle* obstacle) { Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); const Feature& feature = obstacle->latest_feature(); if (!feature.has_lane() || !feature.lane().has_lane_graph()) { AERROR << "Obstacle [" << obstacle->id() << " has no lane graph."; return; } std::string lane_id = ""; if (feature.lane().has_lane_feature()) { lane_id = feature.lane().lane_feature().lane_id(); } int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size(); std::vector<bool> enable_lane_sequence(num_lane_sequence, true); FilterLaneSequences(feature.lane().lane_graph(), lane_id, &enable_lane_sequence); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i); if (sequence.lane_segment_size() <= 0) { AERROR << "Empty lane segments."; continue; } if (!enable_lane_sequence[i]) { ADEBUG << "Lane sequence [" << ToString(sequence) << "] with probability [" <<sequence.probability() << "] is disqualified."; continue; } ADEBUG << "Obstacle [" << obstacle->id() << "] will draw a lane sequence trajectory [" << ToString(sequence) << "] with probability [" << sequence.probability() << "]."; std::string curr_lane_id = sequence.lane_segment(0).lane_id(); std::vector<TrajectoryPoint> points; DrawLaneSequenceTrajectoryPoints( obstacle->kf_lane_tracker(curr_lane_id), sequence, FLAGS_prediction_duration, FLAGS_prediction_freq, &points); Trajectory trajectory; GenerateTrajectory(points, &trajectory); trajectory.set_probability(sequence.probability()); trajectories_.push_back(std::move(trajectory)); } ADEBUG << "Obstacle [" << obstacle->id() << "] has total " << trajectories_.size() << " trajectories."; } void LaneSequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool> *enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<int> lane_change_type(num_lane_sequence, -1); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); // Get ADC status GetADC(); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // Get lane change type lane_change_type[i] = GetLaneChangeType(lane_id, sequence); double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 || (::apollo::common::math::DoubleCompare(probability, all.second) == 0 && lane_change_type[i] == 0)) { all.first = i; all.second = probability; } if (lane_change_type[i] > 0 && ::apollo::common::math::DoubleCompare(probability, change.second) > 0) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // The obstacle has interference with ADC within a small distance if (::apollo::common::math::DoubleCompare( GetLaneChangeDistanceWithADC(sequence), FLAGS_lane_change_dist) < 0) { (*enable_lane_sequence)[i] = false; continue; } double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare( probability, FLAGS_lane_sequence_threshold) < 0 && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (change.first >= 0 && change.first < num_lane_sequence && lane_change_type[i] > 0 && lane_change_type[i] != lane_change_type[change.first]) { (*enable_lane_sequence)[i] = false; } } } void LaneSequencePredictor::GetADC() { ObstaclesContainer *container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); if (container == nullptr) { AERROR << "Unavailable obstacle container"; return; } Obstacle *adc = container->GetObstacle(PoseContainer::ID); if (adc != nullptr) { const Feature& feature = adc->latest_feature(); if (feature.has_lane() && feature.lane().has_lane_feature()) { adc_lane_id_ = feature.lane().lane_feature().lane_id(); adc_lane_s_ = feature.lane().lane_feature().lane_s(); } if (feature.has_position()) { adc_position_[0] = feature.position().x(); adc_position_[1] = feature.position().y(); } } } int LaneSequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap *map = PredictionMap::instance(); std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return 0; } else { if (map->IsLeftNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 1; } else if (map->IsRightNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 2; } } return -1; } double LaneSequencePredictor::GetLaneChangeDistanceWithADC( const LaneSequence& lane_sequence) { if (adc_lane_id_.empty() || lane_sequence.lane_segment_size() <= 0) { return std::numeric_limits<double>::max(); } PredictionMap *map = PredictionMap::instance(); std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id(); double obstacle_lane_s = lane_sequence.lane_segment(0).start_s(); double lane_s = 0.0; double lane_l = 0.0; if (map->GetProjection(adc_position_, map->LaneById(obstacle_lane_id), &lane_s, &lane_l)) { return std::fabs(lane_s - obstacle_lane_s); } return std::numeric_limits<double>::max(); } void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints( const KalmanFilter<double, 4, 2, 0>& kf, const LaneSequence& sequence, double total_time, double freq, std::vector<TrajectoryPoint> *points) { PredictionMap *map = PredictionMap::instance(); Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate()); double lane_s = state(0, 0); double lane_l = state(1, 0); double lane_speed = state(2, 0); double lane_acc = state(3, 0); Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix()); transition(0, 2) = freq; transition(0, 3) = 0.5 * freq * freq; transition(2, 3) = freq; int lane_segment_index = 0; std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id(); for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) { Eigen::Vector2d point; double theta = M_PI; if (!map->SmoothPointFromLane(lane_id, lane_s, lane_l, &point, &theta)) { AERROR << "Unable to get smooth point from lane [" << lane_id << "] with s [" << lane_s << "] and l [" << lane_l << "]"; continue; } if (points->size() > 0) { PathPoint *prev_point = points->back().mutable_path_point(); double x_diff = point.x() - prev_point->x(); double y_diff = point.y() - prev_point->y(); if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 || ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) { theta = std::atan2(y_diff, x_diff); prev_point->set_theta(theta); } else { theta = prev_point->theta(); } } // add trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(point.x()); path_point.set_y(point.y()); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(lane_speed); trajectory_point.set_a(lane_acc); trajectory_point.set_relative_time(static_cast<double>(i) * freq); points->emplace_back(std::move(trajectory_point)); // update state if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) { AWARN << "Non-positive lane_speed tacked : " << lane_speed; lane_speed = 0.0; lane_acc = 0.0; transition(1, 1) = 1.0; } else if (::apollo::common::math::DoubleCompare( lane_speed, FLAGS_max_speed) >= 0) { lane_speed = FLAGS_max_speed; lane_acc = 0.0; } state(2, 0) = lane_speed; state(3, 0) = lane_acc; state = transition * state; if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) { state(0, 0) = lane_s; state(1, 0) = lane_l; state(2, 0) = 0.0; state(3, 0) = 0.0; transition(1, 1) = 1.0; } lane_s = state(0, 0); lane_l = state(1, 0); lane_speed = state(2, 0); lane_acc = state(3, 0); // find next lane id while (lane_s > map->LaneById(lane_id)->total_length() && lane_segment_index + 1 < sequence.lane_segment_size()) { lane_segment_index += 1; lane_s = lane_s - map->LaneById(lane_id)->total_length(); state(0, 0) = lane_s; lane_id = sequence.lane_segment(lane_segment_index).lane_id(); } } } std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } } // namespace prediction } // namespace apollo <commit_msg>Prediction: fixed a minor issue<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/prediction/predictor/vehicle/lane_sequence_predictor.h" #include <cmath> #include <utility> #include <limits> #include "modules/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/obstacles/obstacles_container.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::math::KalmanFilter; using ::apollo::common::adapter::AdapterConfig; void LaneSequencePredictor::Clear() { trajectories_.clear(); adc_lane_id_.clear(); adc_lane_s_ = 0.0; } void LaneSequencePredictor::Predict(Obstacle* obstacle) { Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); const Feature& feature = obstacle->latest_feature(); if (!feature.has_lane() || !feature.lane().has_lane_graph()) { AERROR << "Obstacle [" << obstacle->id() << " has no lane graph."; return; } std::string lane_id = ""; if (feature.lane().has_lane_feature()) { lane_id = feature.lane().lane_feature().lane_id(); } int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size(); std::vector<bool> enable_lane_sequence(num_lane_sequence, true); FilterLaneSequences(feature.lane().lane_graph(), lane_id, &enable_lane_sequence); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i); if (sequence.lane_segment_size() <= 0) { AERROR << "Empty lane segments."; continue; } if (!enable_lane_sequence[i]) { ADEBUG << "Lane sequence [" << ToString(sequence) << "] with probability [" <<sequence.probability() << "] is disqualified."; continue; } ADEBUG << "Obstacle [" << obstacle->id() << "] will draw a lane sequence trajectory [" << ToString(sequence) << "] with probability [" << sequence.probability() << "]."; std::string curr_lane_id = sequence.lane_segment(0).lane_id(); std::vector<TrajectoryPoint> points; DrawLaneSequenceTrajectoryPoints( obstacle->kf_lane_tracker(curr_lane_id), sequence, FLAGS_prediction_duration, FLAGS_prediction_freq, &points); Trajectory trajectory; GenerateTrajectory(points, &trajectory); trajectory.set_probability(sequence.probability()); trajectories_.push_back(std::move(trajectory)); } ADEBUG << "Obstacle [" << obstacle->id() << "] has total " << trajectories_.size() << " trajectories."; } void LaneSequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool> *enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<int> lane_change_type(num_lane_sequence, -1); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); // Get ADC status GetADC(); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // Get lane change type lane_change_type[i] = GetLaneChangeType(lane_id, sequence); double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 || (::apollo::common::math::DoubleCompare(probability, all.second) == 0 && lane_change_type[i] == 0)) { all.first = i; all.second = probability; } if (lane_change_type[i] > 0 && ::apollo::common::math::DoubleCompare(probability, change.second) > 0) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // The obstacle has interference with ADC within a small distance if (::apollo::common::math::DoubleCompare( GetLaneChangeDistanceWithADC(sequence), FLAGS_lane_change_dist) < 0) { (*enable_lane_sequence)[i] = false; continue; } double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare( probability, FLAGS_lane_sequence_threshold) < 0 && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (change.first >= 0 && change.first < num_lane_sequence && lane_change_type[i] > 0 && lane_change_type[i] != lane_change_type[change.first]) { (*enable_lane_sequence)[i] = false; } } } void LaneSequencePredictor::GetADC() { ObstaclesContainer *container = dynamic_cast<ObstaclesContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PERCEPTION_OBSTACLES)); if (container == nullptr) { AERROR << "Unavailable obstacle container"; return; } Obstacle *adc = container->GetObstacle(PoseContainer::ID); if (adc != nullptr) { const Feature& feature = adc->latest_feature(); if (feature.has_lane() && feature.lane().has_lane_feature()) { adc_lane_id_ = feature.lane().lane_feature().lane_id(); adc_lane_s_ = feature.lane().lane_feature().lane_s(); } if (feature.has_position()) { adc_position_[0] = feature.position().x(); adc_position_[1] = feature.position().y(); } } } int LaneSequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap *map = PredictionMap::instance(); std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return 0; } else { if (map->IsLeftNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 1; } else if (map->IsRightNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 2; } } return -1; } double LaneSequencePredictor::GetLaneChangeDistanceWithADC( const LaneSequence& lane_sequence) { if (adc_lane_id_.empty() || lane_sequence.lane_segment_size() <= 0) { return std::numeric_limits<double>::max(); } PredictionMap *map = PredictionMap::instance(); std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id(); double obstacle_lane_s = lane_sequence.lane_segment(0).start_s(); double lane_s = 0.0; double lane_l = 0.0; if (map->GetProjection(adc_position_, map->LaneById(obstacle_lane_id), &lane_s, &lane_l)) { return std::fabs(lane_s - obstacle_lane_s); } return std::numeric_limits<double>::max(); } void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints( const KalmanFilter<double, 4, 2, 0>& kf, const LaneSequence& sequence, double total_time, double freq, std::vector<TrajectoryPoint> *points) { PredictionMap *map = PredictionMap::instance(); Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate()); double lane_s = state(0, 0); double lane_l = state(1, 0); double lane_speed = state(2, 0); double lane_acc = state(3, 0); Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix()); transition(0, 2) = freq; transition(0, 3) = 0.5 * freq * freq; transition(2, 3) = freq; int lane_segment_index = 0; std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id(); for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) { Eigen::Vector2d point; double theta = M_PI; if (!map->SmoothPointFromLane(lane_id, lane_s, lane_l, &point, &theta)) { AERROR << "Unable to get smooth point from lane [" << lane_id << "] with s [" << lane_s << "] and l [" << lane_l << "]"; break; } if (points->size() > 0) { PathPoint *prev_point = points->back().mutable_path_point(); double x_diff = point.x() - prev_point->x(); double y_diff = point.y() - prev_point->y(); if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 || ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) { theta = std::atan2(y_diff, x_diff); prev_point->set_theta(theta); } else { theta = prev_point->theta(); } } // add trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(point.x()); path_point.set_y(point.y()); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(lane_speed); trajectory_point.set_a(lane_acc); trajectory_point.set_relative_time(static_cast<double>(i) * freq); points->emplace_back(std::move(trajectory_point)); // update state if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) { AWARN << "Non-positive lane_speed tacked : " << lane_speed; lane_speed = 0.0; lane_acc = 0.0; transition(1, 1) = 1.0; } else if (::apollo::common::math::DoubleCompare( lane_speed, FLAGS_max_speed) >= 0) { lane_speed = FLAGS_max_speed; lane_acc = 0.0; } state(2, 0) = lane_speed; state(3, 0) = lane_acc; state = transition * state; if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) { state(0, 0) = lane_s; state(1, 0) = lane_l; state(2, 0) = 0.0; state(3, 0) = 0.0; transition(1, 1) = 1.0; } lane_s = state(0, 0); lane_l = state(1, 0); lane_speed = state(2, 0); lane_acc = state(3, 0); // find next lane id while (lane_s > map->LaneById(lane_id)->total_length() && lane_segment_index + 1 < sequence.lane_segment_size()) { lane_segment_index += 1; lane_s = lane_s - map->LaneById(lane_id)->total_length(); state(0, 0) = lane_s; lane_id = sequence.lane_segment(lane_segment_index).lane_id(); } } } std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) { return false; } vector<int> m1(256, 0); vector<int> m2(256, 0); int n = s.size(); for (int i = 0; i < n; ++i) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; } }; <commit_msg>Update isomorphic-strings.cpp<commit_after>// Time: O(n) // Space: O(1) class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) { return false; } vector<int> s2t(256, 0), t2s(256, 0); for (int i = 0; i < s.length(); ++i) { if (s2t[s[i]] == 0 && t2s[t[i]] == 0) { s2t[s[i]] = t[i]; t2s[t[i]] = s[i]; } else if (s2t[s[i]] == 0 || s2t[s[i]] != t[i]) { // Contradict mapping. return false; } } return true; } }; <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "future.hh" #include "do_with.hh" #include "future-util.hh" #include <memory> #include <setjmp.h> #include <type_traits> /// \defgroup thread-module Seastar threads /// /// Seastar threads provide an execution environment where blocking /// is tolerated; you can issue I/O, and wait for it in the same function, /// rather then establishing a callback to be called with \ref future<>::then(). /// /// Seastar threads are not the same as operating system threads: /// - seastar threads are cooperative; they are never preempted except /// at blocking points (see below) /// - seastar threads always run on the same core they were launched on /// /// Like other seastar code, seastar threads may not issue blocking system calls. /// /// A seastar thread blocking point is any function that returns a \ref future<>. /// you block by calling \ref future<>::get(); this waits for the future to become /// available, and in the meanwhile, other seastar threads and seastar non-threaded /// code may execute. /// /// Example: /// \code /// seastar::thread th([] { /// sleep(5s).get(); // blocking point /// }); /// \endcode /// Seastar API namespace namespace seastar { /// \addtogroup thread-module /// @{ class thread; /// \cond internal class thread_context; namespace thread_impl { thread_context* get(); void switch_in(thread_context* to); void switch_out(thread_context* from); void init(); } extern thread_local jmp_buf g_unthreaded_context; // Internal class holding thread state. We can't hold this in // \c thread itself because \c thread is movable, and we want pointers // to this state to be captured. class thread_context { static constexpr size_t _stack_size = 128*1024; std::unique_ptr<char[]> _stack{new char[_stack_size]}; std::function<void ()> _func; jmp_buf _context; promise<> _done; bool _joined = false; private: static void s_main(unsigned int lo, unsigned int hi); void setup(); void main(); public: thread_context(std::function<void ()> func); void switch_in(); void switch_out(); friend class thread; friend void thread_impl::switch_in(thread_context*); friend void thread_impl::switch_out(thread_context*); }; /// \endcond /// \brief thread - stateful thread of execution /// /// Threads allow using seastar APIs in a blocking manner, /// by calling future::get() on a non-ready future. When /// this happens, the thread is put to sleep until the future /// becomes ready. class thread { std::unique_ptr<thread_context> _context; static thread_local thread* _current; public: /// \brief Constructs a \c thread object that does not represent a thread /// of execution. thread() = default; /// \brief Constructs a \c thread object that represents a thread of execution /// /// \param func Callable object to execute in thread. The callable is /// called immediately. template <typename Func> thread(Func func); /// \brief Moves a thread object. thread(thread&& x) noexcept = default; /// \brief Move-assigns a thread object. thread& operator=(thread&& x) noexcept = default; /// \brief Destroys a \c thread object. /// /// The thread must not represent a running thread of execution (see join()). ~thread() { assert(!_context || _context->_joined); } /// \brief Waits for thread execution to terminate. /// /// Waits for thread execution to terminate, and marks the thread object as not /// representing a running thread of execution. future<> join(); }; template <typename Func> inline thread::thread(Func func) : _context(std::make_unique<thread_context>(func)) { } inline future<> thread::join() { _context->_joined = true; return _context->_done.get_future(); } /// Executes a callable in a seastar thread. /// /// Runs a block of code in a threaded context, /// which allows it to block (using \ref future::get()). The /// result of the callable is returned as a future. /// /// \param func a callable to be executed in a thread /// \param args a parameter pack to be forwarded to \c func. /// \return whatever \c func returns, as a future. template <typename Func, typename... Args> inline futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>> async(Func&& func, Args&&... args) { using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>; struct work { Func func; std::tuple<Args...> args; promise<return_type> pr; thread th; }; return do_with(work{std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) { auto ret = w.pr.get_future(); w.th = thread([&w] { futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr)); }); return w.th.join().then([ret = std::move(ret)] () mutable { return std::move(ret); }); }); } /// @} } <commit_msg>thread: point out async() as an easy way to launch a thread<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "future.hh" #include "do_with.hh" #include "future-util.hh" #include <memory> #include <setjmp.h> #include <type_traits> /// \defgroup thread-module Seastar threads /// /// Seastar threads provide an execution environment where blocking /// is tolerated; you can issue I/O, and wait for it in the same function, /// rather then establishing a callback to be called with \ref future<>::then(). /// /// Seastar threads are not the same as operating system threads: /// - seastar threads are cooperative; they are never preempted except /// at blocking points (see below) /// - seastar threads always run on the same core they were launched on /// /// Like other seastar code, seastar threads may not issue blocking system calls. /// /// A seastar thread blocking point is any function that returns a \ref future<>. /// you block by calling \ref future<>::get(); this waits for the future to become /// available, and in the meanwhile, other seastar threads and seastar non-threaded /// code may execute. /// /// Example: /// \code /// seastar::thread th([] { /// sleep(5s).get(); // blocking point /// }); /// \endcode /// /// An easy way to launch a thread and carry out some computation, and return a /// result from this execution is by using the \ref seastar::async() function. /// The result is returned as a future, so that non-threaded code can wait for /// the thread to terminate and yield a result. /// Seastar API namespace namespace seastar { /// \addtogroup thread-module /// @{ class thread; /// \cond internal class thread_context; namespace thread_impl { thread_context* get(); void switch_in(thread_context* to); void switch_out(thread_context* from); void init(); } extern thread_local jmp_buf g_unthreaded_context; // Internal class holding thread state. We can't hold this in // \c thread itself because \c thread is movable, and we want pointers // to this state to be captured. class thread_context { static constexpr size_t _stack_size = 128*1024; std::unique_ptr<char[]> _stack{new char[_stack_size]}; std::function<void ()> _func; jmp_buf _context; promise<> _done; bool _joined = false; private: static void s_main(unsigned int lo, unsigned int hi); void setup(); void main(); public: thread_context(std::function<void ()> func); void switch_in(); void switch_out(); friend class thread; friend void thread_impl::switch_in(thread_context*); friend void thread_impl::switch_out(thread_context*); }; /// \endcond /// \brief thread - stateful thread of execution /// /// Threads allow using seastar APIs in a blocking manner, /// by calling future::get() on a non-ready future. When /// this happens, the thread is put to sleep until the future /// becomes ready. class thread { std::unique_ptr<thread_context> _context; static thread_local thread* _current; public: /// \brief Constructs a \c thread object that does not represent a thread /// of execution. thread() = default; /// \brief Constructs a \c thread object that represents a thread of execution /// /// \param func Callable object to execute in thread. The callable is /// called immediately. template <typename Func> thread(Func func); /// \brief Moves a thread object. thread(thread&& x) noexcept = default; /// \brief Move-assigns a thread object. thread& operator=(thread&& x) noexcept = default; /// \brief Destroys a \c thread object. /// /// The thread must not represent a running thread of execution (see join()). ~thread() { assert(!_context || _context->_joined); } /// \brief Waits for thread execution to terminate. /// /// Waits for thread execution to terminate, and marks the thread object as not /// representing a running thread of execution. future<> join(); }; template <typename Func> inline thread::thread(Func func) : _context(std::make_unique<thread_context>(func)) { } inline future<> thread::join() { _context->_joined = true; return _context->_done.get_future(); } /// Executes a callable in a seastar thread. /// /// Runs a block of code in a threaded context, /// which allows it to block (using \ref future::get()). The /// result of the callable is returned as a future. /// /// \param func a callable to be executed in a thread /// \param args a parameter pack to be forwarded to \c func. /// \return whatever \c func returns, as a future. /// /// Example: /// \code /// future<int> compute_sum(int a, int b) { /// return seastar::async([a, b] { /// // some blocking code: /// sleep(1s).get(); /// return a + b; /// }); /// } /// \endcode template <typename Func, typename... Args> inline futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>> async(Func&& func, Args&&... args) { using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>; struct work { Func func; std::tuple<Args...> args; promise<return_type> pr; thread th; }; return do_with(work{std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) { auto ret = w.pr.get_future(); w.th = thread([&w] { futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr)); }); return w.th.join().then([ret = std::move(ret)] () mutable { return std::move(ret); }); }); } /// @} } <|endoftext|>
<commit_before> /****************************************************************************** * Copyright 2017 The Apollo 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 "modules/perception/obstacle/onboard/cipv_subnode.h" #include <vector> #include <string> #include <map> #include <memory> #include "modules/perception/obstacle/onboard/motion_service.h" #include "modules/perception/onboard/dag_streaming.h" #include "modules/perception/onboard/event_manager.h" #include "modules/perception/onboard/shared_data_manager.h" #include "modules/perception/onboard/subnode_helper.h" namespace apollo { namespace perception { using apollo::common::ErrorCode; using apollo::common::Status; using std::vector; using std::string; using std::map; // using Event; // using EventID; // using EventMeta; // using IoStreamType; // using SharedDataPtr; // using SubnodeHelper; // using Status; // using StreamOutput; // using std_msgs::String; bool CIPVSubnode::InitInternal() { CHECK(shared_data_manager_ != nullptr); // init camera object data _camera_object_data = dynamic_cast<CameraObjectData*>( shared_data_manager_->GetSharedData("CameraObjectData")); if (_camera_object_data == nullptr) { AERROR << "Failed to get CameraObjectData."; return false; } // init camera object data _lane_shared_data = dynamic_cast<LaneSharedData*>( shared_data_manager_->GetSharedData("LaneSharedData")); if (_lane_shared_data == nullptr) { AERROR << "Failed to get LaneSharedData."; return false; } _cipv_object_data = dynamic_cast<CIPVObjectData*>( shared_data_manager_->GetSharedData("CIPVObjectData")); if (_cipv_object_data == nullptr) { AERROR << "Failed to get CIPVObjectData"; return false; } AINFO << "Init shared datas successfully"; string _reserve; map<string, string> reserve_field_map; if (!SubnodeHelper::ParseReserveField(_reserve, &reserve_field_map)) { AERROR << "Failed to parse reserve string: " << _reserve; return false; } if (!InitOutputStream(reserve_field_map)) { AERROR << "Failed to init output or input stream."; return false; } // init Cipv _cipv.Init(); AINFO << "Init CIPVSubnode succ."; return true; } apollo::common::Status CIPVSubnode::ProcEvents() { Event event; if (!SubscribeEvents(&event)) { return Status(ErrorCode::PERCEPTION_ERROR, "Failed to subscribe events."); } std::shared_ptr<SensorObjects> sensor_objs; if (!GetSharedData(event, &sensor_objs)) { return Status(ErrorCode::PERCEPTION_ERROR, "Failed to get shared data."); } CipvOptions cipv_options; // *** To Do *** use motion manager // MotionService* motion_service = // dynamic_cast<MotionService*> // (DAGStreaming::GetSubnodeByName("MotionService")); // double timestamp = event.timestamp; // VehicleInformation vehicle_information; // motion_service->get_vehicle_information(timestamp, // &vehicle_information); // cipv_options.yaw_angle = vehicle_information.yaw_angle; // cipv_options.velocity = vehicle_information.velocity; // cipv_options.yaw_rate = vehicle_information.yaw_rate; cipv_options.yaw_angle = 0.0f; // ***** fill in the value ***** cipv_options.velocity = 5.0f; // ***** fill in the value ***** cipv_options.yaw_rate = 0.0f; // ***** fill in the value ***** AINFO << "[CIPVSubnode] velocity " << cipv_options.velocity << ", yaw rate: " << cipv_options.yaw_rate << ", yaw angle: " << cipv_options.yaw_angle; // call cipv module if (_cipv.DetermineCipv(sensor_objs, &cipv_options)) { // *** To Do *** when camera_detector_subnode.cpp is included, add this // publish_data_and_event(event.timestamp, event.reserve, // sensor_objs, _cipv_object_data); } return Status::OK(); } bool CIPVSubnode::InitOutputStream(const map<string, string>& fields) { auto camera_iter = fields.find("camera_event_id"); if (camera_iter == fields.end()) { AERROR << "Failed to find camera_event_id"; _camera_event_id = -1; } else { _camera_event_id = static_cast<EventID>(atoi((camera_iter->second).c_str())); AINFO << "camera event id is " << _camera_event_id; } auto lane_iter = fields.find("lane_event_id"); if (lane_iter == fields.end()) { AERROR << "Failed to find lane_event_id"; _lane_event_id = -1; } else { _lane_event_id = static_cast<EventID>(atoi((lane_iter->second).c_str())); AINFO << "lane event id is " << _lane_event_id; } AINFO << "Init output stream succ"; return true; } bool CIPVSubnode::SubscribeEvents(Event *event) const { if (!event_manager_->Subscribe(_camera_event_id, event)) { AERROR << "Failed to subscribe event: " << _camera_event_id; return false; } if (!event_manager_->Subscribe(_lane_event_id, event)) { AERROR << "Failed to subscribe event: " << _lane_event_id; return false; } return true; } bool CIPVSubnode::GetSharedData(const Event& event, std::shared_ptr<SensorObjects>* objs) const { double timestamp = event.timestamp; const string& device_id = event.reserve; string data_key; if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) { AERROR << "Failed to produce shared data key. EventID:" << event.event_id << " timestamp:" << timestamp << " device_id:" << device_id; return false; } bool get_data_succ = false; // *** To DO *** uncomment // get_data_succ = _camera_object_data->get(data_key, objs); // std::shared_ptr<lane_post_process::LaneObjects> lane_objects; // get_data_succ = _lane_shared_data->get(data_key, &lane_objects); // (*objs)->lane_objects = lane_objects; if (!get_data_succ) { AERROR << "Failed to get shared data. event:" << event.to_string(); return false; } return true; } REGISTER_SUBNODE(CIPVSubnode); } // namespace perception } // namespace apollo <commit_msg>Enable CIPV using camera process subnode<commit_after> /****************************************************************************** * Copyright 2017 The Apollo 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 "modules/perception/obstacle/onboard/cipv_subnode.h" #include <vector> #include <string> #include <map> #include <memory> #include "modules/perception/obstacle/onboard/motion_service.h" #include "modules/perception/onboard/dag_streaming.h" #include "modules/perception/onboard/event_manager.h" #include "modules/perception/onboard/shared_data_manager.h" #include "modules/perception/onboard/subnode_helper.h" namespace apollo { namespace perception { using apollo::common::ErrorCode; using apollo::common::Status; using std::vector; using std::string; using std::map; // using Event; // using EventID; // using EventMeta; // using IoStreamType; // using SharedDataPtr; // using SubnodeHelper; // using Status; // using StreamOutput; // using std_msgs::String; bool CIPVSubnode::InitInternal() { CHECK(shared_data_manager_ != nullptr); // init camera object data _camera_object_data = dynamic_cast<CameraObjectData*>( shared_data_manager_->GetSharedData("CameraObjectData")); if (_camera_object_data == nullptr) { AERROR << "Failed to get CameraObjectData."; return false; } // init camera object data _lane_shared_data = dynamic_cast<LaneSharedData*>( shared_data_manager_->GetSharedData("LaneSharedData")); if (_lane_shared_data == nullptr) { AERROR << "Failed to get LaneSharedData."; return false; } _cipv_object_data = dynamic_cast<CIPVObjectData*>( shared_data_manager_->GetSharedData("CIPVObjectData")); if (_cipv_object_data == nullptr) { AERROR << "Failed to get CIPVObjectData"; return false; } AINFO << "Init shared datas successfully"; string _reserve; map<string, string> reserve_field_map; if (!SubnodeHelper::ParseReserveField(_reserve, &reserve_field_map)) { AERROR << "Failed to parse reserve string: " << _reserve; return false; } if (!InitOutputStream(reserve_field_map)) { AERROR << "Failed to init output or input stream."; return false; } // init Cipv _cipv.Init(); AINFO << "Init CIPVSubnode succ."; return true; } apollo::common::Status CIPVSubnode::ProcEvents() { Event event; if (!SubscribeEvents(&event)) { return Status(ErrorCode::PERCEPTION_ERROR, "Failed to subscribe events."); } std::shared_ptr<SensorObjects> sensor_objs; if (!GetSharedData(event, &sensor_objs)) { return Status(ErrorCode::PERCEPTION_ERROR, "Failed to get shared data."); } CipvOptions cipv_options; // *** To Do *** use motion manager // MotionService* motion_service = // dynamic_cast<MotionService*> // (DAGStreaming::GetSubnodeByName("MotionService")); // double timestamp = event.timestamp; // VehicleInformation vehicle_information; // motion_service->get_vehicle_information(timestamp, // &vehicle_information); // cipv_options.yaw_angle = vehicle_information.yaw_angle; // cipv_options.velocity = vehicle_information.velocity; // cipv_options.yaw_rate = vehicle_information.yaw_rate; cipv_options.yaw_angle = 0.0f; // ***** fill in the value ***** cipv_options.velocity = 5.0f; // ***** fill in the value ***** cipv_options.yaw_rate = 0.0f; // ***** fill in the value ***** AINFO << "[CIPVSubnode] velocity " << cipv_options.velocity << ", yaw rate: " << cipv_options.yaw_rate << ", yaw angle: " << cipv_options.yaw_angle; // call cipv module if (_cipv.DetermineCipv(sensor_objs, &cipv_options)) { // *** To Do *** when camera_detector_subnode.cpp is included, add this // publish_data_and_event(event.timestamp, event.reserve, // sensor_objs, _cipv_object_data); } return Status::OK(); } bool CIPVSubnode::InitOutputStream(const map<string, string>& fields) { auto camera_iter = fields.find("camera_event_id"); if (camera_iter == fields.end()) { AERROR << "Failed to find camera_event_id"; _camera_event_id = -1; } else { _camera_event_id = static_cast<EventID>(atoi((camera_iter->second).c_str())); AINFO << "camera event id is " << _camera_event_id; } auto lane_iter = fields.find("lane_event_id"); if (lane_iter == fields.end()) { AERROR << "Failed to find lane_event_id"; _lane_event_id = -1; } else { _lane_event_id = static_cast<EventID>(atoi((lane_iter->second).c_str())); AINFO << "lane event id is " << _lane_event_id; } AINFO << "Init output stream succ"; return true; } bool CIPVSubnode::SubscribeEvents(Event *event) const { if (!event_manager_->Subscribe(_camera_event_id, event)) { AERROR << "Failed to subscribe event: " << _camera_event_id; return false; } if (!event_manager_->Subscribe(_lane_event_id, event)) { AERROR << "Failed to subscribe event: " << _lane_event_id; return false; } return true; } bool CIPVSubnode::GetSharedData(const Event& event, std::shared_ptr<SensorObjects>* objs) const { double timestamp = event.timestamp; const string& device_id = event.reserve; string data_key; if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) { AERROR << "Failed to produce shared data key. EventID:" << event.event_id << " timestamp:" << timestamp << " device_id:" << device_id; return false; } bool get_data_succ = false; // *** To DO *** uncomment get_data_succ = _camera_object_data->Get(data_key, objs); std::shared_ptr<LaneObjects> lane_objects; get_data_succ = _lane_shared_data->Get(data_key, &lane_objects); (*objs)->lane_objects = lane_objects; if (!get_data_succ) { AERROR << "Failed to get shared data. event:" << event.to_string(); return false; } return true; } REGISTER_SUBNODE(CIPVSubnode); } // namespace perception } // namespace apollo <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #include "launcher.hxx" #include "appusermodelid.hxx" #ifndef _WINDOWS_ # define WIN32_LEAN_AND_MEAN #if defined _MSC_VER #pragma warning(push, 1) #endif # include <windows.h> # include <shellapi.h> #if defined _MSC_VER #pragma warning(pop) #endif #endif #include <stdlib.h> #include <malloc.h> #ifdef __MINGW32__ extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int ) #else extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int ) #endif { // Set an explicit Application User Model ID for the process SetExplicitAppUserModelID(APPUSERMODELID); // Retreive startup info STARTUPINFO aStartupInfo; ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) ); aStartupInfo.cb = sizeof( aStartupInfo ); GetStartupInfo( &aStartupInfo ); // Retrieve command line LPTSTR lpCommandLine = GetCommandLine(); { lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) ); _tcscpy( lpCommandLine, GetCommandLine() ); _tcscat( lpCommandLine, _T(" ") ); _tcscat( lpCommandLine, APPLICATION_SWITCH ); } // Calculate application name TCHAR szApplicationName[MAX_PATH]; TCHAR szDrive[MAX_PATH]; TCHAR szDir[MAX_PATH]; TCHAR szFileName[MAX_PATH]; TCHAR szExt[MAX_PATH]; GetModuleFileName( NULL, szApplicationName, MAX_PATH ); _tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt ); _tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") ); PROCESS_INFORMATION aProcessInfo; BOOL fSuccess = CreateProcess( szApplicationName, lpCommandLine, NULL, NULL, TRUE, 0, NULL, NULL, &aStartupInfo, &aProcessInfo ); if ( fSuccess ) { // Wait for soffice process to be terminated to allow other applications // to wait for termination of started process WaitForSingleObject( aProcessInfo.hProcess, INFINITE ); CloseHandle( aProcessInfo.hProcess ); CloseHandle( aProcessInfo.hThread ); return 0; } DWORD dwError = GetLastError(); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR)&lpMsgBuf, 0, NULL ); // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR ); // Free the buffer. LocalFree( lpMsgBuf ); return GetLastError(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Don't spam fellow developers until I fix the problem in MinGW<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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. * ************************************************************************/ #include "launcher.hxx" #include "appusermodelid.hxx" #ifndef _WINDOWS_ # define WIN32_LEAN_AND_MEAN #if defined _MSC_VER #pragma warning(push, 1) #endif # include <windows.h> # include <shellapi.h> #if defined _MSC_VER #pragma warning(pop) #endif #endif #include <stdlib.h> #include <malloc.h> #ifdef __MINGW32__ extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int ) #else extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int ) #endif { // Set an explicit Application User Model ID for the process // FIXME: Comment this out until I find a fix for minGW. // SetExplicitAppUserModelID(APPUSERMODELID); // Retreive startup info STARTUPINFO aStartupInfo; ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) ); aStartupInfo.cb = sizeof( aStartupInfo ); GetStartupInfo( &aStartupInfo ); // Retrieve command line LPTSTR lpCommandLine = GetCommandLine(); { lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) ); _tcscpy( lpCommandLine, GetCommandLine() ); _tcscat( lpCommandLine, _T(" ") ); _tcscat( lpCommandLine, APPLICATION_SWITCH ); } // Calculate application name TCHAR szApplicationName[MAX_PATH]; TCHAR szDrive[MAX_PATH]; TCHAR szDir[MAX_PATH]; TCHAR szFileName[MAX_PATH]; TCHAR szExt[MAX_PATH]; GetModuleFileName( NULL, szApplicationName, MAX_PATH ); _tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt ); _tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") ); PROCESS_INFORMATION aProcessInfo; BOOL fSuccess = CreateProcess( szApplicationName, lpCommandLine, NULL, NULL, TRUE, 0, NULL, NULL, &aStartupInfo, &aProcessInfo ); if ( fSuccess ) { // Wait for soffice process to be terminated to allow other applications // to wait for termination of started process WaitForSingleObject( aProcessInfo.hProcess, INFINITE ); CloseHandle( aProcessInfo.hProcess ); CloseHandle( aProcessInfo.hThread ); return 0; } DWORD dwError = GetLastError(); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR)&lpMsgBuf, 0, NULL ); // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR ); // Free the buffer. LocalFree( lpMsgBuf ); return GetLastError(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cout << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } ch_max(ans, DP[v][l - e.weight] + e.value); } return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cout << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } ch_max(ans, DP[v][l - e.weight] + e.value); } #if DEBUG == 1 cerr << "Here" << endl; #endif return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cout << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } #if DEBUG == 1 cerr << "Here" << endl; #endif int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } ch_max(ans, DP[v][l - e.weight] + e.value); } return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cout << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } #if DEBUG == 1 cerr << "e.weight = " << e.weight << endl; cerr << "e.value = " << e.value << endl; #endif ch_max(ans, DP[v][l - e.weight] + e.value); } return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <|endoftext|>
<commit_before>/* * File: FieldDetector.cpp * Author: Heinrich Mellmann * */ #include "FieldDetector.h" #include <Tools/Math/ConvexHull.h> using namespace std; FieldDetector::FieldDetector() : cameraID(CameraInfo::Bottom) { DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon", "mark polygonal boundary of the detected field on the image", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_corrected_field_polygon", "mark polygonal boundary of the detected field cutted by horizon on the image", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:setHoleImageAsField", "mark hole image as if field were detected", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_old", "mark polygonal boundary of the detected field before outlier detection", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_new", "mark new polygonal boundary of the detected field after outlier detection", false); getDebugParameterList().add(&theParameters); } FieldDetector::~FieldDetector() {} void FieldDetector::execute(CameraInfo::CameraID id) { cameraID = id; bool simulateField = false; DEBUG_REQUEST("Vision:FieldDetector:setHoleImageAsField", simulateField = true; ); if(simulateField) { vector<Vector2i> result; result.push_back(Vector2i(0,0)); result.push_back(Vector2i(0,getImage().height()-1)); result.push_back(Vector2i(getImage().width()-1, getImage().height()-0)); result.push_back(Vector2i(getImage().width()-1,0)); result.push_back(Vector2i(0,0)); // create the polygon FieldPercept::FieldPoly fieldPoly; for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } Math::LineSegment horizon(Vector2i(0, 0), Vector2i(getImage().width() - 1, 0)); getFieldPercept().setField(fieldPoly, horizon); if(fieldPoly.getArea() >= 5600) { getFieldPercept().valid = true; } DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon", size_t idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red; for(size_t i = 1; i < result.size(); i++) { LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y); idx = i; } ); } else if(!getScanLineEdgelPercept().endPoints.empty()) { static vector<Vector2i> points; points.clear(); for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++) { const ScanLineEdgelPercept::EndPoint& p = getScanLineEdgelPercept().endPoints[i]; if(p.greenFound && p.posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(p.posInImage); } } // move the outer points //points.front().x = 0; //points.back().x = getImage().width()-1; // lower image points //points.push_back(Vector2i(0,getImage().height()-1)); //points.push_back(Vector2i(getImage().width()-1, getImage().height()-1)); if(points.size() > 1) { Vector2i p1 = points.front(); p1.y = getImage().height() - 1; Vector2i p2 = points.back(); p2.y = getImage().height() - 1; points.push_back(p1); points.push_back(p2); if(getScanLineEdgelPercept().endPoints.front().posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(Vector2i(0, getScanLineEdgelPercept().endPoints.front().posInImage.y)); points.push_back(Vector2i(0, getImage().height() - 1)); } if(getScanLineEdgelPercept().endPoints.back().posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(Vector2i(getImage().width() - 1, getScanLineEdgelPercept().endPoints.back().posInImage.y)); points.push_back(Vector2i(getImage().width() - 1, getImage().height() - 1)); } } // calculate the convex hull vector<Vector2i> result = ConvexHull::convexHull(points); // create the polygon FieldPercept::FieldPoly fieldPoly; for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_old", int idx = 0; for(int i = 1; i < fieldPoly.length; i++) { LINE_PX(ColorClasses::red, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y); idx = i; } ); // sort points by x value std::sort(points.begin(), points.end(), cmpVectorInstance); /* // remove points on the edge of the BodyContour std::vector<size_t> badPoints; for(size_t i = 2; i+2 < points.size(); i++) { if(points[i].y > 0) { //Vector2i dummyPoint = points[i]; //dummyPoint.y += 6; //if(getBodyContour().isOccupied(dummyPoint)) { badPoints.push_back(i); } } } if(badPoints.size() > 0) { for(size_t i = 0; i < badPoints.size(); i++) { // badPoints are ordered so the small indices are removed first points.erase(points.begin() + (badPoints[i] - i)); } }*/ // check outliers but keep first and last point in any case static std::vector<size_t> badPoints; badPoints.clear(); for(size_t nLoop = 0; nLoop < 5; nLoop++) { badPoints.clear(); for(size_t i = 2; i+2 < points.size(); i++) { std::vector<Vector2i> pointsCheck = points; pointsCheck.erase(pointsCheck.begin()+i); vector<Vector2i> resultCheck = ConvexHull::convexHull(pointsCheck); FieldPercept::FieldPoly fieldPolyCheck; for(size_t j = 0; j < resultCheck.size(); j++) { fieldPolyCheck.add(resultCheck[j]); } if(fieldPolyCheck.getArea() / fieldPoly.getArea() < theParameters.pruneThresholdArea) { badPoints.push_back(i); } } // remove outliers if(!badPoints.empty()) { for(size_t i = 0; i < badPoints.size(); i++) { // badPoints are ordered so the small indices are removed first points.erase(points.begin() + (badPoints[i] - i)); } result = ConvexHull::convexHull(points); // clear old polygon fieldPoly = FieldPercept::FieldPoly(); for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } } else { break; } } DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_new", int idx = 0; for(int i = 1; i < fieldPoly.length; i++) { LINE_PX(ColorClasses::green, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y); idx = i; } ); // add field to percept getFieldPercept().setField(fieldPoly, getArtificialHorizon()); // check result if(fieldPoly.getArea() >= 5600) { getFieldPercept().valid = true; } else { getFieldPercept().valid = false; } DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon", size_t idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::black : ColorClasses::red; for(size_t i = 1; i < result.size(); i++) { LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y); idx = i; } ); DEBUG_REQUEST( "Vision:FieldDetector:mark_corrected_field_polygon", int idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red; const FieldPercept::FieldPoly& fieldpoly = getFieldPercept().getValidField(); for(int i = 1; i < fieldpoly.length; i++) { LINE_PX(color, fieldpoly[idx].x, fieldpoly[idx].y, fieldpoly[i].x, fieldpoly[i].y); idx = i; } ); } }//end execute <commit_msg>don't re-initialize FieldPoly all the time<commit_after>/* * File: FieldDetector.cpp * Author: Heinrich Mellmann * */ #include "FieldDetector.h" #include <Tools/Math/ConvexHull.h> using namespace std; FieldDetector::FieldDetector() : cameraID(CameraInfo::Bottom) { DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon", "mark polygonal boundary of the detected field on the image", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_corrected_field_polygon", "mark polygonal boundary of the detected field cutted by horizon on the image", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:setHoleImageAsField", "mark hole image as if field were detected", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_old", "mark polygonal boundary of the detected field before outlier detection", false); DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_new", "mark new polygonal boundary of the detected field after outlier detection", false); getDebugParameterList().add(&theParameters); } FieldDetector::~FieldDetector() {} void FieldDetector::execute(CameraInfo::CameraID id) { cameraID = id; bool simulateField = false; DEBUG_REQUEST("Vision:FieldDetector:setHoleImageAsField", simulateField = true; ); if(simulateField) { vector<Vector2i> result; result.push_back(Vector2i(0,0)); result.push_back(Vector2i(0,getImage().height()-1)); result.push_back(Vector2i(getImage().width()-1, getImage().height()-0)); result.push_back(Vector2i(getImage().width()-1,0)); result.push_back(Vector2i(0,0)); // create the polygon FieldPercept::FieldPoly fieldPoly; for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } Math::LineSegment horizon(Vector2i(0, 0), Vector2i(getImage().width() - 1, 0)); getFieldPercept().setField(fieldPoly, horizon); if(fieldPoly.getArea() >= 5600) { getFieldPercept().valid = true; } DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon", size_t idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red; for(size_t i = 1; i < result.size(); i++) { LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y); idx = i; } ); } else if(!getScanLineEdgelPercept().endPoints.empty()) { static vector<Vector2i> points; points.clear(); for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++) { const ScanLineEdgelPercept::EndPoint& p = getScanLineEdgelPercept().endPoints[i]; if(p.greenFound && p.posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(p.posInImage); } } // move the outer points //points.front().x = 0; //points.back().x = getImage().width()-1; // lower image points //points.push_back(Vector2i(0,getImage().height()-1)); //points.push_back(Vector2i(getImage().width()-1, getImage().height()-1)); if(points.size() > 1) { Vector2i p1 = points.front(); p1.y = getImage().height() - 1; Vector2i p2 = points.back(); p2.y = getImage().height() - 1; points.push_back(p1); points.push_back(p2); if(getScanLineEdgelPercept().endPoints.front().posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(Vector2i(0, getScanLineEdgelPercept().endPoints.front().posInImage.y)); points.push_back(Vector2i(0, getImage().height() - 1)); } if(getScanLineEdgelPercept().endPoints.back().posInImage.y < static_cast<int>(getImage().height()) - 6) { points.push_back(Vector2i(getImage().width() - 1, getScanLineEdgelPercept().endPoints.back().posInImage.y)); points.push_back(Vector2i(getImage().width() - 1, getImage().height() - 1)); } } // calculate the convex hull vector<Vector2i> result = ConvexHull::convexHull(points); // create the polygon static FieldPercept::FieldPoly fieldPoly; fieldPoly.clear(); for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_old", int idx = 0; for(int i = 1; i < fieldPoly.length; i++) { LINE_PX(ColorClasses::red, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y); idx = i; } ); // sort points by x value std::sort(points.begin(), points.end(), cmpVectorInstance); /* // remove points on the edge of the BodyContour std::vector<size_t> badPoints; for(size_t i = 2; i+2 < points.size(); i++) { if(points[i].y > 0) { //Vector2i dummyPoint = points[i]; //dummyPoint.y += 6; //if(getBodyContour().isOccupied(dummyPoint)) { badPoints.push_back(i); } } } if(badPoints.size() > 0) { for(size_t i = 0; i < badPoints.size(); i++) { // badPoints are ordered so the small indices are removed first points.erase(points.begin() + (badPoints[i] - i)); } }*/ // check outliers but keep first and last point in any case static std::vector<size_t> badPoints; badPoints.clear(); for(size_t nLoop = 0; nLoop < 5; nLoop++) { badPoints.clear(); for(size_t i = 2; i+2 < points.size(); i++) { std::vector<Vector2i> pointsCheck = points; pointsCheck.erase(pointsCheck.begin()+i); vector<Vector2i> resultCheck = ConvexHull::convexHull(pointsCheck); static FieldPercept::FieldPoly fieldPolyCheck; fieldPolyCheck.clear(); for(size_t j = 0; j < resultCheck.size(); j++) { fieldPolyCheck.add(resultCheck[j]); } if(fieldPolyCheck.getArea() / fieldPoly.getArea() < theParameters.pruneThresholdArea) { badPoints.push_back(i); } } // remove outliers if(!badPoints.empty()) { for(size_t i = 0; i < badPoints.size(); i++) { // badPoints are ordered so the small indices are removed first points.erase(points.begin() + (badPoints[i] - i)); } result = ConvexHull::convexHull(points); // clear old polygon fieldPoly.clear(); for(size_t i = 0; i < result.size(); i++) { fieldPoly.add(result[i]); } } else { break; } } DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_new", int idx = 0; for(int i = 1; i < fieldPoly.length; i++) { LINE_PX(ColorClasses::green, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y); idx = i; } ); // add field to percept getFieldPercept().setField(fieldPoly, getArtificialHorizon()); // check result if(fieldPoly.getArea() >= 5600) { getFieldPercept().valid = true; } else { getFieldPercept().valid = false; } DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon", size_t idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::black : ColorClasses::red; for(size_t i = 1; i < result.size(); i++) { LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y); idx = i; } ); DEBUG_REQUEST( "Vision:FieldDetector:mark_corrected_field_polygon", int idx = 0; ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red; const FieldPercept::FieldPoly& fieldpoly = getFieldPercept().getValidField(); for(int i = 1; i < fieldpoly.length; i++) { LINE_PX(color, fieldpoly[idx].x, fieldpoly[idx].y, fieldpoly[i].x, fieldpoly[i].y); idx = i; } ); } }//end execute <|endoftext|>
<commit_before>/** * @file * * @brief Some common functions in use for testing framework * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #ifndef KDB_TESTS_HPP #define KDB_TESTS_HPP #include <kdb.hpp> #include <kdbmacros.h> #include <key.hpp> #include <keyset.hpp> #include <cstdlib> #include <cstring> #include <exception> #include <iostream> #include <string> #include <gtest/gtest.h> using namespace std; using namespace kdb; // -- Macros ------------------------------------------------------------------------------------------------------------------------------- #define succeed_if(x, y) ASSERT_TRUE (x) << y #define exit_if_fail(expression, message) \ if (!(expression)) \ { \ cerr << __FILE__ << ":" << __LINE__ << ": Failure" << endl; \ cerr << "Value of: " << ELEKTRA_STRINGIFY (expression) << endl; \ cerr << " Actual: false" << endl; \ cerr << "Expected: true" << endl; \ cerr << message << endl; \ exit (1); \ } \ SUCCEED () << message #define succeed_if_same(x, y, message) ASSERT_EQ (x, y) << message #define compare_keyset(keySet1, keySet2) ASSERT_TRUE (compareKeySet (keySet1, keySet2)) // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function adds the string representation of a key to an assertion result. * * @param stream This parameter specifies the assertion result to which this function adds a string representation of `key`. * @param key This parameter stores the key this function converts to an assertion result. * * @returns An assertion result containing the string representation of `key` */ testing::AssertionResult & operator<< (testing::AssertionResult & stream, kdb::Key & key) { stream << key.getName () << ": " << (key.isString () ? key.getString () : (key.getBinarySize () == 0 ? "NULL" : "BINARY")); key.rewindMeta (); key.rewindMeta (); while (key.nextMeta ()) { stream << ", " << key.currentMeta ().getName () << ": " << key.currentMeta ().getString (); } stream << endl; return stream; } /** * @brief This function adds the string representation of a key set to an assertion result. * * @param stream This parameter specifies the assertion result to which this function adds a string representation of `keys`. * @param key This parameter stores the key set this function converts to an assertion result. * * @returns An assertion result containing the string representation of `keys` */ testing::AssertionResult & operator<< (testing::AssertionResult & stream, kdb::KeySet & keys) { for (auto key : keys) { stream << key; } return stream; } /** * @brief This function checks if the meta key set of two keys are equal. * * @param key1 This parameter stores the first meta key set this function uses for comparison. * @param key2 This parameter stores the second meta key set this function uses for comparison. * * @retval true if all meta keys of `key1` and `key2` are equal * @retval false otherwise */ bool isMetaDataEqual (kdb::Key & key1, kdb::Key & key2) { key1.rewindMeta (); key2.rewindMeta (); while (key1.nextMeta ()) { key2.nextMeta (); if (!key2.currentMeta ()) return false; if (key1.currentMeta ().getName () != key2.currentMeta ().getName ()) return false; if (key1.currentMeta ().getString () != key2.currentMeta ().getString ()) return false; } return key1.nextMeta () == key2.nextMeta (); } /** * @brief This function checks if two keys are equal. * * @param key1 This parameter stores the first key this function compares. * @param key2 This parameter stores the second key this function compares. * * @retval true if all attributes of `key1` and `key2` are equal * @retval false otherwise */ bool isKeyEqual (kdb::Key & key1, kdb::Key & key2) { if (key1.getName () != key2.getName ()) return false; if ((key1.isString () && key2.isBinary ()) || (key1.isBinary () && key2.isString ())) return false; if (key1.getBinarySize () != key2.getBinarySize ()) return false; if (memcmp (key1.getValue (), key2.getValue (), key1.getBinarySize ())) return false; return isMetaDataEqual (key1, key2); } /** * @brief This function checks if two key sets are equal. * * @param keys1 This parameter stores the first key set this function compares. * @param keys2 This parameter stores the second key set this function compares. * * @retval true if all keys of `keys1` and `keys2` are equal * @retval false otherwise */ bool isKeySetEqual (kdb::KeySet & keys1, kdb::KeySet & keys2) { if (keys1.size () != keys2.size ()) return false; keys1.rewind (); keys2.rewind (); while (keys1.next ()) { keys2.next (); if (!keys2.current ()) return false; kdb::Key key1 = keys1.current (); kdb::Key key2 = keys2.current (); if (!isKeyEqual (key1, key2)) return false; } return true; } /** * @brief This function compares the given key sets. * * @param keys1 This parameter stores the first key set this function compares. * @param keys2 This parameter stores the second key set this function compares. * * @retval AssertionSuccess if all keys of `keys1` and `keys2` are equal * @retval AssertionFailure otherwise */ testing::AssertionResult compareKeySet (kdb::KeySet & keys1, kdb::KeySet & keys2) { if (isKeySetEqual (keys1, keys2)) return testing::AssertionSuccess (); else return testing::AssertionFailure () << endl << endl << "First key set:" << endl << endl << keys1 << endl << "——————————" << endl << endl << "Second key set:" << endl << endl << keys2 << endl; } #endif <commit_msg>Test: Fix comparison of key sets<commit_after>/** * @file * * @brief Some common functions in use for testing framework * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #ifndef KDB_TESTS_HPP #define KDB_TESTS_HPP #include <kdb.hpp> #include <kdbmacros.h> #include <key.hpp> #include <keyset.hpp> #include <cstdlib> #include <cstring> #include <exception> #include <iostream> #include <string> #include <gtest/gtest.h> using namespace std; using namespace kdb; // -- Macros ------------------------------------------------------------------------------------------------------------------------------- #define succeed_if(x, y) ASSERT_TRUE (x) << y #define exit_if_fail(expression, message) \ if (!(expression)) \ { \ cerr << __FILE__ << ":" << __LINE__ << ": Failure" << endl; \ cerr << "Value of: " << ELEKTRA_STRINGIFY (expression) << endl; \ cerr << " Actual: false" << endl; \ cerr << "Expected: true" << endl; \ cerr << message << endl; \ exit (1); \ } \ SUCCEED () << message #define succeed_if_same(x, y, message) ASSERT_EQ (x, y) << message #define compare_keyset(keySet1, keySet2) ASSERT_TRUE (compareKeySet (keySet1, keySet2)) // -- Functions ---------------------------------------------------------------------------------------------------------------------------- /** * @brief This function adds the string representation of a key to an assertion result. * * @param stream This parameter specifies the assertion result to which this function adds a string representation of `key`. * @param key This parameter stores the key this function converts to an assertion result. * * @returns An assertion result containing the string representation of `key` */ testing::AssertionResult & operator<< (testing::AssertionResult & stream, kdb::Key & key) { stream << key.getName () << ": " << (key.isString () ? key.getString () : (key.getBinarySize () == 0 ? "NULL" : "BINARY")); key.rewindMeta (); key.rewindMeta (); while (key.nextMeta ()) { stream << ", " << key.currentMeta ().getName () << ": " << key.currentMeta ().getString (); } stream << endl; return stream; } /** * @brief This function adds the string representation of a key set to an assertion result. * * @param stream This parameter specifies the assertion result to which this function adds a string representation of `keys`. * @param key This parameter stores the key set this function converts to an assertion result. * * @returns An assertion result containing the string representation of `keys` */ testing::AssertionResult & operator<< (testing::AssertionResult & stream, kdb::KeySet & keys) { for (auto key : keys) { stream << key; } return stream; } /** * @brief This function checks if the meta key set of two keys are equal. * * @param key1 This parameter stores the first meta key set this function uses for comparison. * @param key2 This parameter stores the second meta key set this function uses for comparison. * * @retval true if all meta keys of `key1` and `key2` are equal * @retval false otherwise */ bool isMetaDataEqual (kdb::Key & key1, kdb::Key & key2) { key1.rewindMeta (); key2.rewindMeta (); while (key1.nextMeta ()) { key2.nextMeta (); if (!key2.currentMeta ()) return false; if (key1.currentMeta ().getName () != key2.currentMeta ().getName ()) return false; if (key1.currentMeta ().getString () != key2.currentMeta ().getString ()) return false; } return key1.nextMeta () == key2.nextMeta (); } /** * @brief This function checks if two keys are equal. * * @param key1 This parameter stores the first key this function compares. * @param key2 This parameter stores the second key this function compares. * * @retval true if all attributes of `key1` and `key2` are equal * @retval false otherwise */ bool isKeyEqual (kdb::Key & key1, kdb::Key & key2) { if (key1.getName () != key2.getName ()) return false; if ((key1.isString () && key2.isBinary ()) || (key1.isBinary () && key2.isString ())) return false; if (key1.getBinarySize () != key2.getBinarySize ()) return false; if (memcmp (key1.getValue (), key2.getValue (), key1.getBinarySize ())) return false; return isMetaDataEqual (key1, key2); } /** * @brief This function checks if two key sets are equal. * * @param keys1 This parameter stores the first key set this function compares. * @param keys2 This parameter stores the second key set this function compares. * * @retval true if all keys of `keys1` and `keys2` are equal * @retval false otherwise */ bool isKeySetEqual (kdb::KeySet & keys1, kdb::KeySet & keys2) { if (keys1.size () != keys2.size ()) return false; keys1.rewind (); keys2.rewind (); while (keys1.next ()) { keys2.next (); if (!keys2.current ()) return false; kdb::Key key1 = keys1.current (); kdb::Key key2 = keys2.current (); if (!isKeyEqual (key1, key2)) return false; } return keys1.next () == keys2.next (); } /** * @brief This function compares the given key sets. * * @param keys1 This parameter stores the first key set this function compares. * @param keys2 This parameter stores the second key set this function compares. * * @retval AssertionSuccess if all keys of `keys1` and `keys2` are equal * @retval AssertionFailure otherwise */ testing::AssertionResult compareKeySet (kdb::KeySet & keys1, kdb::KeySet & keys2) { if (isKeySetEqual (keys1, keys2)) return testing::AssertionSuccess (); else return testing::AssertionFailure () << endl << endl << "First key set:" << endl << endl << keys1 << endl << "——————————" << endl << endl << "Second key set:" << endl << endl << keys2 << endl; } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ 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 "mitkPolygonToRingFilter.h" #include "mitkMesh.h" #include "mitkSurface.h" #include "mitkPlaneGeometry.h" #include <vnl/vnl_cross.h> #include <vnl/vnl_quaternion.h> #include <vnl/vnl_quaternion.txx> #include <vtkPolyData.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkCardinalSpline.h> #include <vector> mitk::PolygonToRingFilter::PolygonToRingFilter() : m_RingRadius(3.5f), m_RingResolution(30), m_SplineResolution(20) { m_SplineX = vtkCardinalSpline::New(); m_SplineY = vtkCardinalSpline::New(); m_SplineZ = vtkCardinalSpline::New(); } mitk::PolygonToRingFilter::~PolygonToRingFilter() { m_SplineX->Delete(); m_SplineY->Delete(); m_SplineZ->Delete(); } void mitk::PolygonToRingFilter::GenerateOutputInformation() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; output->SetGeometry(static_cast<Geometry3D*>(input->GetGeometry()->Clone().GetPointer())); output->Resize( input->GetPointSetSeriesSize() ); } void mitk::PolygonToRingFilter::GenerateData() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); int t; for ( t = 0; t < input->GetPointSetSeriesSize(); ++t ) { vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *vPoints = vtkPoints::New(); vtkCellArray *polys = vtkCellArray::New(); mitk::Mesh::PointType thisPoint; // iterate through all cells and build tubes Mesh::CellIterator cellIt, cellEnd; cellEnd = input->GetMesh( t )->GetCells()->End(); for ( cellIt = input->GetMesh( t )->GetCells()->Begin(); cellIt != cellEnd; ++cellIt ) { m_PointList.clear(); m_VectorList.clear(); this->BuildPointAndVectorList( *cellIt->Value(), m_PointList, m_VectorList, t ); this->BuildVtkTube( vPoints, polys, m_PointList, m_VectorList ); } polyData->SetPoints( vPoints ); vPoints->Delete(); polyData->SetPolys( polys ); polys->Delete(); output->SetVtkPolyData( polyData, t ); polyData->Delete(); } } //sl: Stern Letzter //sc: Stern Current=aktueller Stern //idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. //last_p: Mittelpunkt des letzten Sterns //cur_p: Mittelpunkt des aktuellen Sterns void mitk::PolygonToRingFilter::DrawCyl(vtkPoints *vPoints, vtkCellArray *polys, VectorListType &sl, VectorListType &sc, int idmax, Point3D & last_p, Point3D & cur_p) { unsigned int i; //jetzt haben wir alles: sl0 wird mit sc->at(idmax) verbunden usw. VectorListType::iterator slit=sl.begin(), scit=sc.begin(), scend=sc.end(); scit+=idmax; Point3D a,b; Point3D a_first,b_first; int a_firstID = 0, b_firstID = 0; int front[4]; for(i=0;i<m_RingResolution;++i) { VnlVector v0,v1,v2,v3,normal; v0=a.Get_vnl_vector(); v1=b.Get_vnl_vector(); a=last_p+*slit*m_RingRadius; b=cur_p+*scit*m_RingRadius; v2=b.Get_vnl_vector(); v3=a.Get_vnl_vector(); normal=vnl_cross_3d(v1-v0,v3-v0); if(i!=0) { front[3]=vPoints->InsertNextPoint(v0[0],v0[1],v0[2]); front[2]=vPoints->InsertNextPoint(v1[0],v1[1],v1[2]); front[1]=vPoints->InsertNextPoint(v2[0],v2[1],v2[2]); front[0]=vPoints->InsertNextPoint(v3[0],v3[1],v3[2]); polys->InsertNextCell( 4, front ); if(i==1) { a_firstID=front[3]; b_firstID=front[2]; //continue; } } ++slit; ++scit; if(scit==scend) scit=sc.begin(); } front[3]=front[0]; front[2]=front[1]; front[1]=b_firstID; front[0]=a_firstID; polys->InsertNextCell( 4, front ); } void mitk::PolygonToRingFilter::BuildVtkTube(vtkPoints *vPoints, vtkCellArray *polys, PointListType& ptList, VectorListType& vecList) { PointListType::iterator pit = ptList.begin(), pend = ptList.end(); VectorListType::iterator vit = vecList.begin(); Vector3D axis, last_v, next_v, s; Point3D cur_p,last_p; //Listen fr den Stern VectorListType *sl, *sc, *swp, sfirst, buf1, buf2; sl=&buf1; sc=&buf2; Vector3D a,b; Matrix3D m; //Initialisierung fr ersten Punkt //alternative1: // last_v=*(vl.getLast()); next_v=*vit.current(); axis=last_v+next_v; s.cross(last_v,next_v); s.normalize(); //alternative2: // last_v=*(vl.getLast()); next_v=*vit.current(); s.cross(last_v,next_v); s.normalize(); // axis=next_v-last_v; axis.normalize(); aa.set(s, M_PI/2.0); m.set(aa); m.transform(&axis); //alternative3: last_v=vecList.back(); next_v=*vit; s.Set_vnl_vector( vnl_cross_3d(last_v.Get_vnl_vector(),next_v.Get_vnl_vector()) ); s.Normalize(); a=last_v; b=next_v; a.Normalize(); b.Normalize(); axis=a+b; axis.Normalize(); //Stern am ersten Punkt aufbauen m = vnl_quaternion<mitk::ScalarType>(axis.Get_vnl_vector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); unsigned int i; for(i=0;i<m_RingResolution;++i) { sfirst.push_back(s); s=m*s; } *sl=sfirst; last_p=*pit; ++pit; ++vit; //nun die Hauptschleife ber alle Punkte for ( ; pit != pend; ++pit, ++vit ) { // cur_p=*pit.current(); last_v=next_v; next_v=*vit.current(); axis=last_v+next_v; s.cross(last_v,next_v); s.normalize(); cur_p=*pit; last_v=next_v; next_v=*vit; s.Set_vnl_vector( vnl_cross_3d(last_v.Get_vnl_vector(),next_v.Get_vnl_vector()) ); s.Normalize(); // axis=next_v-last_v; axis.normalize(); aa.set(s, M_PI/2.0); m.set(aa); m.transform(&axis); a=last_v; b=next_v; a.Normalize(); b.Normalize(); axis=a+b; axis.Normalize(); //neuen Stern sc (SternCurrent) bauen und dabei Start fr neuen Stern suchen double max=0; int idmax=0; Vector3D sl0=*(sl->begin()); m = vnl_quaternion<mitk::ScalarType>(axis.Get_vnl_vector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); for(i=0;i<m_RingResolution;++i) { sc->push_back(s); double tmp=s*sl0; if(tmp>max) { max=tmp; idmax=i; } s=m*s; } //sl: Stern Letzter //sc: Stern Current=aktueller Stern //idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. //last_p: Mittelpunkt des letzten Sterns //cur_p: Mittelpunkt des aktuellen Sterns DrawCyl(vPoints, polys, *sl, *sc, idmax, last_p, cur_p); //bergang zum nchsten last_p=cur_p; swp=sl; sl=sc; sc=swp; sc->clear(); } //idmax fr Verbindung ersten mit letztem ausrechnen: double max=0; int idmax=0; Vector3D sl0=*(sl->begin()); for(i=0;i<m_RingResolution;++i) { s=sfirst[i]; double tmp=s*sl0; if(tmp>max) { max=tmp; idmax=i; } } cur_p=*ptList.begin(); DrawCyl(vPoints, polys, *sl, sfirst, idmax, last_p, cur_p); } void mitk::PolygonToRingFilter ::BuildPointAndVectorList( mitk::Mesh::CellType& cell, PointListType& ptList, VectorListType& vecList, int timeStep ) { // This method constructs a spline from the given point list and retrieves // a number of interpolated points from it to form a ring-like structure. // // To make the spline "closed", the end point is connected to the start // point. For ensuring smoothness at the start-end-point transition, the // (intrinsically non-circular) spline array is extended on both sides // by wrapping a number of points from the respective other side. // // The used VTK filters do principally support this kind of "closed" spline, // but it does not produce results as consistent as with the method used // here. Also, the spline class of VTK 4.4 has only poor support for // arbitrary parametric coordinates (t values in vtkSpline). VTK 5.0 has // better support, and also provides a new class vtkParametricSpline for // directly calculating 3D splines. // Remove points from previous call of this method m_SplineX->RemoveAllPoints(); m_SplineY->RemoveAllPoints(); m_SplineZ->RemoveAllPoints(); int numberOfPoints = cell.GetNumberOfPoints(); Mesh::PointType inputPoint; vtkFloatingPointType t, tStart(0), tEnd(0); // Add input points to the spline and assign each the parametric value t // derived from the point euclidean distances. int i; Mesh::PointIdIterator pit = cell.PointIdsEnd() - 3; for ( i = -3, t = 0.0; i < numberOfPoints + 3; ++i ) { if ( i == 0 ) { tStart = t; } if ( i == numberOfPoints ) { tEnd = t; } inputPoint = this->GetInput()->GetPoint( *pit, timeStep ); m_SplineX->AddPoint( t, inputPoint[0] ); m_SplineY->AddPoint( t, inputPoint[1] ); m_SplineZ->AddPoint( t, inputPoint[2] ); ++pit; if ( pit == cell.PointIdsEnd() ) { pit = cell.PointIdsBegin(); } t += inputPoint.EuclideanDistanceTo( this->GetInput()->GetPoint( *pit, timeStep ) ); } // Evaluate the spline for the desired number of points // (number of input points) * (spline resolution) Point3D point, firstPoint, lastPoint; int numberOfSegments = numberOfPoints * m_SplineResolution; vtkFloatingPointType step = (tEnd - tStart) / numberOfSegments; for ( i = 0, t = tStart; i < numberOfSegments; ++i, t += step ) { FillVector3D( point, m_SplineX->Evaluate(t), m_SplineY->Evaluate(t), m_SplineZ->Evaluate(t) ); ptList.push_back( point ); if ( i == 0 ) { firstPoint = point; } else { vecList.push_back( point - lastPoint ); } lastPoint = point; } vecList.push_back( firstPoint - lastPoint ); } const mitk::Mesh *mitk::PolygonToRingFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Mesh * > (this->ProcessObject::GetInput(0) ); } void mitk::PolygonToRingFilter::SetInput(const mitk::Mesh *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Mesh * >( input ) ); } <commit_msg>BUGFIX: replaced int with vtkIdType due to a mail from Christian Teich on the sourceforge list. He said, his compiler (?) argued about this.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ 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 "mitkPolygonToRingFilter.h" #include "mitkMesh.h" #include "mitkSurface.h" #include "mitkPlaneGeometry.h" #include <vnl/vnl_cross.h> #include <vnl/vnl_quaternion.h> #include <vnl/vnl_quaternion.txx> #include <vtkPolyData.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkCardinalSpline.h> #include <vector> mitk::PolygonToRingFilter::PolygonToRingFilter() : m_RingRadius(3.5f), m_RingResolution(30), m_SplineResolution(20) { m_SplineX = vtkCardinalSpline::New(); m_SplineY = vtkCardinalSpline::New(); m_SplineZ = vtkCardinalSpline::New(); } mitk::PolygonToRingFilter::~PolygonToRingFilter() { m_SplineX->Delete(); m_SplineY->Delete(); m_SplineZ->Delete(); } void mitk::PolygonToRingFilter::GenerateOutputInformation() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(input.IsNull()) return; output->SetGeometry(static_cast<Geometry3D*>(input->GetGeometry()->Clone().GetPointer())); output->Resize( input->GetPointSetSeriesSize() ); } void mitk::PolygonToRingFilter::GenerateData() { mitk::Mesh::ConstPointer input = this->GetInput(); mitk::Surface::Pointer output = this->GetOutput(); int t; for ( t = 0; t < input->GetPointSetSeriesSize(); ++t ) { vtkPolyData *polyData = vtkPolyData::New(); vtkPoints *vPoints = vtkPoints::New(); vtkCellArray *polys = vtkCellArray::New(); mitk::Mesh::PointType thisPoint; // iterate through all cells and build tubes Mesh::CellIterator cellIt, cellEnd; cellEnd = input->GetMesh( t )->GetCells()->End(); for ( cellIt = input->GetMesh( t )->GetCells()->Begin(); cellIt != cellEnd; ++cellIt ) { m_PointList.clear(); m_VectorList.clear(); this->BuildPointAndVectorList( *cellIt->Value(), m_PointList, m_VectorList, t ); this->BuildVtkTube( vPoints, polys, m_PointList, m_VectorList ); } polyData->SetPoints( vPoints ); vPoints->Delete(); polyData->SetPolys( polys ); polys->Delete(); output->SetVtkPolyData( polyData, t ); polyData->Delete(); } } //sl: Stern Letzter //sc: Stern Current=aktueller Stern //idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. //last_p: Mittelpunkt des letzten Sterns //cur_p: Mittelpunkt des aktuellen Sterns void mitk::PolygonToRingFilter::DrawCyl(vtkPoints *vPoints, vtkCellArray *polys, VectorListType &sl, VectorListType &sc, int idmax, Point3D & last_p, Point3D & cur_p) { unsigned int i; //jetzt haben wir alles: sl0 wird mit sc->at(idmax) verbunden usw. VectorListType::iterator slit=sl.begin(), scit=sc.begin(), scend=sc.end(); scit+=idmax; Point3D a,b; Point3D a_first,b_first; int a_firstID = 0, b_firstID = 0; vtkIdType front[4]; for(i=0;i<m_RingResolution;++i) { VnlVector v0,v1,v2,v3,normal; v0=a.Get_vnl_vector(); v1=b.Get_vnl_vector(); a=last_p+*slit*m_RingRadius; b=cur_p+*scit*m_RingRadius; v2=b.Get_vnl_vector(); v3=a.Get_vnl_vector(); normal=vnl_cross_3d(v1-v0,v3-v0); if(i!=0) { front[3]=vPoints->InsertNextPoint(v0[0],v0[1],v0[2]); front[2]=vPoints->InsertNextPoint(v1[0],v1[1],v1[2]); front[1]=vPoints->InsertNextPoint(v2[0],v2[1],v2[2]); front[0]=vPoints->InsertNextPoint(v3[0],v3[1],v3[2]); polys->InsertNextCell( (vtkIdType) 4, front ); if(i==1) { a_firstID=front[3]; b_firstID=front[2]; //continue; } } ++slit; ++scit; if(scit==scend) scit=sc.begin(); } front[3]=front[0]; front[2]=front[1]; front[1]=b_firstID; front[0]=a_firstID; polys->InsertNextCell( 4, front ); } void mitk::PolygonToRingFilter::BuildVtkTube(vtkPoints *vPoints, vtkCellArray *polys, PointListType& ptList, VectorListType& vecList) { PointListType::iterator pit = ptList.begin(), pend = ptList.end(); VectorListType::iterator vit = vecList.begin(); Vector3D axis, last_v, next_v, s; Point3D cur_p,last_p; //Listen fr den Stern VectorListType *sl, *sc, *swp, sfirst, buf1, buf2; sl=&buf1; sc=&buf2; Vector3D a,b; Matrix3D m; //Initialisierung fr ersten Punkt //alternative1: // last_v=*(vl.getLast()); next_v=*vit.current(); axis=last_v+next_v; s.cross(last_v,next_v); s.normalize(); //alternative2: // last_v=*(vl.getLast()); next_v=*vit.current(); s.cross(last_v,next_v); s.normalize(); // axis=next_v-last_v; axis.normalize(); aa.set(s, M_PI/2.0); m.set(aa); m.transform(&axis); //alternative3: last_v=vecList.back(); next_v=*vit; s.Set_vnl_vector( vnl_cross_3d(last_v.Get_vnl_vector(),next_v.Get_vnl_vector()) ); s.Normalize(); a=last_v; b=next_v; a.Normalize(); b.Normalize(); axis=a+b; axis.Normalize(); //Stern am ersten Punkt aufbauen m = vnl_quaternion<mitk::ScalarType>(axis.Get_vnl_vector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); unsigned int i; for(i=0;i<m_RingResolution;++i) { sfirst.push_back(s); s=m*s; } *sl=sfirst; last_p=*pit; ++pit; ++vit; //nun die Hauptschleife ber alle Punkte for ( ; pit != pend; ++pit, ++vit ) { // cur_p=*pit.current(); last_v=next_v; next_v=*vit.current(); axis=last_v+next_v; s.cross(last_v,next_v); s.normalize(); cur_p=*pit; last_v=next_v; next_v=*vit; s.Set_vnl_vector( vnl_cross_3d(last_v.Get_vnl_vector(),next_v.Get_vnl_vector()) ); s.Normalize(); // axis=next_v-last_v; axis.normalize(); aa.set(s, M_PI/2.0); m.set(aa); m.transform(&axis); a=last_v; b=next_v; a.Normalize(); b.Normalize(); axis=a+b; axis.Normalize(); //neuen Stern sc (SternCurrent) bauen und dabei Start fr neuen Stern suchen double max=0; int idmax=0; Vector3D sl0=*(sl->begin()); m = vnl_quaternion<mitk::ScalarType>(axis.Get_vnl_vector(),2*vnl_math::pi/(double)m_RingResolution).rotation_matrix_transpose(); for(i=0;i<m_RingResolution;++i) { sc->push_back(s); double tmp=s*sl0; if(tmp>max) { max=tmp; idmax=i; } s=m*s; } //sl: Stern Letzter //sc: Stern Current=aktueller Stern //idmax: Id des Strahls des aktuellen Sterns (sc), der am besten zum ersten Strahl vom letzten Stern (sl) passt. //last_p: Mittelpunkt des letzten Sterns //cur_p: Mittelpunkt des aktuellen Sterns DrawCyl(vPoints, polys, *sl, *sc, idmax, last_p, cur_p); //bergang zum nchsten last_p=cur_p; swp=sl; sl=sc; sc=swp; sc->clear(); } //idmax fr Verbindung ersten mit letztem ausrechnen: double max=0; int idmax=0; Vector3D sl0=*(sl->begin()); for(i=0;i<m_RingResolution;++i) { s=sfirst[i]; double tmp=s*sl0; if(tmp>max) { max=tmp; idmax=i; } } cur_p=*ptList.begin(); DrawCyl(vPoints, polys, *sl, sfirst, idmax, last_p, cur_p); } void mitk::PolygonToRingFilter ::BuildPointAndVectorList( mitk::Mesh::CellType& cell, PointListType& ptList, VectorListType& vecList, int timeStep ) { // This method constructs a spline from the given point list and retrieves // a number of interpolated points from it to form a ring-like structure. // // To make the spline "closed", the end point is connected to the start // point. For ensuring smoothness at the start-end-point transition, the // (intrinsically non-circular) spline array is extended on both sides // by wrapping a number of points from the respective other side. // // The used VTK filters do principally support this kind of "closed" spline, // but it does not produce results as consistent as with the method used // here. Also, the spline class of VTK 4.4 has only poor support for // arbitrary parametric coordinates (t values in vtkSpline). VTK 5.0 has // better support, and also provides a new class vtkParametricSpline for // directly calculating 3D splines. // Remove points from previous call of this method m_SplineX->RemoveAllPoints(); m_SplineY->RemoveAllPoints(); m_SplineZ->RemoveAllPoints(); int numberOfPoints = cell.GetNumberOfPoints(); Mesh::PointType inputPoint; vtkFloatingPointType t, tStart(0), tEnd(0); // Add input points to the spline and assign each the parametric value t // derived from the point euclidean distances. int i; Mesh::PointIdIterator pit = cell.PointIdsEnd() - 3; for ( i = -3, t = 0.0; i < numberOfPoints + 3; ++i ) { if ( i == 0 ) { tStart = t; } if ( i == numberOfPoints ) { tEnd = t; } inputPoint = this->GetInput()->GetPoint( *pit, timeStep ); m_SplineX->AddPoint( t, inputPoint[0] ); m_SplineY->AddPoint( t, inputPoint[1] ); m_SplineZ->AddPoint( t, inputPoint[2] ); ++pit; if ( pit == cell.PointIdsEnd() ) { pit = cell.PointIdsBegin(); } t += inputPoint.EuclideanDistanceTo( this->GetInput()->GetPoint( *pit, timeStep ) ); } // Evaluate the spline for the desired number of points // (number of input points) * (spline resolution) Point3D point, firstPoint, lastPoint; int numberOfSegments = numberOfPoints * m_SplineResolution; vtkFloatingPointType step = (tEnd - tStart) / numberOfSegments; for ( i = 0, t = tStart; i < numberOfSegments; ++i, t += step ) { FillVector3D( point, m_SplineX->Evaluate(t), m_SplineY->Evaluate(t), m_SplineZ->Evaluate(t) ); ptList.push_back( point ); if ( i == 0 ) { firstPoint = point; } else { vecList.push_back( point - lastPoint ); } lastPoint = point; } vecList.push_back( firstPoint - lastPoint ); } const mitk::Mesh *mitk::PolygonToRingFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Mesh * > (this->ProcessObject::GetInput(0) ); } void mitk::PolygonToRingFilter::SetInput(const mitk::Mesh *input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Mesh * >( input ) ); } <|endoftext|>
<commit_before>// ================================================================================ // == This file is a part of TinkerBell UI Toolkit. (C) 2011-2013, Emil Segers == // == See tinkerbell.h for more information. == // ================================================================================ #include "tinkerbell.h" #include "tb_skin.h" #include "tb_widgets_reader.h" #include "tb_language.h" #include "tb_font_renderer.h" #include "tb_addon.h" #include <stdlib.h> #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> namespace tinkerbell { static const char *empty = ""; inline void safe_delete(char *&str) { if(str != empty && str) free(str); str = const_cast<char*>(empty); } // ================================================================ TBRenderer *g_renderer = nullptr; TBSkin *g_tb_skin = nullptr; TBWidgetsReader *g_widgets_reader = nullptr; TBLanguage *g_tb_lng = nullptr; TBFontManager *g_font_manager = nullptr; bool init_tinkerbell(TBRenderer *renderer, const char *lng_file) { g_renderer = renderer; g_tb_lng = new TBLanguage; g_tb_lng->Load(lng_file); g_font_manager = new TBFontManager(); g_tb_skin = new TBSkin(); g_widgets_reader = TBWidgetsReader::Create(); return TBInitAddons(); } void shutdown_tinkerbell() { TBShutdownAddons(); delete g_widgets_reader; delete g_tb_skin; delete g_font_manager; delete g_tb_lng; } // == TBRect ====================================================== bool TBRect::Intersects(const TBRect &rect) const { if (IsEmpty() || rect.IsEmpty()) return false; if (x + w > rect.x && x < rect.x + rect.w && y + h > rect.y && y < rect.y + rect.h) return true; return false; } TBRect TBRect::Union(const TBRect &rect) const { assert(!IsInsideOut()); assert(!rect.IsInsideOut()); if (IsEmpty()) return rect; if (rect.IsEmpty()) return *this; int minx = MIN(x, rect.x); int miny = MIN(y, rect.y); int maxx = x + w > rect.x + rect.w ? x + w : rect.x + rect.w; int maxy = y + h > rect.y + rect.h ? y + h : rect.y + rect.h; return TBRect(minx, miny, maxx - minx, maxy - miny); } TBRect TBRect::Clip(const TBRect &clip_rect) const { assert(!clip_rect.IsInsideOut()); TBRect tmp; if (!Intersects(clip_rect)) return tmp; tmp.x = MAX(x, clip_rect.x); tmp.y = MAX(y, clip_rect.y); tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x; tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y; return tmp; } // =================================================================== const char *stristr(const char *arg1, const char *arg2) { const char *a, *b; for(;*arg1;*arg1++) { a = arg1; b = arg2; while(toupper(*a++) == toupper(*b++)) if(!*b) return arg1; } return nullptr; } // == TBStr ========================================================== TBStr::TBStr() : TBStrC(empty) { } TBStr::TBStr(const char* str) : TBStrC(str == empty ? empty : strdup(str)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const TBStr &str) : TBStrC(str.s == empty ? empty : strdup(str.s)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const char* str, int len) : TBStrC(empty) { Set(str, len); } TBStr::~TBStr() { safe_delete(s); } bool TBStr::Set(const char* str, int len) { safe_delete(s); if (len == TB_ALL_TO_TERMINATION) len = strlen(str); if (char *new_s = (char *) malloc(len + 1)) { s = new_s; memcpy(s, str, len); s[len] = 0; return true; } return false; } bool TBStr::SetFormatted(const char* format, ...) { safe_delete(s); if (!format) return true; va_list ap; int max_len = 64; char *new_s = nullptr; while (true) { if (char *tris_try_new_s = (char *) realloc(new_s, max_len)) { new_s = tris_try_new_s; va_start(ap, format); int ret = vsnprintf(new_s, max_len, format, ap); va_end(ap); if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity) max_len = ret + 2; else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations. max_len *= 2; else // Everything fit for sure { s = new_s; return true; } } else { // Out of memory free(new_s); break; } } return false; } void TBStr::Clear() { safe_delete(s); } void TBStr::Remove(int ofs, int len) { assert(ofs >= 0 && (ofs + len <= (int)strlen(s))); if (!len) return; char *dst = s + ofs; char *src = s + ofs + len; while (*src != 0) *(dst++) = *(src++); *dst = *src; } bool TBStr::Insert(int ofs, const char *ins, int ins_len) { int len1 = strlen(s); if (ins_len == TB_ALL_TO_TERMINATION) ins_len = strlen(ins); int newlen = len1 + ins_len; if (char *news = (char *) malloc(newlen + 1)) { memcpy(&news[0], s, ofs); memcpy(&news[ofs], ins, ins_len); memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs); news[newlen] = 0; safe_delete(s); s = news; return true; } return false; } // == TBID ================================================================================================== #ifdef _DEBUG // Hash table for checking if we get any collisions (same hash value for TBID's created // from different strings) static TBHashTableAutoDeleteOf<TBID> all_id_hash; static bool is_adding = false; void TBID::Set(uint32 newid) { id = newid; debug_string.Clear(); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.IsEmpty()); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const TBID &newid) { id = newid; TB_IF_DEBUG(debug_string.Set(newid.debug_string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { // If this happens, 2 different strings result in the same hash. // It might be a good idea to change one of them, but it might not matter. assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const char *string) { id = TBGetHash(string); TB_IF_DEBUG(debug_string.Set(string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } #endif // _DEBUG // == TBColor =============================================================================================== void TBColor::SetFromString(const char *str, int len) { int r, g, b, a; if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4) // rrggbbaa Set(TBColor(r, g, b, a)); else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3) // rrggbb Set(TBColor(r, g, b)); else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4) // rgba Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4))); else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3) // rgb Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4))); else Set(TBColor()); } // == TBDimensionConverter ================================================================================== void TBDimensionConverter::SetDPI(int src_dpi, int dst_dpi) { m_src_dpi = src_dpi; m_dst_dpi = dst_dpi; m_dst_dpi_str.Clear(); if (NeedConversion()) m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi); } void TBDimensionConverter::GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const { int dot_pos = 0; for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--) if (filename[dot_pos] == '.') break; tempbuf->ResetAppendPos(); tempbuf->Append(filename, dot_pos); tempbuf->AppendString(GetDstDPIStr()); tempbuf->AppendString(filename + dot_pos); } int TBDimensionConverter::DpToPx(int dp) const { if (dp <= TB_INVALID_DIMENSION || dp == 0) return dp; if (dp > 0) { dp = dp * m_dst_dpi / m_src_dpi; return MAX(dp, 1); } else { dp = dp * m_dst_dpi / m_src_dpi; return MIN(dp, -1); } } // == TBPx ================================================================================================== void TBPx::SetFromString(const TBDimensionConverter &converter, const char *str) { if (!str || !isdigit(*str)) return; int len = strlen(str); int val = atoi(str); if (len > 2 && strcmp(str + len - 2, "dp") == 0) px = converter.DpToPx(val); else px = val; } void TBPx::SetDP(const TBDimensionConverter &converter, int dp) { px = converter.DpToPx(dp); } }; // namespace tinkerbell <commit_msg>Minor optimization<commit_after>// ================================================================================ // == This file is a part of TinkerBell UI Toolkit. (C) 2011-2013, Emil Segers == // == See tinkerbell.h for more information. == // ================================================================================ #include "tinkerbell.h" #include "tb_skin.h" #include "tb_widgets_reader.h" #include "tb_language.h" #include "tb_font_renderer.h" #include "tb_addon.h" #include <stdlib.h> #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> namespace tinkerbell { static const char *empty = ""; inline void safe_delete(char *&str) { if(str != empty && str) free(str); str = const_cast<char*>(empty); } // ================================================================ TBRenderer *g_renderer = nullptr; TBSkin *g_tb_skin = nullptr; TBWidgetsReader *g_widgets_reader = nullptr; TBLanguage *g_tb_lng = nullptr; TBFontManager *g_font_manager = nullptr; bool init_tinkerbell(TBRenderer *renderer, const char *lng_file) { g_renderer = renderer; g_tb_lng = new TBLanguage; g_tb_lng->Load(lng_file); g_font_manager = new TBFontManager(); g_tb_skin = new TBSkin(); g_widgets_reader = TBWidgetsReader::Create(); return TBInitAddons(); } void shutdown_tinkerbell() { TBShutdownAddons(); delete g_widgets_reader; delete g_tb_skin; delete g_font_manager; delete g_tb_lng; } // == TBRect ====================================================== bool TBRect::Intersects(const TBRect &rect) const { if (IsEmpty() || rect.IsEmpty()) return false; if (x + w > rect.x && x < rect.x + rect.w && y + h > rect.y && y < rect.y + rect.h) return true; return false; } TBRect TBRect::Union(const TBRect &rect) const { assert(!IsInsideOut()); assert(!rect.IsInsideOut()); if (IsEmpty()) return rect; if (rect.IsEmpty()) return *this; int minx = MIN(x, rect.x); int miny = MIN(y, rect.y); int maxx = x + w > rect.x + rect.w ? x + w : rect.x + rect.w; int maxy = y + h > rect.y + rect.h ? y + h : rect.y + rect.h; return TBRect(minx, miny, maxx - minx, maxy - miny); } TBRect TBRect::Clip(const TBRect &clip_rect) const { assert(!clip_rect.IsInsideOut()); TBRect tmp; if (!Intersects(clip_rect)) return tmp; tmp.x = MAX(x, clip_rect.x); tmp.y = MAX(y, clip_rect.y); tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x; tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y; return tmp; } // =================================================================== const char *stristr(const char *arg1, const char *arg2) { const char *a, *b; for(;*arg1;*arg1++) { a = arg1; b = arg2; while(toupper(*a++) == toupper(*b++)) if(!*b) return arg1; } return nullptr; } // == TBStr ========================================================== TBStr::TBStr() : TBStrC(empty) { } TBStr::TBStr(const char* str) : TBStrC(str == empty ? empty : strdup(str)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const TBStr &str) : TBStrC(str.s == empty ? empty : strdup(str.s)) { if (!s) s = const_cast<char*>(empty); } TBStr::TBStr(const char* str, int len) : TBStrC(empty) { Set(str, len); } TBStr::~TBStr() { safe_delete(s); } bool TBStr::Set(const char* str, int len) { safe_delete(s); if (len == TB_ALL_TO_TERMINATION) len = strlen(str); if (char *new_s = (char *) malloc(len + 1)) { s = new_s; memcpy(s, str, len); s[len] = 0; return true; } return false; } bool TBStr::SetFormatted(const char* format, ...) { safe_delete(s); if (!format) return true; va_list ap; int max_len = 64; char *new_s = nullptr; while (true) { if (char *tris_try_new_s = (char *) realloc(new_s, max_len)) { new_s = tris_try_new_s; va_start(ap, format); int ret = vsnprintf(new_s, max_len, format, ap); va_end(ap); if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity) max_len = ret + 2; else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations. max_len *= 2; else // Everything fit for sure { s = new_s; return true; } } else { // Out of memory free(new_s); break; } } return false; } void TBStr::Clear() { safe_delete(s); } void TBStr::Remove(int ofs, int len) { assert(ofs >= 0 && (ofs + len <= (int)strlen(s))); if (!len) return; char *dst = s + ofs; char *src = s + ofs + len; while (*src != 0) *(dst++) = *(src++); *dst = *src; } bool TBStr::Insert(int ofs, const char *ins, int ins_len) { int len1 = strlen(s); if (ins_len == TB_ALL_TO_TERMINATION) ins_len = strlen(ins); int newlen = len1 + ins_len; if (char *news = (char *) malloc(newlen + 1)) { memcpy(&news[0], s, ofs); memcpy(&news[ofs], ins, ins_len); memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs); news[newlen] = 0; safe_delete(s); s = news; return true; } return false; } // == TBID ================================================================================================== #ifdef _DEBUG // Hash table for checking if we get any collisions (same hash value for TBID's created // from different strings) static TBHashTableAutoDeleteOf<TBID> all_id_hash; static bool is_adding = false; void TBID::Set(uint32 newid) { id = newid; debug_string.Clear(); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.IsEmpty()); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const TBID &newid) { id = newid; TB_IF_DEBUG(debug_string.Set(newid.debug_string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { // If this happens, 2 different strings result in the same hash. // It might be a good idea to change one of them, but it might not matter. assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } void TBID::Set(const char *string) { id = TBGetHash(string); TB_IF_DEBUG(debug_string.Set(string)); if (!is_adding) { if (TBID *other_id = all_id_hash.Get(id)) { assert(other_id->debug_string.Equals(debug_string)); } else { is_adding = true; all_id_hash.Add(id, new TBID(*this)); is_adding = false; } } } #endif // _DEBUG // == TBColor =============================================================================================== void TBColor::SetFromString(const char *str, int len) { int r, g, b, a; if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4) // rrggbbaa Set(TBColor(r, g, b, a)); else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3) // rrggbb Set(TBColor(r, g, b)); else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4) // rgba Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4))); else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3) // rgb Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4))); else Set(TBColor()); } // == TBDimensionConverter ================================================================================== void TBDimensionConverter::SetDPI(int src_dpi, int dst_dpi) { m_src_dpi = src_dpi; m_dst_dpi = dst_dpi; m_dst_dpi_str.Clear(); if (NeedConversion()) m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi); } void TBDimensionConverter::GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const { int dot_pos = 0; for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--) if (filename[dot_pos] == '.') break; tempbuf->ResetAppendPos(); tempbuf->Append(filename, dot_pos); tempbuf->AppendString(GetDstDPIStr()); tempbuf->AppendString(filename + dot_pos); } int TBDimensionConverter::DpToPx(int dp) const { if (dp <= TB_INVALID_DIMENSION || dp == 0 || !NeedConversion()) return dp; if (dp > 0) { dp = dp * m_dst_dpi / m_src_dpi; return MAX(dp, 1); } else { dp = dp * m_dst_dpi / m_src_dpi; return MIN(dp, -1); } } // == TBPx ================================================================================================== void TBPx::SetFromString(const TBDimensionConverter &converter, const char *str) { if (!str || !isdigit(*str)) return; int len = strlen(str); int val = atoi(str); if (len > 2 && strcmp(str + len - 2, "dp") == 0) px = converter.DpToPx(val); else px = val; } void TBPx::SetDP(const TBDimensionConverter &converter, int dp) { px = converter.DpToPx(dp); } }; // namespace tinkerbell <|endoftext|>
<commit_before>#include "main.h" // --- Params --- // NoiseParams noise_params; WaterParams water_params; LightParams light_params; TextureParams texture_params; WindowParams window_params{ WIDTH, HEIGHT }; GridParams grid_params; // --- Scene Objects --- // Grid grid; Water water; Box box; Sky sky; // --- Buffers --- // Framebuffer fbw(WIDTH, HEIGHT); Depthbuffer fb_water_depth(WIDTH, HEIGHT); // --- Textures --- // GLuint tex_height; GLuint tex_mirror; GLuint tex_water_depth; GLuint tex_normal_map; // --- Other --- // NoiseGenerator noise_generator(&tex_height, &noise_params); Camera camera(&window_params); // --- TODO: refactor and move bezier related code to a better location */ NAVIGATION_MODE navmode; Bezier bezier; // Gets called when the windows is resized. void resize_callback(int width, int height) { window_params.width = width; window_params.height = height; glViewport(0, 0, width, height); fbw.resize(width, height); fb_water_depth.resize(width, height); camera.compute_projection_matrix(); } void compute_height_map() { noise_generator.renderFractal(); box.set_height_texture(tex_height); grid.set_height_texture(tex_height); water.set_height_texture(tex_height); water.set_mirror_texture(tex_mirror); water.set_normal_map(tex_normal_map); } void init(){ // Sets background color. glClearColor(/*gray*/ .937,.937,.937, /*solid*/1.0); // Enable depth test. glEnable(GL_DEPTH_TEST); bezier.init(); initParams(); initTextures(); initSceneObjects(); noise_generator.init(); navmode = FREE; compute_height_map(); #ifdef WITH_ANTTWEAKBAR initAntTwBar(&grid_params, &window_params, &noise_params, &water_params, &texture_params); #endif check_error_gl(); } // Gets called for every frame. void display(){ opengp::update_title_fps("Terrain"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mat4 view_matrix = camera.get_view_matrix(); mat4 view_matrix_mirrored = camera.get_view_matrix_mirrored(); // for water reflections if (navmode == BEZIER) { vec3 cam_pos(2.0f, 2.0f, 2.0f); vec3 cam_look(0.0f, 0.0f, 0.0f); vec3 cam_up(0.0f, 0.0f, 1.0f); float t = (glfwGetTime() - bezier.get_start_time()) / bezier.get_travel_time(); if (t >= 1) { bezier.set_start_time(glfwGetTime()); t = t - 1; } bezier.pos_curve_sample_point(t, cam_pos); bezier.cam_look_sample_point(t, cam_look); view_matrix = Eigen::lookAt(cam_pos, cam_look, cam_up); } else { // FREE/default mode camera.move(); } // Render the water reflect fbw.bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); grid.draw(view_matrix_mirrored, camera.get_projection_matrix(), true); fbw.unbind(); glViewport(0, 0, window_params.width, window_params.height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); fb_water_depth.bind(); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); grid.draw(view_matrix, camera.get_projection_matrix(), false); fb_water_depth.unbind(); grid.draw(view_matrix, camera.get_projection_matrix(), false); water.draw(view_matrix, camera.get_projection_matrix()); box.draw(view_matrix, camera.get_projection_matrix()); sky.draw(view_matrix, camera.get_projection_matrix()); #ifdef WITH_ANTTWEAKBAR TwDraw(); #endif } void cleanup(){ #ifdef WITH_ANTTWEAKBAR TwTerminate(); #endif bezier.cleanup(); } int main(int, char**){ glfwInitWindowSize(window_params.width, window_params.height); glfwCreateWindow("Terrain"); glfwDisplayFunc(display); glfwSetWindowSizeCallback(OnWindowSize); glfwSetMouseButtonCallback(OnMouseButton); glfwSetMousePosCallback(OnMousePos); glfwSetMouseWheelCallback(OnMouseWheel); glfwSetKeyCallback(OnKey); glfwSetCharCallback(OnChar); init(); glfwMainLoop(); cleanup(); return EXIT_SUCCESS; } // --- Helpers --- // void initParams() { // --- Window --- window_params.width = WIDTH; window_params.height = HEIGHT; // --- Grid --- grid_params.resolution = 100; grid_params.length = 2; grid_params.width = 2; // --- Noise --- noise_params.noise_type = PERLIN_NOISE; noise_params.fractal_type = FBM; noise_params.noise_effect = NO_EFFECT; noise_params.fractal_effect = NO_EFFECT; noise_params.height = 1; noise_params.width = 1; noise_params.offset = 0.0f; noise_params.amplitude = 1.0f; noise_params.H = 1.2f; noise_params.lacunarity = 2; noise_params.octaves = 12; noise_params.seed = glfwGetTime(); noise_params.seed -= floor(noise_params.seed); // --- Water --- water_params.height = 0; water_params.color = vec3(0.4f, 0.55f, 0.6f); water_params.depth_alpha_factor = 1.4f; water_params.depth_color_factor = 0.05f; water_params.transparency = 0.4f; water_params.reflection_factor = 0.25f; /*water_params.waves_speed = 0.04f; water_params.waves_tile_factor = 2.0; water_params.waves_amplitude = 1.0f;*/ // --- Light --- light_params.Ia = vec3(0.7f, 0.7f, 0.7f); light_params.Id = vec3(0.3f, 0.3f, 0.3f); light_params.position = vec3(2.0f, 2.0f, 2.0f); // --- Texture --- texture_params.sand_min_height = -1; texture_params.sand_max_height = 0.15f; texture_params.grass_max_height = 1.0f; texture_params.sand_max_slope = 0.92f; texture_params.grass_max_slope = 0.9f; texture_params.grass_h_transition = 3; texture_params.grass_s_transition = 50; texture_params.sand_h_transition = 5; texture_params.sand_s_transition = 50; } void initSceneObjects() { box.init(&grid_params, &water_params, &noise_params); grid.init(&grid_params, &light_params, &texture_params); tex_mirror = fbw.init_texture(); fbw.init(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE); tex_water_depth = fb_water_depth.init_texture(); fb_water_depth.init(); water.init(&grid_params, &water_params, &light_params); water.set_depth_texture(tex_water_depth); sky.init(); check_error_gl(); } void initTextures() { glGenTextures(1, &tex_normal_map); glBindTexture(GL_TEXTURE_2D, tex_normal_map); glfwLoadTexture2D("textures/water/tex_normal_map.tga", 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // --- Callbacks --- // // Callback function called by GLFW when a mouse button is clicked void GLFWCALL OnMouseButton(int glfwButton, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMouseButtonGLFW(glfwButton, glfwAction)) // Send event to AntTweakBar { #endif if (navmode == BEZIER) { std::cout << "[Warning] No mouse interaction in Bezier mode.\n" << std::flush; return; } // Event not handled by AntTweakBar, we handle it ourselves camera.mouse_button(glfwButton, glfwAction); #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW when mouse has moved void GLFWCALL OnMousePos(int mouseX, int mouseY) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMousePosGLFW(mouseX, mouseY)) // Send event to AntTweakBar { #endif if (navmode == BEZIER) { return; } camera.mouse_pos(mouseX, mouseY); #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on mouse wheel event void GLFWCALL OnMouseWheel(int pos) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMouseWheelGLFW(pos)) // Send event to AntTweakBar { #endif // Nothing for the moment #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on key event void GLFWCALL OnKey(int glfwKey, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventKeyGLFW(glfwKey, glfwAction)) // Send event to AntTweakBar { #endif if (glfwKey == GLFW_KEY_ESC && glfwAction == GLFW_PRESS) // Want to quit? glfwCloseWindow(); else { camera.keyboard(glfwKey, glfwAction); if (glfwAction != GLFW_RELEASE) return; ///< only act on release switch (glfwKey){ case '1': navmode = FREE; std::cout << "[Info] Running in free mode\n" << std::flush; isVisible(true); break; case '2': navmode = BEZIER; std::cout << "[Info] Running in bezier mode\n" << std::flush; bezier.set_start_time(glfwGetTime()); isVisible(false); break; default: std::cout << "[Warning] No keyboard interaction in bezier mode.\n" << std::flush; break; } } #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on char event void GLFWCALL OnChar(int glfwChar, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventCharGLFW(glfwChar, glfwAction)) // Send event to AntTweakBar { #endif // Nothing for the moment #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW when window size changes void GLFWCALL OnWindowSize(int width, int height) { #ifdef WITH_ANTTWEAKBAR // Send the new window size to AntTweakBar TwWindowSize(width, height); #endif resize_callback(width, height); }<commit_msg>Ready to merge<commit_after>#include "main.h" // --- Params --- // NoiseParams noise_params; WaterParams water_params; LightParams light_params; TextureParams texture_params; WindowParams window_params{ WIDTH, HEIGHT }; GridParams grid_params; // --- Scene Objects --- // Grid grid; Water water; Box box; Sky sky; // --- Buffers --- // Framebuffer fbw(WIDTH, HEIGHT); Depthbuffer fb_water_depth(WIDTH, HEIGHT); // --- Textures --- // GLuint tex_height; GLuint tex_mirror; GLuint tex_water_depth; GLuint tex_normal_map; // --- Camera --- // Camera camera(&window_params); NAVIGATION_MODE navmode; Bezier bezier; // --- Other --- // NoiseGenerator noise_generator(&tex_height, &noise_params); // Gets called when the windows is resized. void resize_callback(int width, int height) { window_params.width = width; window_params.height = height; glViewport(0, 0, width, height); fbw.resize(width, height); fb_water_depth.resize(width, height); camera.compute_projection_matrix(); } void compute_height_map() { noise_generator.renderFractal(); box.set_height_texture(tex_height); grid.set_height_texture(tex_height); water.set_height_texture(tex_height); water.set_mirror_texture(tex_mirror); water.set_normal_map(tex_normal_map); } void init(){ // Sets background color. glClearColor(/*gray*/ .937,.937,.937, /*solid*/1.0); // Enable depth test. glEnable(GL_DEPTH_TEST); bezier.init(); initParams(); initTextures(); initSceneObjects(); noise_generator.init(); navmode = FREE; compute_height_map(); #ifdef WITH_ANTTWEAKBAR initAntTwBar(&grid_params, &window_params, &noise_params, &water_params, &texture_params); #endif check_error_gl(); } // Gets called for every frame. void display(){ opengp::update_title_fps("Terrain"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mat4 view_matrix = camera.get_view_matrix(); mat4 view_matrix_mirrored = camera.get_view_matrix_mirrored(); // for water reflections if (navmode == BEZIER) { vec3 cam_pos(2.0f, 2.0f, 2.0f); vec3 cam_look(0.0f, 0.0f, 0.0f); vec3 cam_up(0.0f, 0.0f, 1.0f); float t = (glfwGetTime() - bezier.get_start_time()) / bezier.get_travel_time(); if (t >= 1) { bezier.set_start_time(glfwGetTime()); t = t - 1; } bezier.pos_curve_sample_point(t, cam_pos); bezier.cam_look_sample_point(t, cam_look); view_matrix = Eigen::lookAt(cam_pos, cam_look, cam_up); } else { // FREE/default mode camera.move(); } // Render the water reflect fbw.bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); grid.draw(view_matrix_mirrored, camera.get_projection_matrix(), true); fbw.unbind(); glViewport(0, 0, window_params.width, window_params.height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); fb_water_depth.bind(); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); grid.draw(view_matrix, camera.get_projection_matrix(), false); fb_water_depth.unbind(); grid.draw(view_matrix, camera.get_projection_matrix(), false); water.draw(view_matrix, camera.get_projection_matrix()); box.draw(view_matrix, camera.get_projection_matrix()); sky.draw(view_matrix, camera.get_projection_matrix()); #ifdef WITH_ANTTWEAKBAR TwDraw(); #endif } void cleanup(){ #ifdef WITH_ANTTWEAKBAR TwTerminate(); #endif bezier.cleanup(); } int main(int, char**){ glfwInitWindowSize(window_params.width, window_params.height); glfwCreateWindow("Terrain"); glfwDisplayFunc(display); glfwSetWindowSizeCallback(OnWindowSize); glfwSetMouseButtonCallback(OnMouseButton); glfwSetMousePosCallback(OnMousePos); glfwSetMouseWheelCallback(OnMouseWheel); glfwSetKeyCallback(OnKey); glfwSetCharCallback(OnChar); init(); glfwMainLoop(); cleanup(); return EXIT_SUCCESS; } // --- Helpers --- // void initParams() { // --- Window --- window_params.width = WIDTH; window_params.height = HEIGHT; // --- Grid --- grid_params.resolution = 100; grid_params.length = 2; grid_params.width = 2; // --- Noise --- noise_params.noise_type = PERLIN_NOISE; noise_params.fractal_type = FBM; noise_params.noise_effect = NO_EFFECT; noise_params.fractal_effect = NO_EFFECT; noise_params.height = 1; noise_params.width = 1; noise_params.offset = 0.0f; noise_params.amplitude = 1.0f; noise_params.H = 1.2f; noise_params.lacunarity = 2; noise_params.octaves = 12; noise_params.seed = glfwGetTime(); noise_params.seed -= floor(noise_params.seed); // --- Water --- water_params.height = 0; water_params.color = vec3(0.4f, 0.55f, 0.6f); water_params.depth_alpha_factor = 1.4f; water_params.depth_color_factor = 0.05f; water_params.transparency = 0.4f; water_params.reflection_factor = 0.25f; /*water_params.waves_speed = 0.04f; water_params.waves_tile_factor = 2.0; water_params.waves_amplitude = 1.0f;*/ // --- Light --- light_params.Ia = vec3(0.7f, 0.7f, 0.7f); light_params.Id = vec3(0.3f, 0.3f, 0.3f); light_params.position = vec3(2.0f, 2.0f, 2.0f); // --- Texture --- texture_params.sand_min_height = -1; texture_params.sand_max_height = 0.15f; texture_params.grass_max_height = 1.0f; texture_params.sand_max_slope = 0.92f; texture_params.grass_max_slope = 0.9f; texture_params.grass_h_transition = 3; texture_params.grass_s_transition = 50; texture_params.sand_h_transition = 5; texture_params.sand_s_transition = 50; } void initSceneObjects() { box.init(&grid_params, &water_params, &noise_params); grid.init(&grid_params, &light_params, &texture_params); tex_mirror = fbw.init_texture(); fbw.init(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE); tex_water_depth = fb_water_depth.init_texture(); fb_water_depth.init(); water.init(&grid_params, &water_params, &light_params); water.set_depth_texture(tex_water_depth); sky.init(); check_error_gl(); } void initTextures() { glGenTextures(1, &tex_normal_map); glBindTexture(GL_TEXTURE_2D, tex_normal_map); glfwLoadTexture2D("textures/water/tex_normal_map.tga", 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // --- Callbacks --- // // Callback function called by GLFW when a mouse button is clicked void GLFWCALL OnMouseButton(int glfwButton, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMouseButtonGLFW(glfwButton, glfwAction)) // Send event to AntTweakBar { #endif if (navmode == BEZIER) { std::cout << "[Warning] No mouse interaction in Bezier mode.\n" << std::flush; return; } // Event not handled by AntTweakBar, we handle it ourselves camera.mouse_button(glfwButton, glfwAction); #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW when mouse has moved void GLFWCALL OnMousePos(int mouseX, int mouseY) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMousePosGLFW(mouseX, mouseY)) // Send event to AntTweakBar { #endif if (navmode == BEZIER) { return; } camera.mouse_pos(mouseX, mouseY); #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on mouse wheel event void GLFWCALL OnMouseWheel(int pos) { #ifdef WITH_ANTTWEAKBAR if (!TwEventMouseWheelGLFW(pos)) // Send event to AntTweakBar { #endif // Nothing for the moment #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on key event void GLFWCALL OnKey(int glfwKey, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventKeyGLFW(glfwKey, glfwAction)) // Send event to AntTweakBar { #endif if (glfwKey == GLFW_KEY_ESC && glfwAction == GLFW_PRESS) // Want to quit? glfwCloseWindow(); else { camera.keyboard(glfwKey, glfwAction); if (glfwAction != GLFW_RELEASE) return; ///< only act on release switch (glfwKey){ case '1': navmode = FREE; std::cout << "[Info] Running in free mode\n" << std::flush; isVisible(true); break; case '2': navmode = BEZIER; std::cout << "[Info] Running in bezier mode\n" << std::flush; bezier.set_start_time(glfwGetTime()); isVisible(false); break; default: std::cout << "[Warning] No keyboard interaction in bezier mode.\n" << std::flush; break; } } #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW on char event void GLFWCALL OnChar(int glfwChar, int glfwAction) { #ifdef WITH_ANTTWEAKBAR if (!TwEventCharGLFW(glfwChar, glfwAction)) // Send event to AntTweakBar { #endif // Nothing for the moment #ifdef WITH_ANTTWEAKBAR } #endif } // Callback function called by GLFW when window size changes void GLFWCALL OnWindowSize(int width, int height) { #ifdef WITH_ANTTWEAKBAR // Send the new window size to AntTweakBar TwWindowSize(width, height); #endif resize_callback(width, height); }<|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/serialization/vector.hpp> #include <boost/foreach.hpp> #include <bh.h> #include <vector> #include <map> #include <iostream> #include <sstream> #include <stdexcept> #include "bh_ir.h" #include "bh_fuse.h" using namespace std; using namespace boost; namespace io = boost::iostreams; /* Creates a Bohrium Internal Representation (BhIR) from a instruction list. * * @ninstr Number of instructions * @instr_list The instruction list */ bh_ir::bh_ir(bh_intp ninstr, const bh_instruction instr_list[]) { bh_ir::instr_list = vector<bh_instruction>(instr_list, &instr_list[ninstr]); } /* Creates a BhIR from a serialized BhIR. * * @bhir The BhIr serialized as a char array or vector */ bh_ir::bh_ir(const char bhir[], bh_intp size) { io::basic_array_source<char> source(bhir,size); io::stream<io::basic_array_source <char> > input_stream(source); archive::binary_iarchive ia(input_stream); ia >> *this; } /* Serialize the BhIR object into a char buffer * (use the bh_ir constructor for deserialization) * * @buffer The char vector to serialize into */ void bh_ir::serialize(vector<char> &buffer) const { io::stream<io::back_insert_device<vector<char> > > output_stream(buffer); archive::binary_oarchive oa(output_stream); oa << *this; output_stream.flush(); } /* Returns the cost of the BhIR */ uint64_t bh_ir::cost() const { uint64_t sum = 0; BOOST_FOREACH(const bh_ir_kernel &k, kernel_list) { sum += k.cost(); } return sum; } /* Pretty print the kernel list */ void bh_ir::pprint_kernel_list() const { char msg[100]; int i=0; BOOST_FOREACH(const bh_ir_kernel &k, kernel_list) { snprintf(msg, 100, "kernel-%d", i++); bh_pprint_instr_krnl(&k, msg); } } void bh_ir_kernel::add_instr(uint64_t instr_idx) { /* Help function that checks if aligned view 'v' exist in 'views' */ struct { bool operator()(const bh_view &v, const vector<bh_view> &views) { BOOST_FOREACH(const bh_view &i, views) { if(bh_view_aligned(&v, &i)) return true; } return false; } }aligned_view_exist; const bh_instruction& instr = bhir->instr_list[instr_idx]; if(instr.opcode == BH_DISCARD) { //When discarding we might have to remove arrays from 'outputs' and 'temps' const bh_base *base = instr.operand[0].base; for(vector<bh_view>::iterator it=outputs.begin(); it != outputs.end(); ++it) { if(base == it->base) { outputs.erase(it); //If the discarded array isn't in 'inputs' (and not in 'outputs') //than it is a temp array if(not aligned_view_exist(*it, inputs)) temps.push_back(base); break; } } } else if(instr.opcode != BH_FREE) { //Add the output of the instruction to 'outputs' if(not aligned_view_exist(instr.operand[0], outputs)) outputs.push_back(instr.operand[0]); //Add the inputs of the instruction to 'inputs' const int nop = bh_operands(instr.opcode); for(int i=1; i<nop; ++i) { const bh_view &v = instr.operand[i]; if(bh_is_constant(&v)) continue; //If 'v' is in 'inputs' already we can continue if(aligned_view_exist(v, inputs)) continue; //Additionally, we shouldn't add 'v' to 'inputs' if it is //the output of an existing instruction. bool local_source = false; BOOST_FOREACH(uint64_t idx, instr_indexes) { if(bh_view_aligned(&v, &bhir->instr_list[idx].operand[0])) { local_source = true; break; } } if(!local_source) inputs.push_back(v); } } instr_indexes.push_back(instr_idx); }; /* Determines whether all instructions in 'this' kernel * are system opcodes (e.g. BH_DISCARD, BH_FREE, etc.) * * @return The boolean answer */ bool bh_ir_kernel::only_system_opcodes() const { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { if(not bh_opcode_is_system(bhir->instr_list[this_idx].opcode)) return false; } return true; } /* Determines whether the kernel fusible legal * * @return The boolean answer */ bool bh_ir_kernel::fusible() const { for(uint64_t i=0; i<instr_indexes.size(); ++i) { const bh_instruction *instr = &bhir->instr_list[instr_indexes[i]]; for(uint64_t j=i+1; j<instr_indexes.size(); ++j) { if(not bohrium::check_fusible(instr, &bhir->instr_list[instr_indexes[j]])) return false; } } return true; } /* Determines whether it is legal to fuse with the instruction * * @instr_idx The index of the instruction * @return The boolean answer */ bool bh_ir_kernel::fusible(uint64_t instr_idx) const { const bh_instruction *instr = &bhir->instr_list[instr_idx]; BOOST_FOREACH(uint64_t i, instr_indexes) { if(not bohrium::check_fusible(instr, &bhir->instr_list[i])) return false; } return true; } /* Determines whether it is legal to fuse with the kernel * * @other The other kernel * @return The boolean answer */ bool bh_ir_kernel::fusible(const bh_ir_kernel &other) const { BOOST_FOREACH(uint64_t idx1, instr_indexes) { const bh_instruction *instr = &bhir->instr_list[idx1]; BOOST_FOREACH(uint64_t idx2, other.instr_indexes) { if(not bohrium::check_fusible(instr, &other.bhir->instr_list[idx2])) return false; } } return true; } /* Determines whether it is legal to fuse with the instruction * without changing 'this' kernel's dependencies. * * @instr_idx The index of the instruction * @return The boolean answer */ bool bh_ir_kernel::fusible_gently(uint64_t instr_idx) const { const bh_instruction &instr = bhir->instr_list[instr_idx]; //Check that 'instr' is gentle fusible with at least one existing instruction //that is not a system opcode (unless all instructions in 'this' kernel are //system opcodes) if(only_system_opcodes()) { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { const bh_instruction &this_instr = bhir->instr_list[this_idx]; if(bh_instr_fusible_gently(&instr, &this_instr) && bohrium::check_fusible(&instr, &this_instr)) return true; } } else { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { const bh_instruction &this_instr = bhir->instr_list[this_idx]; if(bh_opcode_is_system(this_instr.opcode)) continue; if(bh_instr_fusible_gently(&instr, &this_instr) && bohrium::check_fusible(&instr, &this_instr)) return true; } } return false; } /* Determines whether it is legal to fuse with the kernel without * changing 'this' kernel's dependencies. * * @other The other kernel * @return The boolean answer */ bool bh_ir_kernel::fusible_gently(const bh_ir_kernel &other) const { //When all instructions in the 'other' kernel are system opcodes //only one of the instructions needs to be gentle fusible. if(other.only_system_opcodes()) { BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { if(fusible_gently(other_idx)) return true; } return false; } else { //Check that each instruction in 'other' is gentle fusible //with 'this' kernel while ignoring system opcodes. BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { if(bh_opcode_is_system(bhir->instr_list[other_idx].opcode)) continue; if(not fusible_gently(other_idx)) return false; } } return true; } /* Determines dependency between 'this' kernel and the instruction 'instr', * which is true when: * 'instr' writes to an array that 'this' access * or * 'this' writes to an array that 'instr' access * * @instr_idx The index of the instruction * @return 0: no dependency * 1: this kernel depend on 'instr' * -1: 'instr' depend on this kernel */ int bh_ir_kernel::dependency(uint64_t instr_idx) const { int ret = 0; BOOST_FOREACH(uint64_t this_idx, instr_indexes) { if(bh_instr_dependency(&bhir->instr_list[instr_idx], &bhir->instr_list[this_idx])) { if(this_idx >= instr_idx) { assert(ret == 0 or ret == 1);//Check for cyclic dependency ret = 1; //TODO: return 'ret' here, but for now we check all instructions } else { assert(ret == 0 or ret == -1);//Check for cyclic dependency ret = -1; //TODO: return 'ret' here, but for now we check all instructions } } } return ret; } /* Determines dependency between this kernel and 'other', * which is true when: * 'other' writes to an array that 'this' access * or * 'this' writes to an array that 'other' access * * @other The other kernel * @return 0: no dependency * 1: this kernel depend on 'other' * -1: 'other' depend on this kernel */ int bh_ir_kernel::dependency(const bh_ir_kernel &other) const { int ret = 0; BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { const int dep = dependency(other_idx); if(dep != 0) { assert(ret == 0 or ret == dep);//Check for cyclic dependency ret = dep; //TODO: return 'ret' here, but for now we check all instructions } } return ret; } /* Returns the cost of a bh_view */ inline static uint64_t cost_of_view(const bh_view &v) { return bh_nelements_nbcast(&v) * bh_type_size(v.base->type); } /* Returns the cost of the kernel */ uint64_t bh_ir_kernel::cost() const { uint64_t sum = 0; BOOST_FOREACH(const bh_view &v, input_list()) { sum += cost_of_view(v); } BOOST_FOREACH(const bh_view &v, output_list()) { sum += cost_of_view(v); } return sum; } /* Returns the cost savings of merging with the 'other' kernel. * The cost savings is defined as the amount the BhIR will drop * in price if the two kernels are fused. * NB: This function determens the dependency order between the * two kernels and calculate the cost saving based on that order. * * @other The other kernel * @return The cost value. Returns -1 if 'this' and the 'other' * kernel isn't fusible. */ int64_t bh_ir_kernel::merge_cost_savings(const bh_ir_kernel &other) const { if(this == &other) return 0; if(not fusible(other)) return -1; const bh_ir_kernel *a; const bh_ir_kernel *b; //Lets make sure that 'a' depend on 'b' if(this->dependency(other) == 1) { a = this; b = &other; } else { a = &other; b = this; } int64_t price_drop = 0; //Subtract inputs in 'a' that comes from 'b' or is already an input in 'b' BOOST_FOREACH(const bh_view &i, a->input_list()) { BOOST_FOREACH(const bh_view &o, b->output_list()) { if(bh_view_aligned(&i, &o)) price_drop += cost_of_view(i); } BOOST_FOREACH(const bh_view &o, b->input_list()) { if(bh_view_aligned(&i, &o)) price_drop += cost_of_view(i); } } //Subtract outputs from 'b' that are discared in 'a' BOOST_FOREACH(const bh_view &o, b->output_list()) { BOOST_FOREACH(uint64_t a_instr_idx, a->instr_indexes) { const bh_instruction &a_instr = a->bhir->instr_list[a_instr_idx]; if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base) { price_drop += cost_of_view(o); break; } } } return price_drop; } <commit_msg>bhir: now bh_ir_kernel::add_instr() only add arrays to 'temps' when they are not previously synchronized<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/serialization/vector.hpp> #include <boost/foreach.hpp> #include <bh.h> #include <vector> #include <map> #include <iostream> #include <sstream> #include <stdexcept> #include "bh_ir.h" #include "bh_fuse.h" using namespace std; using namespace boost; namespace io = boost::iostreams; /* Creates a Bohrium Internal Representation (BhIR) from a instruction list. * * @ninstr Number of instructions * @instr_list The instruction list */ bh_ir::bh_ir(bh_intp ninstr, const bh_instruction instr_list[]) { bh_ir::instr_list = vector<bh_instruction>(instr_list, &instr_list[ninstr]); } /* Creates a BhIR from a serialized BhIR. * * @bhir The BhIr serialized as a char array or vector */ bh_ir::bh_ir(const char bhir[], bh_intp size) { io::basic_array_source<char> source(bhir,size); io::stream<io::basic_array_source <char> > input_stream(source); archive::binary_iarchive ia(input_stream); ia >> *this; } /* Serialize the BhIR object into a char buffer * (use the bh_ir constructor for deserialization) * * @buffer The char vector to serialize into */ void bh_ir::serialize(vector<char> &buffer) const { io::stream<io::back_insert_device<vector<char> > > output_stream(buffer); archive::binary_oarchive oa(output_stream); oa << *this; output_stream.flush(); } /* Returns the cost of the BhIR */ uint64_t bh_ir::cost() const { uint64_t sum = 0; BOOST_FOREACH(const bh_ir_kernel &k, kernel_list) { sum += k.cost(); } return sum; } /* Pretty print the kernel list */ void bh_ir::pprint_kernel_list() const { char msg[100]; int i=0; BOOST_FOREACH(const bh_ir_kernel &k, kernel_list) { snprintf(msg, 100, "kernel-%d", i++); bh_pprint_instr_krnl(&k, msg); } } void bh_ir_kernel::add_instr(uint64_t instr_idx) { /* Help function that checks if aligned view 'v' exist in 'views' */ struct { bool operator()(const bh_view &v, const vector<bh_view> &views) { BOOST_FOREACH(const bh_view &i, views) { if(bh_view_aligned(&v, &i)) return true; } return false; } }aligned_view_exist; /* Help function that checks if 'b' is synchronized in kernel 'k' */ struct { bool operator()(const bh_ir_kernel &k, const bh_base *b) { BOOST_FOREACH(uint64_t idx, k.instr_indexes) { const bh_instruction &instr = k.bhir->instr_list[idx]; if(instr.opcode == BH_SYNC and instr.operand[0].base == b) return true; } return false; } }is_base_synced; const bh_instruction& instr = bhir->instr_list[instr_idx]; if(instr.opcode == BH_DISCARD) { //When discarding we might have to remove arrays from 'outputs' and 'temps' //if the discared array isn't synchronized const bh_base *base = instr.operand[0].base; if(not is_base_synced(*this, base)) { for(vector<bh_view>::iterator it=outputs.begin(); it != outputs.end(); ++it) { if(base == it->base) { outputs.erase(it); //If the discarded array isn't in 'inputs' (and not in 'outputs') //than it is a temp array if(not aligned_view_exist(*it, inputs)) temps.push_back(base); break; } } } } else if(instr.opcode != BH_FREE) { //Add the output of the instruction to 'outputs' if(not aligned_view_exist(instr.operand[0], outputs)) outputs.push_back(instr.operand[0]); //Add the inputs of the instruction to 'inputs' const int nop = bh_operands(instr.opcode); for(int i=1; i<nop; ++i) { const bh_view &v = instr.operand[i]; if(bh_is_constant(&v)) continue; //If 'v' is in 'inputs' already we can continue if(aligned_view_exist(v, inputs)) continue; //Additionally, we shouldn't add 'v' to 'inputs' if it is //the output of an existing instruction. bool local_source = false; BOOST_FOREACH(uint64_t idx, instr_indexes) { if(bh_view_aligned(&v, &bhir->instr_list[idx].operand[0])) { local_source = true; break; } } if(!local_source) inputs.push_back(v); } } instr_indexes.push_back(instr_idx); }; /* Determines whether all instructions in 'this' kernel * are system opcodes (e.g. BH_DISCARD, BH_FREE, etc.) * * @return The boolean answer */ bool bh_ir_kernel::only_system_opcodes() const { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { if(not bh_opcode_is_system(bhir->instr_list[this_idx].opcode)) return false; } return true; } /* Determines whether the kernel fusible legal * * @return The boolean answer */ bool bh_ir_kernel::fusible() const { for(uint64_t i=0; i<instr_indexes.size(); ++i) { const bh_instruction *instr = &bhir->instr_list[instr_indexes[i]]; for(uint64_t j=i+1; j<instr_indexes.size(); ++j) { if(not bohrium::check_fusible(instr, &bhir->instr_list[instr_indexes[j]])) return false; } } return true; } /* Determines whether it is legal to fuse with the instruction * * @instr_idx The index of the instruction * @return The boolean answer */ bool bh_ir_kernel::fusible(uint64_t instr_idx) const { const bh_instruction *instr = &bhir->instr_list[instr_idx]; BOOST_FOREACH(uint64_t i, instr_indexes) { if(not bohrium::check_fusible(instr, &bhir->instr_list[i])) return false; } return true; } /* Determines whether it is legal to fuse with the kernel * * @other The other kernel * @return The boolean answer */ bool bh_ir_kernel::fusible(const bh_ir_kernel &other) const { BOOST_FOREACH(uint64_t idx1, instr_indexes) { const bh_instruction *instr = &bhir->instr_list[idx1]; BOOST_FOREACH(uint64_t idx2, other.instr_indexes) { if(not bohrium::check_fusible(instr, &other.bhir->instr_list[idx2])) return false; } } return true; } /* Determines whether it is legal to fuse with the instruction * without changing 'this' kernel's dependencies. * * @instr_idx The index of the instruction * @return The boolean answer */ bool bh_ir_kernel::fusible_gently(uint64_t instr_idx) const { const bh_instruction &instr = bhir->instr_list[instr_idx]; //Check that 'instr' is gentle fusible with at least one existing instruction //that is not a system opcode (unless all instructions in 'this' kernel are //system opcodes) if(only_system_opcodes()) { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { const bh_instruction &this_instr = bhir->instr_list[this_idx]; if(bh_instr_fusible_gently(&instr, &this_instr) && bohrium::check_fusible(&instr, &this_instr)) return true; } } else { BOOST_FOREACH(uint64_t this_idx, instr_indexes) { const bh_instruction &this_instr = bhir->instr_list[this_idx]; if(bh_opcode_is_system(this_instr.opcode)) continue; if(bh_instr_fusible_gently(&instr, &this_instr) && bohrium::check_fusible(&instr, &this_instr)) return true; } } return false; } /* Determines whether it is legal to fuse with the kernel without * changing 'this' kernel's dependencies. * * @other The other kernel * @return The boolean answer */ bool bh_ir_kernel::fusible_gently(const bh_ir_kernel &other) const { //When all instructions in the 'other' kernel are system opcodes //only one of the instructions needs to be gentle fusible. if(other.only_system_opcodes()) { BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { if(fusible_gently(other_idx)) return true; } return false; } else { //Check that each instruction in 'other' is gentle fusible //with 'this' kernel while ignoring system opcodes. BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { if(bh_opcode_is_system(bhir->instr_list[other_idx].opcode)) continue; if(not fusible_gently(other_idx)) return false; } } return true; } /* Determines dependency between 'this' kernel and the instruction 'instr', * which is true when: * 'instr' writes to an array that 'this' access * or * 'this' writes to an array that 'instr' access * * @instr_idx The index of the instruction * @return 0: no dependency * 1: this kernel depend on 'instr' * -1: 'instr' depend on this kernel */ int bh_ir_kernel::dependency(uint64_t instr_idx) const { int ret = 0; BOOST_FOREACH(uint64_t this_idx, instr_indexes) { if(bh_instr_dependency(&bhir->instr_list[instr_idx], &bhir->instr_list[this_idx])) { if(this_idx >= instr_idx) { assert(ret == 0 or ret == 1);//Check for cyclic dependency ret = 1; //TODO: return 'ret' here, but for now we check all instructions } else { assert(ret == 0 or ret == -1);//Check for cyclic dependency ret = -1; //TODO: return 'ret' here, but for now we check all instructions } } } return ret; } /* Determines dependency between this kernel and 'other', * which is true when: * 'other' writes to an array that 'this' access * or * 'this' writes to an array that 'other' access * * @other The other kernel * @return 0: no dependency * 1: this kernel depend on 'other' * -1: 'other' depend on this kernel */ int bh_ir_kernel::dependency(const bh_ir_kernel &other) const { int ret = 0; BOOST_FOREACH(uint64_t other_idx, other.instr_indexes) { const int dep = dependency(other_idx); if(dep != 0) { assert(ret == 0 or ret == dep);//Check for cyclic dependency ret = dep; //TODO: return 'ret' here, but for now we check all instructions } } return ret; } /* Returns the cost of a bh_view */ inline static uint64_t cost_of_view(const bh_view &v) { return bh_nelements_nbcast(&v) * bh_type_size(v.base->type); } /* Returns the cost of the kernel */ uint64_t bh_ir_kernel::cost() const { uint64_t sum = 0; BOOST_FOREACH(const bh_view &v, input_list()) { sum += cost_of_view(v); } BOOST_FOREACH(const bh_view &v, output_list()) { sum += cost_of_view(v); } return sum; } /* Returns the cost savings of merging with the 'other' kernel. * The cost savings is defined as the amount the BhIR will drop * in price if the two kernels are fused. * NB: This function determens the dependency order between the * two kernels and calculate the cost saving based on that order. * * @other The other kernel * @return The cost value. Returns -1 if 'this' and the 'other' * kernel isn't fusible. */ int64_t bh_ir_kernel::merge_cost_savings(const bh_ir_kernel &other) const { if(this == &other) return 0; if(not fusible(other)) return -1; const bh_ir_kernel *a; const bh_ir_kernel *b; //Lets make sure that 'a' depend on 'b' if(this->dependency(other) == 1) { a = this; b = &other; } else { a = &other; b = this; } int64_t price_drop = 0; //Subtract inputs in 'a' that comes from 'b' or is already an input in 'b' BOOST_FOREACH(const bh_view &i, a->input_list()) { BOOST_FOREACH(const bh_view &o, b->output_list()) { if(bh_view_aligned(&i, &o)) price_drop += cost_of_view(i); } BOOST_FOREACH(const bh_view &o, b->input_list()) { if(bh_view_aligned(&i, &o)) price_drop += cost_of_view(i); } } //Subtract outputs from 'b' that are discared in 'a' BOOST_FOREACH(const bh_view &o, b->output_list()) { BOOST_FOREACH(uint64_t a_instr_idx, a->instr_indexes) { const bh_instruction &a_instr = a->bhir->instr_list[a_instr_idx]; if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base) { price_drop += cost_of_view(o); break; } } } return price_drop; } <|endoftext|>
<commit_before>// [WriteFile Name=SearchForWebmap, Category=CloudAndPortal] // [Legal] // Copyright 2016 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the Sample code usage restrictions document for further information. // #include "AuthenticationManager.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "Portal.h" #include "PortalItem.h" #include "PortalItemListModel.h" #include "PortalQueryParametersForItems.h" #include "SearchForWebmap.h" #include <QDate> using namespace Esri::ArcGISRuntime; SearchForWebmap::SearchForWebmap(QQuickItem* parent /* = nullptr */): QQuickItem(parent) { AuthenticationManager::instance()->setCredentialCacheEnabled(false); } SearchForWebmap::~SearchForWebmap() { } void SearchForWebmap::componentComplete() { QQuickItem::componentComplete(); emit authManagerChanged(); connect(m_portal, &Portal::loadStatusChanged, this, [this](){ m_portalLoaded = m_portal->loadStatus() == LoadStatus::Loaded; emit portalLoadedChanged(); }); //! [SearchForWebmap CPP Portal find items completed] connect(m_portal, &Portal::findItemsCompleted, this, [this](PortalQueryResultSetForItems *webmapResults){ m_webmapResults = webmapResults; m_webmaps = m_webmapResults->itemResults(); emit webmapsChanged(); emit hasMoreResultsChanged(); }); //! [SearchForWebmap CPP Portal find items completed] m_portal->load(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); } bool SearchForWebmap::portalLoaded() const { return m_portalLoaded; } QAbstractListModel* SearchForWebmap::webmaps() const { return m_webmaps; } bool SearchForWebmap::hasMoreResults() const { return m_webmapResults && m_webmapResults->nextQueryParameters().startIndex() > -1; } QString SearchForWebmap::mapLoadError() const { return m_mapLoadeError; } void SearchForWebmap::search(const QString keyword) { //! [SearchForWebmap CPP Portal find items] // webmaps authored prior to July 2nd, 2014 are not supported - so search only from that date to the current time QString fromDate = QString("000000%1").arg(QDateTime(QDate(2014, 7, 2)).toTime_t()); QString toDate = QString("000000%1").arg(QDateTime::currentDateTime().toTime_t()); PortalQueryParametersForItems query; query.setSearchString(QString("tags:\"%1\" AND +uploaded:[%2 TO %3]") .arg(keyword) .arg(fromDate) .arg(toDate)); query.setTypes(QList<PortalItemType>() << PortalItemType::WebMap); m_portal->findItems(query); //! [SearchForWebmap CPP Portal find items] m_mapView->setVisible(false); } void SearchForWebmap::searchNext() { if (!m_webmapResults) return; //! [Portal find with nextQueryParameters] PortalQueryParameters nextQuery = m_webmapResults->nextQueryParameters(); // check whether the startIndex of the new query is valid if (nextQuery.startIndex() != -1) m_portal->findItems(nextQuery); //! [Portal find with nextQueryParameters] } void SearchForWebmap::loadSelectedWebmap(int index) { if (!m_webmaps) return; PortalItem* selectedItem = m_webmaps->at(index); if (!selectedItem) return; if (m_selectedItem) m_selectedItem->disconnect(); m_selectedItem = selectedItem; connect(m_selectedItem, &PortalItem::loadStatusChanged, this, [this]{ if (!m_selectedItem || m_selectedItem->loadStatus() != LoadStatus::Loaded) return; if (m_map) m_map->disconnect(); m_mapLoadeError.clear(); emit mapLoadErrorChanged(); m_map = new Map(m_selectedItem, this); connect(m_map, &Map::errorOccurred, this, [this](){ m_mapLoadeError = m_map->loadError().message(); emit mapLoadErrorChanged(); }); connect(m_map, &Map::loadStatusChanged, this, [this](){ if (!m_map || m_map->loadStatus() != LoadStatus::Loaded) return; m_mapView->setMap(m_map); m_mapView->setVisible(true); }); m_map->load(); }); m_selectedItem->load(); } void SearchForWebmap::errorAccepted() { m_mapLoadeError.clear(); emit mapLoadErrorChanged(); } AuthenticationManager *SearchForWebmap::authManager() const { return AuthenticationManager::instance(); } <commit_msg>fix name (#460)<commit_after>// [WriteFile Name=SearchForWebmap, Category=CloudAndPortal] // [Legal] // Copyright 2016 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the Sample code usage restrictions document for further information. // #include "AuthenticationManager.h" #include "Map.h" #include "MapQuickView.h" #include "Basemap.h" #include "Portal.h" #include "PortalItem.h" #include "PortalItemListModel.h" #include "PortalQueryParametersForItems.h" #include "SearchForWebmap.h" #include <QDate> using namespace Esri::ArcGISRuntime; SearchForWebmap::SearchForWebmap(QQuickItem* parent /* = nullptr */): QQuickItem(parent) { AuthenticationManager::instance()->setCredentialCacheEnabled(false); } SearchForWebmap::~SearchForWebmap() { } void SearchForWebmap::componentComplete() { QQuickItem::componentComplete(); emit authManagerChanged(); connect(m_portal, &Portal::loadStatusChanged, this, [this](){ m_portalLoaded = m_portal->loadStatus() == LoadStatus::Loaded; emit portalLoadedChanged(); }); //! [SearchForWebmap CPP Portal find items completed] connect(m_portal, &Portal::findItemsCompleted, this, [this](PortalQueryResultSetForItems *webmapResults){ m_webmapResults = webmapResults; m_webmaps = m_webmapResults->itemResults(); emit webmapsChanged(); emit hasMoreResultsChanged(); }); //! [SearchForWebmap CPP Portal find items completed] m_portal->load(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); } bool SearchForWebmap::portalLoaded() const { return m_portalLoaded; } QAbstractListModel* SearchForWebmap::webmaps() const { return m_webmaps; } bool SearchForWebmap::hasMoreResults() const { return m_webmapResults && m_webmapResults->nextQueryParameters().startIndex() > -1; } QString SearchForWebmap::mapLoadError() const { return m_mapLoadeError; } void SearchForWebmap::search(const QString keyword) { //! [SearchForWebmap CPP Portal find items] // webmaps authored prior to July 2nd, 2014 are not supported - so search only from that date to the current time QString fromDate = QString("000000%1").arg(QDateTime(QDate(2014, 7, 2)).toTime_t()); QString toDate = QString("000000%1").arg(QDateTime::currentDateTime().toTime_t()); PortalQueryParametersForItems query; query.setSearchString(QString("tags:\"%1\" AND +uploaded:[%2 TO %3]") .arg(keyword) .arg(fromDate) .arg(toDate)); query.setTypes(QList<PortalItemType>() << PortalItemType::WebMap); m_portal->findItems(query); //! [SearchForWebmap CPP Portal find items] m_mapView->setVisible(false); } void SearchForWebmap::searchNext() { if (!m_webmapResults) return; //! [Portal find with nextQueryParameters] PortalQueryParametersForItems nextQuery = m_webmapResults->nextQueryParameters(); // check whether the startIndex of the new query is valid if (nextQuery.startIndex() != -1) m_portal->findItems(nextQuery); //! [Portal find with nextQueryParameters] } void SearchForWebmap::loadSelectedWebmap(int index) { if (!m_webmaps) return; PortalItem* selectedItem = m_webmaps->at(index); if (!selectedItem) return; if (m_selectedItem) m_selectedItem->disconnect(); m_selectedItem = selectedItem; connect(m_selectedItem, &PortalItem::loadStatusChanged, this, [this]{ if (!m_selectedItem || m_selectedItem->loadStatus() != LoadStatus::Loaded) return; if (m_map) m_map->disconnect(); m_mapLoadeError.clear(); emit mapLoadErrorChanged(); m_map = new Map(m_selectedItem, this); connect(m_map, &Map::errorOccurred, this, [this](){ m_mapLoadeError = m_map->loadError().message(); emit mapLoadErrorChanged(); }); connect(m_map, &Map::loadStatusChanged, this, [this](){ if (!m_map || m_map->loadStatus() != LoadStatus::Loaded) return; m_mapView->setMap(m_map); m_mapView->setVisible(true); }); m_map->load(); }); m_selectedItem->load(); } void SearchForWebmap::errorAccepted() { m_mapLoadeError.clear(); emit mapLoadErrorChanged(); } AuthenticationManager *SearchForWebmap::authManager() const { return AuthenticationManager::instance(); } <|endoftext|>
<commit_before>#include <sstream> // Include 3rd party headers. #include <odb/transaction.hxx> #include <odb/mysql/database.hxx> #include <bites.hpp> // Include application headers. #include "Captor.hpp" #include "DBWriter.hpp" #include "mapping.hpp" #include "mapping-odb.hxx" namespace wabbit { void DBWriter::run () { // Connect to database. odb::mysql::database db ( m_config["username"], m_config["password"], m_config["db_name"] ); // Pull from the queue while there are valid tasks. Captor::FrameAndTime task; m_input_queue.wait_and_pop(task); while(task.first) { // Assemble the time string. auto tstring = bites::time2string ( task.second, "%Y-%m-%d %H:%M:%S:%f" ); // Create the image field. wabbit::Image img (tstring); // Start the transaction. odb::transaction trans (db.begin()); // Add the image field. db.persist(img); // Increment the size. typedef odb::query<wabbit::Datum> query; auto result = db.query<wabbit::Datum> (query::name == "size"); auto datum = result.begin(); int size = atoi(datum->value().c_str()); std::stringstream ss; ss << size + 1; datum->value (ss.str()); db.update(*datum); // Update latest timestamp. result = db.query<wabbit::Datum> (query::name == "latest_tstamp"); datum = result.begin(); datum->value (tstring); db.update(*datum); // Commit to database. trans.commit(); // Signal done. m_done_queue.push (task.first); // Pull the next frame. m_input_queue.wait_and_pop (task); } } } // namespace wabbit. <commit_msg>Fix bug in timestamp-to-string conversion.<commit_after>#include <sstream> // Include 3rd party headers. #include <odb/transaction.hxx> #include <odb/mysql/database.hxx> #include <bites.hpp> // Include application headers. #include "Captor.hpp" #include "DBWriter.hpp" #include "mapping.hpp" #include "mapping-odb.hxx" namespace wabbit { void DBWriter::run () { // Connect to database. odb::mysql::database db ( m_config["username"], m_config["password"], m_config["db_name"] ); // Pull from the queue while there are valid tasks. Captor::FrameAndTime task; m_input_queue.wait_and_pop(task); while(task.first) { // Assemble the time string. auto tstring = bites::time2string ( task.second, "%Y-%m-%d %H:%M:%S.%f" ); // Create the image field. wabbit::Image img (tstring); // Start the transaction. odb::transaction trans (db.begin()); // Add the image field. db.persist(img); // Increment the size. typedef odb::query<wabbit::Datum> query; auto result = db.query<wabbit::Datum> (query::name == "size"); auto datum = result.begin(); int size = atoi(datum->value().c_str()); std::stringstream ss; ss << size + 1; datum->value (ss.str()); db.update(*datum); // Update latest timestamp. result = db.query<wabbit::Datum> (query::name == "latest_tstamp"); datum = result.begin(); datum->value (tstring); db.update(*datum); // Commit to database. trans.commit(); // Signal done. m_done_queue.push (task.first); // Pull the next frame. m_input_queue.wait_and_pop (task); } } } // namespace wabbit. <|endoftext|>
<commit_before>/* OF-TangibleFramework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2009 Daniel Gallardo Grassot <daniel.gallardo@upf.edu> 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 "ofMain.h" #include "GraphicDispatcher.hpp" GraphicDispatcher::GraphicDispatcher(){ } GraphicDispatcher::~GraphicDispatcher(){ } void GraphicDispatcher::Draw(){ glDisable(GL_DEPTH_TEST); for(std::list<Graphic*>::iterator it = graphics.begin(); it != graphics.end(); it++) (*it)->draw(); glEnable(GL_DEPTH_TEST); } void GraphicDispatcher::Update(){ for(std::list<Graphic*>::iterator it = graphics.begin(); it != graphics.end(); it++) (*it)->update(); } void GraphicDispatcher::Resize(int w, int h){ for(std::list<Graphic*>::iterator it = graphics.begin(); it != graphics.end(); it++) (*it)->resize(w,h); } void GraphicDispatcher::AddGraphic(Graphic* graphic){ graphics.push_back(graphic); graphics.sort(CompareLayers); } void GraphicDispatcher::RemoveGraphic(Graphic* graphic){ graphics.remove(graphic); } void GraphicDispatcher::bring_top(Graphic* graphic){ for ( std::list<Graphic*>::iterator it=graphics.begin(); it!=graphics.end();it++){ if ( (*it) == graphic){ graphics.remove(*it); break; } } graphics.push_back(graphic); graphics.sort(CompareLayers); } <commit_msg>Allowing to delete Graphics on update or draw<commit_after>/* OF-TangibleFramework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2009 Daniel Gallardo Grassot <daniel.gallardo@upf.edu> 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 "ofMain.h" #include "GraphicDispatcher.hpp" GraphicDispatcher::GraphicDispatcher(){ } GraphicDispatcher::~GraphicDispatcher(){ } void GraphicDispatcher::Draw(){ glDisable(GL_DEPTH_TEST); for(std::list<Graphic*>::iterator it = graphics.begin(); it != graphics.end(); it++) (*it)->draw(); glEnable(GL_DEPTH_TEST); } void GraphicDispatcher::Update(){ std::list<Graphic*> l (graphics); for(std::list<Graphic*>::iterator it = l.begin(); it != l.end(); it++) (*it)->update(); } void GraphicDispatcher::Resize(int w, int h){ std::list<Graphic*> l (graphics); for(std::list<Graphic*>::iterator it = l.begin(); it != l.end(); it++) (*it)->resize(w,h); } void GraphicDispatcher::AddGraphic(Graphic* graphic){ graphics.push_back(graphic); graphics.sort(CompareLayers); } void GraphicDispatcher::RemoveGraphic(Graphic* graphic){ graphics.remove(graphic); } void GraphicDispatcher::bring_top(Graphic* graphic){ for ( std::list<Graphic*>::iterator it=graphics.begin(); it!=graphics.end();it++){ if ( (*it) == graphic){ graphics.remove(*it); break; } } graphics.push_back(graphic); graphics.sort(CompareLayers); } <|endoftext|>
<commit_before>/* * HMAC_RNG * (C) 2008-2009,2013 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/hmac_rng.h> #include <botan/libstate.h> #include <botan/get_byte.h> #include <botan/entropy_src.h> #include <botan/internal/xor_buf.h> #include <algorithm> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode& prf, secure_vector<byte>& K, u32bit& counter, const std::string& label) { prf.update(K); prf.update(label); prf.update_be(counter); prf.final(&K[0]); ++counter; } } /* * HMAC_RNG Constructor */ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor, MessageAuthenticationCode* prf) : m_extractor(extractor), m_prf(prf) { if(!m_prf->valid_keylength(m_extractor->output_length()) || !m_extractor->valid_keylength(m_prf->output_length())) throw Invalid_Argument("HMAC_RNG: Bad algo combination " + m_extractor->name() + " and " + m_prf->name()); // First PRF inputs are all zero, as specified in section 2 m_K.resize(m_prf->output_length()); /* Normally we want to feedback PRF outputs to the extractor function to ensure a single bad poll does not reduce entropy. Thus in reseed we'll want to invoke the PRF before we reset the PRF key, but until the first reseed the PRF is unkeyed. Rather than trying to keep track of this, just set the initial PRF key to constant zero. Since all PRF inputs in the first reseed are constants, this amounts to suffixing the seed in the first poll with a fixed constant string. The PRF key will not be used to generate outputs until after reseed sets m_seeded to true. */ secure_vector<byte> prf_key(m_extractor->output_length()); m_prf->set_key(prf_key); /* Use PRF("Botan HMAC_RNG XTS") as the intitial XTS key. This will be used during the first extraction sequence; XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ m_extractor->set_key(prf->process("Botan HMAC_RNG XTS")); } /* * Generate a buffer of random bytes */ void HMAC_RNG::randomize(byte out[], size_t length) { if(!is_seeded()) throw PRNG_Unseeded(name()); /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(*m_prf, m_K, m_counter, "rng"); if(m_counter % AUTOMATIC_RESEED_RATE == 0) reseed(AUTOMATIC_RESEED_BITS); const size_t copied = std::min<size_t>(m_K.size() / 2, length); copy_mem(out, &m_K[0], copied); out += copied; length -= copied; } } /* * Poll for entropy and reset the internal keys */ void HMAC_RNG::reseed(size_t poll_bits) { /* Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by polling as many sources as we think needed to reach our polling goal. We then also include feedback of the current PRK so that a bad poll doesn't wipe us out. */ Entropy_Accumulator_BufferedComputation accum(*m_extractor, poll_bits); global_state().poll_available_sources(accum); /* * It is necessary to feed forward poll data. Otherwise, a good poll * (collecting a large amount of conditional entropy) followed by a * bad one (collecting little) would be unsafe. Do this by * generating new PRF outputs using the previous key and feeding * them into the extractor function. * * Cycle the RNG once (CTXinfo="rng"), then generate a new PRF * output using the CTXinfo "reseed". Provide these values as input * to the extractor function. */ hmac_prf(*m_prf, m_K, m_counter, "rng"); m_extractor->update(m_K); // K is the CTXinfo=rng PRF output hmac_prf(*m_prf, m_K, m_counter, "reseed"); m_extractor->update(m_K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that */ m_prf->set_key(m_extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(*m_prf, m_K, m_counter, "xts"); m_extractor->set_key(m_K); // Reset state zeroise(m_K); m_counter = 0; /* * Consider ourselves seeded once we've collected an estimated 128 bits of * entropy in a single poll. */ if(accum.bits_collected() >= 128) m_seeded = true; } /* * Add user-supplied entropy to the extractor input */ void HMAC_RNG::add_entropy(const byte input[], size_t length) { m_extractor->update(input, length); reseed(AUTOMATIC_RESEED_BITS); } /* * Clear memory of sensitive data */ void HMAC_RNG::clear() { m_seeded = false; m_extractor->clear(); m_prf->clear(); zeroise(m_K); m_counter = 0; } /* * Return the name of this type */ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + m_extractor->name() + "," + m_prf->name() + ")"; } } <commit_msg>Include a timestamp as part of the HMAC_RNG PRF inputs<commit_after>/* * HMAC_RNG * (C) 2008-2009,2013 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/hmac_rng.h> #include <botan/libstate.h> #include <botan/get_byte.h> #include <botan/entropy_src.h> #include <botan/internal/xor_buf.h> #include <algorithm> #include <chrono> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode& prf, secure_vector<byte>& K, u32bit& counter, const std::string& label) { typedef std::chrono::high_resolution_clock clock; auto timestamp = clock::now().time_since_epoch().count(); prf.update(K); prf.update(label); prf.update_be(timestamp); prf.update_be(counter); prf.final(&K[0]); ++counter; } } /* * HMAC_RNG Constructor */ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor, MessageAuthenticationCode* prf) : m_extractor(extractor), m_prf(prf) { if(!m_prf->valid_keylength(m_extractor->output_length()) || !m_extractor->valid_keylength(m_prf->output_length())) throw Invalid_Argument("HMAC_RNG: Bad algo combination " + m_extractor->name() + " and " + m_prf->name()); // First PRF inputs are all zero, as specified in section 2 m_K.resize(m_prf->output_length()); /* Normally we want to feedback PRF outputs to the extractor function to ensure a single bad poll does not reduce entropy. Thus in reseed we'll want to invoke the PRF before we reset the PRF key, but until the first reseed the PRF is unkeyed. Rather than trying to keep track of this, just set the initial PRF key to constant zero. Since all PRF inputs in the first reseed are constants, this amounts to suffixing the seed in the first poll with a fixed constant string. The PRF key will not be used to generate outputs until after reseed sets m_seeded to true. */ secure_vector<byte> prf_key(m_extractor->output_length()); m_prf->set_key(prf_key); /* Use PRF("Botan HMAC_RNG XTS") as the intitial XTS key. This will be used during the first extraction sequence; XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ m_extractor->set_key(prf->process("Botan HMAC_RNG XTS")); } /* * Generate a buffer of random bytes */ void HMAC_RNG::randomize(byte out[], size_t length) { if(!is_seeded()) throw PRNG_Unseeded(name()); /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(*m_prf, m_K, m_counter, "rng"); if(m_counter % AUTOMATIC_RESEED_RATE == 0) reseed(AUTOMATIC_RESEED_BITS); const size_t copied = std::min<size_t>(m_K.size() / 2, length); copy_mem(out, &m_K[0], copied); out += copied; length -= copied; } } /* * Poll for entropy and reset the internal keys */ void HMAC_RNG::reseed(size_t poll_bits) { /* Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by polling as many sources as we think needed to reach our polling goal. We then also include feedback of the current PRK so that a bad poll doesn't wipe us out. */ Entropy_Accumulator_BufferedComputation accum(*m_extractor, poll_bits); global_state().poll_available_sources(accum); /* * It is necessary to feed forward poll data. Otherwise, a good poll * (collecting a large amount of conditional entropy) followed by a * bad one (collecting little) would be unsafe. Do this by * generating new PRF outputs using the previous key and feeding * them into the extractor function. * * Cycle the RNG once (CTXinfo="rng"), then generate a new PRF * output using the CTXinfo "reseed". Provide these values as input * to the extractor function. */ hmac_prf(*m_prf, m_K, m_counter, "rng"); m_extractor->update(m_K); // K is the CTXinfo=rng PRF output hmac_prf(*m_prf, m_K, m_counter, "reseed"); m_extractor->update(m_K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that */ m_prf->set_key(m_extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(*m_prf, m_K, m_counter, "xts"); m_extractor->set_key(m_K); // Reset state zeroise(m_K); m_counter = 0; /* * Consider ourselves seeded once we've collected an estimated 128 bits of * entropy in a single poll. */ if(accum.bits_collected() >= 128) m_seeded = true; } /* * Add user-supplied entropy to the extractor input */ void HMAC_RNG::add_entropy(const byte input[], size_t length) { m_extractor->update(input, length); reseed(AUTOMATIC_RESEED_BITS); } /* * Clear memory of sensitive data */ void HMAC_RNG::clear() { m_seeded = false; m_extractor->clear(); m_prf->clear(); zeroise(m_K); m_counter = 0; } /* * Return the name of this type */ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + m_extractor->name() + "," + m_prf->name() + ")"; } } <|endoftext|>
<commit_before>/* * HMAC_RNG * (C) 2008-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/hmac_rng.h> #include <botan/get_byte.h> #include <botan/internal/xor_buf.h> #include <botan/internal/stl_util.h> #include <algorithm> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode* prf, MemoryRegion<byte>& K, u32bit& counter, const std::string& label) { prf->update(K, K.size()); prf->update(label); for(u32bit i = 0; i != 4; ++i) prf->update(get_byte(i, counter)); prf->final(K); ++counter; } } /** * Generate a buffer of random bytes */ void HMAC_RNG::randomize(byte out[], u32bit length) { if(!is_seeded()) throw PRNG_Unseeded(name()); /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(prf, K, counter, "rng"); const u32bit copied = std::min(K.size(), length); copy_mem(out, K.begin(), copied); out += copied; length -= copied; } } /** * Reseed the internal state, also accepting user input to include */ void HMAC_RNG::reseed_with_input(u32bit poll_bits, const byte input[], u32bit input_length) { /** Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by fast polling each source, and then slow polling as many as we think we need (in the following loop), and feeding all of the poll results, along with any optional user input, along with, finally, feedback of the current PRK value, into the extractor function. */ Entropy_Accumulator_BufferedComputation accum(*extractor, poll_bits); if(!entropy_sources.empty()) { u32bit poll_attempt = 0; while(!accum.polling_goal_achieved() && poll_attempt < poll_bits) { entropy_sources[poll_attempt % entropy_sources.size()]->poll(accum); ++poll_attempt; } } // And now add the user-provided input, if any if(input_length) accum.add(input, input_length, 1); /* It is necessary to feed forward poll data. Otherwise, a good poll (collecting a large amount of conditional entropy) followed by a bad one (collecting little) would be unsafe. Do this by generating new PRF outputs using the previous key and feeding them into the extractor function. Cycle the RNG once (CTXinfo="rng"), then generate a new PRF output using the CTXinfo "reseed". Provide these values as input to the extractor function. */ hmac_prf(prf, K, counter, "rng"); extractor->update(K); // K is the CTXinfo=rng PRF output hmac_prf(prf, K, counter, "reseed"); extractor->update(K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that */ prf->set_key(extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(prf, K, counter, "xts"); extractor->set_key(K, K.size()); // Reset state K.clear(); counter = 0; if(input_length || accum.bits_collected() >= poll_bits) seeded = true; } /** * Reseed the internal state */ void HMAC_RNG::reseed(u32bit poll_bits) { reseed_with_input(poll_bits, 0, 0); } /** * Add user-supplied entropy by reseeding and including this * input among the poll data */ void HMAC_RNG::add_entropy(const byte input[], u32bit length) { reseed_with_input(0, input, length); } /** * Add another entropy source to the list */ void HMAC_RNG::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /* * Clear memory of sensitive data */ void HMAC_RNG::clear() { extractor->clear(); prf->clear(); K.clear(); counter = 0; seeded = false; } /** * Return the name of this type */ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + extractor->name() + "," + prf->name() + ")"; } /** * HMAC_RNG Constructor */ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor_mac, MessageAuthenticationCode* prf_mac) : extractor(extractor_mac), prf(prf_mac) { // First PRF inputs are all zero, as specified in section 2 K.resize(prf->OUTPUT_LENGTH); counter = 0; seeded = false; /* Normally we want to feedback PRF output into the input to the extractor function to ensure a single bad poll does not damage the RNG, but obviously that is meaningless to do on the first poll. We will want to use the PRF before we set the first key (in reseed_with_input), and it is a pain to keep track if it is set or not. Since the first time it doesn't matter anyway, just set it to a constant: randomize() will not produce output unless is_seeded() returns true, and that will only be the case if the estimated entropy counter is high enough. That variable is only set when a reseeding is performed. */ std::string prf_key = "Botan HMAC_RNG PRF"; prf->set_key(reinterpret_cast<const byte*>(prf_key.c_str()), prf_key.length()); /* This will be used as the first XTS value when extracting input. XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ std::string xts = "Botan HMAC_RNG XTS"; extractor->set_key(reinterpret_cast<const byte*>(xts.c_str()), xts.length()); } /** * HMAC_RNG Destructor */ HMAC_RNG::~HMAC_RNG() { delete extractor; delete prf; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); counter = 0; } } <commit_msg>In add_entropy(), additionally poll for 64 bits of system entropy to mix in with the user input.<commit_after>/* * HMAC_RNG * (C) 2008-2009 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/hmac_rng.h> #include <botan/get_byte.h> #include <botan/internal/xor_buf.h> #include <botan/internal/stl_util.h> #include <algorithm> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode* prf, MemoryRegion<byte>& K, u32bit& counter, const std::string& label) { prf->update(K, K.size()); prf->update(label); for(u32bit i = 0; i != 4; ++i) prf->update(get_byte(i, counter)); prf->final(K); ++counter; } } /** * Generate a buffer of random bytes */ void HMAC_RNG::randomize(byte out[], u32bit length) { if(!is_seeded()) throw PRNG_Unseeded(name()); /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(prf, K, counter, "rng"); const u32bit copied = std::min(K.size(), length); copy_mem(out, K.begin(), copied); out += copied; length -= copied; } } /** * Reseed the internal state, also accepting user input to include */ void HMAC_RNG::reseed_with_input(u32bit poll_bits, const byte input[], u32bit input_length) { /** Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by fast polling each source, and then slow polling as many as we think we need (in the following loop), and feeding all of the poll results, along with any optional user input, along with, finally, feedback of the current PRK value, into the extractor function. */ Entropy_Accumulator_BufferedComputation accum(*extractor, poll_bits); if(!entropy_sources.empty()) { u32bit poll_attempt = 0; while(!accum.polling_goal_achieved() && poll_attempt < poll_bits) { entropy_sources[poll_attempt % entropy_sources.size()]->poll(accum); ++poll_attempt; } } // And now add the user-provided input, if any if(input_length) accum.add(input, input_length, 1); /* It is necessary to feed forward poll data. Otherwise, a good poll (collecting a large amount of conditional entropy) followed by a bad one (collecting little) would be unsafe. Do this by generating new PRF outputs using the previous key and feeding them into the extractor function. Cycle the RNG once (CTXinfo="rng"), then generate a new PRF output using the CTXinfo "reseed". Provide these values as input to the extractor function. */ hmac_prf(prf, K, counter, "rng"); extractor->update(K); // K is the CTXinfo=rng PRF output hmac_prf(prf, K, counter, "reseed"); extractor->update(K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that */ prf->set_key(extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(prf, K, counter, "xts"); extractor->set_key(K, K.size()); // Reset state K.clear(); counter = 0; if(input_length > 64 || accum.bits_collected() >= 128) seeded = true; } /** * Reseed the internal state */ void HMAC_RNG::reseed(u32bit poll_bits) { reseed_with_input(poll_bits, 0, 0); } /** * Add user-supplied entropy by reseeding and including this * input among the poll data */ void HMAC_RNG::add_entropy(const byte input[], u32bit length) { reseed_with_input(64, input, length); } /** * Add another entropy source to the list */ void HMAC_RNG::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /* * Clear memory of sensitive data */ void HMAC_RNG::clear() { extractor->clear(); prf->clear(); K.clear(); counter = 0; seeded = false; } /** * Return the name of this type */ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + extractor->name() + "," + prf->name() + ")"; } /** * HMAC_RNG Constructor */ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor_mac, MessageAuthenticationCode* prf_mac) : extractor(extractor_mac), prf(prf_mac) { if(!prf->valid_keylength(extractor->OUTPUT_LENGTH) || !extractor->valid_keylength(prf->OUTPUT_LENGTH)) throw Invalid_Argument("HMAC_RNG: Bad algo combination " + extractor->name() + " and " + prf->name()); // First PRF inputs are all zero, as specified in section 2 K.resize(prf->OUTPUT_LENGTH); counter = 0; seeded = false; /* Normally we want to feedback PRF output into the input to the extractor function to ensure a single bad poll does not damage the RNG, but obviously that is meaningless to do on the first poll. We will want to use the PRF before we set the first key (in reseed_with_input), and it is a pain to keep track if it is set or not. Since the first time it doesn't matter anyway, just set the PRF key to constant zero: randomize() will not produce output unless is_seeded() returns true, and that will only be the case if the estimated entropy counter is high enough. That variable is only set when a reseeding is performed. */ MemoryVector<byte> prf_key(extractor->OUTPUT_LENGTH); prf->set_key(prf_key); /* Use PRF("Botan HMAC_RNG XTS") as the intitial XTS key. This will be used during the first extraction sequence; XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ extractor->set_key(prf->process("Botan HMAC_RNG XTS")); } /** * HMAC_RNG Destructor */ HMAC_RNG::~HMAC_RNG() { delete extractor; delete prf; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); counter = 0; } } <|endoftext|>
<commit_before>//============================================================================= // // OpenMesh // Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen // www.openmesh.org // //----------------------------------------------------------------------------- // // License // // 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. // // 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., 675 Mass Ave, Cambridge, MA 02139, USA. // //============================================================================= #ifdef _MSC_VER # pragma warning(disable: 4267 4311) #endif #include <iostream> #include <fstream> #include <QApplication> #include <QMessageBox> #include "SubdivideWidget.hh" #include <GL/glut.h> int main(int argc, char **argv) { // OpenGL check QApplication::setColorSpec( QApplication::CustomColor ); QApplication app(argc,argv); glutInit(&argc,argv); if ( !QGLFormat::hasOpenGL() ) { QString msg = "System has no OpenGL support!"; QMessageBox::critical( NULL, "OpenGL", msg + argv[1], QMessageBox::Ok ); return -1; } // create widget SubdivideWidget* w = new SubdivideWidget(0, "Subdivider"); w->resize(400, 400); w->show(); // load scene if (argc > 1) { if ( ! w->open_mesh(argv[1]) ) { QString msg = "Cannot read mesh from file "; QMessageBox::critical( NULL, argv[1], msg + argv[1], QMessageBox::Ok ); return -1; } } return app.exec(); } <commit_msg>Adapted include path for darwin compatibility<commit_after>//============================================================================= // // OpenMesh // Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen // www.openmesh.org // //----------------------------------------------------------------------------- // // License // // 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. // // 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., 675 Mass Ave, Cambridge, MA 02139, USA. // //============================================================================= #ifdef _MSC_VER # pragma warning(disable: 4267 4311) #endif #include <iostream> #include <fstream> #include <QApplication> #include <QMessageBox> #include "SubdivideWidget.hh" #ifdef ARCH_DARWIN #include <glut.h> #else #include <GL/glut.h> #endif int main(int argc, char **argv) { // OpenGL check QApplication::setColorSpec( QApplication::CustomColor ); QApplication app(argc,argv); glutInit(&argc,argv); if ( !QGLFormat::hasOpenGL() ) { QString msg = "System has no OpenGL support!"; QMessageBox::critical( NULL, "OpenGL", msg + argv[1], QMessageBox::Ok ); return -1; } // create widget SubdivideWidget* w = new SubdivideWidget(0, "Subdivider"); w->resize(400, 400); w->show(); // load scene if (argc > 1) { if ( ! w->open_mesh(argv[1]) ) { QString msg = "Cannot read mesh from file "; QMessageBox::critical( NULL, argv[1], msg + argv[1], QMessageBox::Ok ); return -1; } } return app.exec(); } <|endoftext|>
<commit_before>#include "FontBlankSymbol.h" #include "FontSprite.h" #include "Font.h" #include "common/Vector.h" #include "common/color_trans.h" #include "common/FileNameTools.h" #include "common/FileNameParser.h" #include "common/Settings.h" #include "common/Math.h" #include "dataset/SpriteTools.h" #include "render/PrimitiveDraw.h" #include "render/Shader.h" #include "render/LabelNew.h" //OpenGL Headers #include <windows.h> #include <GL/gl.h> #include <json/json.h> namespace d2d { FontBlankSymbol::FontBlankSymbol() { static int id = 0; m_name = wxT("fontblank") + wxVariant(id++); align_hori = align_vert = 0; size = 0; width = height = 100; m_font = NULL; m_style.fill = true; m_style.color.set(0.7f, 0.7f, 0.7f, 0.7f); } FontBlankSymbol::~FontBlankSymbol() { // m_font->release(); } void FontBlankSymbol::reloadTexture() const { } void FontBlankSymbol::draw(const Screen& scr, const Matrix& mt, const Colorf& mul, const Colorf& add, const ISprite* sprite/* = NULL*/) const { // if (Settings::DrawFontType & Settings::DrawFontBg) { // DrawBackground(scr, sprite, mt); // } if (Settings::DrawFontType & Settings::DrawFontText) { DrawText(scr, sprite, mt); } SpriteTools::DrawName(scr, sprite, mt); } Rect FontBlankSymbol::getSize(const ISprite* sprite/* = NULL*/) const { return Rect(width, height); } void FontBlankSymbol::refresh() { } bool FontBlankSymbol::loadFont(const std::string& _filename) { if (_filename == filename) return false; std::string filename = FilenameTools::getAbsolutePath(m_filepath, _filename); if (!FileNameParser::isType(filename, FileNameParser::e_freetype) || !FilenameTools::isExist(filename)) return false; delete m_font, m_font = NULL; m_font = FontMgr::Instance()->getItem(filename); return m_font != NULL; } void FontBlankSymbol::loadResources() { Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(m_filepath.fn_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); name = value["name"].asString(); font = value["font"].asString(); color = value["color"].asString(); if (!value["align"].isNull()) { align_hori = value["align"].asDouble(); } else { align_hori = value["align hori"].asDouble(); align_vert = value["align vert"].asDouble(); } size = value["size"].asDouble(); width = value["width"].asDouble(); height = value["height"].asDouble(); if (value["font filename"].isNull()) m_font = NULL; else { filename = value["font filename"].asString(); loadFont(filename); } } void FontBlankSymbol::DrawBackground(const Screen& scr, const ISprite* sprite, const Matrix& mt) const { float w = width, h = height; const FontSprite* s = dynamic_cast<const FontSprite*>(sprite); if (s) { w = s->width; h = s->height; if (m_font) glColor4f(s->color.r, s->color.g, s->color.b, s->color.a); } Vector center(0, 0); center = Math::transVector(center, mt); PrimitiveDraw::rect(scr, center, w*0.5f, h*0.5f, m_style); } void FontBlankSymbol::DrawText(const Screen& scr, const ISprite* sprite, const Matrix& mt) const { if (sprite) { if (const FontSprite* font = dynamic_cast<const FontSprite*>(sprite)) { const std::string& str = font->GetTextContext(); if (!str.empty()) { Vector pos = sprite->getPosition(); pos = Math::transVector(Vector(pos), mt); LabelStyle style; style.has_edge = font->has_edge; style.font_size = font->size; style.width = font->width; style.height = font->height; style.color = font->color; style.align_hori = font->align_hori; style.align_vert = font->align_vert; LabelNew::Print(scr, str.c_str(), pos, style); } } } // if (sprite) { // if (const FontSprite* font = dynamic_cast<const FontSprite*>(sprite)) { // const std::string& str = font->GetTextContext(); // if (!str.empty()) { // d2d::PrimitiveDraw::text(str.c_str()); // } // } // } // if (m_font) // { // float w = width; // if (const FontSprite* s = dynamic_cast<const FontSprite*>(sprite)) { // w = s->width; // } // Shader::Instance()->null(); // print(-w*0.5f, 0, "abcdEFGH1234"); // } } void FontBlankSymbol::print(float x, float y, const char* text) const { // We want a coordinate system where things coresponding to window pixels. // pushScreenCoordinateMatrix(); GLuint font=m_font->list_base; float h=m_font->h/.63f; //We make the height about 1.5* that of //Here is some code to split the text that we have been //given into a set of lines. //This could be made much neater by using //a regular expression library such as the one avliable from //boost.org (I've only done it out by hand to avoid complicating //this tutorial with unnecessary library dependencies). const char *start_line=text; const char *c; std::vector<std::string> lines; for(c=text;*c;c++) { if(*c=='\n') { std::string line; for(const char *n=start_line;n<c;n++) line.append(1,*n); lines.push_back(line); start_line=c+1; } } if(start_line) { std::string line; for(const char *n=start_line;n<c;n++) line.append(1,*n); lines.push_back(line); } glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); //glEnable(GL_BLEND); // set in shader // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glListBase(font); float modelview_matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix); //This is where the text display actually happens. //For each line of text we reset the modelview matrix //so that the line's text will start in the correct position. //Notice that we need to reset the matrix, rather than just translating //down by h. This is because when each character is //draw it modifies the current matrix so that the next character //will be drawn immediatly after it. for(int i=0;i<lines.size();i++) { glPushMatrix(); glLoadIdentity(); glTranslatef(x,y-h*i,0); glMultMatrixf(modelview_matrix); // The commented out raster position stuff can be useful if you need to // know the length of the text that you are creating. // If you decide to use it make sure to also uncomment the glBitmap command // in make_dlist(). // glRasterPos2f(0,0); glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str()); // float rpos[4]; // glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos); // float len=x-rpos[0]; glPopMatrix(); } glPopAttrib(); // pop_projection_matrix(); glBindTexture(GL_TEXTURE_2D, NULL); } } // d2d<commit_msg>[FIXED] font content偏移<commit_after>#include "FontBlankSymbol.h" #include "FontSprite.h" #include "Font.h" #include "common/Vector.h" #include "common/color_trans.h" #include "common/FileNameTools.h" #include "common/FileNameParser.h" #include "common/Settings.h" #include "common/Math.h" #include "dataset/SpriteTools.h" #include "render/PrimitiveDraw.h" #include "render/Shader.h" #include "render/LabelNew.h" //OpenGL Headers #include <windows.h> #include <GL/gl.h> #include <json/json.h> namespace d2d { FontBlankSymbol::FontBlankSymbol() { static int id = 0; m_name = wxT("fontblank") + wxVariant(id++); align_hori = align_vert = 0; size = 0; width = height = 100; m_font = NULL; m_style.fill = true; m_style.color.set(0.7f, 0.7f, 0.7f, 0.7f); } FontBlankSymbol::~FontBlankSymbol() { // m_font->release(); } void FontBlankSymbol::reloadTexture() const { } void FontBlankSymbol::draw(const Screen& scr, const Matrix& mt, const Colorf& mul, const Colorf& add, const ISprite* sprite/* = NULL*/) const { if (Settings::DrawFontType & Settings::DrawFontBg) { DrawBackground(scr, sprite, mt); } if (Settings::DrawFontType & Settings::DrawFontText) { DrawText(scr, sprite, mt); } SpriteTools::DrawName(scr, sprite, mt); } Rect FontBlankSymbol::getSize(const ISprite* sprite/* = NULL*/) const { return Rect(width, height); } void FontBlankSymbol::refresh() { } bool FontBlankSymbol::loadFont(const std::string& _filename) { if (_filename == filename) return false; std::string filename = FilenameTools::getAbsolutePath(m_filepath, _filename); if (!FileNameParser::isType(filename, FileNameParser::e_freetype) || !FilenameTools::isExist(filename)) return false; delete m_font, m_font = NULL; m_font = FontMgr::Instance()->getItem(filename); return m_font != NULL; } void FontBlankSymbol::loadResources() { Json::Value value; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(m_filepath.fn_str()); std::locale::global(std::locale("C")); reader.parse(fin, value); fin.close(); name = value["name"].asString(); font = value["font"].asString(); color = value["color"].asString(); if (!value["align"].isNull()) { align_hori = value["align"].asDouble(); } else { align_hori = value["align hori"].asDouble(); align_vert = value["align vert"].asDouble(); } size = value["size"].asDouble(); width = value["width"].asDouble(); height = value["height"].asDouble(); if (value["font filename"].isNull()) m_font = NULL; else { filename = value["font filename"].asString(); loadFont(filename); } } void FontBlankSymbol::DrawBackground(const Screen& scr, const ISprite* sprite, const Matrix& mt) const { float w = width, h = height; const FontSprite* s = dynamic_cast<const FontSprite*>(sprite); if (s) { w = s->width; h = s->height; if (m_font) glColor4f(s->color.r, s->color.g, s->color.b, s->color.a); } Vector center(0, 0); center = Math::transVector(center, mt); PrimitiveDraw::rect(scr, center, w*0.5f, h*0.5f, m_style); } void FontBlankSymbol::DrawText(const Screen& scr, const ISprite* sprite, const Matrix& mt) const { if (sprite) { if (const FontSprite* font = dynamic_cast<const FontSprite*>(sprite)) { const std::string& str = font->GetTextContext(); if (!str.empty()) { Vector pos = Math::transVector(Vector(0, 0), mt); LabelStyle style; style.has_edge = font->has_edge; style.font_size = font->size; style.width = font->width; style.height = font->height; style.color = font->color; style.align_hori = font->align_hori; style.align_vert = font->align_vert; LabelNew::Print(scr, str.c_str(), pos, style); } } } // if (sprite) { // if (const FontSprite* font = dynamic_cast<const FontSprite*>(sprite)) { // const std::string& str = font->GetTextContext(); // if (!str.empty()) { // d2d::PrimitiveDraw::text(str.c_str()); // } // } // } // if (m_font) // { // float w = width; // if (const FontSprite* s = dynamic_cast<const FontSprite*>(sprite)) { // w = s->width; // } // Shader::Instance()->null(); // print(-w*0.5f, 0, "abcdEFGH1234"); // } } void FontBlankSymbol::print(float x, float y, const char* text) const { // We want a coordinate system where things coresponding to window pixels. // pushScreenCoordinateMatrix(); GLuint font=m_font->list_base; float h=m_font->h/.63f; //We make the height about 1.5* that of //Here is some code to split the text that we have been //given into a set of lines. //This could be made much neater by using //a regular expression library such as the one avliable from //boost.org (I've only done it out by hand to avoid complicating //this tutorial with unnecessary library dependencies). const char *start_line=text; const char *c; std::vector<std::string> lines; for(c=text;*c;c++) { if(*c=='\n') { std::string line; for(const char *n=start_line;n<c;n++) line.append(1,*n); lines.push_back(line); start_line=c+1; } } if(start_line) { std::string line; for(const char *n=start_line;n<c;n++) line.append(1,*n); lines.push_back(line); } glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT); glMatrixMode(GL_MODELVIEW); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); //glEnable(GL_BLEND); // set in shader // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glListBase(font); float modelview_matrix[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix); //This is where the text display actually happens. //For each line of text we reset the modelview matrix //so that the line's text will start in the correct position. //Notice that we need to reset the matrix, rather than just translating //down by h. This is because when each character is //draw it modifies the current matrix so that the next character //will be drawn immediatly after it. for(int i=0;i<lines.size();i++) { glPushMatrix(); glLoadIdentity(); glTranslatef(x,y-h*i,0); glMultMatrixf(modelview_matrix); // The commented out raster position stuff can be useful if you need to // know the length of the text that you are creating. // If you decide to use it make sure to also uncomment the glBitmap command // in make_dlist(). // glRasterPos2f(0,0); glCallLists(lines[i].length(), GL_UNSIGNED_BYTE, lines[i].c_str()); // float rpos[4]; // glGetFloatv(GL_CURRENT_RASTER_POSITION ,rpos); // float len=x-rpos[0]; glPopMatrix(); } glPopAttrib(); // pop_projection_matrix(); glBindTexture(GL_TEXTURE_2D, NULL); } } // d2d<|endoftext|>
<commit_before>//===-- Support/DJB.cpp ---DJB Hash -----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains support for the DJ Bernstein hash function. // //===----------------------------------------------------------------------===// #include "llvm/Support/DJB.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Unicode.h" using namespace llvm; static UTF32 chopOneUTF32(StringRef &Buffer) { UTF32 C; const UTF8 *const Begin8Const = reinterpret_cast<const UTF8 *>(Buffer.begin()); const UTF8 *Begin8 = Begin8Const; UTF32 *Begin32 = &C; // In lenient mode we will always end up with a "reasonable" value in C for // non-empty input. assert(!Buffer.empty()); ConvertUTF8toUTF32(&Begin8, reinterpret_cast<const UTF8 *>(Buffer.end()), &Begin32, &C + 1, lenientConversion); Buffer = Buffer.drop_front(Begin8 - Begin8Const); return C; } static StringRef toUTF8(UTF32 C, MutableArrayRef<UTF8> Storage) { const UTF32 *Begin32 = &C; UTF8 *Begin8 = Storage.begin(); // The case-folded output should always be a valid unicode character, so use // strict mode here. ConversionResult CR = ConvertUTF32toUTF8(&Begin32, &C + 1, &Begin8, Storage.end(), strictConversion); assert(CR == conversionOK && "Case folding produced invalid char?"); (void)CR; return StringRef(reinterpret_cast<char *>(Storage.begin()), Begin8 - Storage.begin()); } static UTF32 foldCharDwarf(UTF32 C) { // DWARF v5 addition to the unicode folding rules. // Fold "Latin Small Letter Dotless I" and "Latin Capital Letter I With Dot // Above" into "i". if (C == 0x130 || C == 0x131) return 'i'; return sys::unicode::foldCharSimple(C); } static uint32_t caseFoldingDjbHashCharSlow(StringRef &Buffer, uint32_t H) { UTF32 C = chopOneUTF32(Buffer); C = foldCharDwarf(C); std::array<UTF8, UNI_MAX_UTF8_BYTES_PER_CODE_POINT> Storage; StringRef Folded = toUTF8(C, Storage); return djbHash(Folded, H); } uint32_t llvm::caseFoldingDjbHash(StringRef Buffer, uint32_t H) { while (!Buffer.empty()) { unsigned char C = Buffer.front(); if (LLVM_LIKELY(C <= 0x7f)) { // US-ASCII, encoded as one character in utf-8. // This is by far the most common case, so handle this specially. if (C >= 'A' && C <= 'Z') C = 'a' + (C - 'A'); // fold uppercase into lowercase H = (H << 5) + H + C; Buffer = Buffer.drop_front(); continue; } H = caseFoldingDjbHashCharSlow(Buffer, H); } return H; } <commit_msg>caseFoldingDjbHash: simplify and make the US-ASCII fast path faster<commit_after>//===-- Support/DJB.cpp ---DJB Hash -----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains support for the DJ Bernstein hash function. // //===----------------------------------------------------------------------===// #include "llvm/Support/DJB.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Unicode.h" using namespace llvm; static UTF32 chopOneUTF32(StringRef &Buffer) { UTF32 C; const UTF8 *const Begin8Const = reinterpret_cast<const UTF8 *>(Buffer.begin()); const UTF8 *Begin8 = Begin8Const; UTF32 *Begin32 = &C; // In lenient mode we will always end up with a "reasonable" value in C for // non-empty input. assert(!Buffer.empty()); ConvertUTF8toUTF32(&Begin8, reinterpret_cast<const UTF8 *>(Buffer.end()), &Begin32, &C + 1, lenientConversion); Buffer = Buffer.drop_front(Begin8 - Begin8Const); return C; } static StringRef toUTF8(UTF32 C, MutableArrayRef<UTF8> Storage) { const UTF32 *Begin32 = &C; UTF8 *Begin8 = Storage.begin(); // The case-folded output should always be a valid unicode character, so use // strict mode here. ConversionResult CR = ConvertUTF32toUTF8(&Begin32, &C + 1, &Begin8, Storage.end(), strictConversion); assert(CR == conversionOK && "Case folding produced invalid char?"); (void)CR; return StringRef(reinterpret_cast<char *>(Storage.begin()), Begin8 - Storage.begin()); } static UTF32 foldCharDwarf(UTF32 C) { // DWARF v5 addition to the unicode folding rules. // Fold "Latin Small Letter Dotless I" and "Latin Capital Letter I With Dot // Above" into "i". if (C == 0x130 || C == 0x131) return 'i'; return sys::unicode::foldCharSimple(C); } static Optional<uint32_t> fastCaseFoldingDjbHash(StringRef Buffer, uint32_t H) { bool allASCII = true; for (unsigned char C : Buffer) { H = H * 33 + ('A' <= C && C <= 'Z' ? C - 'A' + 'a' : C); allASCII &= C <= 0x7f; } if (allASCII) return H; return None; } uint32_t llvm::caseFoldingDjbHash(StringRef Buffer, uint32_t H) { if (Optional<uint32_t> Result = fastCaseFoldingDjbHash(Buffer, H)) return *Result; std::array<UTF8, UNI_MAX_UTF8_BYTES_PER_CODE_POINT> Storage; while (!Buffer.empty()) { UTF32 C = foldCharDwarf(chopOneUTF32(Buffer)); StringRef Folded = toUTF8(C, Storage); H = djbHash(Folded, H); } return H; } <|endoftext|>
<commit_before>//===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LLVM Pass infrastructure. It is primarily // responsible with ensuring that passes are executed and batched together // optimally. // //===----------------------------------------------------------------------===// #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/Module.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Atomic.h" #include "llvm/System/Mutex.h" #include "llvm/System/Threading.h" #include <algorithm> #include <map> #include <set> using namespace llvm; //===----------------------------------------------------------------------===// // Pass Implementation // // Force out-of-line virtual method. Pass::~Pass() { delete Resolver; } // Force out-of-line virtual method. ModulePass::~ModulePass() { } Pass *ModulePass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintModulePass(&O, false, Banner); } PassManagerType ModulePass::getPotentialPassManagerType() const { return PMT_ModulePassManager; } bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const { return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0; } // dumpPassStructure - Implement the -debug-passes=Structure option void Pass::dumpPassStructure(unsigned Offset) { dbgs().indent(Offset*2) << getPassName() << "\n"; } /// getPassName - Return a nice clean name for a pass. This usually /// implemented in terms of the name that is registered by one of the /// Registration templates, but can be overloaded directly. /// const char *Pass::getPassName() const { if (const PassInfo *PI = getPassInfo()) return PI->getPassName(); return "Unnamed pass: implement Pass::getPassName()"; } void Pass::preparePassManager(PMStack &) { // By default, don't do anything. } PassManagerType Pass::getPotentialPassManagerType() const { // Default implementation. return PMT_Unknown; } void Pass::getAnalysisUsage(AnalysisUsage &) const { // By default, no analysis results are used, all are invalidated. } void Pass::releaseMemory() { // By default, don't do anything. } void Pass::verifyAnalysis() const { // By default, don't do anything. } // print - Print out the internal state of the pass. This is called by Analyze // to print out the contents of an analysis. Otherwise it is not necessary to // implement this method. // void Pass::print(raw_ostream &O,const Module*) const { O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n"; } // dump - call print(cerr); void Pass::dump() const { print(dbgs(), 0); } //===----------------------------------------------------------------------===// // ImmutablePass Implementation // // Force out-of-line virtual method. ImmutablePass::~ImmutablePass() { } void ImmutablePass::initializePass() { // By default, don't do anything. } //===----------------------------------------------------------------------===// // FunctionPass Implementation // Pass *FunctionPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintFunctionPass(Banner, &O); } // run - On a module, we run this pass by initializing, runOnFunction'ing once // for every function in the module, then by finalizing. // bool FunctionPass::runOnModule(Module &M) { bool Changed = doInitialization(M); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) // Passes are not run on external functions! Changed |= runOnFunction(*I); return Changed | doFinalization(M); } // run - On a function, we simply initialize, run the function, then finalize. // bool FunctionPass::run(Function &F) { // Passes are not run on external functions! if (F.isDeclaration()) return false; bool Changed = doInitialization(*F.getParent()); Changed |= runOnFunction(F); return Changed | doFinalization(*F.getParent()); } bool FunctionPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool FunctionPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType FunctionPass::getPotentialPassManagerType() const { return PMT_FunctionPassManager; } //===----------------------------------------------------------------------===// // BasicBlockPass Implementation // Pass *BasicBlockPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { llvm_unreachable("BasicBlockPass printing unsupported."); return 0; } // To run this pass on a function, we simply call runOnBasicBlock once for each // function. // bool BasicBlockPass::runOnFunction(Function &F) { bool Changed = doInitialization(F); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed | doFinalization(F); } bool BasicBlockPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool BasicBlockPass::doInitialization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType BasicBlockPass::getPotentialPassManagerType() const { return PMT_BasicBlockPassManager; } //===----------------------------------------------------------------------===// // Pass Registration mechanism // namespace { class PassRegistrar { /// Guards the contents of this class. mutable sys::SmartMutex<true> Lock; /// PassInfoMap - Keep track of the passinfo object for each registered llvm /// pass. typedef std::map<intptr_t, const PassInfo*> MapType; MapType PassInfoMap; typedef StringMap<const PassInfo*> StringMapType; StringMapType PassInfoStringMap; /// AnalysisGroupInfo - Keep track of information for each analysis group. struct AnalysisGroupInfo { std::set<const PassInfo *> Implementations; }; /// AnalysisGroupInfoMap - Information for each analysis group. std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap; public: const PassInfo *GetPassInfo(intptr_t TI) const { sys::SmartScopedLock<true> Guard(Lock); MapType::const_iterator I = PassInfoMap.find(TI); return I != PassInfoMap.end() ? I->second : 0; } const PassInfo *GetPassInfo(StringRef Arg) const { sys::SmartScopedLock<true> Guard(Lock); StringMapType::const_iterator I = PassInfoStringMap.find(Arg); return I != PassInfoStringMap.end() ? I->second : 0; } void RegisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); bool Inserted = PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second; assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted; PassInfoStringMap[PI.getPassArgument()] = &PI; } void UnregisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); MapType::iterator I = PassInfoMap.find(PI.getTypeInfo()); assert(I != PassInfoMap.end() && "Pass registered but not in map!"); // Remove pass from the map. PassInfoMap.erase(I); PassInfoStringMap.erase(PI.getPassArgument()); } void EnumerateWith(PassRegistrationListener *L) { sys::SmartScopedLock<true> Guard(Lock); for (MapType::const_iterator I = PassInfoMap.begin(), E = PassInfoMap.end(); I != E; ++I) L->passEnumerate(I->second); } /// Analysis Group Mechanisms. void RegisterAnalysisGroup(PassInfo *InterfaceInfo, const PassInfo *ImplementationInfo, bool isDefault) { sys::SmartScopedLock<true> Guard(Lock); AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo]; assert(AGI.Implementations.count(ImplementationInfo) == 0 && "Cannot add a pass to the same analysis group more than once!"); AGI.Implementations.insert(ImplementationInfo); if (isDefault) { assert(InterfaceInfo->getNormalCtor() == 0 && "Default implementation for analysis group already specified!"); assert(ImplementationInfo->getNormalCtor() && "Cannot specify pass as default if it does not have a default ctor"); InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor()); } } }; } static std::vector<PassRegistrationListener*> *Listeners = 0; static sys::SmartMutex<true> ListenersLock; static PassRegistrar *PassRegistrarObj = 0; static PassRegistrar *getPassRegistrar() { // Use double-checked locking to safely initialize the registrar when // we're running in multithreaded mode. PassRegistrar* tmp = PassRegistrarObj; if (llvm_is_multithreaded()) { sys::MemoryFence(); if (!tmp) { llvm_acquire_global_lock(); tmp = PassRegistrarObj; if (!tmp) { tmp = new PassRegistrar(); sys::MemoryFence(); PassRegistrarObj = tmp; } llvm_release_global_lock(); } } else if (!tmp) { PassRegistrarObj = new PassRegistrar(); } return PassRegistrarObj; } // FIXME: We use ManagedCleanup to erase the pass registrar on shutdown. // Unfortunately, passes are registered with static ctors, and having // llvm_shutdown clear this map prevents successful ressurection after // llvm_shutdown is run. Ideally we should find a solution so that we don't // leak the map, AND can still resurrect after shutdown. void cleanupPassRegistrar(void*) { if (PassRegistrarObj) { delete PassRegistrarObj; PassRegistrarObj = 0; } } ManagedCleanup<&cleanupPassRegistrar> registrarCleanup; // getPassInfo - Return the PassInfo data structure that corresponds to this // pass... const PassInfo *Pass::getPassInfo() const { return lookupPassInfo(PassID); } const PassInfo *Pass::lookupPassInfo(intptr_t TI) { return getPassRegistrar()->GetPassInfo(TI); } const PassInfo *Pass::lookupPassInfo(StringRef Arg) { return getPassRegistrar()->GetPassInfo(Arg); } void PassInfo::registerPass() { getPassRegistrar()->RegisterPass(*this); // Notify any listeners. sys::SmartScopedLock<true> Lock(ListenersLock); if (Listeners) for (std::vector<PassRegistrationListener*>::iterator I = Listeners->begin(), E = Listeners->end(); I != E; ++I) (*I)->passRegistered(this); } void PassInfo::unregisterPass() { getPassRegistrar()->UnregisterPass(*this); } //===----------------------------------------------------------------------===// // Analysis Group Implementation Code //===----------------------------------------------------------------------===// // RegisterAGBase implementation // RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID, intptr_t PassID, bool isDefault) : PassInfo(Name, InterfaceID) { PassInfo *InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID)); if (InterfaceInfo == 0) { // First reference to Interface, register it now. registerPass(); InterfaceInfo = this; } assert(isAnalysisGroup() && "Trying to join an analysis group that is a normal pass!"); if (PassID) { const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID); assert(ImplementationInfo && "Must register pass before adding to AnalysisGroup!"); // Make sure we keep track of the fact that the implementation implements // the interface. PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo); IIPI->addInterfaceImplemented(InterfaceInfo); getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault); } } //===----------------------------------------------------------------------===// // PassRegistrationListener implementation // // PassRegistrationListener ctor - Add the current object to the list of // PassRegistrationListeners... PassRegistrationListener::PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>(); Listeners->push_back(this); } // dtor - Remove object from list of listeners... PassRegistrationListener::~PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); std::vector<PassRegistrationListener*>::iterator I = std::find(Listeners->begin(), Listeners->end(), this); assert(Listeners && I != Listeners->end() && "PassRegistrationListener not registered!"); Listeners->erase(I); if (Listeners->empty()) { delete Listeners; Listeners = 0; } } // enumeratePasses - Iterate over the registered passes, calling the // passEnumerate callback on each PassInfo object. // void PassRegistrationListener::enumeratePasses() { getPassRegistrar()->EnumerateWith(this); } PassNameParser::~PassNameParser() {} //===----------------------------------------------------------------------===// // AnalysisUsage Class Implementation // namespace { struct GetCFGOnlyPasses : public PassRegistrationListener { typedef AnalysisUsage::VectorType VectorType; VectorType &CFGOnlyList; GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {} void passEnumerate(const PassInfo *P) { if (P->isCFGOnlyPass()) CFGOnlyList.push_back(P); } }; } // setPreservesCFG - This function should be called to by the pass, iff they do // not: // // 1. Add or remove basic blocks from the function // 2. Modify terminator instructions in any way. // // This function annotates the AnalysisUsage info object to say that analyses // that only depend on the CFG are preserved by this pass. // void AnalysisUsage::setPreservesCFG() { // Since this transformation doesn't modify the CFG, it preserves all analyses // that only depend on the CFG (like dominators, loop info, etc...) GetCFGOnlyPasses(Preserved).enumeratePasses(); } <commit_msg>Fix namespace polution.<commit_after>//===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the LLVM Pass infrastructure. It is primarily // responsible with ensuring that passes are executed and batched together // optimally. // //===----------------------------------------------------------------------===// #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/Module.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Atomic.h" #include "llvm/System/Mutex.h" #include "llvm/System/Threading.h" #include <algorithm> #include <map> #include <set> using namespace llvm; //===----------------------------------------------------------------------===// // Pass Implementation // // Force out-of-line virtual method. Pass::~Pass() { delete Resolver; } // Force out-of-line virtual method. ModulePass::~ModulePass() { } Pass *ModulePass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintModulePass(&O, false, Banner); } PassManagerType ModulePass::getPotentialPassManagerType() const { return PMT_ModulePassManager; } bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const { return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0; } // dumpPassStructure - Implement the -debug-passes=Structure option void Pass::dumpPassStructure(unsigned Offset) { dbgs().indent(Offset*2) << getPassName() << "\n"; } /// getPassName - Return a nice clean name for a pass. This usually /// implemented in terms of the name that is registered by one of the /// Registration templates, but can be overloaded directly. /// const char *Pass::getPassName() const { if (const PassInfo *PI = getPassInfo()) return PI->getPassName(); return "Unnamed pass: implement Pass::getPassName()"; } void Pass::preparePassManager(PMStack &) { // By default, don't do anything. } PassManagerType Pass::getPotentialPassManagerType() const { // Default implementation. return PMT_Unknown; } void Pass::getAnalysisUsage(AnalysisUsage &) const { // By default, no analysis results are used, all are invalidated. } void Pass::releaseMemory() { // By default, don't do anything. } void Pass::verifyAnalysis() const { // By default, don't do anything. } // print - Print out the internal state of the pass. This is called by Analyze // to print out the contents of an analysis. Otherwise it is not necessary to // implement this method. // void Pass::print(raw_ostream &O,const Module*) const { O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n"; } // dump - call print(cerr); void Pass::dump() const { print(dbgs(), 0); } //===----------------------------------------------------------------------===// // ImmutablePass Implementation // // Force out-of-line virtual method. ImmutablePass::~ImmutablePass() { } void ImmutablePass::initializePass() { // By default, don't do anything. } //===----------------------------------------------------------------------===// // FunctionPass Implementation // Pass *FunctionPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createPrintFunctionPass(Banner, &O); } // run - On a module, we run this pass by initializing, runOnFunction'ing once // for every function in the module, then by finalizing. // bool FunctionPass::runOnModule(Module &M) { bool Changed = doInitialization(M); for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isDeclaration()) // Passes are not run on external functions! Changed |= runOnFunction(*I); return Changed | doFinalization(M); } // run - On a function, we simply initialize, run the function, then finalize. // bool FunctionPass::run(Function &F) { // Passes are not run on external functions! if (F.isDeclaration()) return false; bool Changed = doInitialization(*F.getParent()); Changed |= runOnFunction(F); return Changed | doFinalization(*F.getParent()); } bool FunctionPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool FunctionPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType FunctionPass::getPotentialPassManagerType() const { return PMT_FunctionPassManager; } //===----------------------------------------------------------------------===// // BasicBlockPass Implementation // Pass *BasicBlockPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { llvm_unreachable("BasicBlockPass printing unsupported."); return 0; } // To run this pass on a function, we simply call runOnBasicBlock once for each // function. // bool BasicBlockPass::runOnFunction(Function &F) { bool Changed = doInitialization(F); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed | doFinalization(F); } bool BasicBlockPass::doInitialization(Module &) { // By default, don't do anything. return false; } bool BasicBlockPass::doInitialization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Function &) { // By default, don't do anything. return false; } bool BasicBlockPass::doFinalization(Module &) { // By default, don't do anything. return false; } PassManagerType BasicBlockPass::getPotentialPassManagerType() const { return PMT_BasicBlockPassManager; } //===----------------------------------------------------------------------===// // Pass Registration mechanism // namespace { class PassRegistrar { /// Guards the contents of this class. mutable sys::SmartMutex<true> Lock; /// PassInfoMap - Keep track of the passinfo object for each registered llvm /// pass. typedef std::map<intptr_t, const PassInfo*> MapType; MapType PassInfoMap; typedef StringMap<const PassInfo*> StringMapType; StringMapType PassInfoStringMap; /// AnalysisGroupInfo - Keep track of information for each analysis group. struct AnalysisGroupInfo { std::set<const PassInfo *> Implementations; }; /// AnalysisGroupInfoMap - Information for each analysis group. std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap; public: const PassInfo *GetPassInfo(intptr_t TI) const { sys::SmartScopedLock<true> Guard(Lock); MapType::const_iterator I = PassInfoMap.find(TI); return I != PassInfoMap.end() ? I->second : 0; } const PassInfo *GetPassInfo(StringRef Arg) const { sys::SmartScopedLock<true> Guard(Lock); StringMapType::const_iterator I = PassInfoStringMap.find(Arg); return I != PassInfoStringMap.end() ? I->second : 0; } void RegisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); bool Inserted = PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second; assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted; PassInfoStringMap[PI.getPassArgument()] = &PI; } void UnregisterPass(const PassInfo &PI) { sys::SmartScopedLock<true> Guard(Lock); MapType::iterator I = PassInfoMap.find(PI.getTypeInfo()); assert(I != PassInfoMap.end() && "Pass registered but not in map!"); // Remove pass from the map. PassInfoMap.erase(I); PassInfoStringMap.erase(PI.getPassArgument()); } void EnumerateWith(PassRegistrationListener *L) { sys::SmartScopedLock<true> Guard(Lock); for (MapType::const_iterator I = PassInfoMap.begin(), E = PassInfoMap.end(); I != E; ++I) L->passEnumerate(I->second); } /// Analysis Group Mechanisms. void RegisterAnalysisGroup(PassInfo *InterfaceInfo, const PassInfo *ImplementationInfo, bool isDefault) { sys::SmartScopedLock<true> Guard(Lock); AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo]; assert(AGI.Implementations.count(ImplementationInfo) == 0 && "Cannot add a pass to the same analysis group more than once!"); AGI.Implementations.insert(ImplementationInfo); if (isDefault) { assert(InterfaceInfo->getNormalCtor() == 0 && "Default implementation for analysis group already specified!"); assert(ImplementationInfo->getNormalCtor() && "Cannot specify pass as default if it does not have a default ctor"); InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor()); } } }; } static std::vector<PassRegistrationListener*> *Listeners = 0; static sys::SmartMutex<true> ListenersLock; static PassRegistrar *PassRegistrarObj = 0; static PassRegistrar *getPassRegistrar() { // Use double-checked locking to safely initialize the registrar when // we're running in multithreaded mode. PassRegistrar* tmp = PassRegistrarObj; if (llvm_is_multithreaded()) { sys::MemoryFence(); if (!tmp) { llvm_acquire_global_lock(); tmp = PassRegistrarObj; if (!tmp) { tmp = new PassRegistrar(); sys::MemoryFence(); PassRegistrarObj = tmp; } llvm_release_global_lock(); } } else if (!tmp) { PassRegistrarObj = new PassRegistrar(); } return PassRegistrarObj; } namespace { // FIXME: We use ManagedCleanup to erase the pass registrar on shutdown. // Unfortunately, passes are registered with static ctors, and having // llvm_shutdown clear this map prevents successful ressurection after // llvm_shutdown is run. Ideally we should find a solution so that we don't // leak the map, AND can still resurrect after shutdown. void cleanupPassRegistrar(void*) { if (PassRegistrarObj) { delete PassRegistrarObj; PassRegistrarObj = 0; } } ManagedCleanup<&cleanupPassRegistrar> registrarCleanup; } // getPassInfo - Return the PassInfo data structure that corresponds to this // pass... const PassInfo *Pass::getPassInfo() const { return lookupPassInfo(PassID); } const PassInfo *Pass::lookupPassInfo(intptr_t TI) { return getPassRegistrar()->GetPassInfo(TI); } const PassInfo *Pass::lookupPassInfo(StringRef Arg) { return getPassRegistrar()->GetPassInfo(Arg); } void PassInfo::registerPass() { getPassRegistrar()->RegisterPass(*this); // Notify any listeners. sys::SmartScopedLock<true> Lock(ListenersLock); if (Listeners) for (std::vector<PassRegistrationListener*>::iterator I = Listeners->begin(), E = Listeners->end(); I != E; ++I) (*I)->passRegistered(this); } void PassInfo::unregisterPass() { getPassRegistrar()->UnregisterPass(*this); } //===----------------------------------------------------------------------===// // Analysis Group Implementation Code //===----------------------------------------------------------------------===// // RegisterAGBase implementation // RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID, intptr_t PassID, bool isDefault) : PassInfo(Name, InterfaceID) { PassInfo *InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID)); if (InterfaceInfo == 0) { // First reference to Interface, register it now. registerPass(); InterfaceInfo = this; } assert(isAnalysisGroup() && "Trying to join an analysis group that is a normal pass!"); if (PassID) { const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID); assert(ImplementationInfo && "Must register pass before adding to AnalysisGroup!"); // Make sure we keep track of the fact that the implementation implements // the interface. PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo); IIPI->addInterfaceImplemented(InterfaceInfo); getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault); } } //===----------------------------------------------------------------------===// // PassRegistrationListener implementation // // PassRegistrationListener ctor - Add the current object to the list of // PassRegistrationListeners... PassRegistrationListener::PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>(); Listeners->push_back(this); } // dtor - Remove object from list of listeners... PassRegistrationListener::~PassRegistrationListener() { sys::SmartScopedLock<true> Lock(ListenersLock); std::vector<PassRegistrationListener*>::iterator I = std::find(Listeners->begin(), Listeners->end(), this); assert(Listeners && I != Listeners->end() && "PassRegistrationListener not registered!"); Listeners->erase(I); if (Listeners->empty()) { delete Listeners; Listeners = 0; } } // enumeratePasses - Iterate over the registered passes, calling the // passEnumerate callback on each PassInfo object. // void PassRegistrationListener::enumeratePasses() { getPassRegistrar()->EnumerateWith(this); } PassNameParser::~PassNameParser() {} //===----------------------------------------------------------------------===// // AnalysisUsage Class Implementation // namespace { struct GetCFGOnlyPasses : public PassRegistrationListener { typedef AnalysisUsage::VectorType VectorType; VectorType &CFGOnlyList; GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {} void passEnumerate(const PassInfo *P) { if (P->isCFGOnlyPass()) CFGOnlyList.push_back(P); } }; } // setPreservesCFG - This function should be called to by the pass, iff they do // not: // // 1. Add or remove basic blocks from the function // 2. Modify terminator instructions in any way. // // This function annotates the AnalysisUsage info object to say that analyses // that only depend on the CFG are preserved by this pass. // void AnalysisUsage::setPreservesCFG() { // Since this transformation doesn't modify the CFG, it preserves all analyses // that only depend on the CFG (like dominators, loop info, etc...) GetCFGOnlyPasses(Preserved).enumeratePasses(); } <|endoftext|>
<commit_before>/** * @file */ #pragma once /** * @internal * * @def LIBBIRCH_BASE * * Declare the base type for a class. */ #define LIBBIRCH_BASE(Base...) \ using base_type_ = Base; \ \ auto shared_from_base_() { \ return libbirch::Shared<base_type_>(static_cast<base_type_*>(this)); \ } /** * @internal * * @def LIBBIRCH_THIS * * Declare this type for a class. */ #define LIBBIRCH_THIS(Name...) \ using this_type_ = Name; \ \ auto shared_from_this_() { \ return libbirch::Shared<this_type_>(this); \ } /** * @internal * * @def LIBBIRCH_VIRTUAL * * Declare virtual functions for concrete classes. */ #define LIBBIRCH_VIRTUAL(Name, Base...) \ virtual const char* getClassName() const { \ return #Name; \ } \ \ virtual int size_() const override { \ return sizeof(*this); \ } \ \ virtual Name* copy_() const override { \ return new Name(*this); \ } /** * @def LIBBIRCH_CLASS * * Boilerplate macro for classes to support lazy deep copy. The first * argument is the name of the class; this should exclude any generic type * arguments. The second argument is the base class; this should include any * generic type arguments. It is recommended that the macro is used at the * very end of the class definition. * * LIBBIRCH_CLASS must be followed by LIBBIRCH_MEMBERS, and should be in a * public section, e.g.: * * class A : public B { * private: * int x, y, z; * * public: * LIBBIRCH_CLASS(A, B) * LIBBIRCH_MEMBERS(x, y, z) * }; * * The use of a variadic macro here supports base classes that contain * commas without special treatment, e.g. * * LIBBIRCH_CLASS(A, B<T,U>) */ #define LIBBIRCH_CLASS(Name, Base...) public: \ LIBBIRCH_THIS(Name) \ LIBBIRCH_BASE(Base) \ LIBBIRCH_VIRTUAL(Name, Base) /** * @def LIBBIRCH_ABSTRACT_CLASS * * Use in place of LIBBIRCH_CLASS when the containing class is abstract. */ #define LIBBIRCH_ABSTRACT_CLASS(Name, Base...) public: \ LIBBIRCH_THIS(Name) \ LIBBIRCH_BASE(Base) /** * @def LIBBIRCH_MEMBERS * * Boilerplate macro for classes to support lazy deep copy. The arguments * list all member variables of the class (but not those of a base class, * which should be listed in its own use of LIBBIRCH_MEMBERS). * * LIBBIRCH_MEMBERS must be preceded by LIBBIRCH_CLASS, and should be in a * public section, e.g.: * * class A : public B { * private: * int x, y, z; * * public: * LIBBIRCH_CLASS(A, B) * LIBBIRCH_MEMBERS(x, y, z) * }; */ #define LIBBIRCH_MEMBERS(...) \ void accept_(libbirch::Marker& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Scanner& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Reacher& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Collector& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ std::tuple<int,int,int> accept_(libbirch::Spanner& visitor_, const int i_, const int j_) override { \ int l_, h_, m_, l1_, h1_, m1_; \ std::tie(l_, h_, m_) = base_type_::accept_(visitor_, i_, j_); \ std::tie(l1_, h1_, m1_) = visitor_.visit(i_, j_ + m_ __VA_OPT__(,) __VA_ARGS__); \ l_ = std::min(l_, l1_); \ h_ = std::max(h_, h1_); \ m_ += m1_; \ return std::make_tuple(l_, h_, m_); \ } \ \ std::tuple<int,int,int,int> accept_(libbirch::Bridger& visitor_, const int j_, const int k_) override { \ int l_, h_, m_, n_, l1_, h1_, m1_, n1_; \ std::tie(l_, h_, m_, n_) = base_type_::accept_(visitor_, j_, k_); \ std::tie(l1_, h1_, m1_, n1_) = visitor_.visit(j_ + m_, k_ + n_ __VA_OPT__(,) __VA_ARGS__); \ l_ = std::min(l_, l1_); \ h_ = std::max(h_, h1_); \ m_ += m1_; \ n_ += n1_; \ return std::make_tuple(l_, h_, m_, n_); \ } \ \ void accept_(libbirch::Copier& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } #include "libbirch/Marker.hpp" #include "libbirch/Scanner.hpp" #include "libbirch/Reacher.hpp" #include "libbirch/Collector.hpp" #include "libbirch/Spanner.hpp" #include "libbirch/Bridger.hpp" #include "libbirch/Copier.hpp" <commit_msg>Replaced __VA_OPT__(,) with ## GNU extension.<commit_after>/** * @file */ #pragma once /** * @internal * * @def LIBBIRCH_BASE * * Declare the base type for a class. */ #define LIBBIRCH_BASE(Base...) \ using base_type_ = Base; \ \ auto shared_from_base_() { \ return libbirch::Shared<base_type_>(static_cast<base_type_*>(this)); \ } /** * @internal * * @def LIBBIRCH_THIS * * Declare this type for a class. */ #define LIBBIRCH_THIS(Name...) \ using this_type_ = Name; \ \ auto shared_from_this_() { \ return libbirch::Shared<this_type_>(this); \ } /** * @internal * * @def LIBBIRCH_VIRTUAL * * Declare virtual functions for concrete classes. */ #define LIBBIRCH_VIRTUAL(Name, Base...) \ virtual const char* getClassName() const { \ return #Name; \ } \ \ virtual int size_() const override { \ return sizeof(*this); \ } \ \ virtual Name* copy_() const override { \ return new Name(*this); \ } /** * @def LIBBIRCH_CLASS * * Boilerplate macro for classes to support lazy deep copy. The first * argument is the name of the class; this should exclude any generic type * arguments. The second argument is the base class; this should include any * generic type arguments. It is recommended that the macro is used at the * very end of the class definition. * * LIBBIRCH_CLASS must be followed by LIBBIRCH_MEMBERS, and should be in a * public section, e.g.: * * class A : public B { * private: * int x, y, z; * * public: * LIBBIRCH_CLASS(A, B) * LIBBIRCH_MEMBERS(x, y, z) * }; * * The use of a variadic macro here supports base classes that contain * commas without special treatment, e.g. * * LIBBIRCH_CLASS(A, B<T,U>) */ #define LIBBIRCH_CLASS(Name, Base...) public: \ LIBBIRCH_THIS(Name) \ LIBBIRCH_BASE(Base) \ LIBBIRCH_VIRTUAL(Name, Base) /** * @def LIBBIRCH_ABSTRACT_CLASS * * Use in place of LIBBIRCH_CLASS when the containing class is abstract. */ #define LIBBIRCH_ABSTRACT_CLASS(Name, Base...) public: \ LIBBIRCH_THIS(Name) \ LIBBIRCH_BASE(Base) /** * @def LIBBIRCH_MEMBERS * * Boilerplate macro for classes to support lazy deep copy. The arguments * list all member variables of the class (but not those of a base class, * which should be listed in its own use of LIBBIRCH_MEMBERS). * * LIBBIRCH_MEMBERS must be preceded by LIBBIRCH_CLASS, and should be in a * public section, e.g.: * * class A : public B { * private: * int x, y, z; * * public: * LIBBIRCH_CLASS(A, B) * LIBBIRCH_MEMBERS(x, y, z) * }; */ #define LIBBIRCH_MEMBERS(...) \ void accept_(libbirch::Marker& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Scanner& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Reacher& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ void accept_(libbirch::Collector& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } \ \ std::tuple<int,int,int> accept_(libbirch::Spanner& visitor_, const int i_, const int j_) override { \ int l_, h_, m_, l1_, h1_, m1_; \ std::tie(l_, h_, m_) = base_type_::accept_(visitor_, i_, j_); \ std::tie(l1_, h1_, m1_) = visitor_.visit(i_, j_ + m_, ##__VA_ARGS__); \ l_ = std::min(l_, l1_); \ h_ = std::max(h_, h1_); \ m_ += m1_; \ return std::make_tuple(l_, h_, m_); \ } \ \ std::tuple<int,int,int,int> accept_(libbirch::Bridger& visitor_, const int j_, const int k_) override { \ int l_, h_, m_, n_, l1_, h1_, m1_, n1_; \ std::tie(l_, h_, m_, n_) = base_type_::accept_(visitor_, j_, k_); \ std::tie(l1_, h1_, m1_, n1_) = visitor_.visit(j_ + m_, k_ + n_, ##__VA_ARGS__); \ l_ = std::min(l_, l1_); \ h_ = std::max(h_, h1_); \ m_ += m1_; \ n_ += n1_; \ return std::make_tuple(l_, h_, m_, n_); \ } \ \ void accept_(libbirch::Copier& visitor_) override { \ base_type_::accept_(visitor_); \ visitor_.visit(__VA_ARGS__); \ } #include "libbirch/Marker.hpp" #include "libbirch/Scanner.hpp" #include "libbirch/Reacher.hpp" #include "libbirch/Collector.hpp" #include "libbirch/Spanner.hpp" #include "libbirch/Bridger.hpp" #include "libbirch/Copier.hpp" <|endoftext|>
<commit_before>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp> #include <gmock/gmock.h> #include <boost/filesystem/operations.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <boost/timer.hpp> #include <stdlib.h> #include <sstream> using namespace cucumber::internal; using namespace boost::posix_time; using namespace boost::asio::ip; #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using namespace boost::asio::local; #endif using namespace std; using namespace testing; using boost::bind; using boost::thread; namespace fs = boost::filesystem; static const time_duration THREAD_TEST_TIMEOUT = milliseconds(4000); MATCHER(IsConnected, string(negation ? "is not" : "is") + " connected") { return arg.good(); } MATCHER(HasTerminated, "") { return !arg.joinable(); } MATCHER(EventuallyTerminates, "") { return arg->timed_join(THREAD_TEST_TIMEOUT); } MATCHER_P(EventuallyReceives, value, "") { std::basic_iostream<char> *stream = const_cast<std::basic_iostream<char> *>( static_cast<const std::basic_iostream<char> *>(&arg)); std::string output; // FIXME It should not block (*stream) >> output; // boost::timer timer; // double timeout = THREAD_TEST_TIMEOUT.total_milliseconds() / 1000.0; // while (timer.elapsed() < timeout) { // if (stream->rdbuf()->available() > 0) { // it is zero even if it doesn't block! // (*stream) >> output; // break; // } // boost::this_thread::yield(); // } return (output == value); } class MockProtocolHandler : public ProtocolHandler { public: MOCK_CONST_METHOD1(handle, string(const string &request)); }; class SocketServerTest : public Test { protected: StrictMock<MockProtocolHandler> protocolHandler; boost::scoped_ptr<thread> serverThread; virtual void SetUp() { SocketServer* server = createListeningServer(); serverThread.reset(new thread(&SocketServer::acceptOnce, server)); } virtual void TearDown() { if (serverThread) { serverThread->timed_join(THREAD_TEST_TIMEOUT); serverThread.reset(); } destroyListeningServer(); } virtual SocketServer* createListeningServer() = 0; virtual void destroyListeningServer() = 0; }; class TCPSocketServerTest : public SocketServerTest { protected: boost::scoped_ptr<TCPSocketServer> server; virtual SocketServer* createListeningServer() { server.reset(new TCPSocketServer(&protocolHandler)); server->listen(0); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; TEST_F(TCPSocketServerTest, exitsOnFirstConnectionClosed) { // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); ASSERT_THAT(server->listenEndpoint().address().to_string(), std::string("0.0.0.0")); // when client.close(); // then EXPECT_THAT(serverThread, EventuallyTerminates()); } TEST_F(TCPSocketServerTest, moreThanOneClientCanConnect) { // given tcp::iostream client1(server->listenEndpoint()); ASSERT_THAT(client1, IsConnected()); // when tcp::iostream client2(server->listenEndpoint()); //then ASSERT_THAT(client2, IsConnected()); } TEST_F(TCPSocketServerTest, receiveAndSendsSingleLineMassages) { { InSequence s; EXPECT_CALL(protocolHandler, handle("12")).WillRepeatedly(Return("A")); EXPECT_CALL(protocolHandler, handle("3")).WillRepeatedly(Return("B")); EXPECT_CALL(protocolHandler, handle("4")).WillRepeatedly(Return("C")); } // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); // when client << "1" << flush << "2" << endl << flush; client << "3" << endl << "4" << endl << flush; // then EXPECT_THAT(client, EventuallyReceives("A")); EXPECT_THAT(client, EventuallyReceives("B")); EXPECT_THAT(client, EventuallyReceives("C")); } class TCPSocketServerLocalhostTest : public SocketServerTest { protected: boost::scoped_ptr<TCPSocketServer> server; virtual SocketServer* createListeningServer() { server.reset(new TCPSocketServer(&protocolHandler)); server->listen(tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 0)); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; TEST_F(TCPSocketServerLocalhostTest, listensOnLocalhost) { // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); ASSERT_THAT(server->listenEndpoint().address().to_string(), std::string("127.0.0.1")); // when client.close(); // then EXPECT_THAT(serverThread, EventuallyTerminates()); } #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) class UnixSocketServerTest : public SocketServerTest { protected: boost::scoped_ptr<UnixSocketServer> server; virtual SocketServer* createListeningServer() { fs::path socket = fs::temp_directory_path() / fs::unique_path(); server.reset(new UnixSocketServer(&protocolHandler)); server->listen(socket.string()); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; /* * Tests are flickering on OSX when testing without traffic flowing. * * This full lifecycle test is not optimal but it should be enough * given that the main difference between Unix and TCP is the socket * created at startup and removed on shutdown. */ TEST_F(UnixSocketServerTest, fullLifecycle) { stream_protocol::endpoint socketName = server->listenEndpoint(); EXPECT_CALL(protocolHandler, handle("X")).WillRepeatedly(Return("Y")); // socket created at startup ASSERT_TRUE(fs::exists(socketName.path())); // traffic flows stream_protocol::iostream client(socketName); client << "X" << endl << flush; EXPECT_THAT(client, EventuallyReceives("Y")); // client disconnection terminates server client.close(); EXPECT_THAT(serverThread, EventuallyTerminates()); // socket removed by destructor TearDown(); EXPECT_FALSE(fs::exists(socketName.path())); } #endif <commit_msg>fix conflicting "using std" declaration with "using boost::thread"<commit_after>#include <cucumber-cpp/internal/connectors/wire/WireServer.hpp> #include <gmock/gmock.h> #include <boost/filesystem/operations.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <boost/timer.hpp> #include <stdlib.h> #include <sstream> using namespace cucumber::internal; using namespace boost::posix_time; using namespace boost::asio::ip; #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using namespace boost::asio::local; #endif using namespace testing; using boost::bind; using boost::thread; namespace fs = boost::filesystem; static const time_duration THREAD_TEST_TIMEOUT = milliseconds(4000); MATCHER(IsConnected, std::string(negation ? "is not" : "is") + " connected") { return arg.good(); } MATCHER(HasTerminated, "") { return !arg.joinable(); } MATCHER(EventuallyTerminates, "") { return arg->timed_join(THREAD_TEST_TIMEOUT); } MATCHER_P(EventuallyReceives, value, "") { std::basic_iostream<char> *stream = const_cast<std::basic_iostream<char> *>( static_cast<const std::basic_iostream<char> *>(&arg)); std::string output; // FIXME It should not block (*stream) >> output; // boost::timer timer; // double timeout = THREAD_TEST_TIMEOUT.total_milliseconds() / 1000.0; // while (timer.elapsed() < timeout) { // if (stream->rdbuf()->available() > 0) { // it is zero even if it doesn't block! // (*stream) >> output; // break; // } // boost::this_thread::yield(); // } return (output == value); } class MockProtocolHandler : public ProtocolHandler { public: MOCK_CONST_METHOD1(handle, std::string(const std::string& request)); }; class SocketServerTest : public Test { protected: StrictMock<MockProtocolHandler> protocolHandler; boost::scoped_ptr<thread> serverThread; virtual void SetUp() { SocketServer* server = createListeningServer(); serverThread.reset(new thread(&SocketServer::acceptOnce, server)); } virtual void TearDown() { if (serverThread) { serverThread->timed_join(THREAD_TEST_TIMEOUT); serverThread.reset(); } destroyListeningServer(); } virtual SocketServer* createListeningServer() = 0; virtual void destroyListeningServer() = 0; }; class TCPSocketServerTest : public SocketServerTest { protected: boost::scoped_ptr<TCPSocketServer> server; virtual SocketServer* createListeningServer() { server.reset(new TCPSocketServer(&protocolHandler)); server->listen(0); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; TEST_F(TCPSocketServerTest, exitsOnFirstConnectionClosed) { // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); ASSERT_THAT(server->listenEndpoint().address().to_string(), std::string("0.0.0.0")); // when client.close(); // then EXPECT_THAT(serverThread, EventuallyTerminates()); } TEST_F(TCPSocketServerTest, moreThanOneClientCanConnect) { // given tcp::iostream client1(server->listenEndpoint()); ASSERT_THAT(client1, IsConnected()); // when tcp::iostream client2(server->listenEndpoint()); //then ASSERT_THAT(client2, IsConnected()); } TEST_F(TCPSocketServerTest, receiveAndSendsSingleLineMassages) { { InSequence s; EXPECT_CALL(protocolHandler, handle("12")).WillRepeatedly(Return("A")); EXPECT_CALL(protocolHandler, handle("3")).WillRepeatedly(Return("B")); EXPECT_CALL(protocolHandler, handle("4")).WillRepeatedly(Return("C")); } // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); // when client << "1" << std::flush << "2" << std::endl << std::flush; client << "3" << std::endl << "4" << std::endl << std::flush; // then EXPECT_THAT(client, EventuallyReceives("A")); EXPECT_THAT(client, EventuallyReceives("B")); EXPECT_THAT(client, EventuallyReceives("C")); } class TCPSocketServerLocalhostTest : public SocketServerTest { protected: boost::scoped_ptr<TCPSocketServer> server; virtual SocketServer* createListeningServer() { server.reset(new TCPSocketServer(&protocolHandler)); server->listen(tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 0)); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; TEST_F(TCPSocketServerLocalhostTest, listensOnLocalhost) { // given tcp::iostream client(server->listenEndpoint()); ASSERT_THAT(client, IsConnected()); ASSERT_THAT(server->listenEndpoint().address().to_string(), std::string("127.0.0.1")); // when client.close(); // then EXPECT_THAT(serverThread, EventuallyTerminates()); } #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) class UnixSocketServerTest : public SocketServerTest { protected: boost::scoped_ptr<UnixSocketServer> server; virtual SocketServer* createListeningServer() { fs::path socket = fs::temp_directory_path() / fs::unique_path(); server.reset(new UnixSocketServer(&protocolHandler)); server->listen(socket.string()); return server.get(); } virtual void destroyListeningServer() { server.reset(); } }; /* * Tests are flickering on OSX when testing without traffic flowing. * * This full lifecycle test is not optimal but it should be enough * given that the main difference between Unix and TCP is the socket * created at startup and removed on shutdown. */ TEST_F(UnixSocketServerTest, fullLifecycle) { stream_protocol::endpoint socketName = server->listenEndpoint(); EXPECT_CALL(protocolHandler, handle("X")).WillRepeatedly(Return("Y")); // socket created at startup ASSERT_TRUE(fs::exists(socketName.path())); // traffic flows stream_protocol::iostream client(socketName); client << "X" << std::endl << std::flush; EXPECT_THAT(client, EventuallyReceives("Y")); // client disconnection terminates server client.close(); EXPECT_THAT(serverThread, EventuallyTerminates()); // socket removed by destructor TearDown(); EXPECT_FALSE(fs::exists(socketName.path())); } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectionselectjob.h" #include <QDebug> using namespace PIM; class PIM::CollectionSelectJobPrivate { public: QByteArray path; QByteArray tag; int unseen; }; PIM::CollectionSelectJob::CollectionSelectJob( const QByteArray & path, QObject *parent ) : Job( parent ), d( new CollectionSelectJobPrivate ) { d->path = path; d->unseen = -1; } PIM::CollectionSelectJob::~ CollectionSelectJob( ) { delete d; } void PIM::CollectionSelectJob::doStart( ) { d->tag = newTag(); writeData( d->tag + " SELECT \"" + d->path + "\"" ); } void PIM::CollectionSelectJob::handleResponse( const QByteArray & tag, const QByteArray & data ) { if ( tag == d->tag ) { if ( !data.startsWith( "OK" ) ) setError( Unknown ); emit done( this ); return; } if ( tag == "*" ) { if ( data.startsWith( "OK [UNSEEN" ) ) { int begin = data.indexOf( ' ', 4 ); int end = data.indexOf( ']' ); QByteArray number = data.mid( begin + 1, end - begin - 1 ); d->unseen = number.toInt(); qDebug() << "unseen items " << d->unseen << " in folder " << d->path; return; } } qDebug() << "Unhandled response in collection selection job: " << tag << data; } int PIM::CollectionSelectJob::unseen( ) const { return d->unseen; } #include "collectionselectjob.moc" <commit_msg>Allow leading slash in path for messagefetchjob.<commit_after>/* Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "collectionselectjob.h" #include <QDebug> using namespace PIM; class PIM::CollectionSelectJobPrivate { public: QByteArray path; QByteArray tag; int unseen; }; PIM::CollectionSelectJob::CollectionSelectJob( const QByteArray & path, QObject *parent ) : Job( parent ), d( new CollectionSelectJobPrivate ) { d->path = path; d->unseen = -1; } PIM::CollectionSelectJob::~ CollectionSelectJob( ) { delete d; } void PIM::CollectionSelectJob::doStart( ) { QByteArray path = d->path; if ( path.startsWith( "/" ) ) path.remove( 0, 1 ); d->tag = newTag(); writeData( d->tag + " SELECT \"" + path + "\"" ); } void PIM::CollectionSelectJob::handleResponse( const QByteArray & tag, const QByteArray & data ) { if ( tag == d->tag ) { if ( !data.startsWith( "OK" ) ) setError( Unknown ); emit done( this ); return; } if ( tag == "*" ) { if ( data.startsWith( "OK [UNSEEN" ) ) { int begin = data.indexOf( ' ', 4 ); int end = data.indexOf( ']' ); QByteArray number = data.mid( begin + 1, end - begin - 1 ); d->unseen = number.toInt(); qDebug() << "unseen items " << d->unseen << " in folder " << d->path; return; } } qDebug() << "Unhandled response in collection selection job: " << tag << data; } int PIM::CollectionSelectJob::unseen( ) const { return d->unseen; } #include "collectionselectjob.moc" <|endoftext|>
<commit_before>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> #include "ui_archivestabwidget.h" #include "ui_helpwidget.h" #include "ui_jobstabwidget.h" #include "ui_jobwidget.h" #include "ui_mainwindow.h" WARNINGS_ENABLE #include "../qtest-platform.h" #include "helpwidget.h" #include "jobstabwidget.h" #include "mainwindow.h" #include "archivewidget.h" #include "persistentmodel/archive.h" #include <ConsoleLog.h> #include <TSettings.h> class TestMainWindow : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void about_window_menubar(); void quit_simple(); void quit_tasks(); void tab_navigation(); void other_navigation(); }; void TestMainWindow::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); HANDLE_IGNORING_XDG_HOME; ConsoleLog::initializeConsoleLog(); Translator::initializeTranslator(); IF_NOT_VISUAL { // Use a custom message handler to filter out unwanted messages orig_message_handler = qInstallMessageHandler(offscreenMessageOutput); } // Initialization normally done in init_shared.cpp's init_no_app() qRegisterMetaType<QVector<File>>("QVector<File>"); // Deal with PersistentStore PersistentStore::initializePersistentStore(); PersistentStore &store = PersistentStore::instance(); int ok = store.init(); QVERIFY(ok); } void TestMainWindow::cleanupTestCase() { PersistentStore::destroy(); Translator::destroy(); TSettings::destroy(); ConsoleLog::destroy(); // Wait for everything to finish QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } static QAction *get_menubar_about(QMenuBar *menubar) { for(QAction *action : menubar->actions()) { if(action->menu()) { for(QAction *subaction : action->menu()->actions()) { if(subaction->menuRole() == QAction::AboutRole) { return subaction; } } } } return (nullptr); } void TestMainWindow::about_window_menubar() { MainWindow * mainwindow = new MainWindow(); HelpWidget * help = &mainwindow->_helpWidget; Ui::HelpWidget *ui = help->_ui; VISUAL_INIT(mainwindow); // Test the "About Tarsnap" menubar item, if applicable. if(mainwindow->_menuBar != nullptr) { // find "About Tarsnap" menu item QAction *menuAction = get_menubar_about(mainwindow->_menuBar); QVERIFY(menuAction != nullptr); VISUAL_WAIT; // Becomes visible using the menu bar action menuAction->trigger(); QVERIFY(help->_aboutWindow.isVisible() == true); QVERIFY(ui->aboutButton->isChecked() == true); VISUAL_WAIT; // Stay visible even when clicking the menu bar action again menuAction->trigger(); QVERIFY(help->_aboutWindow.isVisible() == true); QVERIFY(ui->aboutButton->isChecked() == true); VISUAL_WAIT; // Becomes invisible by clicking the Help->About button ui->aboutButton->click(); QVERIFY(help->_aboutWindow.isVisible() == false); QVERIFY(ui->aboutButton->isChecked() == false); VISUAL_WAIT; } delete mainwindow; } void TestMainWindow::quit_simple() { MainWindow *mainwindow = new MainWindow(); QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo())); VISUAL_INIT(mainwindow); // If we try to close the window, we emit a getTaskInfo instead QCloseEvent *close_event = new QCloseEvent(); mainwindow->closeEvent(close_event); QVERIFY(sig_getTaskInfo.count() == 1); sig_getTaskInfo.clear(); // Fake getting a reply which says there's no tasks. mainwindow->closeWithTaskInfo(false, 0, 0); // After quitting, we don't respond to more events. QCloseEvent *close_event_another = new QCloseEvent(); mainwindow->closeEvent(close_event_another); QVERIFY(sig_getTaskInfo.count() == 0); delete mainwindow; delete close_event; delete close_event_another; } void TestMainWindow::quit_tasks() { MainWindow *mainwindow = new MainWindow(); QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo())); VISUAL_INIT(mainwindow); // Fake getting a response to a closeEvent (not sent in this test) which // says that there's running tasks, but cancel the quitting. QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo", Qt::QueuedConnection, Q_ARG(bool, true), Q_ARG(int, 1), Q_ARG(int, 1)); QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "close", Qt::QueuedConnection); VISUAL_WAIT; // After cancelling the quit, we still respond to events QCloseEvent *close_event = new QCloseEvent(); mainwindow->closeEvent(close_event); QVERIFY(sig_getTaskInfo.count() == 1); sig_getTaskInfo.clear(); VISUAL_WAIT; // Quit the app // FIXME: sending an "accept" is a hack because the task-specific choices // (e.g., stop tasks, run in background) are only added to the dialog box // after MainWindow receives the closeWithTaskInfo, so we can't // "queue up" sending a message to one of those objects. QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo", Qt::QueuedConnection, Q_ARG(bool, true), Q_ARG(int, 1), Q_ARG(int, 1)); QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "accept", Qt::QueuedConnection); VISUAL_WAIT; // After quitting, we don't respond to more events QCloseEvent *close_event_another = new QCloseEvent(); mainwindow->closeEvent(close_event_another); QVERIFY(sig_getTaskInfo.count() == 0); VISUAL_WAIT; delete mainwindow; delete close_event; delete close_event_another; } void TestMainWindow::tab_navigation() { MainWindow * mainwindow = new MainWindow(); Ui::MainWindow *ui = mainwindow->_ui; VISUAL_INIT(mainwindow); // Start in the Backup tab QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); // Switch between tabs // Unfortunately we can't test the Ctrl+X keyboard shortcuts, because // QTest::keyClick() doesn't work with -platform offscreen. mainwindow->displayTab(ui->archivesTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; mainwindow->displayTab(ui->jobsTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; mainwindow->displayTab(ui->settingsTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->settingsTab); VISUAL_WAIT; mainwindow->displayTab(ui->helpTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->helpTab); VISUAL_WAIT; mainwindow->displayTab(ui->backupTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); VISUAL_WAIT; delete mainwindow; } void TestMainWindow::other_navigation() { MainWindow * mainwindow = new MainWindow(); Ui::MainWindow * ui = mainwindow->_ui; JobsTabWidget * jobsTabWidget = &mainwindow->_jobsTabWidget; Ui::JobsTabWidget *jui = jobsTabWidget->_ui; BackupTabWidget *backupTabWidget = &mainwindow->_backupTabWidget; ArchiveWidget *archiveDetailsWidget = mainwindow->_archivesTabWidget._ui->archiveDetailsWidget; VISUAL_INIT(mainwindow); #if defined(Q_OS_OSX) // HACK: Load directory that we'll want for creating a Job. This is // slow to load on OSX (relative to the -platform offscreen test), so we // add an extra delay. jobsTabWidget->_ui->jobDetailsWidget->_ui->jobTreeWidget->_model .setRootPath(TEST_DIR); QTest::qWait(1000); #endif QList<QUrl> testdir_urls({QUrl("file://" TEST_DIR)}); // Switch to a different tab. mainwindow->displayTab(ui->helpTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->helpTab); VISUAL_WAIT; // Switch back to Backup tab QMetaObject::invokeMethod(mainwindow, "browseForBackupItems", Qt::QueuedConnection); QMetaObject::invokeMethod(&backupTabWidget->_filePickerDialog, "close", Qt::QueuedConnection); QTest::qWait(100); QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); VISUAL_WAIT; // Add a Job mainwindow->displayTab(ui->jobsTab); jobsTabWidget->createNewJob(testdir_urls, QString("test-job")); jobsTabWidget->addJobClicked(); // Make sure that MainWindow has a job, then get a pointer to it. QVERIFY(jui->jobListWidget->count() == 1); QVERIFY(jui->jobListWidget->currentItem() != nullptr); JobPtr job = static_cast<JobListWidgetItem *>(jui->jobListWidget->currentItem()) ->job(); QVERIFY(job != nullptr); VISUAL_WAIT; // Add an Archive mainwindow->displayTab(ui->archivesTab); ArchivePtr archive(new Archive); archive->setName("Job_test-job_archive1"); mainwindow->addArchive(archive); archive->setJobRef("test-job"); VISUAL_WAIT; // Link them job->setArchives(QList<ArchivePtr>() << archive); // Create a second job, this time via morphBackupIntoJob mainwindow->displayTab(ui->backupTab); VISUAL_WAIT; backupTabWidget->morphBackupIntoJob(testdir_urls, "test-job2"); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; jobsTabWidget->addJobClicked(); QVERIFY(jui->jobListWidget->count() == 2); VISUAL_WAIT; // Switch back and forth between the job and archive. mainwindow->displayInspectArchive(archive); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; mainwindow->displayJobDetails(job); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; // Click on the Job name in the archive tab. mainwindow->displayInspectArchive(archive); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; archiveDetailsWidget->jobClicked("test-job"); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; delete mainwindow; } QTEST_MAIN(TestMainWindow) #include "test-mainwindow.moc" <commit_msg>tests/mainwindow: increate cleanup wait-time<commit_after>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> #include "ui_archivestabwidget.h" #include "ui_helpwidget.h" #include "ui_jobstabwidget.h" #include "ui_jobwidget.h" #include "ui_mainwindow.h" WARNINGS_ENABLE #include "../qtest-platform.h" #include "helpwidget.h" #include "jobstabwidget.h" #include "mainwindow.h" #include "archivewidget.h" #include "persistentmodel/archive.h" #include <ConsoleLog.h> #include <TSettings.h> class TestMainWindow : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void about_window_menubar(); void quit_simple(); void quit_tasks(); void tab_navigation(); void other_navigation(); }; void TestMainWindow::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); HANDLE_IGNORING_XDG_HOME; ConsoleLog::initializeConsoleLog(); Translator::initializeTranslator(); IF_NOT_VISUAL { // Use a custom message handler to filter out unwanted messages orig_message_handler = qInstallMessageHandler(offscreenMessageOutput); } // Initialization normally done in init_shared.cpp's init_no_app() qRegisterMetaType<QVector<File>>("QVector<File>"); // Deal with PersistentStore PersistentStore::initializePersistentStore(); PersistentStore &store = PersistentStore::instance(); int ok = store.init(); QVERIFY(ok); } void TestMainWindow::cleanupTestCase() { PersistentStore::destroy(); Translator::destroy(); TSettings::destroy(); ConsoleLog::destroy(); // Wait for everything to finish QCoreApplication::processEvents(QEventLoop::AllEvents, 5000); } static QAction *get_menubar_about(QMenuBar *menubar) { for(QAction *action : menubar->actions()) { if(action->menu()) { for(QAction *subaction : action->menu()->actions()) { if(subaction->menuRole() == QAction::AboutRole) { return subaction; } } } } return (nullptr); } void TestMainWindow::about_window_menubar() { MainWindow * mainwindow = new MainWindow(); HelpWidget * help = &mainwindow->_helpWidget; Ui::HelpWidget *ui = help->_ui; VISUAL_INIT(mainwindow); // Test the "About Tarsnap" menubar item, if applicable. if(mainwindow->_menuBar != nullptr) { // find "About Tarsnap" menu item QAction *menuAction = get_menubar_about(mainwindow->_menuBar); QVERIFY(menuAction != nullptr); VISUAL_WAIT; // Becomes visible using the menu bar action menuAction->trigger(); QVERIFY(help->_aboutWindow.isVisible() == true); QVERIFY(ui->aboutButton->isChecked() == true); VISUAL_WAIT; // Stay visible even when clicking the menu bar action again menuAction->trigger(); QVERIFY(help->_aboutWindow.isVisible() == true); QVERIFY(ui->aboutButton->isChecked() == true); VISUAL_WAIT; // Becomes invisible by clicking the Help->About button ui->aboutButton->click(); QVERIFY(help->_aboutWindow.isVisible() == false); QVERIFY(ui->aboutButton->isChecked() == false); VISUAL_WAIT; } delete mainwindow; } void TestMainWindow::quit_simple() { MainWindow *mainwindow = new MainWindow(); QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo())); VISUAL_INIT(mainwindow); // If we try to close the window, we emit a getTaskInfo instead QCloseEvent *close_event = new QCloseEvent(); mainwindow->closeEvent(close_event); QVERIFY(sig_getTaskInfo.count() == 1); sig_getTaskInfo.clear(); // Fake getting a reply which says there's no tasks. mainwindow->closeWithTaskInfo(false, 0, 0); // After quitting, we don't respond to more events. QCloseEvent *close_event_another = new QCloseEvent(); mainwindow->closeEvent(close_event_another); QVERIFY(sig_getTaskInfo.count() == 0); delete mainwindow; delete close_event; delete close_event_another; } void TestMainWindow::quit_tasks() { MainWindow *mainwindow = new MainWindow(); QSignalSpy sig_getTaskInfo(mainwindow, SIGNAL(getTaskInfo())); VISUAL_INIT(mainwindow); // Fake getting a response to a closeEvent (not sent in this test) which // says that there's running tasks, but cancel the quitting. QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo", Qt::QueuedConnection, Q_ARG(bool, true), Q_ARG(int, 1), Q_ARG(int, 1)); QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "close", Qt::QueuedConnection); VISUAL_WAIT; // After cancelling the quit, we still respond to events QCloseEvent *close_event = new QCloseEvent(); mainwindow->closeEvent(close_event); QVERIFY(sig_getTaskInfo.count() == 1); sig_getTaskInfo.clear(); VISUAL_WAIT; // Quit the app // FIXME: sending an "accept" is a hack because the task-specific choices // (e.g., stop tasks, run in background) are only added to the dialog box // after MainWindow receives the closeWithTaskInfo, so we can't // "queue up" sending a message to one of those objects. QMetaObject::invokeMethod(mainwindow, "closeWithTaskInfo", Qt::QueuedConnection, Q_ARG(bool, true), Q_ARG(int, 1), Q_ARG(int, 1)); QMetaObject::invokeMethod(&mainwindow->_stopTasksDialog, "accept", Qt::QueuedConnection); VISUAL_WAIT; // After quitting, we don't respond to more events QCloseEvent *close_event_another = new QCloseEvent(); mainwindow->closeEvent(close_event_another); QVERIFY(sig_getTaskInfo.count() == 0); VISUAL_WAIT; delete mainwindow; delete close_event; delete close_event_another; } void TestMainWindow::tab_navigation() { MainWindow * mainwindow = new MainWindow(); Ui::MainWindow *ui = mainwindow->_ui; VISUAL_INIT(mainwindow); // Start in the Backup tab QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); // Switch between tabs // Unfortunately we can't test the Ctrl+X keyboard shortcuts, because // QTest::keyClick() doesn't work with -platform offscreen. mainwindow->displayTab(ui->archivesTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; mainwindow->displayTab(ui->jobsTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; mainwindow->displayTab(ui->settingsTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->settingsTab); VISUAL_WAIT; mainwindow->displayTab(ui->helpTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->helpTab); VISUAL_WAIT; mainwindow->displayTab(ui->backupTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); VISUAL_WAIT; delete mainwindow; } void TestMainWindow::other_navigation() { MainWindow * mainwindow = new MainWindow(); Ui::MainWindow * ui = mainwindow->_ui; JobsTabWidget * jobsTabWidget = &mainwindow->_jobsTabWidget; Ui::JobsTabWidget *jui = jobsTabWidget->_ui; BackupTabWidget *backupTabWidget = &mainwindow->_backupTabWidget; ArchiveWidget *archiveDetailsWidget = mainwindow->_archivesTabWidget._ui->archiveDetailsWidget; VISUAL_INIT(mainwindow); #if defined(Q_OS_OSX) // HACK: Load directory that we'll want for creating a Job. This is // slow to load on OSX (relative to the -platform offscreen test), so we // add an extra delay. jobsTabWidget->_ui->jobDetailsWidget->_ui->jobTreeWidget->_model .setRootPath(TEST_DIR); QTest::qWait(1000); #endif QList<QUrl> testdir_urls({QUrl("file://" TEST_DIR)}); // Switch to a different tab. mainwindow->displayTab(ui->helpTab); QVERIFY(ui->mainTabWidget->currentWidget() == ui->helpTab); VISUAL_WAIT; // Switch back to Backup tab QMetaObject::invokeMethod(mainwindow, "browseForBackupItems", Qt::QueuedConnection); QMetaObject::invokeMethod(&backupTabWidget->_filePickerDialog, "close", Qt::QueuedConnection); QTest::qWait(100); QVERIFY(ui->mainTabWidget->currentWidget() == ui->backupTab); VISUAL_WAIT; // Add a Job mainwindow->displayTab(ui->jobsTab); jobsTabWidget->createNewJob(testdir_urls, QString("test-job")); jobsTabWidget->addJobClicked(); // Make sure that MainWindow has a job, then get a pointer to it. QVERIFY(jui->jobListWidget->count() == 1); QVERIFY(jui->jobListWidget->currentItem() != nullptr); JobPtr job = static_cast<JobListWidgetItem *>(jui->jobListWidget->currentItem()) ->job(); QVERIFY(job != nullptr); VISUAL_WAIT; // Add an Archive mainwindow->displayTab(ui->archivesTab); ArchivePtr archive(new Archive); archive->setName("Job_test-job_archive1"); mainwindow->addArchive(archive); archive->setJobRef("test-job"); VISUAL_WAIT; // Link them job->setArchives(QList<ArchivePtr>() << archive); // Create a second job, this time via morphBackupIntoJob mainwindow->displayTab(ui->backupTab); VISUAL_WAIT; backupTabWidget->morphBackupIntoJob(testdir_urls, "test-job2"); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; jobsTabWidget->addJobClicked(); QVERIFY(jui->jobListWidget->count() == 2); VISUAL_WAIT; // Switch back and forth between the job and archive. mainwindow->displayInspectArchive(archive); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; mainwindow->displayJobDetails(job); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; // Click on the Job name in the archive tab. mainwindow->displayInspectArchive(archive); QVERIFY(ui->mainTabWidget->currentWidget() == ui->archivesTab); VISUAL_WAIT; archiveDetailsWidget->jobClicked("test-job"); QVERIFY(ui->mainTabWidget->currentWidget() == ui->jobsTab); VISUAL_WAIT; delete mainwindow; } QTEST_MAIN(TestMainWindow) #include "test-mainwindow.moc" <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief 配列クラス(ヘッダー) @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <vector> #include <boost/unordered_map.hpp> namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 配列クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class dim { uint32_t unit_size_; std::vector<uint8_t> array_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// dim() : unit_size_(1) { } void set_unit_size(uint32_t us) { unit_size_ = us; } uint32_t get_unit_size() const { return unit_size_; } void create(uint32_t size) { array_.resize(size); } void* get_ptr(uint32_t idx) { return &array_[idx * unit_size_]; } uint32_t get(uint32_t idx) { if(unit_size_ == 2) { uint16_t* p = reinterpret_cast<uint16_t*>(&array_[0]); return p[idx]; } else if(unit_size_ == 4) { uint32_t* p = reinterpret_cast<uint32_t*>(&array_[0]); return p[idx]; } else { return array_[idx]; } } void put(uint32_t idx, uint32_t data) { if(unit_size_ == 2) { uint16_t* p = reinterpret_cast<uint16_t*>(&array_[0]); p[idx] = data; } else if(unit_size_ == 4) { uint32_t* p = reinterpret_cast<uint32_t*>(&array_[0]); p[idx] = data; } else { array_[idx] = data; } } }; } <commit_msg>dim クラス、全面改修<commit_after>#pragma once //=====================================================================// /*! @file @brief 配列クラス(ヘッダー) @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <vector> namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 配列クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class dim { struct i_dim { virtual ~i_dim() { } virtual void resize(uint32_t s) = 0; virtual uint32_t size() const = 0; virtual uint32_t unit_size() const = 0; virtual uint32_t get(uint32_t idx) const = 0; virtual void put(uint32_t idx, uint32_t val) = 0; virtual void* ptr(uint32_t idx) = 0; }; template <typename T> class dimx : public i_dim { std::vector<T> array_; public: typedef T value_type; virtual ~dimx() { } void resize(uint32_t s) { array_.resize(s); } uint32_t size() const { return array_.size(); } uint32_t unit_size() const { return sizeof(T); } uint32_t get(uint32_t idx) const { return array_[idx]; } void put(uint32_t idx, uint32_t val) { array_[idx] = val; } void* ptr(uint32_t idx) { return &array_[idx]; } }; i_dim* array_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// dim() : array_(0) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// ~dim() { delete array_; } //-----------------------------------------------------------------// /*! @brief ユニットサイズを選択 @param[in] n ユニットサイズ(1、2,4) */ //-----------------------------------------------------------------// void select(uint32_t n) { delete array_; array_ = 0; if(n == 1) { array_ = new dimx<uint8_t>; } else if(n == 2) { array_ = new dimx<uint16_t>; } else if(n == 4) { array_ = new dimx<uint32_t>; } } //-----------------------------------------------------------------// /*! @brief リサイズ @param[in] s サイズ */ //-----------------------------------------------------------------// void resize(uint32_t s) { array_->resize(s); } //-----------------------------------------------------------------// /*! @brief 要素サイズを返す @return 要素サイズ */ //-----------------------------------------------------------------// uint32_t size() const { return array_->size(); } //-----------------------------------------------------------------// /*! @brief 要素が空か? @return 要素が空の場合「true」 */ //-----------------------------------------------------------------// bool empty() const { return array_->size() == 0; } //-----------------------------------------------------------------// /*! @brief ユニットサイズを返す @return ユニットサイズ */ //-----------------------------------------------------------------// uint32_t unit_size() const { return array_->unit_size(); } //-----------------------------------------------------------------// /*! @brief 要素を取得 @param[in] idx 要素位置 @return 要素 */ //-----------------------------------------------------------------// uint32_t get(uint32_t idx) const { return array_->get(idx); } //-----------------------------------------------------------------// /*! @brief 要素を設定 @param[in] idx 要素位置 @param[in] val 値 */ //-----------------------------------------------------------------// void put(uint32_t idx, uint32_t val) { array_->put(idx, val); } //-----------------------------------------------------------------// /*! @brief 要素をポインターを取得 @param[in] idx 要素位置 @return 要素ポインター */ //-----------------------------------------------------------------// void* ptr(uint32_t idx = 0) { return array_->ptr(idx); } }; } <|endoftext|>
<commit_before>/// /// EMCal Tender configuration macro /// AliAnalysisTaskSE *AddTaskEMCALTender( Bool_t distBC = kTRUE, // distance to bad channel Bool_t recalibClus = kTRUE, // recalibrate cluster energy Bool_t recalcClusPos = kTRUE, // recalculate cluster position Bool_t nonLinearCorr = kTRUE, // apply non-linearity Bool_t remExoticCell = kTRUE, // remove exotic cells Bool_t remExoticClus = kTRUE, // remove exotic clusters Bool_t fidRegion = kFALSE, // apply fiducial cuts Bool_t calibEnergy = kTRUE, // calibrate energy Bool_t calibTime = kTRUE, // calibrate timing Bool_t remBC = kTRUE, // remove bad channels UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected, Bool_t reclusterize = kTRUE, // reclusterize Float_t seedthresh = 0.100, // seed threshold Float_t cellthresh = 0.050, // cell threshold UInt_t clusterizer = AliEMCALRecParam::kClusterizerv2, Bool_t trackMatch = kTRUE, // track matching Bool_t updateCellOnly = kFALSE, // only change if you run your own clusterizer task Float_t timeMin = 100e-9, // minimum time of physical signal in a cell/digit (s) Float_t timeMax = 900e-9, // maximum time of physical signal in a cell/digit (s) Float_t timeCut = 900e-9, // maximum time difference between the digits inside EMC cluster (s) const char *pass = 0, // string defining pass (use none if figured out from path) Bool_t remapMcAod = kFALSE, // switch on the remaping for the MC labels in AOD productions, TString cdbStorage = "raw://", // "local://" Float_t diffEAggregation = 0. // difference E in aggregation of cells (i.e. stop aggregation if E_{new} > E_{prev} + diffEAggregation) ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEMCALTender", "No analysis manager to connect to."); return NULL; } AliVEventHandler *evhand = mgr->GetInputEventHandler(); // Create the task and configure it. //=========================================================================== AliAnalysisTaskSE *ana = 0; AliAnalysisDataContainer *coutput1 = 0; #ifdef __CLING__ // ROOT6 version of the Config macro. JIT cannot handle load and execute macro (compiler error) - need to call via gROOT->ProcessLine(...) std::stringstream configbuilder; configbuilder << ".x " << gSystem->Getenv("ALICE_PHYSICS") << "/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C("; configbuilder << (distBC ? "kTRUE" : "kFALSE") << ", "; configbuilder << (recalibClus ? "kTRUE" : "kFALSE") << ", "; configbuilder << (recalcClusPos ? "kTRUE" : "kFALSE") << ", "; configbuilder << (nonLinearCorr ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remExoticCell ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remExoticClus ? "kTRUE" : "kFALSE") << ", "; configbuilder << (fidRegion ? "kTRUE" : "kFALSE") << ", "; configbuilder << (calibEnergy ? "kTRUE" : "kFALSE") << ", "; configbuilder << (calibTime ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remBC ? "kTRUE" : "kFALSE") << ", "; configbuilder << nonLinFunct << ", "; configbuilder << (reclusterize ? "kTRUE" : "kFALSE") << ", "; configbuilder << seedthresh << ", "; configbuilder << cellthresh << ", "; configbuilder << clusterizer << ", "; configbuilder << trackMatch << ", "; configbuilder << (updateCellOnly ? "kTRUE" : "kFALSE") << ", "; configbuilder << timeMin << ", "; configbuilder << timeMax << ", "; configbuilder << timeCut; configbuilder << ")"; std::string configbuilderstring = configbuilder.str(); std::cout << "Running config macro " << configbuilderstring << std::endl; AliEMCALTenderSupply *EMCALSupply = (AliEMCALTenderSupply *)gROOT->ProcessLine(configbuilderstring.c_str()); #else // ROOT5 version, allows loading a macro gROOT->LoadMacro("$ALICE_PHYSICS/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C"); AliEMCALTenderSupply *EMCALSupply = ConfigEmcalTenderSupply(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut, diffEAggregation); #endif if (pass) EMCALSupply->SetPass(pass); if (evhand->InheritsFrom("AliESDInputHandler")) { #ifdef __CLING__ AliTender* alitender = dynamic_cast<AliTender *>(mgr->GetTopTasks()->FindObject("AliTender")); #else AliTender* alitender = (AliTender *)mgr->GetTopTasks()->FindObject("AliTender"); #endif if (!alitender) alitender = new AliTender("AliTender"); alitender->AddSupply(EMCALSupply); alitender->SetDefaultCDBStorage(cdbStorage); ana = alitender; coutput1 = mgr->CreateContainer("emcal_tender_event", AliESDEvent::Class(), AliAnalysisManager::kExchangeContainer, "default_tender"); } else if (evhand->InheritsFrom("AliAODInputHandler")) { #ifdef __CLING__ AliEmcalTenderTask* emcaltender = dynamic_cast<AliEmcalTenderTask *>(mgr->GetTopTasks()->FindObject("AliEmcalTenderTask")); #else AliEmcalTenderTask* emcaltender = (AliEmcalTenderTask *)mgr->GetTopTasks()->FindObject("AliEmcalTenderTask"); #endif if (!emcaltender) emcaltender = new AliEmcalTenderTask("AliEmcalTenderTask"); if (remapMcAod) EMCALSupply->SwitchOnRemapMCLabelForAODs(); emcaltender->SetEMCALTenderSupply(EMCALSupply); ana = emcaltender; coutput1 = mgr->CreateContainer( "emcal_tender_event", AliAODEvent::Class(), AliAnalysisManager::kExchangeContainer, "default_tender"); } else { ::Error("AddTaskEMCALTender", "Input event handler not recognized, AOD/ESD expected. Returning..."); return NULL; } mgr->AddTask(ana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput(ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(ana, 1, coutput1 ); ::Info("AddTaskEMCALTender", "Tender configured"); return ana; } <commit_msg>open default parameters to avoid confusions; also update the recommended non linearity correction function<commit_after>/// /// EMCal Tender configuration macro /// AliAnalysisTaskSE *AddTaskEMCALTender( Bool_t distBC = kTRUE, // distance to bad channel Bool_t recalibClus = kTRUE, // recalibrate cluster energy Bool_t recalcClusPos = kTRUE, // recalculate cluster position Bool_t nonLinearCorr = kTRUE, // apply non-linearity Bool_t remExoticCell = kTRUE, // remove exotic cells Bool_t remExoticClus = kTRUE, // remove exotic clusters Bool_t fidRegion = kFALSE, // apply fiducial cuts Bool_t calibEnergy = kTRUE, // calibrate energy Bool_t calibTime = kTRUE, // calibrate timing Bool_t remBC = kTRUE, // remove bad channels UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrectedv3, // For MC use kPi0MCv3 Bool_t reclusterize = kTRUE, // reclusterize Float_t seedthresh = 0.100, // seed threshold Float_t cellthresh = 0.050, // cell threshold UInt_t clusterizer = AliEMCALRecParam::kClusterizerv2, Bool_t trackMatch = kTRUE, // track matching Bool_t updateCellOnly = kFALSE, // only change if you run your own clusterizer task Float_t timeMin =-1000e-9, // minimum time of physical signal in a cell/digit (s) Float_t timeMax = 1000e-9, // maximum time of physical signal in a cell/digit (s) Float_t timeCut = 1000e-9, // maximum time difference between the digits inside EMC cluster (s) const char *pass = 0, // string defining pass (use none if figured out from path) Bool_t remapMcAod = kFALSE, // switch on the remaping for the MC labels in AOD productions, TString cdbStorage = "raw://", // "local://" Float_t diffEAggregation = 0. // difference E in aggregation of cells (i.e. stop aggregation if E_{new} > E_{prev} + diffEAggregation) ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEMCALTender", "No analysis manager to connect to."); return NULL; } AliVEventHandler *evhand = mgr->GetInputEventHandler(); // Create the task and configure it. //=========================================================================== AliAnalysisTaskSE *ana = 0; AliAnalysisDataContainer *coutput1 = 0; #ifdef __CLING__ // ROOT6 version of the Config macro. JIT cannot handle load and execute macro (compiler error) - need to call via gROOT->ProcessLine(...) std::stringstream configbuilder; configbuilder << ".x " << gSystem->Getenv("ALICE_PHYSICS") << "/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C("; configbuilder << (distBC ? "kTRUE" : "kFALSE") << ", "; configbuilder << (recalibClus ? "kTRUE" : "kFALSE") << ", "; configbuilder << (recalcClusPos ? "kTRUE" : "kFALSE") << ", "; configbuilder << (nonLinearCorr ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remExoticCell ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remExoticClus ? "kTRUE" : "kFALSE") << ", "; configbuilder << (fidRegion ? "kTRUE" : "kFALSE") << ", "; configbuilder << (calibEnergy ? "kTRUE" : "kFALSE") << ", "; configbuilder << (calibTime ? "kTRUE" : "kFALSE") << ", "; configbuilder << (remBC ? "kTRUE" : "kFALSE") << ", "; configbuilder << nonLinFunct << ", "; configbuilder << (reclusterize ? "kTRUE" : "kFALSE") << ", "; configbuilder << seedthresh << ", "; configbuilder << cellthresh << ", "; configbuilder << clusterizer << ", "; configbuilder << trackMatch << ", "; configbuilder << (updateCellOnly ? "kTRUE" : "kFALSE") << ", "; configbuilder << timeMin << ", "; configbuilder << timeMax << ", "; configbuilder << timeCut; configbuilder << ")"; std::string configbuilderstring = configbuilder.str(); std::cout << "Running config macro " << configbuilderstring << std::endl; AliEMCALTenderSupply *EMCALSupply = (AliEMCALTenderSupply *)gROOT->ProcessLine(configbuilderstring.c_str()); #else // ROOT5 version, allows loading a macro gROOT->LoadMacro("$ALICE_PHYSICS/PWG/EMCAL/macros/ConfigEmcalTenderSupply.C"); AliEMCALTenderSupply *EMCALSupply = ConfigEmcalTenderSupply(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut, diffEAggregation); #endif if (pass) EMCALSupply->SetPass(pass); if (evhand->InheritsFrom("AliESDInputHandler")) { #ifdef __CLING__ AliTender* alitender = dynamic_cast<AliTender *>(mgr->GetTopTasks()->FindObject("AliTender")); #else AliTender* alitender = (AliTender *)mgr->GetTopTasks()->FindObject("AliTender"); #endif if (!alitender) alitender = new AliTender("AliTender"); alitender->AddSupply(EMCALSupply); alitender->SetDefaultCDBStorage(cdbStorage); ana = alitender; coutput1 = mgr->CreateContainer("emcal_tender_event", AliESDEvent::Class(), AliAnalysisManager::kExchangeContainer, "default_tender"); } else if (evhand->InheritsFrom("AliAODInputHandler")) { #ifdef __CLING__ AliEmcalTenderTask* emcaltender = dynamic_cast<AliEmcalTenderTask *>(mgr->GetTopTasks()->FindObject("AliEmcalTenderTask")); #else AliEmcalTenderTask* emcaltender = (AliEmcalTenderTask *)mgr->GetTopTasks()->FindObject("AliEmcalTenderTask"); #endif if (!emcaltender) emcaltender = new AliEmcalTenderTask("AliEmcalTenderTask"); if (remapMcAod) EMCALSupply->SwitchOnRemapMCLabelForAODs(); emcaltender->SetEMCALTenderSupply(EMCALSupply); ana = emcaltender; coutput1 = mgr->CreateContainer( "emcal_tender_event", AliAODEvent::Class(), AliAnalysisManager::kExchangeContainer, "default_tender"); } else { ::Error("AddTaskEMCALTender", "Input event handler not recognized, AOD/ESD expected. Returning..."); return NULL; } mgr->AddTask(ana); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput(ana, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(ana, 1, coutput1 ); ::Info("AddTaskEMCALTender", "Tender configured"); return ana; } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 12/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "Strlen.h" #include "TROOT.h" #include "TAttText.h" #include "TVirtualPad.h" #include "TStyle.h" #include "TVirtualX.h" #include "TError.h" #include "TVirtualPadEditor.h" #include "TColor.h" ClassImp(TAttText); /** \class TAttText \ingroup Base \ingroup GraphicsAtt Text Attributes class. This class is used (in general by secondary inheritance) by many other classes (graphics, histograms). It holds all the text attributes. ## Text attributes Text attributes are: - [Text Alignment](#T1) - [Text Angle](#T2) - [Text Color](#T3) - [Text Size](#T4) - [Text Font and Precision](#T5) - [Font quality and speed](#T51) - [How to use True Type Fonts](#T52) - [List of the currently supported fonts](#T53) ## <a name="T1"></a> Text Alignment The text alignment is an integer number (`align`) allowing to control the horizontal and vertical position of the text string with respect to the text position. The text alignment of any class inheriting from `TAttText` can be changed using the method `SetTextAlign` and retrieved using the method `GetTextAlign`. ~~~ {.cpp} align = 10*HorizontalAlign + VerticalAlign ~~~ For horizontal alignment the following convention applies: ~~~ {.cpp} 1=left adjusted, 2=centered, 3=right adjusted ~~~ For vertical alignment the following convention applies: ~~~ {.cpp} 1=bottom adjusted, 2=centered, 3=top adjusted ~~~ For example: ~~~ {.cpp} align = 11 = left adjusted and bottom adjusted align = 32 = right adjusted and vertically centered ~~~ Begin_Macro(source) textalign.C End_Macro Mnemonic constants are available: ~~~ {.cpp} kHAlignLeft = 10, kHAlignCenter = 20, kHAlignRight = 30, kVAlignBottom = 1, kVAlignCenter = 2, kVAlignTop = 3 ~~~ They allow to write: ~~~ {.cpp} object->SetTextAlign(kHAlignLeft+kVAlignTop); ~~~ ## <a name="T2"></a> Text Angle Text angle in degrees. The text angle of any class inheriting from `TAttText` can be changed using the method `SetTextAngle` and retrieved using the method `GetTextAngle`. The following picture shows the text angle: Begin_Macro(source) textangle.C End_Macro ## <a name="T3"></a> Text Color The text color is a color index (integer) pointing in the ROOT color table. The text color of any class inheriting from `TAttText` can be changed using the method `SetTextColor` and retrieved using the method `GetTextColor`. The following table shows the first 50 default colors. Begin_Macro { TCanvas *c = new TCanvas("c","Text colors",0,0,500,200); c->DrawColorTable(); } End_Macro ### Color transparency `SetTextColorAlpha()`, allows to set a transparent color. In the following example the text color of the text `text` is set to blue with a transparency of 35%. The color `kBlue` itself remains fully opaque. ~~~ {.cpp} text->SetTextColorAlpha(kBlue, 0.35); ~~~ The transparency is available on all platforms when the `flagOpenGL.CanvasPreferGL` is set to `1` in `$ROOTSYS/etc/system.rootrc`, or on Mac with the Cocoa backend. On the file output it is visible with PDF, PNG, Gif, JPEG, SVG ... but not PostScript. ## <a name="T4"></a> Text Size If the text precision (see next paragraph) is smaller than 3, the text size (`textsize`) is a fraction of the current pad size. Therefore the same `textsize` value can generate text outputs with different absolute sizes in two different pads. The text size in pixels (`charheight`) is computed the following way: ~~~ {.cpp} pad_width = gPad->XtoPixel(gPad->GetX2()); pad_height = gPad->YtoPixel(gPad->GetY1()); if (pad_width < pad_height) charheight = textsize*pad_width; else charheight = textsize*pad_height; ~~~ If the text precision is equal to 3, the text size doesn't depend on the pad's dimensions. A given `textsize` value always generates the same absolute size. The text size (`charheight`) is given in pixels: ~~~ {.cpp} charheight = textsize; ~~~ Note that to scale fonts to the same size as the old True Type package a scale factor of `0.93376068` is apply to the text size before drawing. The text size of any class inheriting from `TAttText` can be changed using the method `SetTextSize` and retrieved using the method `GetTextSize`. ## <a name="T5"></a> Text Font and Precision The text font code is combination of the font number and the precision. ~~~ {.cpp} Text font code = 10*fontnumber + precision ~~~ Font numbers must be between 1 and 14. The precision can be: - `precision = 0` fast hardware fonts (steps in the size) - `precision = 1` scalable and rotatable hardware fonts (see below) - `precision = 2` scalable and rotatable hardware fonts - `precision = 3` scalable and rotatable hardware fonts. Text size is given in pixels. The text font and precision of any class inheriting from `TAttText` can be changed using the method `SetTextFont` and retrieved using the method `GetTextFont`. ### <a name="T51"></a> Font quality and speed When precision 0 is used, only the original non-scaled system fonts are used. The fonts have a minimum (4) and maximum (37) size in pixels. These fonts are fast and are of good quality. Their size varies with large steps and they cannot be rotated. Precision 1 and 2 fonts have a different behaviour depending if the True Type Fonts (TTF) are used or not. If TTF are used, you always get very good quality scalable and rotatable fonts. However TTF are slow. ### <a name="T52"></a> How to use True Type Fonts One can activate the TTF by adding (or activating) the following line in the `.rootrc` file: ~~~ {.cpp} Unix.*.Root.UseTTFonts: true ~~~ It is possible to check the TTF are in use in a Root session with the command: ~~~ {.cpp} gEnv->Print(); ~~~ If the TTF are in use the following line will appear at the beginning of the printout given by this command: ~~~ {.cpp} Unix.*.Root.UseTTFonts: true [Global] ~~~ ### <a name="T53"></a> List of the currently supported fonts ~~~ {.cpp} Font number X11 Names Win32/TTF Names 1 : times-medium-i-normal "Times New Roman" 2 : times-bold-r-normal "Times New Roman" 3 : times-bold-i-normal "Times New Roman" 4 : helvetica-medium-r-normal "Arial" 5 : helvetica-medium-o-normal "Arial" 6 : helvetica-bold-r-normal "Arial" 7 : helvetica-bold-o-normal "Arial" 8 : courier-medium-r-normal "Courier New" 9 : courier-medium-o-normal "Courier New" 10 : courier-bold-r-normal "Courier New" 11 : courier-bold-o-normal "Courier New" 12 : symbol-medium-r-normal "Symbol" 13 : times-medium-r-normal "Times New Roman" 14 : "Wingdings" 15 : Symbol italic (derived from Symbol) ~~~ The following picture shows how each font looks. The number on the left is the "text font code". In this picture precision 2 was selected. Begin_Macro fonts.C End_Macro */ //////////////////////////////////////////////////////////////////////////////// /// AttText default constructor. /// /// Default text attributes are taken from the current style. TAttText::TAttText() { if (!gStyle) { ResetAttText(); return; } fTextAlign = gStyle->GetTextAlign(); fTextAngle = gStyle->GetTextAngle(); fTextColor = gStyle->GetTextColor(); fTextFont = gStyle->GetTextFont(); fTextSize = gStyle->GetTextSize(); } //////////////////////////////////////////////////////////////////////////////// /// AttText normal constructor. /// /// Text attributes are taken from the argument list. TAttText::TAttText(Int_t align, Float_t angle, Color_t color, Style_t font, Float_t tsize) { fTextAlign = align; fTextAngle = angle; fTextColor = color; fTextFont = font; fTextSize = tsize; } //////////////////////////////////////////////////////////////////////////////// /// AttText destructor. TAttText::~TAttText() { } //////////////////////////////////////////////////////////////////////////////// /// Copy this text attributes to a new TAttText. void TAttText::Copy(TAttText &atttext) const { atttext.fTextAlign = fTextAlign; atttext.fTextAngle = fTextAngle; atttext.fTextColor = fTextColor; atttext.fTextFont = fTextFont; atttext.fTextSize = fTextSize; } //////////////////////////////////////////////////////////////////////////////// /// Change current text attributes if necessary. void TAttText::Modify() { if (!gPad) return; // Do we need to change font? if (!gPad->IsBatch()) { gVirtualX->SetTextAngle(fTextAngle); Float_t wh = (Float_t)gPad->XtoPixel(gPad->GetX2()); Float_t hh = (Float_t)gPad->YtoPixel(gPad->GetY1()); Float_t tsize; if (wh < hh) tsize = fTextSize*wh; else tsize = fTextSize*hh; if (fTextFont%10 > 2) tsize = fTextSize; if (gVirtualX->GetTextFont() != fTextFont) { gVirtualX->SetTextFont(fTextFont); gVirtualX->SetTextSize(tsize); } if (gVirtualX->GetTextSize() != tsize) gVirtualX->SetTextSize(tsize); gVirtualX->SetTextAlign(fTextAlign); gVirtualX->SetTextColor(fTextColor); } gPad->SetAttTextPS(fTextAlign,fTextAngle,fTextColor,fTextFont,fTextSize); } //////////////////////////////////////////////////////////////////////////////// /// Reset this text attributes to default values. void TAttText::ResetAttText(Option_t *) { fTextAlign = 11; fTextAngle = 0; fTextColor = 1; fTextFont = 62; fTextSize = 0.05; } //////////////////////////////////////////////////////////////////////////////// /// Save text attributes as C++ statement(s) on output stream out. void TAttText::SaveTextAttributes(std::ostream &out, const char *name, Int_t alidef, Float_t angdef, Int_t coldef, Int_t fondef, Float_t sizdef) { if (fTextAlign != alidef) { out<<" "<<name<<"->SetTextAlign("<<fTextAlign<<");"<<std::endl; } if (fTextColor != coldef) { if (fTextColor > 228) { TColor::SaveColor(out, fTextColor); out<<" "<<name<<"->SetTextColor(ci);" << std::endl; } else out<<" "<<name<<"->SetTextColor("<<fTextColor<<");"<<std::endl; } if (fTextFont != fondef) { out<<" "<<name<<"->SetTextFont("<<fTextFont<<");"<<std::endl; } if (fTextSize != sizdef) { out<<" "<<name<<"->SetTextSize("<<fTextSize<<");"<<std::endl; } if (fTextAngle != angdef) { out<<" "<<name<<"->SetTextAngle("<<fTextAngle<<");"<<std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Invoke the DialogCanvas Text attributes. void TAttText::SetTextAttributes() { TVirtualPadEditor::UpdateTextAttributes(fTextAlign,fTextAngle,fTextColor, fTextFont,fTextSize); } //////////////////////////////////////////////////////////////////////////////// /// Set a transparent marker color. talpha defines the percentage of /// the color opacity from 0. (fully transparent) to 1. (fully opaque). void TAttText::SetTextColorAlpha(Color_t tcolor, Float_t talpha) { fTextColor = TColor::GetColorTransparent(tcolor, talpha); } //////////////////////////////////////////////////////////////////////////////// /// Set the text size in pixels. /// /// If the font precision is greater than 2, the text size is set to npixels, /// otherwise the text size is computed as a percent of the pad size. void TAttText::SetTextSizePixels(Int_t npixels) { if (fTextFont%10 > 2) { fTextSize = Float_t(npixels); } else { TVirtualPad *pad = gROOT->GetSelectedPad(); if (!pad) return; Float_t dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels); fTextSize = dy/(pad->GetY2() - pad->GetY1()); } } <commit_msg>High def images<commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 12/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "Strlen.h" #include "TROOT.h" #include "TAttText.h" #include "TVirtualPad.h" #include "TStyle.h" #include "TVirtualX.h" #include "TError.h" #include "TVirtualPadEditor.h" #include "TColor.h" ClassImp(TAttText); /** \class TAttText \ingroup Base \ingroup GraphicsAtt Text Attributes class. This class is used (in general by secondary inheritance) by many other classes (graphics, histograms). It holds all the text attributes. ## Text attributes Text attributes are: - [Text Alignment](#T1) - [Text Angle](#T2) - [Text Color](#T3) - [Text Size](#T4) - [Text Font and Precision](#T5) - [Font quality and speed](#T51) - [How to use True Type Fonts](#T52) - [List of the currently supported fonts](#T53) ## <a name="T1"></a> Text Alignment The text alignment is an integer number (`align`) allowing to control the horizontal and vertical position of the text string with respect to the text position. The text alignment of any class inheriting from `TAttText` can be changed using the method `SetTextAlign` and retrieved using the method `GetTextAlign`. ~~~ {.cpp} align = 10*HorizontalAlign + VerticalAlign ~~~ For horizontal alignment the following convention applies: ~~~ {.cpp} 1=left adjusted, 2=centered, 3=right adjusted ~~~ For vertical alignment the following convention applies: ~~~ {.cpp} 1=bottom adjusted, 2=centered, 3=top adjusted ~~~ For example: ~~~ {.cpp} align = 11 = left adjusted and bottom adjusted align = 32 = right adjusted and vertically centered ~~~ Begin_Macro(source) textalign.C End_Macro Mnemonic constants are available: ~~~ {.cpp} kHAlignLeft = 10, kHAlignCenter = 20, kHAlignRight = 30, kVAlignBottom = 1, kVAlignCenter = 2, kVAlignTop = 3 ~~~ They allow to write: ~~~ {.cpp} object->SetTextAlign(kHAlignLeft+kVAlignTop); ~~~ ## <a name="T2"></a> Text Angle Text angle in degrees. The text angle of any class inheriting from `TAttText` can be changed using the method `SetTextAngle` and retrieved using the method `GetTextAngle`. The following picture shows the text angle: Begin_Macro(source) textangle.C End_Macro ## <a name="T3"></a> Text Color The text color is a color index (integer) pointing in the ROOT color table. The text color of any class inheriting from `TAttText` can be changed using the method `SetTextColor` and retrieved using the method `GetTextColor`. The following table shows the first 50 default colors. Begin_Macro("width=500") { TCanvas *c = new TCanvas("c","Fill Area colors",0,0,1500,600); c->DrawColorTable(); return c; } End_Macro ### Color transparency `SetTextColorAlpha()`, allows to set a transparent color. In the following example the text color of the text `text` is set to blue with a transparency of 35%. The color `kBlue` itself remains fully opaque. ~~~ {.cpp} text->SetTextColorAlpha(kBlue, 0.35); ~~~ The transparency is available on all platforms when the `flagOpenGL.CanvasPreferGL` is set to `1` in `$ROOTSYS/etc/system.rootrc`, or on Mac with the Cocoa backend. On the file output it is visible with PDF, PNG, Gif, JPEG, SVG ... but not PostScript. ## <a name="T4"></a> Text Size If the text precision (see next paragraph) is smaller than 3, the text size (`textsize`) is a fraction of the current pad size. Therefore the same `textsize` value can generate text outputs with different absolute sizes in two different pads. The text size in pixels (`charheight`) is computed the following way: ~~~ {.cpp} pad_width = gPad->XtoPixel(gPad->GetX2()); pad_height = gPad->YtoPixel(gPad->GetY1()); if (pad_width < pad_height) charheight = textsize*pad_width; else charheight = textsize*pad_height; ~~~ If the text precision is equal to 3, the text size doesn't depend on the pad's dimensions. A given `textsize` value always generates the same absolute size. The text size (`charheight`) is given in pixels: ~~~ {.cpp} charheight = textsize; ~~~ Note that to scale fonts to the same size as the old True Type package a scale factor of `0.93376068` is apply to the text size before drawing. The text size of any class inheriting from `TAttText` can be changed using the method `SetTextSize` and retrieved using the method `GetTextSize`. ## <a name="T5"></a> Text Font and Precision The text font code is combination of the font number and the precision. ~~~ {.cpp} Text font code = 10*fontnumber + precision ~~~ Font numbers must be between 1 and 14. The precision can be: - `precision = 0` fast hardware fonts (steps in the size) - `precision = 1` scalable and rotatable hardware fonts (see below) - `precision = 2` scalable and rotatable hardware fonts - `precision = 3` scalable and rotatable hardware fonts. Text size is given in pixels. The text font and precision of any class inheriting from `TAttText` can be changed using the method `SetTextFont` and retrieved using the method `GetTextFont`. ### <a name="T51"></a> Font quality and speed When precision 0 is used, only the original non-scaled system fonts are used. The fonts have a minimum (4) and maximum (37) size in pixels. These fonts are fast and are of good quality. Their size varies with large steps and they cannot be rotated. Precision 1 and 2 fonts have a different behaviour depending if the True Type Fonts (TTF) are used or not. If TTF are used, you always get very good quality scalable and rotatable fonts. However TTF are slow. ### <a name="T52"></a> How to use True Type Fonts One can activate the TTF by adding (or activating) the following line in the `.rootrc` file: ~~~ {.cpp} Unix.*.Root.UseTTFonts: true ~~~ It is possible to check the TTF are in use in a Root session with the command: ~~~ {.cpp} gEnv->Print(); ~~~ If the TTF are in use the following line will appear at the beginning of the printout given by this command: ~~~ {.cpp} Unix.*.Root.UseTTFonts: true [Global] ~~~ ### <a name="T53"></a> List of the currently supported fonts ~~~ {.cpp} Font number X11 Names Win32/TTF Names 1 : times-medium-i-normal "Times New Roman" 2 : times-bold-r-normal "Times New Roman" 3 : times-bold-i-normal "Times New Roman" 4 : helvetica-medium-r-normal "Arial" 5 : helvetica-medium-o-normal "Arial" 6 : helvetica-bold-r-normal "Arial" 7 : helvetica-bold-o-normal "Arial" 8 : courier-medium-r-normal "Courier New" 9 : courier-medium-o-normal "Courier New" 10 : courier-bold-r-normal "Courier New" 11 : courier-bold-o-normal "Courier New" 12 : symbol-medium-r-normal "Symbol" 13 : times-medium-r-normal "Times New Roman" 14 : "Wingdings" 15 : Symbol italic (derived from Symbol) ~~~ The following picture shows how each font looks. The number on the left is the "text font code". In this picture precision 2 was selected. Begin_Macro fonts.C End_Macro */ //////////////////////////////////////////////////////////////////////////////// /// AttText default constructor. /// /// Default text attributes are taken from the current style. TAttText::TAttText() { if (!gStyle) { ResetAttText(); return; } fTextAlign = gStyle->GetTextAlign(); fTextAngle = gStyle->GetTextAngle(); fTextColor = gStyle->GetTextColor(); fTextFont = gStyle->GetTextFont(); fTextSize = gStyle->GetTextSize(); } //////////////////////////////////////////////////////////////////////////////// /// AttText normal constructor. /// /// Text attributes are taken from the argument list. TAttText::TAttText(Int_t align, Float_t angle, Color_t color, Style_t font, Float_t tsize) { fTextAlign = align; fTextAngle = angle; fTextColor = color; fTextFont = font; fTextSize = tsize; } //////////////////////////////////////////////////////////////////////////////// /// AttText destructor. TAttText::~TAttText() { } //////////////////////////////////////////////////////////////////////////////// /// Copy this text attributes to a new TAttText. void TAttText::Copy(TAttText &atttext) const { atttext.fTextAlign = fTextAlign; atttext.fTextAngle = fTextAngle; atttext.fTextColor = fTextColor; atttext.fTextFont = fTextFont; atttext.fTextSize = fTextSize; } //////////////////////////////////////////////////////////////////////////////// /// Change current text attributes if necessary. void TAttText::Modify() { if (!gPad) return; // Do we need to change font? if (!gPad->IsBatch()) { gVirtualX->SetTextAngle(fTextAngle); Float_t wh = (Float_t)gPad->XtoPixel(gPad->GetX2()); Float_t hh = (Float_t)gPad->YtoPixel(gPad->GetY1()); Float_t tsize; if (wh < hh) tsize = fTextSize*wh; else tsize = fTextSize*hh; if (fTextFont%10 > 2) tsize = fTextSize; if (gVirtualX->GetTextFont() != fTextFont) { gVirtualX->SetTextFont(fTextFont); gVirtualX->SetTextSize(tsize); } if (gVirtualX->GetTextSize() != tsize) gVirtualX->SetTextSize(tsize); gVirtualX->SetTextAlign(fTextAlign); gVirtualX->SetTextColor(fTextColor); } gPad->SetAttTextPS(fTextAlign,fTextAngle,fTextColor,fTextFont,fTextSize); } //////////////////////////////////////////////////////////////////////////////// /// Reset this text attributes to default values. void TAttText::ResetAttText(Option_t *) { fTextAlign = 11; fTextAngle = 0; fTextColor = 1; fTextFont = 62; fTextSize = 0.05; } //////////////////////////////////////////////////////////////////////////////// /// Save text attributes as C++ statement(s) on output stream out. void TAttText::SaveTextAttributes(std::ostream &out, const char *name, Int_t alidef, Float_t angdef, Int_t coldef, Int_t fondef, Float_t sizdef) { if (fTextAlign != alidef) { out<<" "<<name<<"->SetTextAlign("<<fTextAlign<<");"<<std::endl; } if (fTextColor != coldef) { if (fTextColor > 228) { TColor::SaveColor(out, fTextColor); out<<" "<<name<<"->SetTextColor(ci);" << std::endl; } else out<<" "<<name<<"->SetTextColor("<<fTextColor<<");"<<std::endl; } if (fTextFont != fondef) { out<<" "<<name<<"->SetTextFont("<<fTextFont<<");"<<std::endl; } if (fTextSize != sizdef) { out<<" "<<name<<"->SetTextSize("<<fTextSize<<");"<<std::endl; } if (fTextAngle != angdef) { out<<" "<<name<<"->SetTextAngle("<<fTextAngle<<");"<<std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Invoke the DialogCanvas Text attributes. void TAttText::SetTextAttributes() { TVirtualPadEditor::UpdateTextAttributes(fTextAlign,fTextAngle,fTextColor, fTextFont,fTextSize); } //////////////////////////////////////////////////////////////////////////////// /// Set a transparent marker color. talpha defines the percentage of /// the color opacity from 0. (fully transparent) to 1. (fully opaque). void TAttText::SetTextColorAlpha(Color_t tcolor, Float_t talpha) { fTextColor = TColor::GetColorTransparent(tcolor, talpha); } //////////////////////////////////////////////////////////////////////////////// /// Set the text size in pixels. /// /// If the font precision is greater than 2, the text size is set to npixels, /// otherwise the text size is computed as a percent of the pad size. void TAttText::SetTextSizePixels(Int_t npixels) { if (fTextFont%10 > 2) { fTextSize = Float_t(npixels); } else { TVirtualPad *pad = gROOT->GetSelectedPad(); if (!pad) return; Float_t dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY(npixels); fTextSize = dy/(pad->GetY2() - pad->GetY1()); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <string> #include "itkMetaImageIO.h" #include "itkExceptionObject.h" namespace itk { MetaImageIO::MetaImageIO() { if(MET_SystemByteOrderMSB()) m_ByteOrder = BigEndian; else m_ByteOrder = LittleEndian; } MetaImageIO::~MetaImageIO() { m_Ifstream.close(); } void MetaImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); m_MetaImage.PrintInfo(); } void MetaImageIO::SetDataFileName( const char* filename ) { m_MetaImage.ElementDataFileName( filename ); } // This method will only test if the header looks like a // MetaImage. Some code is redundant with ReadImageInformation // a StateMachine could provide a better implementation bool MetaImageIO::CanReadFile( const char* filename ) { std::ifstream inputStream; inputStream.open( filename, std::ios::in | std::ios::binary ); if( inputStream.fail() ) { return false; } char key[8000]; inputStream >> key; if( inputStream.eof() ) { inputStream.close(); return false; } if( strcmp(key,"NDims")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ObjectType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"TransformType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ParentID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"BinaryData")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Comment")==0 ) { inputStream.close(); return true; } if( strcmp(key,"AcquisitionDate")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Modality")==0 ) { inputStream.close(); return true; } inputStream.close(); return false; } void MetaImageIO::ReadImageInformation() { if(!m_MetaImage.Read(m_FileName.c_str()), false) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } if(m_MetaImage.BinaryData()) { this->SetFileType(Binary); } else { this->SetFileType(ASCII); } this->SetNumberOfComponents(m_MetaImage.ElementNumberOfChannels()); switch(m_MetaImage.ElementType()) { default: case MET_OTHER: case MET_NONE: this->SetPixelType( UNKNOWN ); this->SetComponentType( UNKNOWN ); break; case MET_CHAR: case MET_CHAR_ARRAY: case MET_STRING: case MET_ASCII_CHAR: this->SetPixelType( CHAR ); this->SetComponentType( CHAR ); break; case MET_UCHAR: case MET_UCHAR_ARRAY: this->SetPixelType( UCHAR ); this->SetComponentType( UCHAR ); break; case MET_SHORT: case MET_SHORT_ARRAY: this->SetPixelType( SHORT ); this->SetComponentType( SHORT ); break; case MET_USHORT: case MET_USHORT_ARRAY: this->SetPixelType( USHORT ); this->SetComponentType( USHORT ); break; case MET_INT: case MET_INT_ARRAY: this->SetPixelType( INT ); this->SetComponentType( INT ); break; case MET_UINT: case MET_UINT_ARRAY: this->SetPixelType( UINT ); this->SetComponentType( UINT ); break; case MET_FLOAT: case MET_FLOAT_ARRAY: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); break; case MET_DOUBLE: case MET_DOUBLE_ARRAY: this->SetPixelType( DOUBLE ); this->SetComponentType( DOUBLE ); break; case MET_FLOAT_MATRIX: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } this->SetNumberOfDimensions(m_MetaImage.NDims()); int i; for(i=0; i<(int)m_NumberOfDimensions; i++) { this->SetDimensions(i, m_MetaImage.DimSize(i)); this->SetSpacing(i, m_MetaImage.ElementSpacing(i)); this->SetOrigin(i, m_MetaImage.Position(i)); } } void MetaImageIO::Read(void* buffer) { if(!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } m_MetaImage.ElementByteOrderFix(); } MetaImage * MetaImageIO::GetMetaImagePointer(void) { return & m_MetaImage; } bool MetaImageIO::CanWriteFile(const char*) { return true; } void MetaImageIO ::WriteImageInformation(void) { } /** * */ void MetaImageIO ::Write( const void* buffer) { int nDims = this->GetNumberOfDimensions(); bool binaryData = false; if(this->GetFileType() == Binary) { binaryData = true; } int nChannels = this->GetNumberOfComponents(); MET_ValueEnumType eType = MET_OTHER; switch(m_PixelType) { default: case UNKNOWN: eType = MET_OTHER; break; case CHAR: eType = MET_CHAR; break; case UCHAR: eType = MET_UCHAR; break; case SHORT: eType = MET_SHORT; break; case USHORT: eType = MET_USHORT; break; case INT: eType = MET_INT; break; case UINT: eType = MET_UINT; break; case FLOAT: eType = MET_FLOAT; break; case DOUBLE: eType = MET_DOUBLE; break; } int i; int * dSize = new int[nDims]; float * eSpacing = new float[nDims]; float * eOrigin = new float[nDims]; for(i=0; i<nDims; i++) { dSize[i] = this->GetDimensions(i); eSpacing[i] = this->GetSpacing(i); eOrigin[i] = this->GetOrigin(i); } m_MetaImage.InitializeEssential(nDims, dSize, eSpacing, eType, nChannels, (void *)buffer); m_MetaImage.Position(eOrigin); m_MetaImage.BinaryData(binaryData); std::string dataName; dataName = m_FileName + ".raw"; std::cout << "dataName = " << dataName << std::endl; m_MetaImage.Write(m_FileName.c_str(), dataName.c_str()); delete dSize; delete eSpacing; delete eOrigin; } } // end namespace itk <commit_msg>ENH: Removed an extra cout<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkMetaImageIO.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <string> #include "itkMetaImageIO.h" #include "itkExceptionObject.h" namespace itk { MetaImageIO::MetaImageIO() { if(MET_SystemByteOrderMSB()) m_ByteOrder = BigEndian; else m_ByteOrder = LittleEndian; } MetaImageIO::~MetaImageIO() { m_Ifstream.close(); } void MetaImageIO::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os, indent); m_MetaImage.PrintInfo(); } void MetaImageIO::SetDataFileName( const char* filename ) { m_MetaImage.ElementDataFileName( filename ); } // This method will only test if the header looks like a // MetaImage. Some code is redundant with ReadImageInformation // a StateMachine could provide a better implementation bool MetaImageIO::CanReadFile( const char* filename ) { std::ifstream inputStream; inputStream.open( filename, std::ios::in | std::ios::binary ); if( inputStream.fail() ) { return false; } char key[8000]; inputStream >> key; if( inputStream.eof() ) { inputStream.close(); return false; } if( strcmp(key,"NDims")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ObjectType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"TransformType")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"ParentID")==0 ) { inputStream.close(); return true; } if( strcmp(key,"BinaryData")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Comment")==0 ) { inputStream.close(); return true; } if( strcmp(key,"AcquisitionDate")==0 ) { inputStream.close(); return true; } if( strcmp(key,"Modality")==0 ) { inputStream.close(); return true; } inputStream.close(); return false; } void MetaImageIO::ReadImageInformation() { if(!m_MetaImage.Read(m_FileName.c_str()), false) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } if(m_MetaImage.BinaryData()) { this->SetFileType(Binary); } else { this->SetFileType(ASCII); } this->SetNumberOfComponents(m_MetaImage.ElementNumberOfChannels()); switch(m_MetaImage.ElementType()) { default: case MET_OTHER: case MET_NONE: this->SetPixelType( UNKNOWN ); this->SetComponentType( UNKNOWN ); break; case MET_CHAR: case MET_CHAR_ARRAY: case MET_STRING: case MET_ASCII_CHAR: this->SetPixelType( CHAR ); this->SetComponentType( CHAR ); break; case MET_UCHAR: case MET_UCHAR_ARRAY: this->SetPixelType( UCHAR ); this->SetComponentType( UCHAR ); break; case MET_SHORT: case MET_SHORT_ARRAY: this->SetPixelType( SHORT ); this->SetComponentType( SHORT ); break; case MET_USHORT: case MET_USHORT_ARRAY: this->SetPixelType( USHORT ); this->SetComponentType( USHORT ); break; case MET_INT: case MET_INT_ARRAY: this->SetPixelType( INT ); this->SetComponentType( INT ); break; case MET_UINT: case MET_UINT_ARRAY: this->SetPixelType( UINT ); this->SetComponentType( UINT ); break; case MET_FLOAT: case MET_FLOAT_ARRAY: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); break; case MET_DOUBLE: case MET_DOUBLE_ARRAY: this->SetPixelType( DOUBLE ); this->SetComponentType( DOUBLE ); break; case MET_FLOAT_MATRIX: this->SetPixelType( FLOAT ); this->SetComponentType( FLOAT ); this->SetNumberOfComponents(m_NumberOfComponents * m_NumberOfComponents); break; } this->SetNumberOfDimensions(m_MetaImage.NDims()); int i; for(i=0; i<(int)m_NumberOfDimensions; i++) { this->SetDimensions(i, m_MetaImage.DimSize(i)); this->SetSpacing(i, m_MetaImage.ElementSpacing(i)); this->SetOrigin(i, m_MetaImage.Position(i)); } } void MetaImageIO::Read(void* buffer) { if(!m_MetaImage.Read(m_FileName.c_str(), true, buffer)) { ExceptionObject exception(__FILE__, __LINE__); exception.SetDescription("File cannot be read"); throw exception; } m_MetaImage.ElementByteOrderFix(); } MetaImage * MetaImageIO::GetMetaImagePointer(void) { return & m_MetaImage; } bool MetaImageIO::CanWriteFile(const char*) { return true; } void MetaImageIO ::WriteImageInformation(void) { } /** * */ void MetaImageIO ::Write( const void* buffer) { int nDims = this->GetNumberOfDimensions(); bool binaryData = false; if(this->GetFileType() == Binary) { binaryData = true; } int nChannels = this->GetNumberOfComponents(); MET_ValueEnumType eType = MET_OTHER; switch(m_PixelType) { default: case UNKNOWN: eType = MET_OTHER; break; case CHAR: eType = MET_CHAR; break; case UCHAR: eType = MET_UCHAR; break; case SHORT: eType = MET_SHORT; break; case USHORT: eType = MET_USHORT; break; case INT: eType = MET_INT; break; case UINT: eType = MET_UINT; break; case FLOAT: eType = MET_FLOAT; break; case DOUBLE: eType = MET_DOUBLE; break; } int i; int * dSize = new int[nDims]; float * eSpacing = new float[nDims]; float * eOrigin = new float[nDims]; for(i=0; i<nDims; i++) { dSize[i] = this->GetDimensions(i); eSpacing[i] = this->GetSpacing(i); eOrigin[i] = this->GetOrigin(i); } m_MetaImage.InitializeEssential(nDims, dSize, eSpacing, eType, nChannels, (void *)buffer); m_MetaImage.Position(eOrigin); m_MetaImage.BinaryData(binaryData); std::string dataName; dataName = m_FileName + ".raw"; m_MetaImage.Write(m_FileName.c_str(), dataName.c_str()); delete dSize; delete eSpacing; delete eOrigin; } } // end namespace itk <|endoftext|>
<commit_before>/* This file is part of the E_GUI library. Copyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2008-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_Connector.h" #include <EScript/EScript.h> #include <EScript/Utils/DeprecatedMacros.h> #include "../ELibGUI.h" namespace E_GUI { //! [static] initMembers void E_Connector::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); addFactory<GUI::Connector,E_Connector>(); using namespace GUI; //! [ESF] (static) Array GUI.findConnectors( container,endpoint ) ES_FUNCTION2(&lib,"findConnectors",2,2,{ EScript::Array * a = EScript::Array::create(); std::list<GUI::Connector *> connectors; GUI::Connector::findConnectors( parameter[0].to<Container*>(rt), parameter[1].to<Component*>(rt),connectors); for(const auto & connector : connectors) a->pushBack(EScript::create(connector)); return a; }) //! [ESMF] Component Connector.getFirstComponent() ES_MFUN(typeObject,Connector,"getFirstComponent",0,0, EScript::create(thisObj->getFirstComponent())) //! [ESMF] Number Connector.getLength() ES_MFUN(typeObject,const Connector,"getLength",0,0, thisObj->getLength()) //! [ESMF] Component Connector.getSecondComponent() ES_MFUN(typeObject,Connector,"getSecondComponent",0,0, EScript::create(thisObj->getSecondComponent())) //! [ESMF] self Connector.setFirstComponent(Component|nullptr) ES_MFUN(typeObject,Connector,"setFirstComponent",1,1,( thisObj->setFirstComponent( parameter[0].toType<E_Component>() == nullptr ? nullptr : (**parameter[0].toType<E_Component>())),thisEObj)) //! [ESMF] self Connector.setSecondComponent(Component|nullptr) ES_MFUN(typeObject,Connector,"setSecondComponent",1,1,( thisObj->setSecondComponent( parameter[0].toType<E_Component>() == nullptr ? nullptr : (**parameter[0].toType<E_Component>())),thisEObj)) } } <commit_msg>Replace deprecated macros.<commit_after>/* This file is part of the E_GUI library. Copyright (C) 2008-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2008-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2008-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "E_Connector.h" #include <EScript/EScript.h> #include "../ELibGUI.h" namespace E_GUI { //! [static] initMembers void E_Connector::init(EScript::Namespace & lib) { EScript::Type * typeObject = getTypeObject(); declareConstant(&lib,getClassName(),typeObject); addFactory<GUI::Connector,E_Connector>(); using namespace GUI; //! [ESF] (static) Array GUI.findConnectors( container,endpoint ) ES_FUNCTION(&lib,"findConnectors",2,2,{ EScript::Array * a = EScript::Array::create(); std::list<GUI::Connector *> connectors; GUI::Connector::findConnectors( parameter[0].to<Container*>(rt), parameter[1].to<Component*>(rt),connectors); for(const auto & connector : connectors) a->pushBack(EScript::create(connector)); return a; }) //! [ESMF] Component Connector.getFirstComponent() ES_MFUN(typeObject,Connector,"getFirstComponent",0,0, EScript::create(thisObj->getFirstComponent())) //! [ESMF] Number Connector.getLength() ES_MFUN(typeObject,const Connector,"getLength",0,0, thisObj->getLength()) //! [ESMF] Component Connector.getSecondComponent() ES_MFUN(typeObject,Connector,"getSecondComponent",0,0, EScript::create(thisObj->getSecondComponent())) //! [ESMF] self Connector.setFirstComponent(Component|nullptr) ES_MFUN(typeObject,Connector,"setFirstComponent",1,1,( thisObj->setFirstComponent( parameter[0].toType<E_Component>() == nullptr ? nullptr : (**parameter[0].toType<E_Component>())),thisEObj)) //! [ESMF] self Connector.setSecondComponent(Component|nullptr) ES_MFUN(typeObject,Connector,"setSecondComponent",1,1,( thisObj->setSecondComponent( parameter[0].toType<E_Component>() == nullptr ? nullptr : (**parameter[0].toType<E_Component>())),thisEObj)) } } <|endoftext|>
<commit_before>#include "anki/scene/ParticleEmitter.h" #include "anki/scene/Scene.h" #include "anki/resource/Model.h" #include "anki/util/Functions.h" #include "anki/physics/PhysWorld.h" #include <limits> namespace anki { //============================================================================== // Misc = //============================================================================== //============================================================================== F32 getRandom(F32 initial, F32 deviation) { return (deviation == 0.0) ? initial : initial + randFloat(deviation) * 2.0 - deviation; } //============================================================================== Vec3 getRandom(const Vec3& initial, const Vec3& deviation) { if(deviation == Vec3(0.0)) { return initial; } else { Vec3 out; for(U i = 0; i < 3; i++) { out[i] = getRandom(initial[i], deviation[i]); } return out; } } //============================================================================== // ParticleBase = //============================================================================== //============================================================================== ParticleBase::ParticleBase( ParticleType type_, // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : SceneNode(name, scene), Movable(movableFlags, movParent, *this), type(type_) {} //============================================================================== ParticleBase::~ParticleBase() {} //============================================================================== void ParticleBase::revive(const ParticleEmitter& pe, F32 /*prevUpdateTime*/, F32 crntTime) { ANKI_ASSERT(isDead()); const ParticleEmitterProperties& props = pe; // life timeOfDeath = getRandom(crntTime + props.particle.life, props.particle.lifeDeviation); timeOfBirth = crntTime; } //============================================================================== // ParticleSimple = //============================================================================== //============================================================================== ParticleSimple::ParticleSimple( // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : ParticleBase(PT_SIMPLE, name, scene, movableFlags, movParent) {} //============================================================================== void ParticleSimple::simulate(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { F32 dt = crntTime - prevUpdateTime; ANKI_ASSERT(props.particle.gravity.getLength() > 0.0); Transform trf = getWorldTransform(); Vec3 xp = trf.getOrigin(); Vec3 xc = acceleration * (dt * dt) + velocity * dt + xp; trf.setOrigin(xc); setLocalTransform(trf); velocity += acceleration * dt; } //============================================================================== void ParticleSimple::revive(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { ParticleBase::revive(pe, prevUpdateTime, crntTime); velocity = Vec3(0.0); const ParticleEmitterProperties& props = pe; acceleration = getRandom(props.particle.gravity, props.particle.gravityDeviation); // Set the initial position Vec3 pos = getRandom(props.particle.startingPos, props.particle.startingPosDeviation); pos += pe.getWorldTransform().getOrigin(); Transform trf; trf.setIdentity(); trf.setOrigin(pos); setLocalTransform(trf); } //============================================================================== // Particle = //============================================================================== //============================================================================== Particle::Particle( // Scene const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent, // RigidBody PhysWorld* masterContainer, const Initializer& init) : ParticleBase(PT_PHYSICS, name, scene, movableFlags, movParent), RigidBody(masterContainer, init, this) {} //============================================================================== Particle::~Particle() {} //============================================================================== void Particle::revive(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { ParticleBase::revive(pe, prevUpdateTime, crntTime); const ParticleEmitterProperties& props = pe; RigidBody& body = *this; // pre calculate Bool forceFlag = props.forceEnabled; Bool worldGravFlag = props.wordGravityEnabled; // activate it (Bullet stuff) body.forceActivationState(ACTIVE_TAG); body.activate(); body.clearForces(); body.setLinearVelocity(btVector3(0.0, 0.0, 0.0)); body.setAngularVelocity(btVector3(0.0, 0.0, 0.0)); // force if(forceFlag) { Vec3 forceDir = getRandom(props.particle.forceDirection, props.particle.forceDirectionDeviation); forceDir.normalize(); if(!pe.identityRotation) { // the forceDir depends on the particle emitter rotation forceDir = pe.getWorldTransform().getRotation() * forceDir; } F32 forceMag = getRandom(props.particle.forceMagnitude, props.particle.forceMagnitudeDeviation); body.applyCentralForce(toBt(forceDir * forceMag)); } // gravity if(!worldGravFlag) { body.setGravity(toBt(getRandom(props.particle.gravity, props.particle.gravityDeviation))); } // Starting pos. In local space Vec3 pos = getRandom(props.particle.startingPos, props.particle.startingPosDeviation); if(pe.identityRotation) { pos += pe.getWorldTransform().getOrigin(); } else { pos.transform(pe.getWorldTransform()); } btTransform trf( toBt(Transform(pos, pe.getWorldTransform().getRotation(), 1.0))); body.setWorldTransform(trf); } //============================================================================== // ParticleEmitter = //============================================================================== //============================================================================== ParticleEmitter::ParticleEmitter( const char* filename, // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : SceneNode(name, scene), Spatial(this, &aabb), Movable(movableFlags, movParent, *this) { // Load resource particleEmitterResource.load(filename); // copy the resource to me ParticleEmitterProperties& me = *this; const ParticleEmitterProperties& other = particleEmitterResource->getProperties(); me = other; if(usePhysicsEngine) { createParticlesSimulation(scene); } else { createParticlesSimpleSimulation(scene); } timeLeftForNextEmission = 0.0; instancesCount = particles.size(); Renderable::init(*this); // Find the "alpha" material variable for(auto it = Renderable::getVariablesBegin(); it != Renderable::getVariablesEnd(); ++it) { if((*it)->getName() == "alpha") { alphaRenderableVar = *it; } } } //============================================================================== ParticleEmitter::~ParticleEmitter() {} //============================================================================== const ModelPatchBase& ParticleEmitter::getRenderableModelPatchBase() const { return *particleEmitterResource->getModel().getModelPatches()[0]; } //============================================================================== const Material& ParticleEmitter::getRenderableMaterial() const { return particleEmitterResource->getModel().getModelPatches()[0]->getMaterial(); } //============================================================================== void ParticleEmitter::movableUpdate() { identityRotation = getWorldTransform().getRotation() == Mat3::getIdentity(); } //============================================================================== void ParticleEmitter::createParticlesSimulation(Scene* scene) { // create the particles collShape.reset(new btSphereShape(particle.size)); RigidBody::Initializer binit; binit.shape = collShape.get(); binit.group = PhysWorld::CG_PARTICLE; binit.mask = PhysWorld::CG_MAP; for(U i = 0; i < maxNumOfParticles; i++) { binit.mass = getRandom(particle.mass, particle.massDeviation); Particle* part = new Particle( (getName() + std::to_string(i)).c_str(), scene, Movable::MF_NONE, nullptr, &scene->getPhysics(), binit); particles.push_back(part); part->forceActivationState(DISABLE_SIMULATION); } } //============================================================================== void ParticleEmitter::createParticlesSimpleSimulation(Scene* scene) { for(U i = 0; i < maxNumOfParticles; i++) { ParticleSimple* p = new ParticleSimple( (getName() + std::to_string(i)).c_str(), scene, Movable::MF_NONE, nullptr); particles.push_back(p); } } //============================================================================== void ParticleEmitter::frameUpdate(F32 prevUpdateTime, F32 crntTime, I frame) { SceneNode::frameUpdate(prevUpdateTime, crntTime, frame); // - Deactivate the dead particles // - Calc the AABB // - Calc the instancing stuff // Vec3 aabbmin(std::numeric_limits<F32>::max()); Vec3 aabbmax(std::numeric_limits<F32>::min()); instancingTransformations.clear(); Vector<F32> alpha; for(ParticleBase* p : particles) { if(p->isDead()) { // if its already dead so dont deactivate it again continue; } if(p->getTimeOfDeath() < crntTime) { // Just died p->kill(); } else { // This will calculate a new world transformation p->simulate(*this, prevUpdateTime, crntTime); // An alive const Vec3& origin = p->Movable::getWorldTransform().getOrigin(); for(U i = 0; i < 3; i++) { aabbmin[i] = std::min(aabbmin[i], origin[i]); aabbmax[i] = std::max(aabbmax[i], origin[i]); } F32 lifePercent = (crntTime - p->getTimeOfBirth()) / (p->getTimeOfDeath() - p->getTimeOfBirth()); Transform trf = p->Movable::getWorldTransform(); // XXX set a flag for scale trf.setScale( particle.size + (lifePercent * particle.sizeAnimation)); instancingTransformations.push_back(trf); // Set alpha if(alphaRenderableVar) { alpha.push_back((1.0 - lifePercent) * particle.alpha); } } } instancesCount = instancingTransformations.size(); if(instancesCount != 0) { aabb = Aabb(aabbmin - particle.size, aabbmax + particle.size); } else { aabb = Aabb(Vec3(0.0), Vec3(0.01)); } spatialMarkUpdated(); if(alphaRenderableVar) { alphaRenderableVar->setValues(&alpha[0], alpha.size()); } // // Emit new particles // if(timeLeftForNextEmission <= 0.0) { U particlesCount = 0; // How many particles I am allowed to emmit for(ParticleBase* pp : particles) { ParticleBase& p = *pp; if(!p.isDead()) { // its alive so skip it continue; } p.revive(*this, prevUpdateTime, crntTime); // do the rest ++particlesCount; if(particlesCount >= particlesPerEmittion) { break; } } // end for all particles timeLeftForNextEmission = emissionPeriod; } // end if can emit else { timeLeftForNextEmission -= crntTime - prevUpdateTime; } } } // end namespace anki <commit_msg>Particles: Making the alpha transition better<commit_after>#include "anki/scene/ParticleEmitter.h" #include "anki/scene/Scene.h" #include "anki/resource/Model.h" #include "anki/util/Functions.h" #include "anki/physics/PhysWorld.h" #include <limits> namespace anki { //============================================================================== // Misc = //============================================================================== //============================================================================== F32 getRandom(F32 initial, F32 deviation) { return (deviation == 0.0) ? initial : initial + randFloat(deviation) * 2.0 - deviation; } //============================================================================== Vec3 getRandom(const Vec3& initial, const Vec3& deviation) { if(deviation == Vec3(0.0)) { return initial; } else { Vec3 out; for(U i = 0; i < 3; i++) { out[i] = getRandom(initial[i], deviation[i]); } return out; } } //============================================================================== // ParticleBase = //============================================================================== //============================================================================== ParticleBase::ParticleBase( ParticleType type_, // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : SceneNode(name, scene), Movable(movableFlags, movParent, *this), type(type_) {} //============================================================================== ParticleBase::~ParticleBase() {} //============================================================================== void ParticleBase::revive(const ParticleEmitter& pe, F32 /*prevUpdateTime*/, F32 crntTime) { ANKI_ASSERT(isDead()); const ParticleEmitterProperties& props = pe; // life timeOfDeath = getRandom(crntTime + props.particle.life, props.particle.lifeDeviation); timeOfBirth = crntTime; } //============================================================================== // ParticleSimple = //============================================================================== //============================================================================== ParticleSimple::ParticleSimple( // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : ParticleBase(PT_SIMPLE, name, scene, movableFlags, movParent) {} //============================================================================== void ParticleSimple::simulate(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { F32 dt = crntTime - prevUpdateTime; ANKI_ASSERT(props.particle.gravity.getLength() > 0.0); Transform trf = getWorldTransform(); Vec3 xp = trf.getOrigin(); Vec3 xc = acceleration * (dt * dt) + velocity * dt + xp; trf.setOrigin(xc); setLocalTransform(trf); velocity += acceleration * dt; } //============================================================================== void ParticleSimple::revive(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { ParticleBase::revive(pe, prevUpdateTime, crntTime); velocity = Vec3(0.0); const ParticleEmitterProperties& props = pe; acceleration = getRandom(props.particle.gravity, props.particle.gravityDeviation); // Set the initial position Vec3 pos = getRandom(props.particle.startingPos, props.particle.startingPosDeviation); pos += pe.getWorldTransform().getOrigin(); Transform trf; trf.setIdentity(); trf.setOrigin(pos); setLocalTransform(trf); } //============================================================================== // Particle = //============================================================================== //============================================================================== Particle::Particle( // Scene const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent, // RigidBody PhysWorld* masterContainer, const Initializer& init) : ParticleBase(PT_PHYSICS, name, scene, movableFlags, movParent), RigidBody(masterContainer, init, this) {} //============================================================================== Particle::~Particle() {} //============================================================================== void Particle::revive(const ParticleEmitter& pe, F32 prevUpdateTime, F32 crntTime) { ParticleBase::revive(pe, prevUpdateTime, crntTime); const ParticleEmitterProperties& props = pe; RigidBody& body = *this; // pre calculate Bool forceFlag = props.forceEnabled; Bool worldGravFlag = props.wordGravityEnabled; // activate it (Bullet stuff) body.forceActivationState(ACTIVE_TAG); body.activate(); body.clearForces(); body.setLinearVelocity(btVector3(0.0, 0.0, 0.0)); body.setAngularVelocity(btVector3(0.0, 0.0, 0.0)); // force if(forceFlag) { Vec3 forceDir = getRandom(props.particle.forceDirection, props.particle.forceDirectionDeviation); forceDir.normalize(); if(!pe.identityRotation) { // the forceDir depends on the particle emitter rotation forceDir = pe.getWorldTransform().getRotation() * forceDir; } F32 forceMag = getRandom(props.particle.forceMagnitude, props.particle.forceMagnitudeDeviation); body.applyCentralForce(toBt(forceDir * forceMag)); } // gravity if(!worldGravFlag) { body.setGravity(toBt(getRandom(props.particle.gravity, props.particle.gravityDeviation))); } // Starting pos. In local space Vec3 pos = getRandom(props.particle.startingPos, props.particle.startingPosDeviation); if(pe.identityRotation) { pos += pe.getWorldTransform().getOrigin(); } else { pos.transform(pe.getWorldTransform()); } btTransform trf( toBt(Transform(pos, pe.getWorldTransform().getRotation(), 1.0))); body.setWorldTransform(trf); } //============================================================================== // ParticleEmitter = //============================================================================== //============================================================================== ParticleEmitter::ParticleEmitter( const char* filename, // SceneNode const char* name, Scene* scene, // Movable U32 movableFlags, Movable* movParent) : SceneNode(name, scene), Spatial(this, &aabb), Movable(movableFlags, movParent, *this) { // Load resource particleEmitterResource.load(filename); // copy the resource to me ParticleEmitterProperties& me = *this; const ParticleEmitterProperties& other = particleEmitterResource->getProperties(); me = other; if(usePhysicsEngine) { createParticlesSimulation(scene); } else { createParticlesSimpleSimulation(scene); } timeLeftForNextEmission = 0.0; instancesCount = particles.size(); Renderable::init(*this); // Find the "alpha" material variable for(auto it = Renderable::getVariablesBegin(); it != Renderable::getVariablesEnd(); ++it) { if((*it)->getName() == "alpha") { alphaRenderableVar = *it; } } } //============================================================================== ParticleEmitter::~ParticleEmitter() {} //============================================================================== const ModelPatchBase& ParticleEmitter::getRenderableModelPatchBase() const { return *particleEmitterResource->getModel().getModelPatches()[0]; } //============================================================================== const Material& ParticleEmitter::getRenderableMaterial() const { return particleEmitterResource->getModel().getModelPatches()[0]->getMaterial(); } //============================================================================== void ParticleEmitter::movableUpdate() { identityRotation = getWorldTransform().getRotation() == Mat3::getIdentity(); } //============================================================================== void ParticleEmitter::createParticlesSimulation(Scene* scene) { // create the particles collShape.reset(new btSphereShape(particle.size)); RigidBody::Initializer binit; binit.shape = collShape.get(); binit.group = PhysWorld::CG_PARTICLE; binit.mask = PhysWorld::CG_MAP; for(U i = 0; i < maxNumOfParticles; i++) { binit.mass = getRandom(particle.mass, particle.massDeviation); Particle* part = new Particle( (getName() + std::to_string(i)).c_str(), scene, Movable::MF_NONE, nullptr, &scene->getPhysics(), binit); particles.push_back(part); part->forceActivationState(DISABLE_SIMULATION); } } //============================================================================== void ParticleEmitter::createParticlesSimpleSimulation(Scene* scene) { for(U i = 0; i < maxNumOfParticles; i++) { ParticleSimple* p = new ParticleSimple( (getName() + std::to_string(i)).c_str(), scene, Movable::MF_NONE, nullptr); particles.push_back(p); } } //============================================================================== void ParticleEmitter::frameUpdate(F32 prevUpdateTime, F32 crntTime, I frame) { SceneNode::frameUpdate(prevUpdateTime, crntTime, frame); // - Deactivate the dead particles // - Calc the AABB // - Calc the instancing stuff // Vec3 aabbmin(std::numeric_limits<F32>::max()); Vec3 aabbmax(std::numeric_limits<F32>::min()); instancingTransformations.clear(); Vector<F32> alpha; for(ParticleBase* p : particles) { if(p->isDead()) { // if its already dead so dont deactivate it again continue; } if(p->getTimeOfDeath() < crntTime) { // Just died p->kill(); } else { // This will calculate a new world transformation p->simulate(*this, prevUpdateTime, crntTime); // An alive const Vec3& origin = p->Movable::getWorldTransform().getOrigin(); for(U i = 0; i < 3; i++) { aabbmin[i] = std::min(aabbmin[i], origin[i]); aabbmax[i] = std::max(aabbmax[i], origin[i]); } F32 lifePercent = (crntTime - p->getTimeOfBirth()) / (p->getTimeOfDeath() - p->getTimeOfBirth()); Transform trf = p->Movable::getWorldTransform(); // XXX set a flag for scale trf.setScale( particle.size + (lifePercent * particle.sizeAnimation)); instancingTransformations.push_back(trf); // Set alpha if(alphaRenderableVar) { alpha.push_back( sin((lifePercent) * getPi<F32>()) * particle.alpha); } } } instancesCount = instancingTransformations.size(); if(instancesCount != 0) { aabb = Aabb(aabbmin - particle.size, aabbmax + particle.size); } else { aabb = Aabb(Vec3(0.0), Vec3(0.01)); } spatialMarkUpdated(); if(alphaRenderableVar) { alphaRenderableVar->setValues(&alpha[0], alpha.size()); } // // Emit new particles // if(timeLeftForNextEmission <= 0.0) { U particlesCount = 0; // How many particles I am allowed to emmit for(ParticleBase* pp : particles) { ParticleBase& p = *pp; if(!p.isDead()) { // its alive so skip it continue; } p.revive(*this, prevUpdateTime, crntTime); // do the rest ++particlesCount; if(particlesCount >= particlesPerEmittion) { break; } } // end for all particles timeLeftForNextEmission = emissionPeriod; } // end if can emit else { timeLeftForNextEmission -= crntTime - prevUpdateTime; } } } // end namespace anki <|endoftext|>
<commit_before>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical Ltd. * * 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 (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 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 <getopt.h> #include <csignal> #include <gtest/gtest.h> #include "xorg/gtest/xorg-gtest-environment.h" #include "defines.h" namespace { int help = false; int no_dummy_server = false; int xorg_conf_specified = false; int xorg_display_specified = false; int xorg_logfile_specified = false; int server_specified = false; const struct option longopts[] = { { "help", no_argument, &help, true, }, { "no-dummy-server", no_argument, &no_dummy_server, true, }, { "xorg-conf", required_argument, &xorg_conf_specified, true, }, { "xorg-display", required_argument, &xorg_display_specified, true, }, { "xorg-logfile", required_argument, &xorg_logfile_specified, true, }, { "server", required_argument, &server_specified, true, }, { NULL, 0, NULL, 0 } }; } // namespace xorg::testing::Environment* environment = NULL; static void signal_handler(int signum) { if (environment) environment->Kill(); /* This will call the default handler because we used SA_RESETHAND */ raise(signum); } static void setup_signal_handlers() { static const int signals[] = { SIGHUP, SIGTERM, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, SIGBUS, SIGPOLL, SIGPROF, SIGSYS, SIGTRAP, SIGVTALRM, SIGXCPU, SIGXFSZ, SIGIOT, SIGSTKFLT, SIGIO, SIGPWR, SIGUNUSED, }; struct sigaction action; action.sa_handler = signal_handler; sigemptyset(&action.sa_mask); action.sa_flags = SA_RESETHAND; for (unsigned i = 0; i < sizeof(signals) / sizeof(signals[0]); ++i) if (sigaction(signals[i], &action, NULL)) std::cerr << "Warning: Failed to set signal handler for signal " << signals[i] << "\n"; } static int usage(int exitcode) { std::cout << "\nAdditional options:\n"; std::cout << " --no-dummy-server: Use the currently running X server " "for testing\n"; std::cout << " --xorg-conf: Path to xorg configuration file\n"; std::cout << " --server: Path to X server executable\n"; std::cout << " --xorg-display: xorg display port\n"; std::cout << " --xorg-logfile: xorg logfile filename. See -logfile in \"man Xorg\".\n" " Its default value is " DEFAULT_XORG_LOGFILE ".\n"; return exitcode; } int main(int argc, char *argv[]) { std::string xorg_conf_path; std::string xorg_log_file_path; int xorg_display = -1; std::string server; setup_signal_handlers(); testing::InitGoogleTest(&argc, argv); /* Reset getopt state */ optind = 0; while (true) { int ret; int index; ret = getopt_long(argc, argv, "", longopts, &index); if (ret == -1) break; if (ret == '?') exit(-1); switch (index) { case 2: xorg_conf_path = optarg; break; case 3: xorg_display = atoi(optarg); break; case 4: xorg_log_file_path = optarg; break; case 5: server = optarg; break; default: break; } } if (help) return usage(-1); if (!no_dummy_server) { environment = new xorg::testing::Environment; if (xorg_conf_specified) environment->SetConfigFile(xorg_conf_path); if (server_specified) environment->SetServerPath(server); if (xorg_display_specified) environment->SetDisplayNumber(xorg_display); if (xorg_logfile_specified) environment->SetLogFile(xorg_log_file_path); testing::AddGlobalTestEnvironment(environment); } return RUN_ALL_TESTS(); } <commit_msg>xorg-gtest-main: fix trailing whitespace<commit_after>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical Ltd. * * 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 (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 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 <getopt.h> #include <csignal> #include <gtest/gtest.h> #include "xorg/gtest/xorg-gtest-environment.h" #include "defines.h" namespace { int help = false; int no_dummy_server = false; int xorg_conf_specified = false; int xorg_display_specified = false; int xorg_logfile_specified = false; int server_specified = false; const struct option longopts[] = { { "help", no_argument, &help, true, }, { "no-dummy-server", no_argument, &no_dummy_server, true, }, { "xorg-conf", required_argument, &xorg_conf_specified, true, }, { "xorg-display", required_argument, &xorg_display_specified, true, }, { "xorg-logfile", required_argument, &xorg_logfile_specified, true, }, { "server", required_argument, &server_specified, true, }, { NULL, 0, NULL, 0 } }; } // namespace xorg::testing::Environment* environment = NULL; static void signal_handler(int signum) { if (environment) environment->Kill(); /* This will call the default handler because we used SA_RESETHAND */ raise(signum); } static void setup_signal_handlers() { static const int signals[] = { SIGHUP, SIGTERM, SIGQUIT, SIGILL, SIGABRT, SIGFPE, SIGSEGV, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, SIGBUS, SIGPOLL, SIGPROF, SIGSYS, SIGTRAP, SIGVTALRM, SIGXCPU, SIGXFSZ, SIGIOT, SIGSTKFLT, SIGIO, SIGPWR, SIGUNUSED, }; struct sigaction action; action.sa_handler = signal_handler; sigemptyset(&action.sa_mask); action.sa_flags = SA_RESETHAND; for (unsigned i = 0; i < sizeof(signals) / sizeof(signals[0]); ++i) if (sigaction(signals[i], &action, NULL)) std::cerr << "Warning: Failed to set signal handler for signal " << signals[i] << "\n"; } static int usage(int exitcode) { std::cout << "\nAdditional options:\n"; std::cout << " --no-dummy-server: Use the currently running X server " "for testing\n"; std::cout << " --xorg-conf: Path to xorg configuration file\n"; std::cout << " --server: Path to X server executable\n"; std::cout << " --xorg-display: xorg display port\n"; std::cout << " --xorg-logfile: xorg logfile filename. See -logfile in \"man Xorg\".\n" " Its default value is " DEFAULT_XORG_LOGFILE ".\n"; return exitcode; } int main(int argc, char *argv[]) { std::string xorg_conf_path; std::string xorg_log_file_path; int xorg_display = -1; std::string server; setup_signal_handlers(); testing::InitGoogleTest(&argc, argv); /* Reset getopt state */ optind = 0; while (true) { int ret; int index; ret = getopt_long(argc, argv, "", longopts, &index); if (ret == -1) break; if (ret == '?') exit(-1); switch (index) { case 2: xorg_conf_path = optarg; break; case 3: xorg_display = atoi(optarg); break; case 4: xorg_log_file_path = optarg; break; case 5: server = optarg; break; default: break; } } if (help) return usage(-1); if (!no_dummy_server) { environment = new xorg::testing::Environment; if (xorg_conf_specified) environment->SetConfigFile(xorg_conf_path); if (server_specified) environment->SetServerPath(server); if (xorg_display_specified) environment->SetDisplayNumber(xorg_display); if (xorg_logfile_specified) environment->SetLogFile(xorg_log_file_path); testing::AddGlobalTestEnvironment(environment); } return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/** @file traffic_ctl @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "traffic_ctl.h" #include "ts/I_Layout.h" #include "I_RecProcess.h" #include "RecordsConfig.h" #include "ts/runroot.h" AppVersionInfo CtrlVersionInfo; const char * CtrlMgmtRecord::name() const { return this->ele->rec_name; } TSRecordT CtrlMgmtRecord::type() const { return this->ele->rec_type; } int CtrlMgmtRecord::rclass() const { return this->ele->rec_class; } int64_t CtrlMgmtRecord::as_int() const { switch (this->ele->rec_type) { case TS_REC_INT: return this->ele->valueT.int_val; case TS_REC_COUNTER: return this->ele->valueT.counter_val; default: return 0; } } TSMgmtError CtrlMgmtRecord::fetch(const char *name) { return TSRecordGet(name, this->ele); } TSMgmtError CtrlMgmtRecordList::match(const char *name) { return TSRecordGetMatchMlt(name, this->list); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(const CtrlMgmtRecord &rec) { this->init(rec.ele->rec_type, rec.ele->valueT); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(const TSRecordEle *ele) { this->init(ele->rec_type, ele->valueT); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(TSRecordT _t, TSRecordValueT _v) { this->init(_t, _v); } void CtrlMgmtRecordValue::init(TSRecordT _t, TSRecordValueT _v) { this->rec_type = _t; switch (this->rec_type) { case TS_REC_INT: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.int_val); break; case TS_REC_COUNTER: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.counter_val); break; case TS_REC_FLOAT: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%f", _v.float_val); break; case TS_REC_STRING: if (strcmp(_v.string_val, "") == 0) { this->fmt.str = "\"\""; } else { this->fmt.str = _v.string_val; } break; default: rec_type = TS_REC_STRING; this->fmt.str = "(invalid)"; } } const char * CtrlMgmtRecordValue::c_str() const { switch (this->rec_type) { case TS_REC_STRING: return this->fmt.str; default: return this->fmt.nbuf; } } void CtrlMgmtError(TSMgmtError err, const char *fmt, ...) { ats_scoped_str msg(TSGetErrorMessage(err)); if (fmt) { va_list ap; fprintf(stderr, "%s: ", program_name); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, ": %s\n", (const char *)msg); } else { fprintf(stderr, "%s: %s\n", program_name, (const char *)msg); } } int CtrlSubcommandUsage(const char *name, const subcommand *cmds, unsigned ncmds, const ArgumentDescription *desc, unsigned ndesc) { const char *opt = ndesc ? "[OPTIONS]" : ""; const char *sep = (ndesc && name) ? " " : ""; fprintf(stderr, "Usage: traffic_ctl %s%s%s CMD [ARGS ...]\n\nSubcommands:\n", name ? name : "", sep, opt); for (unsigned i = 0; i < ncmds; ++i) { fprintf(stderr, " %-16s%s\n", cmds[i].name, cmds[i].help); } if (ndesc) { usage(desc, ndesc, "\nOptions:"); } return CTRL_EX_USAGE; } int CtrlCommandUsage(const char *msg, const ArgumentDescription *desc, unsigned ndesc) { fprintf(stderr, "Usage: traffic_ctl %s\n", msg); if (ndesc) { usage(desc, ndesc, "\nOptions:"); } return CTRL_EX_USAGE; } bool CtrlProcessArguments(int /* argc */, const char **argv, const ArgumentDescription *desc, unsigned ndesc) { n_file_arguments = 0; return process_args_ex(&CtrlVersionInfo, desc, ndesc, argv); } int CtrlUnimplementedCommand(unsigned /* argc */, const char **argv) { CtrlDebug("the '%s' command is not implemented", *argv); return CTRL_EX_UNIMPLEMENTED; } int CtrlGenericSubcommand(const char *name, const subcommand *cmds, unsigned ncmds, unsigned argc, const char **argv) { CtrlCommandLine cmdline; // Process command line arguments and dump into variables if (!CtrlProcessArguments(argc, argv, nullptr, 0) || n_file_arguments < 1) { return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0); } cmdline.init(n_file_arguments, file_arguments); for (unsigned i = 0; i < ncmds; ++i) { if (strcmp(file_arguments[0], cmds[i].name) == 0) { return cmds[i].handler(cmdline.argc(), cmdline.argv()); } } return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0); } int main(int argc, const char **argv) { CtrlCommandLine cmdline; int debug = false; CtrlVersionInfo.setup(PACKAGE_NAME, "traffic_ctl", PACKAGE_VERSION, __DATE__, __TIME__, BUILD_MACHINE, BUILD_PERSON, ""); program_name = CtrlVersionInfo.AppStr; ArgumentDescription argument_descriptions[] = { {"debug", '-', "Enable debugging output", "F", &debug, nullptr, nullptr}, HELP_ARGUMENT_DESCRIPTION(), VERSION_ARGUMENT_DESCRIPTION(), RUNROOT_ARGUMENT_DESCRIPTION(), }; const subcommand commands[] = { {subcommand_alarm, "alarm", "Manipulate alarms"}, {subcommand_config, "config", "Manipulate configuration records"}, {subcommand_metric, "metric", "Manipulate performance metrics"}, {subcommand_server, "server", "Stop, restart and examine the server"}, {subcommand_storage, "storage", "Manipulate cache storage"}, {subcommand_plugin, "plugin", "Interact with plugins"}, }; BaseLogFile *base_log_file = new BaseLogFile("stderr"); diags = new Diags(program_name, "" /* tags */, "" /* actions */, base_log_file); // Process command line arguments and dump into variables if (!CtrlProcessArguments(argc, argv, argument_descriptions, countof(argument_descriptions))) { return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } if (debug) { diags->activate_taglist("traffic_ctl", DiagsTagType_Debug); diags->config.enabled[DiagsTagType_Debug] = true; diags->show_location = SHOW_LOCATION_DEBUG; } if (n_file_arguments < 1) { return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } runroot_handler(argv); Layout::create(); RecProcessInit(RECM_STAND_ALONE, diags); LibRecordsConfigInit(); ats_scoped_str rundir(RecConfigReadRuntimeDir()); // Make a best effort to connect the control socket. If it turns out we are just displaying help or something then it // doesn't matter that we failed. If we end up performing some operation then that operation will fail and display the // error. TSInit(rundir, static_cast<TSInitOptionT>(TS_MGMT_OPT_NO_EVENTS | TS_MGMT_OPT_NO_SOCK_TESTS)); for (unsigned i = 0; i < countof(commands); ++i) { if (strcmp(file_arguments[0], commands[i].name) == 0) { CtrlCommandLine cmdline; cmdline.init(n_file_arguments, file_arguments); return commands[i].handler(cmdline.argc(), cmdline.argv()); } } // Done with the mgmt API. TSTerminate(); return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } <commit_msg>add custom --help and -h flag to traffic_ctl<commit_after>/** @file traffic_ctl @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "traffic_ctl.h" #include "I_RecProcess.h" #include "RecordsConfig.h" #include "ts/I_Layout.h" #include "ts/runroot.h" AppVersionInfo CtrlVersionInfo; const char *CtrlMgmtRecord::name() const { return this->ele->rec_name; } TSRecordT CtrlMgmtRecord::type() const { return this->ele->rec_type; } int CtrlMgmtRecord::rclass() const { return this->ele->rec_class; } int64_t CtrlMgmtRecord::as_int() const { switch (this->ele->rec_type) { case TS_REC_INT: return this->ele->valueT.int_val; case TS_REC_COUNTER: return this->ele->valueT.counter_val; default: return 0; } } TSMgmtError CtrlMgmtRecord::fetch(const char *name) { return TSRecordGet(name, this->ele); } TSMgmtError CtrlMgmtRecordList::match(const char *name) { return TSRecordGetMatchMlt(name, this->list); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(const CtrlMgmtRecord &rec) { this->init(rec.ele->rec_type, rec.ele->valueT); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(const TSRecordEle *ele) { this->init(ele->rec_type, ele->valueT); } CtrlMgmtRecordValue::CtrlMgmtRecordValue(TSRecordT _t, TSRecordValueT _v) { this->init(_t, _v); } void CtrlMgmtRecordValue::init(TSRecordT _t, TSRecordValueT _v) { this->rec_type = _t; switch (this->rec_type) { case TS_REC_INT: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.int_val); break; case TS_REC_COUNTER: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%" PRId64, _v.counter_val); break; case TS_REC_FLOAT: snprintf(this->fmt.nbuf, sizeof(this->fmt.nbuf), "%f", _v.float_val); break; case TS_REC_STRING: if (strcmp(_v.string_val, "") == 0) { this->fmt.str = "\"\""; } else { this->fmt.str = _v.string_val; } break; default: rec_type = TS_REC_STRING; this->fmt.str = "(invalid)"; } } const char *CtrlMgmtRecordValue::c_str() const { switch (this->rec_type) { case TS_REC_STRING: return this->fmt.str; default: return this->fmt.nbuf; } } void CtrlMgmtError(TSMgmtError err, const char *fmt, ...) { ats_scoped_str msg(TSGetErrorMessage(err)); if (fmt) { va_list ap; fprintf(stderr, "%s: ", program_name); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, ": %s\n", (const char *)msg); } else { fprintf(stderr, "%s: %s\n", program_name, (const char *)msg); } } int CtrlSubcommandUsage(const char *name, const subcommand *cmds, unsigned ncmds, const ArgumentDescription *desc, unsigned ndesc) { const char *opt = ndesc ? "[OPTIONS]" : ""; const char *sep = (ndesc && name) ? " " : ""; fprintf(stderr, "Usage: traffic_ctl %s%s%s CMD [ARGS ...]\n\nSubcommands:\n", name ? name : "", sep, opt); for (unsigned i = 0; i < ncmds; ++i) { fprintf(stderr, " %-16s%s\n", cmds[i].name, cmds[i].help); } if (ndesc) { usage(desc, ndesc, "\nOptions:"); } return CTRL_EX_USAGE; } int CtrlCommandUsage(const char *msg, const ArgumentDescription *desc, unsigned ndesc) { fprintf(stderr, "Usage: traffic_ctl %s\n", msg); if (ndesc) { usage(desc, ndesc, "\nOptions:"); } return CTRL_EX_USAGE; } bool CtrlProcessArguments(int /* argc */, const char **argv, const ArgumentDescription *desc, unsigned ndesc) { n_file_arguments = 0; return process_args_ex(&CtrlVersionInfo, desc, ndesc, argv); } int CtrlUnimplementedCommand(unsigned /* argc */, const char **argv) { CtrlDebug("the '%s' command is not implemented", *argv); return CTRL_EX_UNIMPLEMENTED; } int CtrlGenericSubcommand(const char *name, const subcommand *cmds, unsigned ncmds, unsigned argc, const char **argv) { CtrlCommandLine cmdline; // Process command line arguments and dump into variables if (!CtrlProcessArguments(argc, argv, nullptr, 0) || n_file_arguments < 1) { return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0); } cmdline.init(n_file_arguments, file_arguments); for (unsigned i = 0; i < ncmds; ++i) { if (strcmp(file_arguments[0], cmds[i].name) == 0) { return cmds[i].handler(cmdline.argc(), cmdline.argv()); } } return CtrlSubcommandUsage(name, cmds, ncmds, nullptr, 0); } static const subcommand commands[] = { {subcommand_alarm, "alarm", "Manipulate alarms"}, {subcommand_config, "config", "Manipulate configuration records"}, {subcommand_metric, "metric", "Manipulate performance metrics"}, {subcommand_server, "server", "Stop, restart and examine the server"}, {subcommand_storage, "storage", "Manipulate cache storage"}, {subcommand_plugin, "plugin", "Interact with plugins"}, }; int main(int argc, const char **argv) { CtrlCommandLine cmdline; int debug = false; CtrlVersionInfo.setup(PACKAGE_NAME, "traffic_ctl", PACKAGE_VERSION, __DATE__, __TIME__, BUILD_MACHINE, BUILD_PERSON, ""); program_name = CtrlVersionInfo.AppStr; ArgumentDescription argument_descriptions[] = { {"debug", '-', "Enable debugging output", "F", &debug, nullptr, nullptr}, {"help", 'h', "Print usage information", nullptr, nullptr, nullptr, [](const ArgumentDescription *args, unsigned nargs, const char *arg_unused) { CtrlSubcommandUsage(nullptr, commands, countof(commands), args, nargs); }}, VERSION_ARGUMENT_DESCRIPTION(), RUNROOT_ARGUMENT_DESCRIPTION(), }; BaseLogFile *base_log_file = new BaseLogFile("stderr"); diags = new Diags(program_name, "" /* tags */, "" /* actions */, base_log_file); // Process command line arguments and dump into variables if (!CtrlProcessArguments(argc, argv, argument_descriptions, countof(argument_descriptions))) { return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } if (debug) { diags->activate_taglist("traffic_ctl", DiagsTagType_Debug); diags->config.enabled[DiagsTagType_Debug] = true; diags->show_location = SHOW_LOCATION_DEBUG; } if (n_file_arguments < 1) { return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } runroot_handler(argv); Layout::create(); RecProcessInit(RECM_STAND_ALONE, diags); LibRecordsConfigInit(); ats_scoped_str rundir(RecConfigReadRuntimeDir()); // Make a best effort to connect the control socket. If it turns out we are // just displaying help or something then it // doesn't matter that we failed. If we end up performing some operation then // that operation will fail and display the // error. TSInit(rundir, static_cast<TSInitOptionT>(TS_MGMT_OPT_NO_EVENTS | TS_MGMT_OPT_NO_SOCK_TESTS)); for (unsigned i = 0; i < countof(commands); ++i) { if (strcmp(file_arguments[0], commands[i].name) == 0) { CtrlCommandLine cmdline; cmdline.init(n_file_arguments, file_arguments); return commands[i].handler(cmdline.argc(), cmdline.argv()); } } // Done with the mgmt API. TSTerminate(); return CtrlSubcommandUsage(nullptr, commands, countof(commands), argument_descriptions, countof(argument_descriptions)); } <|endoftext|>
<commit_before>/* Sirikata Utilities -- Sirikata Synchronization Utilities * LockFreeQueue.hpp * * Copyright (c) 2008, Daniel Reiter Horn * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sirikata nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SIRIKATA_LOCK_FREE_QUEUE_HPP_ #define _SIRIKATA_LOCK_FREE_QUEUE_HPP_ #ifdef __APPLE__ #include <libkern/OSAtomic.h> #endif /// LockFreeQueue.hpp namespace Sirikata { /// A queue of any type that has thread-safe push() and pop() functions. template <typename T> class LockFreeQueue { private: struct Node { volatile Node * mNext; T mContent; Node() :mNext(NULL), mContent() { } }; static bool compare_and_swap(volatile Node*volatile *target, volatile Node *comperand, volatile Node * exchange){ #ifdef _WIN32 return InterlockedCompareExchangePointer(target, exchange, comperand)==comperand; #else #ifdef __APPLE__ if (sizeof(exchange)==4) { return OSAtomicCompareAndSwap32((int32_t)comperand, (int32_t)exchange, (int32_t*)target); }else { return OSAtomicCompareAndSwap64((int64_t)comperand, (int64_t)exchange, (int64_t*)target); } #else return __sync_bool_compare_and_swap (target, comperand, exchange); #endif #endif } class FreeNodePool { volatile Node *mHead; public: FreeNodePool() { mHead = new Node(); } Node* allocate() { volatile Node* node=NULL; do { node = mHead->mNext; if (node == NULL) return new Node();//FIXME should probably be aligned to size(Node) bytes } while (!compare_and_swap(&mHead->mNext, node, node->mNext)); Node * return_node=(Node*)node;//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less return_node->mNext = NULL; return_node->mContent=T(); return return_node; } void release(Node *node) { node->mContent = T(); do { node->mNext = mHead->mNext; } while (!compare_and_swap(&mHead->mNext, node->mNext, node)); } } mFreeNodePool; volatile Node *mHead; volatile Node *mTail; public: LockFreeQueue() { mHead = mFreeNodePool.allocate(); mTail = mHead; } class NodeIterator { private: // Noncopyable NodeIterator(const NodeIterator &other); void operator=(const NodeIterator &other); Node *mLastReturned; Node *mCurrent; FreeNodePool *mFreePool; public: NodeIterator(LockFreeQueue<T> &queue) : mLastReturned(queue.fork()), mCurrent(const_cast<Node*>(mLastReturned->mNext)), mFreePool(&queue.mFreeNodePool) { } ~NodeIterator() { if (mLastReturned) { mFreePool->release(mLastReturned); } while (mCurrent) { mFreePool->release(mCurrent); mCurrent = const_cast<Node*>(mCurrent->mNext); } } T *next() { if (mLastReturned) { mFreePool->release(mLastReturned); } mLastReturned = mCurrent; if (mCurrent) { mCurrent = const_cast<Node*>(mCurrent->mNext); return &mLastReturned->mContent; } else { return NULL; } } }; private: friend class NodeIterator; Node *fork() { volatile Node *newHead = mFreeNodePool.allocate(); volatile Node *oldHead = mHead; // Acquire "lock" on head, for multiple people fork()ing at once. { while (oldHead == NULL || !compare_and_swap(&mHead, oldHead, NULL)) { oldHead = mHead; } } { volatile Node *oldTail = mTail; while (!compare_and_swap(&mTail, oldTail, newHead)) { oldTail = mTail; } } mHead = newHead; return const_cast<Node*>(oldHead); } public: /** * Pushes value onto the queue * * @param value Will be copied and placed onto the end of the queue. */ void push(const T &value) { volatile Node* formerTail = NULL; volatile Node* formerTailNext=NULL; Node* newerNode = mFreeNodePool.allocate(); newerNode->mContent = value; volatile Node*newNode=newerNode; bool successfulAddNode = false; while (!successfulAddNode) { formerTail = mTail; formerTailNext = formerTail->mNext; if (mTail == formerTail) { if (formerTailNext == NULL) successfulAddNode = compare_and_swap(&mTail->mNext, NULL, newNode); else compare_and_swap(&mTail, formerTail, formerTailNext); } } compare_and_swap(&mTail, formerTail, newNode); } /** * Pops the front value from the queue and places it in value. * * @param value Will have the T at the front of the queue copied into it. * @returns whether value was changed (if the queue had at least one item). */ bool pop(T &value) { volatile Node* formerHead = NULL; bool headAlreadyAdvanced = false; while (!headAlreadyAdvanced) { formerHead = mHead; if (formerHead == NULL) { // fork() function is operating on mTail. continue; } volatile Node* formerHeadNext = formerHead->mNext; volatile Node*formerTail = mTail; if (formerHead == mHead) { if (formerHead == formerTail) { if (formerHeadNext == NULL) { value=T(); return false; } compare_and_swap(&mTail, formerTail, formerHeadNext); } else { value = ((Node*)formerHeadNext)->mContent;//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less headAlreadyAdvanced = compare_and_swap(&mHead, formerHead, formerHeadNext); } } } mFreeNodePool.release((Node*)formerHead);//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less return true; } bool probablyEmpty() { volatile Node* formerHead = mHead; if (formerHead) { if (formerHead->mNext) { // fork() function is operating on mTail. return false; } } return true; } }; } #endif //_SIRIKATA_LOCK_FREE_QUEUE_HPP_ <commit_msg>corrected types of arguments to the ExchangeCompare instruction<commit_after>/* Sirikata Utilities -- Sirikata Synchronization Utilities * LockFreeQueue.hpp * * Copyright (c) 2008, Daniel Reiter Horn * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sirikata nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _SIRIKATA_LOCK_FREE_QUEUE_HPP_ #define _SIRIKATA_LOCK_FREE_QUEUE_HPP_ #ifdef __APPLE__ #include <libkern/OSAtomic.h> #endif /// LockFreeQueue.hpp namespace Sirikata { /// A queue of any type that has thread-safe push() and pop() functions. template <typename T> class LockFreeQueue { private: struct Node { volatile Node * mNext; T mContent; Node() :mNext(NULL), mContent() { } }; static bool compare_and_swap(volatile Node*volatile *target, volatile Node *comperand, volatile Node * exchange){ #ifdef _WIN32 return InterlockedCompareExchangePointer((volatile PVOID*)target, (volatile PVOID)exchange, (volatile PVOID)comperand)==comperand; #else #ifdef __APPLE__ if (sizeof(exchange)==4) { return OSAtomicCompareAndSwap32((int32_t)comperand, (int32_t)exchange, (int32_t*)target); }else { return OSAtomicCompareAndSwap64((int64_t)comperand, (int64_t)exchange, (int64_t*)target); } #else return __sync_bool_compare_and_swap (target, comperand, exchange); #endif #endif } class FreeNodePool { volatile Node *mHead; public: FreeNodePool() { mHead = new Node(); } Node* allocate() { volatile Node* node=NULL; do { node = mHead->mNext; if (node == NULL) return new Node();//FIXME should probably be aligned to size(Node) bytes } while (!compare_and_swap(&mHead->mNext, node, node->mNext)); Node * return_node=(Node*)node;//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less return_node->mNext = NULL; return_node->mContent=T(); return return_node; } void release(Node *node) { node->mContent = T(); do { node->mNext = mHead->mNext; } while (!compare_and_swap(&mHead->mNext, node->mNext, node)); } } mFreeNodePool; volatile Node *mHead; volatile Node *mTail; public: LockFreeQueue() { mHead = mFreeNodePool.allocate(); mTail = mHead; } class NodeIterator { private: // Noncopyable NodeIterator(const NodeIterator &other); void operator=(const NodeIterator &other); Node *mLastReturned; Node *mCurrent; FreeNodePool *mFreePool; public: NodeIterator(LockFreeQueue<T> &queue) : mLastReturned(queue.fork()), mCurrent(const_cast<Node*>(mLastReturned->mNext)), mFreePool(&queue.mFreeNodePool) { } ~NodeIterator() { if (mLastReturned) { mFreePool->release(mLastReturned); } while (mCurrent) { mFreePool->release(mCurrent); mCurrent = const_cast<Node*>(mCurrent->mNext); } } T *next() { if (mLastReturned) { mFreePool->release(mLastReturned); } mLastReturned = mCurrent; if (mCurrent) { mCurrent = const_cast<Node*>(mCurrent->mNext); return &mLastReturned->mContent; } else { return NULL; } } }; private: friend class NodeIterator; Node *fork() { volatile Node *newHead = mFreeNodePool.allocate(); volatile Node *oldHead = mHead; // Acquire "lock" on head, for multiple people fork()ing at once. { while (oldHead == NULL || !compare_and_swap(&mHead, oldHead, NULL)) { oldHead = mHead; } } { volatile Node *oldTail = mTail; while (!compare_and_swap(&mTail, oldTail, newHead)) { oldTail = mTail; } } mHead = newHead; return const_cast<Node*>(oldHead); } public: /** * Pushes value onto the queue * * @param value Will be copied and placed onto the end of the queue. */ void push(const T &value) { volatile Node* formerTail = NULL; volatile Node* formerTailNext=NULL; Node* newerNode = mFreeNodePool.allocate(); newerNode->mContent = value; volatile Node*newNode=newerNode; bool successfulAddNode = false; while (!successfulAddNode) { formerTail = mTail; formerTailNext = formerTail->mNext; if (mTail == formerTail) { if (formerTailNext == NULL) successfulAddNode = compare_and_swap(&mTail->mNext, NULL, newNode); else compare_and_swap(&mTail, formerTail, formerTailNext); } } compare_and_swap(&mTail, formerTail, newNode); } /** * Pops the front value from the queue and places it in value. * * @param value Will have the T at the front of the queue copied into it. * @returns whether value was changed (if the queue had at least one item). */ bool pop(T &value) { volatile Node* formerHead = NULL; bool headAlreadyAdvanced = false; while (!headAlreadyAdvanced) { formerHead = mHead; if (formerHead == NULL) { // fork() function is operating on mTail. continue; } volatile Node* formerHeadNext = formerHead->mNext; volatile Node*formerTail = mTail; if (formerHead == mHead) { if (formerHead == formerTail) { if (formerHeadNext == NULL) { value=T(); return false; } compare_and_swap(&mTail, formerTail, formerHeadNext); } else { value = ((Node*)formerHeadNext)->mContent;//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less headAlreadyAdvanced = compare_and_swap(&mHead, formerHead, formerHeadNext); } } } mFreeNodePool.release((Node*)formerHead);//FIXME volatile cast only allowed if mContent is primitive type of pointer size or less return true; } bool probablyEmpty() { volatile Node* formerHead = mHead; if (formerHead) { if (formerHead->mNext) { // fork() function is operating on mTail. return false; } } return true; } }; } #endif //_SIRIKATA_LOCK_FREE_QUEUE_HPP_ <|endoftext|>
<commit_before>/* Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com> See license text in LICENSE file */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <getopt.h> #include <mysql.h> #include <map> #include <string> #include <cstdio> #include <cstdlib> #include <ctime> MYSQL *conn; std::map<std::string, std::string> cfg; // // Utility void // void do_benchmark(void (*f)(int), const char *title, int count = 0) { clock_t start = 0, finish = 0; double delta = 0; start = clock(); f(count); finish = clock(); delta = static_cast<double>(finish-start)/CLOCKS_PER_SEC; if (count > 0) { printf("%s %.2lfs (%ld/s)\n", title, delta, static_cast<long int>(static_cast<double>(count)/delta)); } else { printf("%s %.2lfs\n", title, delta); } } // // Benchmarking functions // /*void do_benchmark_select() { rows = array(); r = mysql_query(conn, "SELECT * FROM ".cfg["test_table"].";"); while(row = mysql_fetch_array(r)) { rows[] = row; } }*/ void do_benchmark_inserts(int count) { int i = 0; for (i = 0; i < count; i++) { mysql_query(conn, cfg["insert_query"].c_str()); } } void do_benchmark_reconnect(int count) { int i = 0; for (i = 0; i < count; i++) { mysql_close(conn); conn = mysql_init(NULL); if (!conn) { exit(1); } if (!mysql_real_connect(conn, cfg["host"].c_str(), cfg["user"].c_str(), cfg["password"].length() ? cfg["password"].c_str() : NULL, cfg["database"].c_str(), 0, NULL, 0)) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); mysql_close(conn); exit(1); } } } void do_benchmark_escape_string(int count) { int i = 0; char *escaped_string; for (i = 0; i < count; i++) { escaped_string = new char[2*cfg["string_to_escape"].length() + 1]; mysql_real_escape_string(conn, escaped_string, cfg["string_to_escape"].c_str(), cfg["string_to_escape"].length()); delete[] escaped_string; } } void do_benchmark_initialization(int count) { conn = mysql_init(NULL); if (!conn) { exit(1); } if (!mysql_real_connect(conn, cfg["host"].c_str(), cfg["user"].c_str(), cfg["password"].length() ? cfg["password"].c_str() : NULL, cfg["database"].c_str(), 0, NULL, 0)) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); mysql_close(conn); exit(1); } char drop_query[1024]; sprintf(drop_query, "DROP TABLE IF EXISTS %s;", cfg["test_table"].c_str()); mysql_query(conn, drop_query); mysql_query(conn, cfg["create_table_query"].c_str()); } int main(int argc, char *argv[]) { int c = 0; opterr = 0; static struct option long_options[] = { {"host", required_argument, NULL, 0}, {"user", required_argument, NULL, 0}, {"password", optional_argument, NULL, 0}, {"database", required_argument, NULL, 0}, {"test_table", required_argument, NULL, 0}, {"create_table_query", required_argument, NULL, 0}, {"escape_count", required_argument, NULL, 0}, {"string_to_escape", required_argument, NULL, 0}, {"reconnect_count", required_argument, NULL, 0}, {"insert_rows_count", required_argument, NULL, 0}, {"insert_query", required_argument, NULL, 0}, {"delay_before_select", required_argument, NULL, 0} }; int option_index = 0; while ( (c = getopt_long(argc, argv, "", long_options, &option_index)) != -1 ) { switch (c) { case 0: if (optarg) { cfg[long_options[option_index].name] = optarg; } else { cfg[long_options[option_index].name] = ""; } break; default: break; } } char title[128]; int count = 0; // Initialize connection and database sprintf(title, "**** Benchmark initialization time is"); count = 0; do_benchmark(do_benchmark_initialization, title, count); // Benchmark 1: Escapes sprintf(title, "**** %s escapes in", cfg["escape_count"].c_str()); count = atoi(cfg["escape_count"].c_str()); do_benchmark(do_benchmark_escape_string, title, count); // Benchmark 2: Reconnects sprintf(title, "**** %s sync reconnects in", cfg["reconnect_count"].c_str()); count = atoi(cfg["reconnect_count"].c_str()); do_benchmark(do_benchmark_reconnect, title, count); // Benchmark 3: inserts sprintf(title, "**** %s sync insertions in", cfg["insert_rows_count"].c_str()); count = atoi(cfg["insert_rows_count"].c_str()); do_benchmark(do_benchmark_inserts, title, count); sleep(atoi(cfg["delay_before_select"].c_str())/1000); // _micro_seconds // Benchmark 3: selects /*sprintf(title, "**** %s rows sync selected in", cfg["insert_rows_count"].c_str()); count = atoi(cfg["insert_rows_count"].c_str()); do_benchmark(do_benchmark_select, title, count);*/ mysql_close(conn); } <commit_msg>Make C++ benchmark faster and more similar to V8 structure<commit_after>/* Copyright (C) 2010, Oleg Efimov <efimovov@gmail.com> See license text in LICENSE file */ #ifndef _GNU_SOURCE # define _GNU_SOURCE #endif #include <getopt.h> #include <mysql.h> #include <map> #include <string> #include <cstdio> #include <cstdlib> #include <ctime> MYSQL *conn; std::map<std::string, std::string> cfg; // // Utility void // void do_benchmark(void (*f)(int), const char *title, int count = 0) { clock_t start = 0, finish = 0; double delta = 0; start = clock(); f(count); finish = clock(); delta = static_cast<double>(finish-start)/CLOCKS_PER_SEC; if (count > 0) { printf("%s %.2lfs (%ld/s)\n", title, delta, static_cast<long int>(static_cast<double>(count)/delta)); } else { printf("%s %.2lfs\n", title, delta); } } // // Benchmarking functions // /*void do_benchmark_select() { rows = array(); r = mysql_query(conn, "SELECT * FROM ".cfg["test_table"].";"); while(row = mysql_fetch_array(r)) { rows[] = row; } }*/ void do_benchmark_inserts(int count) { int i = 0; for (i = 0; i < count; i++) { mysql_query(conn, cfg["insert_query"].c_str()); } } void do_benchmark_reconnect(int count) { int i = 0; for (i = 0; i < count; i++) { mysql_close(conn); conn = mysql_init(NULL); if (!conn) { exit(1); } if (!mysql_real_connect(conn, cfg["host"].c_str(), cfg["user"].c_str(), cfg["password"].length() ? cfg["password"].c_str() : NULL, cfg["database"].c_str(), 0, NULL, 0)) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); mysql_close(conn); exit(1); } } } void do_benchmark_escape_string(int count) { int i = 0; char *escaped_string; const char *string_to_escape = cfg["string_to_escape"].c_str(); const int string_to_escape_len = cfg["string_to_escape"].length(); for (i = 0; i < count; i++) { escaped_string = new char[2*string_to_escape_len + 1]; mysql_real_escape_string(conn, escaped_string, string_to_escape, string_to_escape_len); delete[] escaped_string; } } void do_benchmark_initialization(int count) { conn = mysql_init(NULL); if (!conn) { exit(1); } if (!mysql_real_connect(conn, cfg["host"].c_str(), cfg["user"].c_str(), cfg["password"].length() ? cfg["password"].c_str() : NULL, cfg["database"].c_str(), 0, NULL, 0)) { printf("Error %d: %s\n", mysql_errno(conn), mysql_error(conn)); mysql_close(conn); exit(1); } char drop_query[1024]; sprintf(drop_query, "DROP TABLE IF EXISTS %s;", cfg["test_table"].c_str()); mysql_query(conn, drop_query); mysql_query(conn, cfg["create_table_query"].c_str()); } int main(int argc, char *argv[]) { int c = 0; opterr = 0; static struct option long_options[] = { {"host", required_argument, NULL, 0}, {"user", required_argument, NULL, 0}, {"password", optional_argument, NULL, 0}, {"database", required_argument, NULL, 0}, {"test_table", required_argument, NULL, 0}, {"create_table_query", required_argument, NULL, 0}, {"escape_count", required_argument, NULL, 0}, {"string_to_escape", required_argument, NULL, 0}, {"reconnect_count", required_argument, NULL, 0}, {"insert_rows_count", required_argument, NULL, 0}, {"insert_query", required_argument, NULL, 0}, {"delay_before_select", required_argument, NULL, 0} }; int option_index = 0; while ( (c = getopt_long(argc, argv, "", long_options, &option_index)) != -1 ) { switch (c) { case 0: if (optarg) { cfg[long_options[option_index].name] = optarg; } else { cfg[long_options[option_index].name] = ""; } break; default: break; } } char title[128]; int count = 0; // Initialize connection and database sprintf(title, "**** Benchmark initialization time is"); count = 0; do_benchmark(do_benchmark_initialization, title, count); // Benchmark 1: Escapes sprintf(title, "**** %s escapes in", cfg["escape_count"].c_str()); count = atoi(cfg["escape_count"].c_str()); do_benchmark(do_benchmark_escape_string, title, count); // Benchmark 2: Reconnects sprintf(title, "**** %s sync reconnects in", cfg["reconnect_count"].c_str()); count = atoi(cfg["reconnect_count"].c_str()); do_benchmark(do_benchmark_reconnect, title, count); // Benchmark 3: inserts sprintf(title, "**** %s sync insertions in", cfg["insert_rows_count"].c_str()); count = atoi(cfg["insert_rows_count"].c_str()); do_benchmark(do_benchmark_inserts, title, count); sleep(atoi(cfg["delay_before_select"].c_str())/1000); // _micro_seconds // Benchmark 3: selects /*sprintf(title, "**** %s rows sync selected in", cfg["insert_rows_count"].c_str()); count = atoi(cfg["insert_rows_count"].c_str()); do_benchmark(do_benchmark_select, title, count);*/ mysql_close(conn); } <|endoftext|>
<commit_before>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool verifyOnly = false; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { "verify-only", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:v", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'v': verifyOnly = true; break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty()) { cerr << "Must specify output file" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and re-writes that log file" << endl << " ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -o, --output=filename specify output file" << endl << " -v, --verify-only Skip writing output file, only verify that" << endl << " an already existing output file is the repaired" << endl << " version of the input." << endl << " -h, --help Shows some help text and exits." << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; zcm::LogFile* logVer = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) { if (logIn->good()) logIn->close(); delete logIn; } if (logOut) { if (logOut->good()) logOut->close(); delete logOut; } if (logVer) { if (logVer->good()) logVer->close(); delete logVer; } } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } if (!args.verifyOnly) { logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); timestamps.reserve(1e6); return true; } int run() { cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; timestamps.emplace_back(event->timestamp, offset); size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; cout << "Repairing log data" << endl; sort(timestamps.begin(), timestamps.end()); if (!args.verifyOnly) { cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Flushing to disk" << endl; logOut->close(); } cout << "Verifying output" << endl; logVer = new zcm::LogFile(args.outfile, "r"); if (!logVer->good()) { cerr << "Error: Failed to open output log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logVer->readNextEvent(); if (!event) break; if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; cerr << "Expected " << timestamps[i].first << " got " << event->timestamp << " (idx " << i << ")" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } if (i < timestamps.size()) { cerr << endl << "Error: output log was missing " << timestamps.size() - i << " events" << endl; } return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <commit_msg>better cli<commit_after>#include <algorithm> #include <atomic> #include <iostream> #include <limits> #include <utility> #include <vector> #include <getopt.h> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { string infile = ""; string outfile = ""; bool verify = false; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "output", required_argument, 0, 'o' }, { "verify", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "ho:v", long_opts, 0)) >= 0) { switch (c) { case 'o': outfile = string(optarg); break; case 'v': verify = true; break; case 'h': default: usage(); return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; usage(); return false; } infile = string(argv[optind]); if (outfile.empty() && !verify) { cerr << "Must specify output file" << endl; return false; } return true; } void usage() { cerr << "usage: zcm-log-repair [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and re-writes that log file" << endl << " ensuring that all events are stored in recv_utime order." << endl << " This is generally only required if the original log was captured" << endl << " using multiple zcm shards and the user requires a strict ordering" << endl << " of events in the log." << endl << "" << endl << "Options:" << endl << "" << endl << " -o, --output=filename specify output file" << endl << " -v, --verify verify input log is monotonic in timestamp" << endl << " -h, --help Shows some help text and exits." << endl << endl; } }; struct LogRepair { Args args; zcm::LogFile* logIn = nullptr; zcm::LogFile* logOut = nullptr; zcm::LogFile* logVer = nullptr; const zcm::LogEvent* event; off_t length; off_t offset; vector<pair<int64_t, off_t>> timestamps; size_t progress; LogRepair() { } ~LogRepair() { if (logIn) { if (logIn->good()) logIn->close(); delete logIn; } if (logOut) { if (logOut->good()) logOut->close(); delete logOut; } if (logVer) { if (logVer->good()) logVer->close(); delete logVer; } } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; logIn = new zcm::LogFile(args.infile, "r"); if (!logIn->good()) { cerr << "Error: Failed to open '" << args.infile << "'" << endl; return false; } if (!args.verify) { logOut = new zcm::LogFile(args.outfile, "w"); if (!logOut->good()) { cerr << "Error: Failed to create output log" << endl; return false; } } fseeko(logIn->getFilePtr(), 0, SEEK_END); length = ftello(logIn->getFilePtr()); fseeko(logIn->getFilePtr(), 0, SEEK_SET); timestamps.reserve(1e6); return true; } int run() { cout << "Reading log" << endl; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; offset = ftello(logIn->getFilePtr()); event = logIn->readNextEvent(); if (!event) break; if (args.verify && !timestamps.empty() && event->timestamp < timestamps.back().first) { cerr << endl << "Detected nonmonotonic timestamp at event " << timestamps.size() << endl; return 1; } timestamps.emplace_back(event->timestamp, offset); size_t p = (size_t)((100 * offset) / length); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Read " << timestamps.size() << " events" << endl; logIn->close(); if (args.verify) return 0; sort(timestamps.begin(), timestamps.end()); cout << "Writing new log" << endl; progress = 0; cout << progress << "%" << flush; for (size_t i = 0; i < timestamps.size(); ++i) { if (done) return 1; logOut->writeEvent(logIn->readEventAtOffset(timestamps[i].second)); size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } cout << endl << "Flushing to disk" << endl; logOut->close(); cout << "Verifying output" << endl; logVer = new zcm::LogFile(args.verify ? args.infile : args.outfile, "r"); if (!logVer->good()) { cerr << "Error: Failed to open log for verification" << endl; return 1; } size_t i = 0; progress = 0; cout << progress << "%" << flush; while (true) { if (done) return 1; event = logVer->readNextEvent(); if (!event) break; if (event->timestamp != timestamps[i++].first) { cerr << endl << "Error: output log timestamp mismatch" << endl; cerr << "Expected " << timestamps[i].first << " got " << event->timestamp << " (idx " << i << ")" << endl; return 1; } size_t p = (100 * i) / timestamps.size(); if (p != progress) { progress = p; cout << "\r" << progress << "%" << flush; } } if (i < timestamps.size()) { cerr << endl << "Error: output log was missing " << timestamps.size() - i << " events" << endl; } logVer->close(); return 0; } }; int main(int argc, char* argv[]) { LogRepair lr; if (!lr.init(argc, argv)) return 1; // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); int ret = lr.run(); if (ret == 0) { cout << endl << "Success" << endl; } else { cerr << endl << "Failure" << endl; } return ret; } <|endoftext|>
<commit_before>/************************************************* * BigInt Assignment Operators Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/bigint.h> #include <botan/mp_core.h> #include <botan/bit_ops.h> #include <algorithm> namespace Botan { /************************************************* * Addition Operator * *************************************************/ BigInt& BigInt::operator+=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); const u32bit reg_size = std::max(x_sw, y_sw) + 1; grow_to(reg_size); if((sign() == y.sign())) bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); else { s32bit relative_size = bigint_cmp(data(), x_sw, y.data(), y_sw); if(relative_size < 0) { SecureVector<word> z(reg_size - 1); bigint_sub3(z, y.data(), reg_size - 1, data(), x_sw); copy_mem(reg.begin(), z.begin(), z.size()); set_sign(y.sign()); } else if(relative_size == 0) { reg.clear(); set_sign(Positive); } else if(relative_size > 0) bigint_sub2(get_reg(), x_sw, y.data(), y_sw); } return (*this); } /************************************************* * Subtraction Operator * *************************************************/ BigInt& BigInt::operator-=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); s32bit relative_size = bigint_cmp(data(), x_sw, y.data(), y_sw); const u32bit reg_size = std::max(x_sw, y_sw) + 1; grow_to(reg_size); if(relative_size < 0) { if(sign() == y.sign()) { SecureVector<word> z(reg_size - 1); bigint_sub3(z, y.data(), reg_size - 1, data(), x_sw); copy_mem(reg.begin(), z.begin(), z.size()); } else bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); set_sign(y.reverse_sign()); } else if(relative_size == 0) { if(sign() == y.sign()) { reg.clear(); set_sign(Positive); } else bigint_shl1(get_reg(), x_sw, 0, 1); } else if(relative_size > 0) { if(sign() == y.sign()) bigint_sub2(get_reg(), x_sw, y.data(), y_sw); else bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); } return (*this); } /************************************************* * Multiplication Operator * *************************************************/ BigInt& BigInt::operator*=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); set_sign((sign() == y.sign()) ? Positive : Negative); if(x_sw == 0 || y_sw == 0) { reg.clear(); set_sign(Positive); } else if(x_sw == 1 && y_sw) { grow_to(y_sw + 2); bigint_linmul3(get_reg(), y.data(), y_sw, word_at(0)); } else if(y_sw == 1 && x_sw) { grow_to(x_sw + 2); bigint_linmul2(get_reg(), x_sw, y.word_at(0)); } else { grow_to(size() + y.size()); SecureVector<word> z(data(), x_sw); SecureVector<word> workspace(size()); bigint_mul(get_reg(), size(), workspace, z, z.size(), x_sw, y.data(), y.size(), y_sw); } return (*this); } /************************************************* * Division Operator * *************************************************/ BigInt& BigInt::operator/=(const BigInt& y) { if(y.sig_words() == 1 && power_of_2(y.word_at(0))) (*this) >>= (y.bits() - 1); else (*this) = (*this) / y; return (*this); } /************************************************* * Modulo Operator * *************************************************/ BigInt& BigInt::operator%=(const BigInt& mod) { return (*this = (*this) % mod); } /************************************************* * Modulo Operator * *************************************************/ word BigInt::operator%=(word mod) { if(mod == 0) throw BigInt::DivideByZero(); if(power_of_2(mod)) { word result = (word_at(0) & (mod - 1)); clear(); grow_to(2); reg[0] = result; return result; } word remainder = 0; for(u32bit j = sig_words(); j > 0; --j) remainder = bigint_modop(remainder, word_at(j-1), mod); clear(); grow_to(2); if(remainder && sign() == BigInt::Negative) reg[0] = mod - remainder; else reg[0] = remainder; set_sign(BigInt::Positive); return word_at(0); } /************************************************* * Left Shift Operator * *************************************************/ BigInt& BigInt::operator<<=(u32bit shift) { if(shift) { const u32bit shift_words = shift / MP_WORD_BITS, shift_bits = shift % MP_WORD_BITS, words = sig_words(); grow_to(words + shift_words + (shift_bits ? 1 : 0)); bigint_shl1(get_reg(), words, shift_words, shift_bits); } return (*this); } /************************************************* * Right Shift Operator * *************************************************/ BigInt& BigInt::operator>>=(u32bit shift) { if(shift) { const u32bit shift_words = shift / MP_WORD_BITS, shift_bits = shift % MP_WORD_BITS; bigint_shr1(get_reg(), sig_words(), shift_words, shift_bits); if(is_zero()) set_sign(Positive); } return (*this); } } <commit_msg>Remove unneeded parens<commit_after>/************************************************* * BigInt Assignment Operators Source File * * (C) 1999-2007 Jack Lloyd * *************************************************/ #include <botan/bigint.h> #include <botan/mp_core.h> #include <botan/bit_ops.h> #include <algorithm> namespace Botan { /************************************************* * Addition Operator * *************************************************/ BigInt& BigInt::operator+=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); const u32bit reg_size = std::max(x_sw, y_sw) + 1; grow_to(reg_size); if(sign() == y.sign()) bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); else { s32bit relative_size = bigint_cmp(data(), x_sw, y.data(), y_sw); if(relative_size < 0) { SecureVector<word> z(reg_size - 1); bigint_sub3(z, y.data(), reg_size - 1, data(), x_sw); copy_mem(reg.begin(), z.begin(), z.size()); set_sign(y.sign()); } else if(relative_size == 0) { reg.clear(); set_sign(Positive); } else if(relative_size > 0) bigint_sub2(get_reg(), x_sw, y.data(), y_sw); } return (*this); } /************************************************* * Subtraction Operator * *************************************************/ BigInt& BigInt::operator-=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); s32bit relative_size = bigint_cmp(data(), x_sw, y.data(), y_sw); const u32bit reg_size = std::max(x_sw, y_sw) + 1; grow_to(reg_size); if(relative_size < 0) { if(sign() == y.sign()) { SecureVector<word> z(reg_size - 1); bigint_sub3(z, y.data(), reg_size - 1, data(), x_sw); copy_mem(reg.begin(), z.begin(), z.size()); } else bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); set_sign(y.reverse_sign()); } else if(relative_size == 0) { if(sign() == y.sign()) { reg.clear(); set_sign(Positive); } else bigint_shl1(get_reg(), x_sw, 0, 1); } else if(relative_size > 0) { if(sign() == y.sign()) bigint_sub2(get_reg(), x_sw, y.data(), y_sw); else bigint_add2(get_reg(), reg_size - 1, y.data(), y_sw); } return (*this); } /************************************************* * Multiplication Operator * *************************************************/ BigInt& BigInt::operator*=(const BigInt& y) { const u32bit x_sw = sig_words(), y_sw = y.sig_words(); set_sign((sign() == y.sign()) ? Positive : Negative); if(x_sw == 0 || y_sw == 0) { reg.clear(); set_sign(Positive); } else if(x_sw == 1 && y_sw) { grow_to(y_sw + 2); bigint_linmul3(get_reg(), y.data(), y_sw, word_at(0)); } else if(y_sw == 1 && x_sw) { grow_to(x_sw + 2); bigint_linmul2(get_reg(), x_sw, y.word_at(0)); } else { grow_to(size() + y.size()); SecureVector<word> z(data(), x_sw); SecureVector<word> workspace(size()); bigint_mul(get_reg(), size(), workspace, z, z.size(), x_sw, y.data(), y.size(), y_sw); } return (*this); } /************************************************* * Division Operator * *************************************************/ BigInt& BigInt::operator/=(const BigInt& y) { if(y.sig_words() == 1 && power_of_2(y.word_at(0))) (*this) >>= (y.bits() - 1); else (*this) = (*this) / y; return (*this); } /************************************************* * Modulo Operator * *************************************************/ BigInt& BigInt::operator%=(const BigInt& mod) { return (*this = (*this) % mod); } /************************************************* * Modulo Operator * *************************************************/ word BigInt::operator%=(word mod) { if(mod == 0) throw BigInt::DivideByZero(); if(power_of_2(mod)) { word result = (word_at(0) & (mod - 1)); clear(); grow_to(2); reg[0] = result; return result; } word remainder = 0; for(u32bit j = sig_words(); j > 0; --j) remainder = bigint_modop(remainder, word_at(j-1), mod); clear(); grow_to(2); if(remainder && sign() == BigInt::Negative) reg[0] = mod - remainder; else reg[0] = remainder; set_sign(BigInt::Positive); return word_at(0); } /************************************************* * Left Shift Operator * *************************************************/ BigInt& BigInt::operator<<=(u32bit shift) { if(shift) { const u32bit shift_words = shift / MP_WORD_BITS, shift_bits = shift % MP_WORD_BITS, words = sig_words(); grow_to(words + shift_words + (shift_bits ? 1 : 0)); bigint_shl1(get_reg(), words, shift_words, shift_bits); } return (*this); } /************************************************* * Right Shift Operator * *************************************************/ BigInt& BigInt::operator>>=(u32bit shift) { if(shift) { const u32bit shift_words = shift / MP_WORD_BITS, shift_bits = shift % MP_WORD_BITS; bigint_shr1(get_reg(), sig_words(), shift_words, shift_bits); if(is_zero()) set_sign(Positive); } return (*this); } } <|endoftext|>
<commit_before>/*Copyright 2010 George Karagoulis 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 <QString> template <typename T> GUtil::DataObjects::Collection<T>::Collection() :CollectionBase<T>(){} template <typename T> GUtil::DataObjects::Collection<T>::Collection( const DataObjects::Collection<T> &o) :CollectionBase<T>(o){} template <typename T> GUtil::DataObjects::Collection<T>::Collection(const QList<T> &o) :CollectionBase<T>(o){} template <typename T> GUtil::DataObjects::Collection<T>::~Collection(){} template <typename T> T &GUtil::DataObjects::Collection<T>::Add(const T &value) { return CollectionBase<T>::add_protected(value); } template <typename T> T &GUtil::DataObjects::Collection<T>::Insert(const T &value, int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::insert_protected(value, index); } template <typename T> const T &GUtil::DataObjects::Collection<T>::At(int index) const throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> T &GUtil::DataObjects::Collection<T>::At(int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> T &GUtil::DataObjects::Collection<T>::operator [](int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> const T &GUtil::DataObjects::Collection<T>::operator [](int index) const throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> void GUtil::DataObjects::Collection<T>::Remove(int index) throw(Core::IndexOutOfRangeException) { CollectionBase<T>::remove_protected(index); } template <typename T> void GUtil::DataObjects::Collection<T>::RemoveOne(const T &i) { CollectionBase<T>::removeOne_protected(i); } template <typename T> void GUtil::DataObjects::Collection<T>::RemoveAll(const T &i) { CollectionBase<T>::removeAll_protected(i); } template <typename T> void GUtil::DataObjects::Collection<T>::Clear() { CollectionBase<T>::clear_protected(); } template <typename T> bool GUtil::DataObjects::Collection<T>::Contains(const T &o) const { return CollectionBase<T>::contains_protected(o); } template <typename T> int GUtil::DataObjects::Collection<T>::IndexOf(const T &o, int from) const { return CollectionBase<T>::indexOf_protected(o, from); } template <typename T> bool GUtil::DataObjects::Collection<T>::Equals( const DataObjects::Collection<T> &rhs) const { return CollectionBase<T>::Equals(rhs); } template <typename T> int GUtil::DataObjects::Collection<T>::Count() const { return CollectionBase<T>::count_protected(); } template <typename T> int GUtil::DataObjects::Collection<T>::Size() const { return CollectionBase<T>::size_protected(); } template <typename T> GUtil::DataObjects::Collection<T> &GUtil::DataObjects::Collection<T>::CloneTo( DataObjects::Collection<T> &o) const { return (GUtil::DataObjects::Collection<T> &)CollectionBase<T>::CloneTo(o); } template <typename T> GUtil::DataObjects::CollectionBase<T>::CollectionBase( const DataObjects::CollectionBase<T> &o) :IReadOnlyObject(o) { o.CloneTo(*this); } template <typename T> GUtil::DataObjects::CollectionBase<T>::CollectionBase(const QList<T> &o) :_collection(o) {} template <typename T> T &GUtil::DataObjects::CollectionBase<T>::add_protected(const T &value) { FailIfReadOnly(); validate_new_item(value); int index = _collection.size(); _collection.append(value); on_add(index); return _collection[index]; } template <typename T> T &GUtil::DataObjects::CollectionBase<T>::insert_protected(const T &value, int index) throw(Core::IndexOutOfRangeException) { FailIfReadOnly(); _validate_index(index); validate_new_item(value); _collection.insert(index, value); on_add(index); return _collection[index]; } template <typename T> const T &GUtil::DataObjects::CollectionBase<T>::at_protected(int index) const throw(Core::IndexOutOfRangeException) { _validate_index(index); return _collection[index]; } template <typename T> T &GUtil::DataObjects::CollectionBase<T>::at_protected(int index) throw(Core::IndexOutOfRangeException) { _validate_index(index); return _collection[index]; } template <typename T> void GUtil::DataObjects::CollectionBase<T>::remove_protected(int index) throw(Core::IndexOutOfRangeException) { FailIfReadOnly(); on_remove(index); _collection.removeAt(index); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::removeOne_protected(const T &i) { int ind = indexOf_protected(i); if(ind >= 0) remove_protected(ind); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::removeAll_protected(const T &i) { int ind = 0; while((ind = indexOf_protected(i, ind)) >= 0) remove_protected(ind); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::clear_protected() { while(count_protected() > 0) remove_protected(0); } template <typename T> bool GUtil::DataObjects::CollectionBase<T>::contains_protected(const T &o) const { return indexOf_protected(o) != -1; } template <typename T> int GUtil::DataObjects::CollectionBase<T>::indexOf_protected(const T &o, int from) const { int ret = -1; for(int i = from; i < size_protected(); i++) { if(compare_equality(at_protected(i), o)) { ret = i; break; } } return ret; } template<typename T> void GUtil::DataObjects::CollectionBase<T>::_validate_index(int index) const { if(index < 0 || index >= count_protected()) THROW_NEW_GUTIL_EXCEPTION2(Core::IndexOutOfRangeException, QString("Collection only has %1 items in it, and you tried to " "index the item at %2") .arg(count_protected()).arg(index).toStdString()); } template <typename T> bool GUtil::DataObjects::CollectionBase<T>::Equals( const GUtil::DataObjects::CollectionBase<T> &rhs) const { bool ret = _collection == rhs._collection; for(int i = 0; ret && i < count_protected(); i++) if(!compare_equality(at_protected(i), rhs.at_protected(i))) ret = false; return ret; } template <typename T> int GUtil::DataObjects::CollectionBase<T>::count_protected() const { return _collection.length(); } template <typename T> int GUtil::DataObjects::CollectionBase<T>::size_protected() const { return _collection.length(); } template <typename T> GUtil::DataObjects::CollectionBase<T> & GUtil::DataObjects::CollectionBase<T>::CloneTo( GUtil::DataObjects::CollectionBase<T> &o) const { o.FailIfReadOnly(); o._collection = _collection; return o; } <commit_msg>Inserting should have different index validation, which should include the index at the end of the array<commit_after>/*Copyright 2010 George Karagoulis 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 <QString> template <typename T> GUtil::DataObjects::Collection<T>::Collection() :CollectionBase<T>(){} template <typename T> GUtil::DataObjects::Collection<T>::Collection( const DataObjects::Collection<T> &o) :CollectionBase<T>(o){} template <typename T> GUtil::DataObjects::Collection<T>::Collection(const QList<T> &o) :CollectionBase<T>(o){} template <typename T> GUtil::DataObjects::Collection<T>::~Collection(){} template <typename T> T &GUtil::DataObjects::Collection<T>::Add(const T &value) { return CollectionBase<T>::add_protected(value); } template <typename T> T &GUtil::DataObjects::Collection<T>::Insert(const T &value, int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::insert_protected(value, index); } template <typename T> const T &GUtil::DataObjects::Collection<T>::At(int index) const throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> T &GUtil::DataObjects::Collection<T>::At(int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> T &GUtil::DataObjects::Collection<T>::operator [](int index) throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> const T &GUtil::DataObjects::Collection<T>::operator [](int index) const throw(Core::IndexOutOfRangeException) { return CollectionBase<T>::at_protected(index); } template <typename T> void GUtil::DataObjects::Collection<T>::Remove(int index) throw(Core::IndexOutOfRangeException) { CollectionBase<T>::remove_protected(index); } template <typename T> void GUtil::DataObjects::Collection<T>::RemoveOne(const T &i) { CollectionBase<T>::removeOne_protected(i); } template <typename T> void GUtil::DataObjects::Collection<T>::RemoveAll(const T &i) { CollectionBase<T>::removeAll_protected(i); } template <typename T> void GUtil::DataObjects::Collection<T>::Clear() { CollectionBase<T>::clear_protected(); } template <typename T> bool GUtil::DataObjects::Collection<T>::Contains(const T &o) const { return CollectionBase<T>::contains_protected(o); } template <typename T> int GUtil::DataObjects::Collection<T>::IndexOf(const T &o, int from) const { return CollectionBase<T>::indexOf_protected(o, from); } template <typename T> bool GUtil::DataObjects::Collection<T>::Equals( const DataObjects::Collection<T> &rhs) const { return CollectionBase<T>::Equals(rhs); } template <typename T> int GUtil::DataObjects::Collection<T>::Count() const { return CollectionBase<T>::count_protected(); } template <typename T> int GUtil::DataObjects::Collection<T>::Size() const { return CollectionBase<T>::size_protected(); } template <typename T> GUtil::DataObjects::Collection<T> &GUtil::DataObjects::Collection<T>::CloneTo( DataObjects::Collection<T> &o) const { return (GUtil::DataObjects::Collection<T> &)CollectionBase<T>::CloneTo(o); } template <typename T> GUtil::DataObjects::CollectionBase<T>::CollectionBase( const DataObjects::CollectionBase<T> &o) :IReadOnlyObject(o) { o.CloneTo(*this); } template <typename T> GUtil::DataObjects::CollectionBase<T>::CollectionBase(const QList<T> &o) :_collection(o) {} template <typename T> T &GUtil::DataObjects::CollectionBase<T>::add_protected(const T &value) { FailIfReadOnly(); validate_new_item(value); int index = _collection.size(); _collection.append(value); on_add(index); return _collection[index]; } template <typename T> T &GUtil::DataObjects::CollectionBase<T>::insert_protected(const T &value, int index) throw(Core::IndexOutOfRangeException) { FailIfReadOnly(); if(index < 0 || index > this->count_protected()) throw Core::IndexOutOfRangeException(QString("Cannot insert at index %1") .arg(index).toStdString()); validate_new_item(value); _collection.insert(index, value); on_add(index); return _collection[index]; } template <typename T> const T &GUtil::DataObjects::CollectionBase<T>::at_protected(int index) const throw(Core::IndexOutOfRangeException) { _validate_index(index); return _collection[index]; } template <typename T> T &GUtil::DataObjects::CollectionBase<T>::at_protected(int index) throw(Core::IndexOutOfRangeException) { _validate_index(index); return _collection[index]; } template <typename T> void GUtil::DataObjects::CollectionBase<T>::remove_protected(int index) throw(Core::IndexOutOfRangeException) { FailIfReadOnly(); on_remove(index); _collection.removeAt(index); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::removeOne_protected(const T &i) { int ind = indexOf_protected(i); if(ind >= 0) remove_protected(ind); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::removeAll_protected(const T &i) { int ind = 0; while((ind = indexOf_protected(i, ind)) >= 0) remove_protected(ind); } template <typename T> void GUtil::DataObjects::CollectionBase<T>::clear_protected() { while(count_protected() > 0) remove_protected(0); } template <typename T> bool GUtil::DataObjects::CollectionBase<T>::contains_protected(const T &o) const { return indexOf_protected(o) != -1; } template <typename T> int GUtil::DataObjects::CollectionBase<T>::indexOf_protected(const T &o, int from) const { int ret = -1; for(int i = from; i < size_protected(); i++) { if(compare_equality(at_protected(i), o)) { ret = i; break; } } return ret; } template<typename T> void GUtil::DataObjects::CollectionBase<T>::_validate_index(int index) const { if(index < 0 || index >= count_protected()) THROW_NEW_GUTIL_EXCEPTION2(Core::IndexOutOfRangeException, QString("Collection only has %1 items in it, and you tried to " "index the item at %2") .arg(count_protected()).arg(index).toStdString()); } template <typename T> bool GUtil::DataObjects::CollectionBase<T>::Equals( const GUtil::DataObjects::CollectionBase<T> &rhs) const { bool ret = _collection == rhs._collection; for(int i = 0; ret && i < count_protected(); i++) if(!compare_equality(at_protected(i), rhs.at_protected(i))) ret = false; return ret; } template <typename T> int GUtil::DataObjects::CollectionBase<T>::count_protected() const { return _collection.length(); } template <typename T> int GUtil::DataObjects::CollectionBase<T>::size_protected() const { return _collection.length(); } template <typename T> GUtil::DataObjects::CollectionBase<T> & GUtil::DataObjects::CollectionBase<T>::CloneTo( GUtil::DataObjects::CollectionBase<T> &o) const { o.FailIfReadOnly(); o._collection = _collection; return o; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "gc_clock.hh" #include <cstdint> template<typename T> static inline void set_field(bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp><int32_t:ttl>?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:ttl> */ class atomic_cell final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t TTL_FLAG = 0x02; // When present, TTL field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned ttl_offset = timestamp_offset + timestamp_size; static constexpr unsigned ttl_size = 4; public: class view; class one; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & TTL_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto ttl_field_size = bool(cell[0] & TTL_FLAG) * ttl_size; auto value_offset = flags_size + timestamp_size + ttl_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called on live and dead cells. For dead cells, the result is never empty. static ttl_opt ttl(const bytes_view& cell) { auto flags = cell[0]; if (flags == DEAD_FLAGS || (flags & TTL_FLAG)) { auto ttl = get_field<int32_t>(cell, ttl_offset); return {gc_clock::time_point(gc_clock::duration(ttl))}; } return {}; } static bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { bytes b(bytes::initialized_later(), flags_size + timestamp_size + ttl_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, ttl_offset, ttl.time_since_epoch().count()); return b; } static bytes make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { auto value_offset = flags_size + timestamp_size + bool(ttl) * ttl_size; bytes b(bytes::initialized_later(), value_offset + value.size()); b[0] = (ttl ? TTL_FLAG : 0) | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); if (ttl) { set_field(b, ttl_offset, ttl->time_since_epoch().count()); } std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } friend class one; friend class view; }; class atomic_cell::view final { bytes_view _data; private: view(bytes_view data) : _data(data) {} public: static view from_bytes(bytes_view data) { return view(data); } bool is_live() const { return atomic_cell::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell::is_live_and_has_ttl(_data); } bool is_dead(const bytes_view& cell) const { return atomic_cell::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell::ttl(_data); } bytes_view serialize() const { return _data; } friend class atomic_cell::one; }; class atomic_cell::one final { bytes _data; private: one(bytes b) : _data(std::move(b)) {} public: one(const one&) = default; one(one&&) = default; one& operator=(const one&) = default; one& operator=(one&&) = default; static one from_bytes(bytes b) { return one(std::move(b)); } one(atomic_cell::view other) : _data(other._data.begin(), other._data.end()) {} bool is_live() const { return atomic_cell::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell::is_live_and_has_ttl(_data); } bool is_dead(const bytes_view& cell) const { return atomic_cell::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell::ttl(_data); } operator atomic_cell::view() const { return atomic_cell::view(_data); } static one make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { return atomic_cell::make_dead(timestamp, ttl); } static one make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { return atomic_cell::make_live(timestamp, ttl, value); } friend class atomic_cell_or_collection; }; // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { bytes _data; private: atomic_cell_or_collection(bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell::one ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell::one data) { return { std::move(data._data) }; } atomic_cell::view as_atomic_cell() const { return atomic_cell::view::from_bytes(_data); } // FIXME: insert collection variant here }; <commit_msg>atomic_cell: add collection support<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "gc_clock.hh" #include <cstdint> template<typename T> static inline void set_field(bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp><int32_t:ttl>?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:ttl> */ class atomic_cell final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t TTL_FLAG = 0x02; // When present, TTL field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned ttl_offset = timestamp_offset + timestamp_size; static constexpr unsigned ttl_size = 4; public: class view; class one; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & TTL_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto ttl_field_size = bool(cell[0] & TTL_FLAG) * ttl_size; auto value_offset = flags_size + timestamp_size + ttl_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called on live and dead cells. For dead cells, the result is never empty. static ttl_opt ttl(const bytes_view& cell) { auto flags = cell[0]; if (flags == DEAD_FLAGS || (flags & TTL_FLAG)) { auto ttl = get_field<int32_t>(cell, ttl_offset); return {gc_clock::time_point(gc_clock::duration(ttl))}; } return {}; } static bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { bytes b(bytes::initialized_later(), flags_size + timestamp_size + ttl_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, ttl_offset, ttl.time_since_epoch().count()); return b; } static bytes make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { auto value_offset = flags_size + timestamp_size + bool(ttl) * ttl_size; bytes b(bytes::initialized_later(), value_offset + value.size()); b[0] = (ttl ? TTL_FLAG : 0) | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); if (ttl) { set_field(b, ttl_offset, ttl->time_since_epoch().count()); } std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } friend class one; friend class view; }; class atomic_cell::view final { bytes_view _data; private: view(bytes_view data) : _data(data) {} public: static view from_bytes(bytes_view data) { return view(data); } bool is_live() const { return atomic_cell::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell::is_live_and_has_ttl(_data); } bool is_dead(const bytes_view& cell) const { return atomic_cell::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell::ttl(_data); } bytes_view serialize() const { return _data; } friend class atomic_cell::one; }; class atomic_cell::one final { bytes _data; private: one(bytes b) : _data(std::move(b)) {} public: one(const one&) = default; one(one&&) = default; one& operator=(const one&) = default; one& operator=(one&&) = default; static one from_bytes(bytes b) { return one(std::move(b)); } one(atomic_cell::view other) : _data(other._data.begin(), other._data.end()) {} bool is_live() const { return atomic_cell::is_live(_data); } bool is_live_and_has_ttl() const { return atomic_cell::is_live_and_has_ttl(_data); } bool is_dead(const bytes_view& cell) const { return atomic_cell::is_dead(_data); } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell::value(_data); } // Can be called on live and dead cells. For dead cells, the result is never empty. ttl_opt ttl() const { return atomic_cell::ttl(_data); } operator atomic_cell::view() const { return atomic_cell::view(_data); } static one make_dead(api::timestamp_type timestamp, gc_clock::time_point ttl) { return atomic_cell::make_dead(timestamp, ttl); } static one make_live(api::timestamp_type timestamp, ttl_opt ttl, bytes_view value) { return atomic_cell::make_live(timestamp, ttl, value); } friend class atomic_cell_or_collection; }; // Represents a mutation of a collection. Actual format is determined by collection type, // and is: // set: list of atomic_cell // map: list of pair<atomic_cell, bytes> (for key/value) // list: tbd, probably ugly class collection_mutation { public: struct view { bytes_view data; }; struct one { bytes data; operator view() const { return { data }; } }; }; // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { bytes _data; private: atomic_cell_or_collection(bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell::one ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell::one data) { return { std::move(data._data) }; } atomic_cell::view as_atomic_cell() const { return atomic_cell::view::from_bytes(_data); } atomic_cell_or_collection(collection_mutation::one cm) : _data(std::move(cm.data)) {} static atomic_cell_or_collection from_collection_mutation(collection_mutation::one data) { return std::move(data.data); } collection_mutation::view as_collection_mutation() const { return collection_mutation::view{_data}; } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Hideaki Ohno <hide.o.j55{at}gmail.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. */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (C) 2011 Clearspring Technologies, 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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once /** * @file hyperloglog.hpp * @brief HyperLogLog cardinality estimator * @date Created 2013/3/20 * @author Hideaki Ohno */ #include <vector> #include <cmath> #include <sstream> #include <stdexcept> #include <algorithm> #if 0 #include "murmur3.h" #endif #define HLL_HASH_SEED 313 namespace hll { static const double pow_2_32 = 4294967296.0; ///< 2^32 static const double neg_pow_2_32 = -4294967296.0; ///< -(2^32) static inline size_t size_unsigned_var_int(unsigned int value) { size_t size = 0; while ((value & 0xFFFFFF80) != 0L) { size++; value >>= 7; } size++; return size; } static inline size_t write_unsigned_var_int(unsigned int value, uint8_t* to) { size_t size = 0; while ((value & 0xFFFFFF80) != 0L) { *to = (value & 0x7F) | 0x80; value >>= 7; to++; size++; } *to = value & 0x7F; size++; return size; } /** @class HyperLogLog * @brief Implement of 'HyperLogLog' estimate cardinality algorithm */ class HyperLogLog { public: /** * Constructor * * @param[in] b bit width (register size will be 2 to the b power). * This value must be in the range[4,16].Default value is 4. * * @exception std::invalid_argument the argument is out of range. */ HyperLogLog(uint8_t b = 4) throw (std::invalid_argument) : b_(b), m_(1 << b), M_(m_, 0) { if (b < 4 || 16 < b) { throw std::invalid_argument("bit width must be in the range [4,16]"); } double alpha; switch (m_) { case 16: alpha = 0.673; break; case 32: alpha = 0.697; break; case 64: alpha = 0.709; break; default: alpha = 0.7213 / (1.0 + 1.079 / m_); break; } alphaMM_ = alpha * m_ * m_; } static HyperLogLog from_bytes(temporary_buffer<uint8_t> bytes) { // FIXME: implement class that creates a HyperLogLog from an array of bytes. // This will useful if we need to work with the cardinality data from the // compaction metadata. abort(); } /** * Adds element to the estimator * * @param[in] str string to add * @param[in] len length of string */ #if 0 void add(const char* str, uint32_t len) { uint32_t hash; MurmurHash3_x86_32(str, len, HLL_HASH_SEED, (void*) &hash); uint32_t index = hash >> (32 - b_); uint8_t rank = rho((hash << b_), 32 - b_); if (rank > M_[index]) { M_[index] = rank; } } #endif void offer_hashed(uint64_t hash) { uint32_t index = hash >> (64 - b_); uint8_t rank = rho((hash << b_), 64 - b_); if (rank > M_[index]) { M_[index] = rank; } } /* * Calculate the size of buffer returned by get_bytes(). */ size_t get_bytes_size() { size_t size = 0; size += sizeof(int); // version size += size_unsigned_var_int(b_); // p; register width = b_. size += size_unsigned_var_int(0); // sp; // sparse set = 0. size += size_unsigned_var_int(0); // type; size += size_unsigned_var_int(M_.size()); // register size; size += M_.size(); return size; } temporary_buffer<uint8_t> get_bytes() { // FIXME: add support to SPARSE format. static constexpr int version = 2; size_t s = get_bytes_size(); temporary_buffer<uint8_t> bytes(s); size_t offset = 0; // write version *unaligned_cast<int*>(bytes.get_write() + offset) = htonl(-version); offset += sizeof(int); // write register width offset += write_unsigned_var_int(b_, bytes.get_write() + offset); // NOTE: write precision value for sparse set (not supported). offset += write_unsigned_var_int(0, bytes.get_write() + offset); // write type (NORMAL always!) offset += write_unsigned_var_int(0, bytes.get_write() + offset); // write register size offset += write_unsigned_var_int(M_.size(), bytes.get_write() + offset); // write register memcpy(bytes.get_write() + offset, M_.data(), M_.size()); offset += M_.size(); bytes.trim(offset); if (s != offset) { throw std::runtime_error("possible overflow while generating cardinality metadata"); } return bytes; } /** * Estimates cardinality value. * * @return Estimated cardinality value. */ double estimate() const { double estimate; double sum = 0.0; for (uint32_t i = 0; i < m_; i++) { sum += 1.0 / pow(2.0, M_[i]); } estimate = alphaMM_ / sum; // E in the original paper if (estimate <= 2.5 * m_) { uint32_t zeros = 0; for (uint32_t i = 0; i < m_; i++) { if (M_[i] == 0) { zeros++; } } if (zeros != 0) { estimate = m_ * log(static_cast<double>(m_)/ zeros); } } else if (estimate > (1.0 / 30.0) * pow_2_32) { estimate = neg_pow_2_32 * log(1.0 - (estimate / pow_2_32)); } return estimate; } /** * Merges the estimate from 'other' into this object, returning the estimate of their union. * The number of registers in each must be the same. * * @param[in] other HyperLogLog instance to be merged * * @exception std::invalid_argument number of registers doesn't match. */ void merge(const HyperLogLog& other) throw (std::invalid_argument) { if (m_ != other.m_) { std::stringstream ss; ss << "number of registers doesn't match: " << m_ << " != " << other.m_; throw std::invalid_argument(ss.str().c_str()); } for (uint32_t r = 0; r < m_; ++r) { if (M_[r] < other.M_[r]) { M_[r] = other.M_[r]; } } } /** * Clears all internal registers. */ void clear() { std::fill(M_.begin(), M_.end(), 0); } /** * Returns size of register. * * @return Register size */ uint32_t registerSize() const { return m_; } /** * Exchanges the content of the instance * * @param[in,out] rhs Another HyperLogLog instance */ void swap(HyperLogLog& rhs) { std::swap(b_, rhs.b_); std::swap(m_, rhs.m_); std::swap(alphaMM_, rhs.alphaMM_); M_.swap(rhs.M_); } /** * Dump the current status to a stream * * @param[out] os The output stream where the data is saved * * @exception std::runtime_error When failed to dump. */ void dump(std::ostream& os) const throw(std::runtime_error){ os.write((char*)&b_, sizeof(b_)); os.write((char*)&M_[0], sizeof(M_[0]) * M_.size()); if(os.fail()){ throw std::runtime_error("Failed to dump"); } } /** * Restore the status from a stream * * @param[in] is The input stream where the status is saved * * @exception std::runtime_error When failed to restore. */ void restore(std::istream& is) throw(std::runtime_error){ uint8_t b = 0; is.read((char*)&b, sizeof(b)); HyperLogLog tempHLL(b); is.read((char*)&(tempHLL.M_[0]), sizeof(M_[0]) * tempHLL.m_); if(is.fail()){ throw std::runtime_error("Failed to restore"); } swap(tempHLL); } private: uint8_t b_; ///< register bit width uint32_t m_; ///< register size double alphaMM_; ///< alpha * m^2 std::vector<uint8_t> M_; ///< registers uint8_t rho(uint32_t x, uint8_t b) { uint8_t v = 1; while (v <= b && !(x & 0x80000000)) { v++; x <<= 1; } return v; } }; } // namespace hll <commit_msg>sstables: remove HyperLogLog throw() specifier<commit_after>/* * Copyright (c) 2013 Hideaki Ohno <hide.o.j55{at}gmail.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. */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (C) 2011 Clearspring Technologies, 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. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once /** * @file hyperloglog.hpp * @brief HyperLogLog cardinality estimator * @date Created 2013/3/20 * @author Hideaki Ohno */ #include <vector> #include <cmath> #include <sstream> #include <stdexcept> #include <algorithm> #if 0 #include "murmur3.h" #endif #define HLL_HASH_SEED 313 namespace hll { static const double pow_2_32 = 4294967296.0; ///< 2^32 static const double neg_pow_2_32 = -4294967296.0; ///< -(2^32) static inline size_t size_unsigned_var_int(unsigned int value) { size_t size = 0; while ((value & 0xFFFFFF80) != 0L) { size++; value >>= 7; } size++; return size; } static inline size_t write_unsigned_var_int(unsigned int value, uint8_t* to) { size_t size = 0; while ((value & 0xFFFFFF80) != 0L) { *to = (value & 0x7F) | 0x80; value >>= 7; to++; size++; } *to = value & 0x7F; size++; return size; } /** @class HyperLogLog * @brief Implement of 'HyperLogLog' estimate cardinality algorithm */ class HyperLogLog { public: /** * Constructor * * @param[in] b bit width (register size will be 2 to the b power). * This value must be in the range[4,16].Default value is 4. * * @exception std::invalid_argument the argument is out of range. */ HyperLogLog(uint8_t b = 4) : b_(b), m_(1 << b), M_(m_, 0) { if (b < 4 || 16 < b) { throw std::invalid_argument("bit width must be in the range [4,16]"); } double alpha; switch (m_) { case 16: alpha = 0.673; break; case 32: alpha = 0.697; break; case 64: alpha = 0.709; break; default: alpha = 0.7213 / (1.0 + 1.079 / m_); break; } alphaMM_ = alpha * m_ * m_; } static HyperLogLog from_bytes(temporary_buffer<uint8_t> bytes) { // FIXME: implement class that creates a HyperLogLog from an array of bytes. // This will useful if we need to work with the cardinality data from the // compaction metadata. abort(); } /** * Adds element to the estimator * * @param[in] str string to add * @param[in] len length of string */ #if 0 void add(const char* str, uint32_t len) { uint32_t hash; MurmurHash3_x86_32(str, len, HLL_HASH_SEED, (void*) &hash); uint32_t index = hash >> (32 - b_); uint8_t rank = rho((hash << b_), 32 - b_); if (rank > M_[index]) { M_[index] = rank; } } #endif void offer_hashed(uint64_t hash) { uint32_t index = hash >> (64 - b_); uint8_t rank = rho((hash << b_), 64 - b_); if (rank > M_[index]) { M_[index] = rank; } } /* * Calculate the size of buffer returned by get_bytes(). */ size_t get_bytes_size() { size_t size = 0; size += sizeof(int); // version size += size_unsigned_var_int(b_); // p; register width = b_. size += size_unsigned_var_int(0); // sp; // sparse set = 0. size += size_unsigned_var_int(0); // type; size += size_unsigned_var_int(M_.size()); // register size; size += M_.size(); return size; } temporary_buffer<uint8_t> get_bytes() { // FIXME: add support to SPARSE format. static constexpr int version = 2; size_t s = get_bytes_size(); temporary_buffer<uint8_t> bytes(s); size_t offset = 0; // write version *unaligned_cast<int*>(bytes.get_write() + offset) = htonl(-version); offset += sizeof(int); // write register width offset += write_unsigned_var_int(b_, bytes.get_write() + offset); // NOTE: write precision value for sparse set (not supported). offset += write_unsigned_var_int(0, bytes.get_write() + offset); // write type (NORMAL always!) offset += write_unsigned_var_int(0, bytes.get_write() + offset); // write register size offset += write_unsigned_var_int(M_.size(), bytes.get_write() + offset); // write register memcpy(bytes.get_write() + offset, M_.data(), M_.size()); offset += M_.size(); bytes.trim(offset); if (s != offset) { throw std::runtime_error("possible overflow while generating cardinality metadata"); } return bytes; } /** * Estimates cardinality value. * * @return Estimated cardinality value. */ double estimate() const { double estimate; double sum = 0.0; for (uint32_t i = 0; i < m_; i++) { sum += 1.0 / pow(2.0, M_[i]); } estimate = alphaMM_ / sum; // E in the original paper if (estimate <= 2.5 * m_) { uint32_t zeros = 0; for (uint32_t i = 0; i < m_; i++) { if (M_[i] == 0) { zeros++; } } if (zeros != 0) { estimate = m_ * log(static_cast<double>(m_)/ zeros); } } else if (estimate > (1.0 / 30.0) * pow_2_32) { estimate = neg_pow_2_32 * log(1.0 - (estimate / pow_2_32)); } return estimate; } /** * Merges the estimate from 'other' into this object, returning the estimate of their union. * The number of registers in each must be the same. * * @param[in] other HyperLogLog instance to be merged * * @exception std::invalid_argument number of registers doesn't match. */ void merge(const HyperLogLog& other) throw (std::invalid_argument) { if (m_ != other.m_) { std::stringstream ss; ss << "number of registers doesn't match: " << m_ << " != " << other.m_; throw std::invalid_argument(ss.str().c_str()); } for (uint32_t r = 0; r < m_; ++r) { if (M_[r] < other.M_[r]) { M_[r] = other.M_[r]; } } } /** * Clears all internal registers. */ void clear() { std::fill(M_.begin(), M_.end(), 0); } /** * Returns size of register. * * @return Register size */ uint32_t registerSize() const { return m_; } /** * Exchanges the content of the instance * * @param[in,out] rhs Another HyperLogLog instance */ void swap(HyperLogLog& rhs) { std::swap(b_, rhs.b_); std::swap(m_, rhs.m_); std::swap(alphaMM_, rhs.alphaMM_); M_.swap(rhs.M_); } /** * Dump the current status to a stream * * @param[out] os The output stream where the data is saved * * @exception std::runtime_error When failed to dump. */ void dump(std::ostream& os) const throw(std::runtime_error){ os.write((char*)&b_, sizeof(b_)); os.write((char*)&M_[0], sizeof(M_[0]) * M_.size()); if(os.fail()){ throw std::runtime_error("Failed to dump"); } } /** * Restore the status from a stream * * @param[in] is The input stream where the status is saved * * @exception std::runtime_error When failed to restore. */ void restore(std::istream& is) throw(std::runtime_error){ uint8_t b = 0; is.read((char*)&b, sizeof(b)); HyperLogLog tempHLL(b); is.read((char*)&(tempHLL.M_[0]), sizeof(M_[0]) * tempHLL.m_); if(is.fail()){ throw std::runtime_error("Failed to restore"); } swap(tempHLL); } private: uint8_t b_; ///< register bit width uint32_t m_; ///< register size double alphaMM_; ///< alpha * m^2 std::vector<uint8_t> M_; ///< registers uint8_t rho(uint32_t x, uint8_t b) { uint8_t v = 1; while (v <= b && !(x & 0x80000000)) { v++; x <<= 1; } return v; } }; } // namespace hll <|endoftext|>
<commit_before>#ifndef CAMERA_PERSPECTIVE_H #define CAMERA_PERSPECTIVE_H #include "geometry/vec3.hpp" class CameraPerspective { private: // class members int framePixelsX; int framePixelsY; Vec3f originPoint; Vec3f viewDirection; Vec3f upDirection; double focalLength; double frameSize; // private methods public: // public methods CameraPerspective(int _framePixelsX, int _framePixelsY, Vec3f _originPoint, Vec3f _viewDirection, Vec3f _upDirection, double _focalLength, double _frameSize); friend std::ostream& operator << (std::ostream &os, CameraPerspective* cp) { os << "[" << "framePixelsX=" << cp->framePixelsX << ",framePixelsY=" << cp->framePixelsY << ",originPoint=" << cp->originPoint << ",viewDirection=" << cp->viewDirection << ",upDirection=" << cp->upDirection << ",focalLength=" << cp->focalLength << ",frameSize=" << cp->frameSize << "]"; return os; } }; #endif<commit_msg>added x/y pixels and frame size members added declarations for private and public member functions<commit_after>#ifndef CAMERA_PERSPECTIVE_H #define CAMERA_PERSPECTIVE_H #include <cmath> #include <iostream> #include "geometry/vec3.hpp" class CameraPerspective { private: // class members double framePixelsX; double framePixelsY; Vec3f originPoint; Vec3f viewDirection; Vec3f upDirection; Vec3f rightDirection; double focalLength; double frameSize; double frameSize_h; double frameSize_v; // private methods Vec3f getPlaneVectorX(int xcoord); Vec3f getPlaneVectorY(int ycoord); Vec3f getPlaneVector(int xcoord, int ycoord); public: // public methods CameraPerspective(int _framePixelsX, int _framePixelsY, Vec3f _originPoint, Vec3f _viewDirection, Vec3f _upDirection, double _focalLength, double _frameSize); friend std::ostream& operator << (std::ostream &os, CameraPerspective* cp) { os << "[" << "framePixelsX=" << cp->framePixelsX << ",framePixelsY=" << cp->framePixelsY << ",originPoint=" << cp->originPoint << ",viewDirection=" << cp->viewDirection << ",upDirection=" << cp->upDirection << ",focalLength=" << cp->focalLength << ",frameSize=" << cp->frameSize << "]"; return os; } Vec3f getRay(int xcoord, int ycoord); }; #endif<|endoftext|>
<commit_before>#include "template.hpp" #include <iostream> #include <fstream> #include <gtest/gtest.h> // The fixture for testing class Foo. class CollectionsTest : public ::testing::Test { protected: string result_string; string result_file; string template_string; string file; CollectionsTest() { } virtual ~CollectionsTest() { } virtual void SetUp() { template_string = "Hi I am {{me}}.\n"; template_string += "{{# people}}"; template_string += "Hi {{name}}!"; template_string += "{{/ people}}"; file = "collections.mustache"; ofstream myfile; myfile.open (file.c_str()); myfile << template_string; myfile.close(); context ctx; ctx.add("me", "Daniel"); buckets b; bucket b1; b1["name"] = "Tom"; bucket b2; b2["name"] = "Jerry"; b.push_back(b1); b.push_back(b2); ctx.add("people", b); template_t t; result_string = t.render(template_string, ctx); result_file = t.render(file, ctx); } virtual void TearDown() { remove(file.c_str()); } }; // Tests that a simple mustache tag is replaced TEST_F(CollectionsTest, TestCollectionMustacheFromString) { string expected = "Hi I am Daniel.\n"; expected += "Hi Tom!"; expected += "Hi Jerry!"; EXPECT_EQ(expected, result_string); } TEST_F(CollectionsTest, TestCollectionMustacheFromFile) { string expected = "Hi I am Daniel.\n"; expected += "Hi Tom!"; expected += "Hi Jerry!"; EXPECT_EQ(expected, result_file); } TEST_F(CollectionsTest, TestCollectionMustacheWithSingleEntry) { context ctx2; ctx2.add("me", "Daniel"); template_t t; buckets bucks; bucket buck; buck["name"] = "Tom"; bucks.push_back(buck); ctx2.add("people", bucks); string res; res = t.render(template_string, ctx2); string expected = "Hi I am Daniel.\n"; expected += "Hi Tom!"; EXPECT_EQ(expected, res); } <commit_msg>more collections test cases<commit_after>#include "template.hpp" #include <iostream> #include <fstream> #include <gtest/gtest.h> // The fixture for testing class Foo. class CollectionsTest : public ::testing::Test { protected: string result_single; string result_multiple; string result_multiple_fields; string template_string; string template_single_string; CollectionsTest() { } virtual ~CollectionsTest() { } virtual void SetUp() { template_string = "Hi I am {{me}}.\n"; template_string += "{{# people}}"; template_string += "Hi {{me}}, I am {{name}}, I do {{work}}."; template_string += "{{/ people}}"; template_single_string = "Hi I am {{me}}.\n"; template_single_string += "{{# people}}"; template_single_string += "Hi {{name}}!"; template_single_string += "{{/ people}}"; // single entry bucket tom; bucket jerry; tom["name"] = "Tom"; buckets b_single; b_single.push_back(tom); context ctx_single; ctx_single.add("me", "Daniel"); ctx_single.add("people",b_single); // multiple entries jerry["name"] = "Jerry"; buckets b_multiple; b_multiple.push_back(tom); b_multiple.push_back(jerry); context ctx_multiple; ctx_multiple.add("me", "Daniel"); ctx_multiple.add("people", b_multiple); // multiple fields tom["work"] = "Accounting"; jerry["work"] = "Magic"; buckets b_multiple_fields; b_multiple_fields.push_back(tom); b_multiple_fields.push_back(jerry); context ctx; ctx.add("me", "Daniel"); ctx.add("people", b_multiple_fields); template_t t; result_single = t.render(template_single_string, ctx_single); result_multiple = t.render(template_single_string, ctx_multiple); result_multiple_fields = t.render(template_string, ctx); } virtual void TearDown() { } }; // Tests that a simple mustache tag is replaced TEST_F(CollectionsTest, TestCollectionsSingle) { string expected = "Hi I am Daniel.\n"; expected += "Hi Tom!"; EXPECT_EQ(expected, result_single); } TEST_F(CollectionsTest, TestCollectionsMultiple) { string expected = "Hi I am Daniel.\n"; expected += "Hi Tom!"; expected += "Hi Jerry!"; EXPECT_EQ(expected, result_multiple); } TEST_F(CollectionsTest, TestCollectionMultipleWithMultipleFields) { string expected = "Hi I am Daniel.\n"; expected += "Hi Daniel, I am Tom, I do Accounting."; expected += "Hi Daniel, I am Jerry, I do Magic."; EXPECT_EQ(expected, result_multiple_fields); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 PLUMgrid, 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 <map> #include <string> #include <algorithm> #include <fcntl.h> #include <ftw.h> #include <map> #include <stdio.h> #include <string> #include <sys/stat.h> #include <sys/utsname.h> #include <unistd.h> #include <vector> #include <linux/bpf.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/TargetInfo.h> #include <clang/CodeGen/BackendUtil.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Job.h> #include <clang/Driver/Tool.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/FrontendTool/Utils.h> #include <llvm/IR/Module.h> #include "common.h" #include "exception.h" #include "kbuild_helper.h" #include "b_frontend_action.h" #include "loader.h" using std::map; using std::string; using std::unique_ptr; using std::vector; namespace ebpf { ClangLoader::ClangLoader(llvm::LLVMContext *ctx, unsigned flags) : ctx_(ctx), flags_(flags) {} ClangLoader::~ClangLoader() {} int ClangLoader::parse(unique_ptr<llvm::Module> *mod, unique_ptr<vector<TableDesc>> *tables, const string &file, bool in_memory) { using namespace clang; struct utsname un; uname(&un); char kdir[256]; snprintf(kdir, sizeof(kdir), "%s/%s/build", KERNEL_MODULES_DIR, un.release); // clang needs to run inside the kernel dir DirStack dstack(kdir); if (!dstack.ok()) return -1; string abs_file; if (in_memory) { abs_file = "<bcc-memory-buffer>"; } else { if (file.substr(0, 1) == "/") abs_file = file; else abs_file = string(dstack.cwd()) + "/" + file; } vector<const char *> flags_cstr({"-O0", "-emit-llvm", "-I", dstack.cwd(), "-Wno-deprecated-declarations", "-x", "c", "-c", abs_file.c_str()}); KBuildHelper kbuild_helper; vector<string> kflags; if (kbuild_helper.get_flags(un.release, &kflags)) return -1; kflags.push_back("-include"); kflags.push_back(BCC_INSTALL_PREFIX "/share/bcc/include/bcc/helpers.h"); kflags.push_back("-I"); kflags.push_back(BCC_INSTALL_PREFIX "/share/bcc/include"); for (auto it = kflags.begin(); it != kflags.end(); ++it) flags_cstr.push_back(it->c_str()); // set up the error reporting class IntrusiveRefCntPtr<DiagnosticOptions> diag_opts(new DiagnosticOptions()); auto diag_client = new TextDiagnosticPrinter(llvm::errs(), &*diag_opts); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine diags(DiagID, &*diag_opts, diag_client); // set up the command line argument wrapper driver::Driver drv("", "x86_64-unknown-linux-gnu", diags); drv.setTitle("bcc-clang-driver"); drv.setCheckInputsExist(false); unique_ptr<driver::Compilation> compilation(drv.BuildCompilation(flags_cstr)); if (!compilation) return -1; // expect exactly 1 job, otherwise error const driver::JobList &jobs = compilation->getJobs(); if (jobs.size() != 1 || !isa<driver::Command>(*jobs.begin())) { SmallString<256> msg; llvm::raw_svector_ostream os(msg); jobs.Print(os, "; ", true); diags.Report(diag::err_fe_expected_compiler_job) << os.str(); return -1; } const driver::Command &cmd = cast<driver::Command>(*jobs.begin()); if (llvm::StringRef(cmd.getCreator().getName()) != "clang") { diags.Report(diag::err_fe_expected_clang_command); return -1; } // Initialize a compiler invocation object from the clang (-cc1) arguments. const driver::ArgStringList &ccargs = cmd.getArguments(); // first pass auto invocation1 = make_unique<CompilerInvocation>(); if (!CompilerInvocation::CreateFromArgs(*invocation1, const_cast<const char **>(ccargs.data()), const_cast<const char **>(ccargs.data()) + ccargs.size(), diags)) return -1; if (in_memory) { invocation1->getPreprocessorOpts().addRemappedFile("<bcc-memory-buffer>", llvm::MemoryBuffer::getMemBuffer(file).release()); invocation1->getFrontendOpts().Inputs.clear(); invocation1->getFrontendOpts().Inputs.push_back(FrontendInputFile("<bcc-memory-buffer>", IK_C)); } invocation1->getFrontendOpts().DisableFree = false; CompilerInstance compiler1; compiler1.setInvocation(invocation1.release()); compiler1.createDiagnostics(); // capture the rewritten c file string out_str; llvm::raw_string_ostream os(out_str); BFrontendAction bact(os, flags_); if (!compiler1.ExecuteAction(bact)) return -1; // this contains the open FDs *tables = bact.take_tables(); // second pass, clear input and take rewrite buffer auto invocation2 = make_unique<CompilerInvocation>(); if (!CompilerInvocation::CreateFromArgs(*invocation2, const_cast<const char **>(ccargs.data()), const_cast<const char **>(ccargs.data()) + ccargs.size(), diags)) return -1; CompilerInstance compiler2; invocation2->getPreprocessorOpts().addRemappedFile("<bcc-memory-buffer>", llvm::MemoryBuffer::getMemBuffer(out_str).release()); invocation2->getFrontendOpts().Inputs.clear(); invocation2->getFrontendOpts().Inputs.push_back(FrontendInputFile("<bcc-memory-buffer>", IK_C)); invocation2->getFrontendOpts().DisableFree = false; // suppress warnings in the 2nd pass, but bail out on errors (our fault) invocation2->getDiagnosticOpts().IgnoreWarnings = true; compiler2.setInvocation(invocation2.release()); compiler2.createDiagnostics(); EmitLLVMOnlyAction ir_act(&*ctx_); if (!compiler2.ExecuteAction(ir_act)) return -1; *mod = ir_act.takeModule(); return 0; } } // namespace ebpf <commit_msg>Add clang command line invocation to debug=0x4<commit_after>/* * Copyright (c) 2015 PLUMgrid, 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 <map> #include <string> #include <algorithm> #include <fcntl.h> #include <ftw.h> #include <map> #include <stdio.h> #include <string> #include <sys/stat.h> #include <sys/utsname.h> #include <unistd.h> #include <vector> #include <linux/bpf.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/TargetInfo.h> #include <clang/CodeGen/BackendUtil.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Driver/Compilation.h> #include <clang/Driver/Driver.h> #include <clang/Driver/Job.h> #include <clang/Driver/Tool.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Frontend/FrontendActions.h> #include <clang/Frontend/FrontendDiagnostic.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/FrontendTool/Utils.h> #include <llvm/IR/Module.h> #include "common.h" #include "exception.h" #include "kbuild_helper.h" #include "b_frontend_action.h" #include "loader.h" using std::map; using std::string; using std::unique_ptr; using std::vector; namespace ebpf { ClangLoader::ClangLoader(llvm::LLVMContext *ctx, unsigned flags) : ctx_(ctx), flags_(flags) {} ClangLoader::~ClangLoader() {} int ClangLoader::parse(unique_ptr<llvm::Module> *mod, unique_ptr<vector<TableDesc>> *tables, const string &file, bool in_memory) { using namespace clang; struct utsname un; uname(&un); char kdir[256]; snprintf(kdir, sizeof(kdir), "%s/%s/build", KERNEL_MODULES_DIR, un.release); // clang needs to run inside the kernel dir DirStack dstack(kdir); if (!dstack.ok()) return -1; string abs_file; if (in_memory) { abs_file = "<bcc-memory-buffer>"; } else { if (file.substr(0, 1) == "/") abs_file = file; else abs_file = string(dstack.cwd()) + "/" + file; } vector<const char *> flags_cstr({"-O0", "-emit-llvm", "-I", dstack.cwd(), "-Wno-deprecated-declarations", "-x", "c", "-c", abs_file.c_str()}); KBuildHelper kbuild_helper; vector<string> kflags; if (kbuild_helper.get_flags(un.release, &kflags)) return -1; kflags.push_back("-include"); kflags.push_back(BCC_INSTALL_PREFIX "/share/bcc/include/bcc/helpers.h"); kflags.push_back("-I"); kflags.push_back(BCC_INSTALL_PREFIX "/share/bcc/include"); for (auto it = kflags.begin(); it != kflags.end(); ++it) flags_cstr.push_back(it->c_str()); // set up the error reporting class IntrusiveRefCntPtr<DiagnosticOptions> diag_opts(new DiagnosticOptions()); auto diag_client = new TextDiagnosticPrinter(llvm::errs(), &*diag_opts); IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); DiagnosticsEngine diags(DiagID, &*diag_opts, diag_client); // set up the command line argument wrapper driver::Driver drv("", "x86_64-unknown-linux-gnu", diags); drv.setTitle("bcc-clang-driver"); drv.setCheckInputsExist(false); unique_ptr<driver::Compilation> compilation(drv.BuildCompilation(flags_cstr)); if (!compilation) return -1; // expect exactly 1 job, otherwise error const driver::JobList &jobs = compilation->getJobs(); if (jobs.size() != 1 || !isa<driver::Command>(*jobs.begin())) { SmallString<256> msg; llvm::raw_svector_ostream os(msg); jobs.Print(os, "; ", true); diags.Report(diag::err_fe_expected_compiler_job) << os.str(); return -1; } const driver::Command &cmd = cast<driver::Command>(*jobs.begin()); if (llvm::StringRef(cmd.getCreator().getName()) != "clang") { diags.Report(diag::err_fe_expected_clang_command); return -1; } // Initialize a compiler invocation object from the clang (-cc1) arguments. const driver::ArgStringList &ccargs = cmd.getArguments(); if (flags_ & 0x4) { llvm::errs() << "clang"; for (auto arg : ccargs) llvm::errs() << " " << arg; llvm::errs() << "\n"; } // first pass auto invocation1 = make_unique<CompilerInvocation>(); if (!CompilerInvocation::CreateFromArgs(*invocation1, const_cast<const char **>(ccargs.data()), const_cast<const char **>(ccargs.data()) + ccargs.size(), diags)) return -1; if (in_memory) { invocation1->getPreprocessorOpts().addRemappedFile("<bcc-memory-buffer>", llvm::MemoryBuffer::getMemBuffer(file).release()); invocation1->getFrontendOpts().Inputs.clear(); invocation1->getFrontendOpts().Inputs.push_back(FrontendInputFile("<bcc-memory-buffer>", IK_C)); } invocation1->getFrontendOpts().DisableFree = false; CompilerInstance compiler1; compiler1.setInvocation(invocation1.release()); compiler1.createDiagnostics(); // capture the rewritten c file string out_str; llvm::raw_string_ostream os(out_str); BFrontendAction bact(os, flags_); if (!compiler1.ExecuteAction(bact)) return -1; // this contains the open FDs *tables = bact.take_tables(); // second pass, clear input and take rewrite buffer auto invocation2 = make_unique<CompilerInvocation>(); if (!CompilerInvocation::CreateFromArgs(*invocation2, const_cast<const char **>(ccargs.data()), const_cast<const char **>(ccargs.data()) + ccargs.size(), diags)) return -1; CompilerInstance compiler2; invocation2->getPreprocessorOpts().addRemappedFile("<bcc-memory-buffer>", llvm::MemoryBuffer::getMemBuffer(out_str).release()); invocation2->getFrontendOpts().Inputs.clear(); invocation2->getFrontendOpts().Inputs.push_back(FrontendInputFile("<bcc-memory-buffer>", IK_C)); invocation2->getFrontendOpts().DisableFree = false; // suppress warnings in the 2nd pass, but bail out on errors (our fault) invocation2->getDiagnosticOpts().IgnoreWarnings = true; compiler2.setInvocation(invocation2.release()); compiler2.createDiagnostics(); EmitLLVMOnlyAction ir_act(&*ctx_); if (!compiler2.ExecuteAction(ir_act)) return -1; *mod = ir_act.takeModule(); return 0; } } // namespace ebpf <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "FactorizationMachineLayer.h" #include <algorithm> #include <vector> #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Logging.h" #include "paddle/utils/Stat.h" namespace paddle { REGISTER_LAYER(factorization_machine, FactorizationMachineLayer); bool FactorizationMachineLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); factorSize_ = config_.factor_size(); /* initialize the latentVectors_ */ CHECK_EQ(inputLayers_.size(), 1UL); size_t height = inputLayers_[0]->getSize(); CHECK_EQ(parameters_[0]->getSize(), height * factorSize_); latentVectors_ = std::unique_ptr<Weight>(new Weight(height, factorSize_, parameters_[0])); v2_ = Matrix::create(height, factorSize_, false, useGpu_); return true; } void FactorizationMachineLayer::forward(PassType passType) { Layer::forward(passType); const MatrixPtr& inputV = getInputValue(0); size_t batchSize = inputV->getHeight(); size_t size = getSize(); reserveOutput(batchSize, size); MatrixPtr outV = getOutputValue(); Matrix::resizeOrCreate(tmpMul_, batchSize, factorSize_, false, useGpu_); Matrix::resizeOrCreate(tmpOut_, batchSize, factorSize_, false, useGpu_); REGISTER_TIMER_INFO("FwMulTimer", getName().c_str()); tmpMul_->mul(*inputV, *latentVectors_->getW()); tmpMul_->square2(*tmpOut_); outV->sumRows(*tmpOut_, 0.5, 0); x2_ = inputV->clone(0, 0, useGpu_); if (dynamic_cast<CpuSparseMatrix*>(x2_.get())) { x2_->copyFrom(*inputV); (dynamic_cast<CpuSparseMatrix*>(x2_.get()))->square2(); } else { inputV->square2(*x2_); } latentVectors_->getW()->square2(*v2_); tmpOut_->mul(*x2_, *v2_); outV->sumRows(*tmpOut_, -0.5, 1.0); /* activation */ { REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str()); forwardActivation(); } } void FactorizationMachineLayer::backward(const UpdateCallback& callback) { /* Do derivation */ { REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str()); backwardActivation(); } const MatrixPtr& inputV = getInputValue(0); const MatrixPtr& oGrad = getOutputGrad(); MatrixPtr tmpSum = Matrix::create(1, latentVectors_->getW()->getHeight(), false, useGpu_); MatrixPtr tmpSum_T = Matrix::create(tmpSum->getRowBuf(0), latentVectors_->getW()->getHeight(), 1, false, useGpu_); /* Calculate the gradients of the latentVectors_ matrix */ if (latentVectors_->getWGrad()) { MatrixPtr tmpIn = inputV->clone(0, 0, useGpu_); if (dynamic_cast<CpuSparseMatrix*>(inputV.get())) { CpuSparseMatrix* inputV_s = dynamic_cast<CpuSparseMatrix*>(inputV.get()); CpuSparseMatrix* x2_s = dynamic_cast<CpuSparseMatrix*>(x2_.get()); CpuSparseMatrix* tmpIn_s = dynamic_cast<CpuSparseMatrix*>(tmpIn.get()); tmpIn_s->copyFrom(*inputV_s); tmpIn_s->rowScale(0, *inputV_s, *oGrad); latentVectors_->getWGrad()->mul(*tmpIn->getTranspose(), *tmpMul_, 1, 1); tmpIn_s->rowScale(0, *x2_s, *oGrad); } else { tmpIn->rowScale(0, *inputV, *oGrad); latentVectors_->getWGrad()->mul(*tmpIn->getTranspose(), *tmpMul_, 1, 1); tmpIn->rowScale(0, *x2_, *oGrad); } tmpSum->sumCols(*tmpIn, -1, 0); latentVectors_->getWGrad()->addRowScale( 0, *latentVectors_->getW(), *tmpSum_T); /* Increasing the number of gradient */ latentVectors_->getParameterPtr()->incUpdate(callback); } /* Calculate the input layers gradient */ MatrixPtr inGrad = getInputGrad(0); if (inGrad != NULL) { MatrixPtr latentVectors_T = latentVectors_->getW()->getTranspose(); inGrad->mul(*tmpMul_, *latentVectors_T, 1, 1); tmpSum_T->sumRows(*v2_, -1, 0); inGrad->addColScale(0, *inputV, *tmpSum); inGrad->rowScale(0, *inGrad, *oGrad); } } } // namespace paddle <commit_msg>Add sparse input support for factorization machine layer<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "FactorizationMachineLayer.h" #include <algorithm> #include <vector> #include "paddle/math/SparseMatrix.h" #include "paddle/utils/Logging.h" #include "paddle/utils/Stat.h" namespace paddle { REGISTER_LAYER(factorization_machine, FactorizationMachineLayer); bool FactorizationMachineLayer::init(const LayerMap& layerMap, const ParameterMap& parameterMap) { /* Initialize the basic parent class */ Layer::init(layerMap, parameterMap); factorSize_ = config_.factor_size(); /* initialize the latentVectors_ */ CHECK_EQ(inputLayers_.size(), 1UL); size_t height = inputLayers_[0]->getSize(); CHECK_EQ(parameters_[0]->getSize(), height * factorSize_); latentVectors_ = std::unique_ptr<Weight>(new Weight(height, factorSize_, parameters_[0])); v2_ = Matrix::create(height, factorSize_, false, useGpu_); return true; } void FactorizationMachineLayer::forward(PassType passType) { Layer::forward(passType); const MatrixPtr& inputV = getInputValue(0); size_t batchSize = inputV->getHeight(); size_t size = getSize(); reserveOutput(batchSize, size); MatrixPtr outV = getOutputValue(); Matrix::resizeOrCreate(tmpMul_, batchSize, factorSize_, false, useGpu_); Matrix::resizeOrCreate(tmpOut_, batchSize, factorSize_, false, useGpu_); REGISTER_TIMER_INFO("FwMulTimer", getName().c_str()); tmpMul_->mul(*inputV, *latentVectors_->getW()); tmpMul_->square2(*tmpOut_); outV->sumRows(*tmpOut_, 0.5, 0); x2_ = inputV->clone(0, 0, useGpu_); if (dynamic_cast<CpuSparseMatrix*>(x2_.get())) { x2_->copyFrom(*inputV); (dynamic_cast<CpuSparseMatrix*>(x2_.get()))->square2(); } else { inputV->square2(*x2_); } latentVectors_->getW()->square2(*v2_); tmpOut_->mul(*x2_, *v2_); outV->sumRows(*tmpOut_, -0.5, 1.0); /* activation */ { REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str()); forwardActivation(); } } void FactorizationMachineLayer::backward(const UpdateCallback& callback) { /* Do derivation */ { REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str()); backwardActivation(); } const MatrixPtr& inputV = getInputValue(0); const MatrixPtr& oGrad = getOutputGrad(); MatrixPtr tmpSum = Matrix::create(1, latentVectors_->getW()->getHeight(), false, useGpu_); MatrixPtr tmpSum_T = Matrix::create(tmpSum->getRowBuf(0), latentVectors_->getW()->getHeight(), 1, false, useGpu_); /* Calculate the gradients of the latentVectors_ matrix */ if (latentVectors_->getWGrad()) { MatrixPtr tmpIn = inputV->clone(0, 0, useGpu_); if (dynamic_cast<CpuSparseMatrix*>(inputV.get())) { CpuSparseMatrix* inputV_s = dynamic_cast<CpuSparseMatrix*>(inputV.get()); CpuSparseMatrix* x2_s = dynamic_cast<CpuSparseMatrix*>(x2_.get()); CpuSparseMatrix* tmpIn_s = dynamic_cast<CpuSparseMatrix*>(tmpIn.get()); tmpIn_s->copyFrom(*inputV_s); tmpIn_s->rowScale(0, *inputV_s, *oGrad); latentVectors_->getWGrad()->mul(*tmpIn_s->getTranspose(), *tmpMul_, 1, 1); tmpIn_s->rowScale(0, *x2_s, *oGrad); MatrixPtr ones = Matrix::create(1, inputV->getHeight(), false, useGpu_); ones->zeroMem(); ones->add(-1); tmpSum->mul(*ones, *tmpIn_s, 1, 0); } else { tmpIn->rowScale(0, *inputV, *oGrad); latentVectors_->getWGrad()->mul(*tmpIn->getTranspose(), *tmpMul_, 1, 1); tmpIn->rowScale(0, *x2_, *oGrad); tmpSum->sumCols(*tmpIn, -1, 0); } latentVectors_->getWGrad()->addRowScale( 0, *latentVectors_->getW(), *tmpSum_T); /* Increasing the number of gradient */ latentVectors_->getParameterPtr()->incUpdate(callback); } /* Calculate the input layers gradient */ MatrixPtr inGrad = getInputGrad(0); if (inGrad != NULL) { MatrixPtr latentVectors_T = latentVectors_->getW()->getTranspose(); inGrad->mul(*tmpMul_, *latentVectors_T, 1, 1); tmpSum_T->sumRows(*v2_, -1, 0); inGrad->addColScale(0, *inputV, *tmpSum); inGrad->rowScale(0, *inGrad, *oGrad); } } } // namespace paddle <|endoftext|>
<commit_before>/* <plugins/director/DirectorPlugin.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> * * -------------------------------------------------------------------------- * * plugin type: content generator * * description: * Implements basic load balancing, ideally taking out the need of an HAproxy * in front of us. * * setup API: * function director.create(string director_name, * string backend_name_1 => string backend_url_1, * ...); * * function director.load(string director_name_1 => string path_to_db, * ...); * * function director.cache.ttl(timespan, [timespan]) * function director.cache.deliver_stale * function director.cache.deliver_active * * request processing API: * handler director.balance(string director, string bucket = ""); * handler director.pass(string director, string backend); * * handler director.fcgi(socket_spec); * handler director.http(socket_spec); * * handler director.ondemand(); * function director.cache.ttl(timespan ttl); * function director.cache.ttl(timespan ttl, timespan shadow_ttl); * function director.cache.key(string pattern); * function director.cache.bypass(); */ #include "DirectorPlugin.h" #include "Director.h" #include "Backend.h" #include "ApiRequest.h" #include "RequestNotes.h" #include "RoadWarrior.h" #include "HaproxyApi.h" #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/SocketSpec.h> #include <x0/Url.h> #include <x0/Types.h> using namespace x0; DirectorPlugin::DirectorPlugin(HttpServer& srv, const std::string& name) : HttpPlugin(srv, name), directors_(), roadWarrior_(), haproxyApi_(new HaproxyApi(&directors_)) { registerSetupFunction<DirectorPlugin, &DirectorPlugin::director_create>("director.create", FlowValue::VOID); registerSetupFunction<DirectorPlugin, &DirectorPlugin::director_load>("director.load", FlowValue::VOID); registerFunction<DirectorPlugin, &DirectorPlugin::director_cache_bypass>("director.cache.bypass", FlowValue::VOID); registerHandler<DirectorPlugin, &DirectorPlugin::director_balance>("director.balance"); registerHandler<DirectorPlugin, &DirectorPlugin::director_pass>("director.pass"); registerHandler<DirectorPlugin, &DirectorPlugin::director_api>("director.api"); registerHandler<DirectorPlugin, &DirectorPlugin::director_fcgi>("director.fcgi"); // "fastcgi" registerHandler<DirectorPlugin, &DirectorPlugin::director_http>("director.http"); // "proxy.reverse" registerHandler<DirectorPlugin, &DirectorPlugin::director_haproxy_stats>("director.haproxy_stats"); registerHandler<DirectorPlugin, &DirectorPlugin::director_haproxy_monitor>("director.haproxy_monitor"); roadWarrior_ = new RoadWarrior(srv.selectWorker()); } DirectorPlugin::~DirectorPlugin() { for (auto director: directors_) delete director.second; delete roadWarrior_; delete haproxyApi_; } RequestNotes* DirectorPlugin::requestNotes(HttpRequest* r) { if (auto notes = r->customData<RequestNotes>(this)) return notes; return r->setCustomData<RequestNotes>(this, r); } // {{{ setup_function director.load(...) void DirectorPlugin::director_load(const FlowParams& args, FlowValue& result) { for (auto& arg: args) { if (!arg.isArray()) continue; const FlowArray& fa = arg.toArray(); if (fa.size() != 2) continue; const FlowValue& directorName = fa[0]; if (!directorName.isString()) continue; const FlowValue& path = fa[1]; if (!path.isString()) continue; // TODO verify that given director name is still available. // TODO verify that no director has been instanciated already by given path. server().log(Severity::debug, "director: Loading director %s from %s.", directorName.toString(), path.toString()); Director* director = new Director(server().nextWorker(), directorName.toString()); if (!director) continue; director->load(path.toString()); directors_[directorName.toString()] = director; } } // }}} // {{{ setup_function director.create(...) void DirectorPlugin::director_create(const FlowParams& args, FlowValue& result) { const FlowValue& directorId = args[0]; if (!directorId.isString()) return; Director* director = createDirector(directorId.toString()); if (!director) return; for (auto& arg: args.shift()) { if (!arg.isArray()) continue; const FlowArray& fa = arg.toArray(); if (fa.size() != 2) continue; const FlowValue& backendName = fa[0]; if (!backendName.isString()) continue; const FlowValue& backendUrl = fa[1]; if (!backendUrl.isString()) continue; registerBackend(director, backendName.toString(), backendUrl.toString()); } directors_[director->name()] = director; } Director* DirectorPlugin::createDirector(const char* id) { server().log(Severity::debug, "director: Creating director %s", id); Director* director = new Director(server().nextWorker(), id); return director; } Backend* DirectorPlugin::registerBackend(Director* director, const char* name, const char* url) { server().log(Severity::debug, "director: %s, backend %s: %s", director->name().c_str(), name, url); return director->createBackend(name, Url::parse(url)); } // }}} // {{{ function director.cache.bypass() void DirectorPlugin::director_cache_bypass(HttpRequest* r, const FlowParams& args, FlowValue& result) { // FIXME we cannot do this currently, as requestNotes is director-dependant (which is wrong, a request can belong to only one director anyway) // TODO: then add `RequestNotes::manager`. #if 0 auto notes = requestNotes(r); notes->cacheIgnore = true; #endif } // }}} // {{{ handler director.balance(string director_id [, string segment_id ] ); /** * \returns always true. */ bool DirectorPlugin::internalServerError(HttpRequest* r) { if (r->status != x0::HttpStatus::Undefined) r->status = x0::HttpStatus::InternalServerError; r->finish(); return true; } // handler director.balance(string director_name, string bucket_name = ''); bool DirectorPlugin::director_balance(HttpRequest* r, const FlowParams& args) { std::string directorName; Director* director = nullptr; std::string bucketName; RequestShaper::Node* bucket = nullptr; switch (args.size()) { case 2: if (!args[1].isString() && !args[1].isBuffer()) { r->log(Severity::error, "director.balance(): Invalid argument."); return internalServerError(r); } bucketName = args[1].asString(); // fall through case 1: { if (!args[0].isString() && !args[0].isBuffer()) { r->log(Severity::error, "director.balance(): Invalid argument."); return internalServerError(r); } directorName = args[0].asString(); auto i = directors_.find(directorName); if (i == directors_.end()) { r->log(Severity::error, "director.balance(): No director with name '%s' configured.", directorName.c_str()); return internalServerError(r); } director = i->second; if (!bucketName.empty()) { bucket = director->findBucket(bucketName); if (!bucket) { // explicit bucket specified, but not found -> ignore. bucket = director->rootBucket(); r->log(Severity::error, "director: Requested bucket '%s' not found in director '%s'. Assigning root bucket.", bucketName.c_str(), directorName.c_str()); } } else { bucket = director->rootBucket(); } break; } case 0: r->log(Severity::error, "director.balance(): No arguments passed."); return internalServerError(r); default: r->log(Severity::error, "director.balance(): Invalid argument count passed."); return internalServerError(r); } auto rn = requestNotes(r); rn->manager = director; server().log(Severity::debug, "director: passing request to %s [%s].", director->name().c_str(), bucket->name().c_str()); director->schedule(rn, bucket); return true; } // }}} // {{{ handler director.pass(string director_id [, string backend_id ] ); bool DirectorPlugin::director_pass(HttpRequest* r, const FlowParams& args) { std::string directorName; Director* director = nullptr; std::string backendName; Backend* backend = nullptr; switch (args.size()) { case 2: if (!args[1].isString() && !args[1].isBuffer()) { r->log(Severity::error, "director.pass(): Invalid argument."); break; } backendName = args[1].asString(); // fall though case 1: { if (!args[0].isString() && !args[0].isBuffer()) { r->log(Severity::error, "director.pass(): Invalid argument."); break; } directorName = args[0].asString(); auto i = directors_.find(directorName); if (i == directors_.end()) { r->log(Severity::error, "director.pass(): No director with name '%s' configured.", directorName.c_str()); break; } director = i->second; // custom backend route if (!backendName.empty()) { backend = director->findBackend(backendName); if (!backend) { // explicit backend specified, but not found -> do not serve. r->log(Severity::error, "director: Requested backend '%s' not found.", backendName.c_str()); return internalServerError(r); } } break; } case 0: { r->log(Severity::error, "director.pass(): No arguments passed."); break; } default: { r->log(Severity::error, "director.pass(): Too many arguments passed."); break; } } if (!director) return internalServerError(r); server().log(Severity::debug, "director: passing request to %s [backend %s].", director->name().c_str(), backend->name().c_str()); auto rn = requestNotes(r); rn->manager = director; director->schedule(rn, backend); return true; } // }}} // {{{ handler director.api(string prefix); bool DirectorPlugin::director_api(HttpRequest* r, const FlowParams& args) { const char* prefix = args[0].toString(); if (!r->path.begins(prefix)) return false; BufferRef path(r->path.ref(strlen(prefix))); return ApiRequest::process(&directors_, r, path); } // }}} // {{{ handler director.fcgi(socketspec); bool DirectorPlugin::director_fcgi(HttpRequest* r, const FlowParams& args) { x0::SocketSpec spec; spec << args; roadWarrior_->handleRequest(requestNotes(r), spec, RoadWarrior::FCGI); return true; } // }}} // {{{ handler director.http(socketspec); bool DirectorPlugin::director_http(HttpRequest* r, const FlowParams& args) { x0::SocketSpec spec; spec << args; roadWarrior_->handleRequest(requestNotes(r), spec, RoadWarrior::HTTP); return true; } // }}} // {{{ haproxy compatibility API bool DirectorPlugin::director_haproxy_monitor(x0::HttpRequest* r, const x0::FlowParams& args) { std::string prefix("/"); if (!args.empty()) { if (args.size() > 1) { r->log(Severity::error, "director.haproxy_stats: invalid argument count"); r->status = HttpStatus::InternalServerError; r->finish(); return true; } if (!args[0].isString()) { r->log(Severity::error, "director.haproxy_stats: invalid argument type."); r->status = HttpStatus::InternalServerError; r->finish(); return true; } prefix = args[0].toString(); } if (!r->path.begins(prefix) && !r->unparsedUri.begins(prefix)) return false; haproxyApi_->monitor(r); return true; } bool DirectorPlugin::director_haproxy_stats(x0::HttpRequest* r, const x0::FlowParams& args) { std::string prefix("/"); if (!args.empty()) { if (args.size() > 1) { r->log(Severity::error, "director.haproxy_stats: invalid argument count"); r->status = HttpStatus::InternalServerError; r->finish(); return true; } if (!args[0].isString()) { r->log(Severity::error, "director.haproxy_stats: invalid argument type."); r->status = HttpStatus::InternalServerError; r->finish(); return true; } prefix = args[0].toString(); } if (!r->path.begins(prefix) && !r->unparsedUri.begins(prefix)) return false; haproxyApi_->stats(r, prefix); return true; } // }}} X0_EXPORT_PLUGIN_CLASS(DirectorPlugin) <commit_msg>[plugins] director: enables director.cache.bypass() flow function<commit_after>/* <plugins/director/DirectorPlugin.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> * * -------------------------------------------------------------------------- * * plugin type: content generator * * description: * Implements basic load balancing, ideally taking out the need of an HAproxy * in front of us. * * setup API: * function director.create(string director_name, * string backend_name_1 => string backend_url_1, * ...); * * function director.load(string director_name_1 => string path_to_db, * ...); * * function director.cache.ttl(timespan, [timespan]) * function director.cache.deliver_stale * function director.cache.deliver_active * * request processing API: * handler director.balance(string director, string bucket = ""); * handler director.pass(string director, string backend); * * handler director.fcgi(socket_spec); * handler director.http(socket_spec); * * handler director.ondemand(); * function director.cache.ttl(timespan ttl); * function director.cache.ttl(timespan ttl, timespan shadow_ttl); * function director.cache.key(string pattern); * function director.cache.bypass(); */ #include "DirectorPlugin.h" #include "Director.h" #include "Backend.h" #include "ApiRequest.h" #include "RequestNotes.h" #include "RoadWarrior.h" #include "HaproxyApi.h" #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/SocketSpec.h> #include <x0/Url.h> #include <x0/Types.h> using namespace x0; DirectorPlugin::DirectorPlugin(HttpServer& srv, const std::string& name) : HttpPlugin(srv, name), directors_(), roadWarrior_(), haproxyApi_(new HaproxyApi(&directors_)) { registerSetupFunction<DirectorPlugin, &DirectorPlugin::director_create>("director.create", FlowValue::VOID); registerSetupFunction<DirectorPlugin, &DirectorPlugin::director_load>("director.load", FlowValue::VOID); #if defined(X0_DIRECTOR_CACHE) registerFunction<DirectorPlugin, &DirectorPlugin::director_cache_bypass>("director.cache.bypass", FlowValue::VOID); #endif registerHandler<DirectorPlugin, &DirectorPlugin::director_balance>("director.balance"); registerHandler<DirectorPlugin, &DirectorPlugin::director_pass>("director.pass"); registerHandler<DirectorPlugin, &DirectorPlugin::director_api>("director.api"); registerHandler<DirectorPlugin, &DirectorPlugin::director_fcgi>("director.fcgi"); // "fastcgi" registerHandler<DirectorPlugin, &DirectorPlugin::director_http>("director.http"); // "proxy.reverse" registerHandler<DirectorPlugin, &DirectorPlugin::director_haproxy_stats>("director.haproxy_stats"); registerHandler<DirectorPlugin, &DirectorPlugin::director_haproxy_monitor>("director.haproxy_monitor"); roadWarrior_ = new RoadWarrior(srv.selectWorker()); } DirectorPlugin::~DirectorPlugin() { for (auto director: directors_) delete director.second; delete roadWarrior_; delete haproxyApi_; } RequestNotes* DirectorPlugin::requestNotes(HttpRequest* r) { if (auto notes = r->customData<RequestNotes>(this)) return notes; return r->setCustomData<RequestNotes>(this, r); } // {{{ setup_function director.load(...) void DirectorPlugin::director_load(const FlowParams& args, FlowValue& result) { for (auto& arg: args) { if (!arg.isArray()) continue; const FlowArray& fa = arg.toArray(); if (fa.size() != 2) continue; const FlowValue& directorName = fa[0]; if (!directorName.isString()) continue; const FlowValue& path = fa[1]; if (!path.isString()) continue; // TODO verify that given director name is still available. // TODO verify that no director has been instanciated already by given path. server().log(Severity::debug, "director: Loading director %s from %s.", directorName.toString(), path.toString()); Director* director = new Director(server().nextWorker(), directorName.toString()); if (!director) continue; director->load(path.toString()); directors_[directorName.toString()] = director; } } // }}} // {{{ setup_function director.create(...) void DirectorPlugin::director_create(const FlowParams& args, FlowValue& result) { const FlowValue& directorId = args[0]; if (!directorId.isString()) return; Director* director = createDirector(directorId.toString()); if (!director) return; for (auto& arg: args.shift()) { if (!arg.isArray()) continue; const FlowArray& fa = arg.toArray(); if (fa.size() != 2) continue; const FlowValue& backendName = fa[0]; if (!backendName.isString()) continue; const FlowValue& backendUrl = fa[1]; if (!backendUrl.isString()) continue; registerBackend(director, backendName.toString(), backendUrl.toString()); } directors_[director->name()] = director; } Director* DirectorPlugin::createDirector(const char* id) { server().log(Severity::debug, "director: Creating director %s", id); Director* director = new Director(server().nextWorker(), id); return director; } Backend* DirectorPlugin::registerBackend(Director* director, const char* name, const char* url) { server().log(Severity::debug, "director: %s, backend %s: %s", director->name().c_str(), name, url); return director->createBackend(name, Url::parse(url)); } // }}} // {{{ function director.cache.bypass() #if defined(X0_DIRECTOR_CACHE) void DirectorPlugin::director_cache_bypass(HttpRequest* r, const FlowParams& args, FlowValue& result) { auto notes = requestNotes(r); notes->cacheIgnore = true; } #endif // }}} // {{{ handler director.balance(string director_id [, string segment_id ] ); /** * \returns always true. */ bool DirectorPlugin::internalServerError(HttpRequest* r) { if (r->status != x0::HttpStatus::Undefined) r->status = x0::HttpStatus::InternalServerError; r->finish(); return true; } // handler director.balance(string director_name, string bucket_name = ''); bool DirectorPlugin::director_balance(HttpRequest* r, const FlowParams& args) { std::string directorName; Director* director = nullptr; std::string bucketName; RequestShaper::Node* bucket = nullptr; switch (args.size()) { case 2: if (!args[1].isString() && !args[1].isBuffer()) { r->log(Severity::error, "director.balance(): Invalid argument."); return internalServerError(r); } bucketName = args[1].asString(); // fall through case 1: { if (!args[0].isString() && !args[0].isBuffer()) { r->log(Severity::error, "director.balance(): Invalid argument."); return internalServerError(r); } directorName = args[0].asString(); auto i = directors_.find(directorName); if (i == directors_.end()) { r->log(Severity::error, "director.balance(): No director with name '%s' configured.", directorName.c_str()); return internalServerError(r); } director = i->second; if (!bucketName.empty()) { bucket = director->findBucket(bucketName); if (!bucket) { // explicit bucket specified, but not found -> ignore. bucket = director->rootBucket(); r->log(Severity::error, "director: Requested bucket '%s' not found in director '%s'. Assigning root bucket.", bucketName.c_str(), directorName.c_str()); } } else { bucket = director->rootBucket(); } break; } case 0: r->log(Severity::error, "director.balance(): No arguments passed."); return internalServerError(r); default: r->log(Severity::error, "director.balance(): Invalid argument count passed."); return internalServerError(r); } auto rn = requestNotes(r); rn->manager = director; server().log(Severity::debug, "director: passing request to %s [%s].", director->name().c_str(), bucket->name().c_str()); director->schedule(rn, bucket); return true; } // }}} // {{{ handler director.pass(string director_id [, string backend_id ] ); bool DirectorPlugin::director_pass(HttpRequest* r, const FlowParams& args) { std::string directorName; Director* director = nullptr; std::string backendName; Backend* backend = nullptr; switch (args.size()) { case 2: if (!args[1].isString() && !args[1].isBuffer()) { r->log(Severity::error, "director.pass(): Invalid argument."); break; } backendName = args[1].asString(); // fall though case 1: { if (!args[0].isString() && !args[0].isBuffer()) { r->log(Severity::error, "director.pass(): Invalid argument."); break; } directorName = args[0].asString(); auto i = directors_.find(directorName); if (i == directors_.end()) { r->log(Severity::error, "director.pass(): No director with name '%s' configured.", directorName.c_str()); break; } director = i->second; // custom backend route if (!backendName.empty()) { backend = director->findBackend(backendName); if (!backend) { // explicit backend specified, but not found -> do not serve. r->log(Severity::error, "director: Requested backend '%s' not found.", backendName.c_str()); return internalServerError(r); } } break; } case 0: { r->log(Severity::error, "director.pass(): No arguments passed."); break; } default: { r->log(Severity::error, "director.pass(): Too many arguments passed."); break; } } if (!director) return internalServerError(r); server().log(Severity::debug, "director: passing request to %s [backend %s].", director->name().c_str(), backend->name().c_str()); auto rn = requestNotes(r); rn->manager = director; director->schedule(rn, backend); return true; } // }}} // {{{ handler director.api(string prefix); bool DirectorPlugin::director_api(HttpRequest* r, const FlowParams& args) { const char* prefix = args[0].toString(); if (!r->path.begins(prefix)) return false; BufferRef path(r->path.ref(strlen(prefix))); return ApiRequest::process(&directors_, r, path); } // }}} // {{{ handler director.fcgi(socketspec); bool DirectorPlugin::director_fcgi(HttpRequest* r, const FlowParams& args) { x0::SocketSpec spec; spec << args; roadWarrior_->handleRequest(requestNotes(r), spec, RoadWarrior::FCGI); return true; } // }}} // {{{ handler director.http(socketspec); bool DirectorPlugin::director_http(HttpRequest* r, const FlowParams& args) { x0::SocketSpec spec; spec << args; roadWarrior_->handleRequest(requestNotes(r), spec, RoadWarrior::HTTP); return true; } // }}} // {{{ haproxy compatibility API bool DirectorPlugin::director_haproxy_monitor(x0::HttpRequest* r, const x0::FlowParams& args) { std::string prefix("/"); if (!args.empty()) { if (args.size() > 1) { r->log(Severity::error, "director.haproxy_stats: invalid argument count"); r->status = HttpStatus::InternalServerError; r->finish(); return true; } if (!args[0].isString()) { r->log(Severity::error, "director.haproxy_stats: invalid argument type."); r->status = HttpStatus::InternalServerError; r->finish(); return true; } prefix = args[0].toString(); } if (!r->path.begins(prefix) && !r->unparsedUri.begins(prefix)) return false; haproxyApi_->monitor(r); return true; } bool DirectorPlugin::director_haproxy_stats(x0::HttpRequest* r, const x0::FlowParams& args) { std::string prefix("/"); if (!args.empty()) { if (args.size() > 1) { r->log(Severity::error, "director.haproxy_stats: invalid argument count"); r->status = HttpStatus::InternalServerError; r->finish(); return true; } if (!args[0].isString()) { r->log(Severity::error, "director.haproxy_stats: invalid argument type."); r->status = HttpStatus::InternalServerError; r->finish(); return true; } prefix = args[0].toString(); } if (!r->path.begins(prefix) && !r->unparsedUri.begins(prefix)) return false; haproxyApi_->stats(r, prefix); return true; } // }}} X0_EXPORT_PLUGIN_CLASS(DirectorPlugin) <|endoftext|>
<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #include "math/StepFunction.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include <algorithm> #include <limits> #include <utility> #include <vector> #include <cmath> namespace aleph { namespace detail { template <class T> struct EventPoint { T value; bool destroyer; bool operator<( const EventPoint& other ) const noexcept { // Sort event point by their corresponding values. In case of ties, // consider creators to come after destroyers. This makes sense, as // a creator may increase the number of active intervals again. return value < other.value || ( value == other.value && destroyer && !other.destroyer ); } }; template <class T> T next( T x ) { if( std::numeric_limits<T>::is_integer ) return x+1; else return std::nextafter( x, std::numeric_limits<T>::max() ); } } // namespace detail /** Calculates the persistence indicator function of a persistence diagram. This function counts the number of 'active' intervals for every parameter value. It is a stable summary of a diagram and may be used to discern more information about the topology and its variation over time. */ template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D ) { using namespace detail; using namespace math; using EP = EventPoint<DataType>; std::vector<EP> eventPoints; eventPoints.reserve( 2 * D.size() ); for( auto&& p : D ) { eventPoints.push_back( { p.x(), false } ); eventPoints.push_back( { p.y(), true } ); } std::sort( eventPoints.begin(), eventPoints.end() ); unsigned numActiveFeatures = 0; // Lambda expression for counting duplicate event points that appear after a // certain index in the vector of event points. Duplicate event points occur // if the persistence diagram contains points with equal values. auto numDuplicateValues = [&eventPoints] ( std::size_t i ) { auto eventPoint = eventPoints.at(i); unsigned numOccurrences = 0; unsigned numDestroyers = 0; do { numDestroyers += eventPoints.at(i).destroyer; ++numOccurrences; ++i; } while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value ); return std::make_pair( numOccurrences, numDestroyers ); }; StepFunction<DataType> f; // Previous interval end point. This is required in order to create proper // indicator functions later on. DataType previous = DataType(); for( std::size_t i = 0; i < eventPoints.size(); ) { auto pair = numDuplicateValues(i); auto occurrences = pair.first; auto destroyers = pair.second; auto creators = occurrences - destroyers; bool useNextPoint = false; // Case 1: No duplicates or duplicates of the same type. In this case, the // number of active intervals changes and we add an interval. It comprises // the number of active intervals up to this point. if( occurrences == 1 || creators == occurrences || creators == 0 ) { if( i != 0 ) f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) ); } // Case 2: There are duplicate creation & destruction values. This // necessitates the creation of two intervals: one interval at the // current even point, with the proper number of active intervals, // the other one *directly* afterwards to indicate the destruction // implied by the values. else { f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) ); useNextPoint = true; } numActiveFeatures += creators; numActiveFeatures -= destroyers; previous = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value; i += occurrences; } return f; } } // namespace aleph #endif <commit_msg>Updated persistence indicator function calculation<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__ #include "math/StepFunction.hh" #include "persistenceDiagrams/PersistenceDiagram.hh" #include <algorithm> #include <limits> #include <utility> #include <vector> #include <cmath> namespace aleph { namespace detail { template <class T> struct EventPoint { T value; bool destroyer; bool operator<( const EventPoint& other ) const noexcept { // Sort event point by their corresponding values. In case of ties, // consider creators to come after destroyers. This makes sense, as // a creator may increase the number of active intervals again. return value < other.value || ( value == other.value && destroyer && !other.destroyer ); } }; template <class T> T next( T x ) { if( std::numeric_limits<T>::is_integer ) return x+1; else return std::nextafter( x, std::numeric_limits<T>::max() ); } } // namespace detail /** Calculates the persistence indicator function of a persistence diagram. This function counts the number of 'active' intervals for every parameter value. It is a stable summary of a diagram and may be used to discern more information about the topology and its variation over time. */ template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D ) { using namespace detail; using namespace math; using EP = EventPoint<DataType>; std::vector<EP> eventPoints; eventPoints.reserve( 2 * D.size() ); for( auto&& p : D ) { eventPoints.push_back( { p.x(), false } ); eventPoints.push_back( { p.y(), true } ); } std::sort( eventPoints.begin(), eventPoints.end() ); unsigned numActiveFeatures = 0; // Lambda expression for counting duplicate event points that appear after a // certain index in the vector of event points. Duplicate event points occur // if the persistence diagram contains points with equal values. auto numDuplicateValues = [&eventPoints] ( std::size_t i ) { auto eventPoint = eventPoints.at(i); unsigned numOccurrences = 0; unsigned numDestroyers = 0; do { numDestroyers += eventPoints.at(i).destroyer; ++numOccurrences; ++i; } while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value ); return std::make_pair( numOccurrences, numDestroyers ); }; StepFunction<DataType> f; // Previous interval end point. This is required in order to create proper // indicator functions later on. DataType previous = DataType(); for( std::size_t i = 0; i < eventPoints.size(); ) { auto pair = numDuplicateValues(i); auto occurrences = pair.first; auto destroyers = pair.second; auto creators = occurrences - destroyers; bool useNextPoint = false; // Case 1: No duplicates or duplicates of the same type. In this case, the // number of active intervals changes and we add an interval. It comprises // the number of active intervals up to this point. if( occurrences == 1 || creators == occurrences || creators == 0 ) { if( i != 0 ) f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) ); } // Case 2: There are duplicate creation & destruction values. This // necessitates the creation of two intervals: one interval at the // current event point, with the proper number of active intervals, // the other one *directly* afterwards to indicate the destruction // implied by the values. else { f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) ); useNextPoint = true; } numActiveFeatures += creators; numActiveFeatures -= destroyers; previous = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value; i += occurrences; } return f; } } // namespace aleph #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $ #include "postgis.hpp" #include <mapnik/global.hpp> #include <mapnik/wkb.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using std::string; postgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs, unsigned num_attrs=0) : rs_(rs), num_attrs_(num_attrs), totalGeomSize_(0), count_(0) {} feature_ptr postgis_featureset::next() { if (rs_->next()) { feature_ptr feature(new Feature(count_)); int size=rs_->getFieldLength(0); const char *data=rs_->getValue(0); geometry_ptr geom=geometry_utils::from_wkb(data,size,-1); totalGeomSize_+=size; if (geom) { feature->set_geometry(geom); for (unsigned pos=1;pos<num_attrs_;++pos) { std::string name = rs_->getFieldName(pos); const char* buf=rs_->getValue(pos); int oid = rs_->getTypeOID(pos); if (oid==23) //int4 { int val = int4net(buf); boost::put(*feature,name,val); } else if (oid==21) //int2 { int val = int2net(buf); boost::put(*feature,name,val); } else if (oid == 700) // float4 { float val; float4net(val,buf); boost::put(*feature,name,val); } else if (oid == 701) // float8 { double val; float8net(val,buf); boost::put(*feature,name,val); } else if (oid==1042 || oid==1043) //bpchar or varchar { boost::put(*feature,name,buf); } else { boost::put(*feature,name,0); } } ++count_; } return feature; } else { rs_->close(); std::clog << "totalGeomSize="<<totalGeomSize_<<" bytes"<<std::endl; std::clog << "count="<<count_<<std::endl; return feature_ptr(); } } postgis_featureset::~postgis_featureset() { rs_->close(); } <commit_msg>Bugfix for PostGIS plugin.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $ #include "postgis.hpp" #include <mapnik/global.hpp> #include <mapnik/wkb.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using std::string; postgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs, unsigned num_attrs=0) : rs_(rs), num_attrs_(num_attrs), totalGeomSize_(0), count_(0) {} feature_ptr postgis_featureset::next() { if (rs_->next()) { feature_ptr feature(new Feature(count_)); int size=rs_->getFieldLength(0); const char *data=rs_->getValue(0); geometry_ptr geom=geometry_utils::from_wkb(data,size,-1); totalGeomSize_+=size; if (geom) { feature->set_geometry(geom); for (unsigned pos=1;pos<num_attrs_+1;++pos) { std::string name = rs_->getFieldName(pos); const char* buf=rs_->getValue(pos); int oid = rs_->getTypeOID(pos); if (oid==23) //int4 { int val = int4net(buf); boost::put(*feature,name,val); } else if (oid==21) //int2 { int val = int2net(buf); boost::put(*feature,name,val); } else if (oid == 700) // float4 { float val; float4net(val,buf); boost::put(*feature,name,val); } else if (oid == 701) // float8 { double val; float8net(val,buf); boost::put(*feature,name,val); } else if (oid==1042 || oid==1043) //bpchar or varchar { boost::put(*feature,name,buf); } else { boost::put(*feature,name,0); } } ++count_; } return feature; } else { rs_->close(); std::clog << "totalGeomSize="<<totalGeomSize_<<" bytes"<<std::endl; std::clog << "count="<<count_<<std::endl; return feature_ptr(); } } postgis_featureset::~postgis_featureset() { rs_->close(); } <|endoftext|>
<commit_before>//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CursorVisitor.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXTranslationUnit.h" #include "clang/AST/DeclObjC.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/Support/Compiler.h" using namespace clang; using namespace cxcursor; using namespace cxindex; static void getTopOverriddenMethods(CXTranslationUnit TU, const Decl *D, SmallVectorImpl<const Decl *> &Methods) { if (!D) return; if (!isa<ObjCMethodDecl>(D) && !isa<CXXMethodDecl>(D)) return; SmallVector<CXCursor, 8> Overridden; cxcursor::getOverriddenCursors(cxcursor::MakeCXCursor(D, TU), Overridden); if (Overridden.empty()) { Methods.push_back(D->getCanonicalDecl()); return; } for (SmallVector<CXCursor, 8>::iterator I = Overridden.begin(), E = Overridden.end(); I != E; ++I) getTopOverriddenMethods(TU, cxcursor::getCursorDecl(*I), Methods); } namespace { struct FindFileIdRefVisitData { CXTranslationUnit TU; FileID FID; const Decl *Dcl; int SelectorIdIdx; CXCursorAndRangeVisitor visitor; typedef SmallVector<const Decl *, 8> TopMethodsTy; TopMethodsTy TopMethods; FindFileIdRefVisitData(CXTranslationUnit TU, FileID FID, const Decl *D, int selectorIdIdx, CXCursorAndRangeVisitor visitor) : TU(TU), FID(FID), SelectorIdIdx(selectorIdIdx), visitor(visitor) { Dcl = getCanonical(D); getTopOverriddenMethods(TU, Dcl, TopMethods); } ASTContext &getASTContext() const { return cxtu::getASTUnit(TU)->getASTContext(); } /// \brief We are looking to find all semantically relevant identifiers, /// so the definition of "canonical" here is different than in the AST, e.g. /// /// \code /// class C { /// C() {} /// }; /// \endcode /// /// we consider the canonical decl of the constructor decl to be the class /// itself, so both 'C' can be highlighted. const Decl *getCanonical(const Decl *D) const { if (!D) return 0; D = D->getCanonicalDecl(); if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) { if (ImplD->getClassInterface()) return getCanonical(ImplD->getClassInterface()); } else if (const CXXConstructorDecl *CXXCtorD = dyn_cast<CXXConstructorDecl>(D)) { return getCanonical(CXXCtorD->getParent()); } return D; } bool isHit(const Decl *D) const { if (!D) return false; D = getCanonical(D); if (D == Dcl) return true; if (isa<ObjCMethodDecl>(D) || isa<CXXMethodDecl>(D)) return isOverriddingMethod(D); return false; } private: bool isOverriddingMethod(const Decl *D) const { if (std::find(TopMethods.begin(), TopMethods.end(), D) != TopMethods.end()) return true; TopMethodsTy methods; getTopOverriddenMethods(TU, D, methods); for (TopMethodsTy::iterator I = methods.begin(), E = methods.end(); I != E; ++I) { if (std::find(TopMethods.begin(), TopMethods.end(), *I) != TopMethods.end()) return true; } return false; } }; } // end anonymous namespace. /// \brief For a macro \arg Loc, returns the file spelling location and sets /// to \arg isMacroArg whether the spelling resides inside a macro definition or /// a macro argument. static SourceLocation getFileSpellingLoc(SourceManager &SM, SourceLocation Loc, bool &isMacroArg) { assert(Loc.isMacroID()); SourceLocation SpellLoc = SM.getImmediateSpellingLoc(Loc); if (SpellLoc.isMacroID()) return getFileSpellingLoc(SM, SpellLoc, isMacroArg); isMacroArg = SM.isMacroArgExpansion(Loc); return SpellLoc; } static enum CXChildVisitResult findFileIdRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursor declCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(declCursor.kind)) return CXChildVisit_Recurse; const Decl *D = cxcursor::getCursorDecl(declCursor); if (!D) return CXChildVisit_Continue; FindFileIdRefVisitData *data = (FindFileIdRefVisitData *)client_data; if (data->isHit(D)) { cursor = cxcursor::getSelectorIdentifierCursor(data->SelectorIdIdx, cursor); // We are looking for identifiers to highlight so for objc methods (and // not a parameter) we can only highlight the selector identifiers. if ((cursor.kind == CXCursor_ObjCClassMethodDecl || cursor.kind == CXCursor_ObjCInstanceMethodDecl) && cxcursor::getSelectorIdentifierIndex(cursor) == -1) return CXChildVisit_Recurse; if (clang_isExpression(cursor.kind)) { if (cursor.kind == CXCursor_DeclRefExpr || cursor.kind == CXCursor_MemberRefExpr) { // continue.. } else if (cursor.kind == CXCursor_ObjCMessageExpr && cxcursor::getSelectorIdentifierIndex(cursor) != -1) { // continue.. } else return CXChildVisit_Recurse; } SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); SourceLocation SelIdLoc = cxcursor::getSelectorIdentifierLoc(cursor); if (SelIdLoc.isValid()) Loc = SelIdLoc; ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (LocInfo.first != data->FID) return CXChildVisit_Recurse; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Recurse; } data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)); } return CXChildVisit_Recurse; } static void findIdRefsInFile(CXTranslationUnit TU, CXCursor declCursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { assert(clang_isDeclaration(declCursor.kind)); SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); FileID FID = SM.translateFile(File); const Decl *Dcl = cxcursor::getCursorDecl(declCursor); if (!Dcl) return; FindFileIdRefVisitData data(TU, FID, Dcl, cxcursor::getSelectorIdentifierIndex(declCursor), Visitor); if (const DeclContext *DC = Dcl->getParentFunctionOrMethod()) { clang_visitChildren(cxcursor::MakeCXCursor(cast<Decl>(DC), TU), findFileIdRefVisit, &data); return; } SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindIdRefsVisitor(TU, findFileIdRefVisit, &data, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, Range, /*VisitDeclsOnly=*/true); FindIdRefsVisitor.visitFileRegion(); } namespace { struct FindFileMacroRefVisitData { ASTUnit &Unit; const FileEntry *File; const IdentifierInfo *Macro; CXCursorAndRangeVisitor visitor; FindFileMacroRefVisitData(ASTUnit &Unit, const FileEntry *File, const IdentifierInfo *Macro, CXCursorAndRangeVisitor visitor) : Unit(Unit), File(File), Macro(Macro), visitor(visitor) { } ASTContext &getASTContext() const { return Unit.getASTContext(); } }; } // anonymous namespace static enum CXChildVisitResult findFileMacroRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { const IdentifierInfo *Macro = 0; if (cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(cursor)->getName(); else if (cursor.kind == CXCursor_MacroExpansion) Macro = getCursorMacroExpansion(cursor).getName(); if (!Macro) return CXChildVisit_Continue; FindFileMacroRefVisitData *data = (FindFileMacroRefVisitData *)client_data; if (data->Macro != Macro) return CXChildVisit_Continue; SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (SM.getFileEntryForID(LocInfo.first) != data->File) return CXChildVisit_Continue; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Continue; } data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)); return CXChildVisit_Continue; } static void findMacroRefsInFile(CXTranslationUnit TU, CXCursor Cursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { if (Cursor.kind != CXCursor_MacroDefinition && Cursor.kind != CXCursor_MacroExpansion) return; ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); FileID FID = SM.translateFile(File); const IdentifierInfo *Macro = 0; if (Cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(Cursor)->getName(); else Macro = getCursorMacroExpansion(Cursor).getName(); if (!Macro) return; FindFileMacroRefVisitData data(*Unit, File, Macro, Visitor); SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindMacroRefsVisitor(TU, findFileMacroRefVisit, &data, /*VisitPreprocessorLast=*/false, /*VisitIncludedEntities=*/false, Range); FindMacroRefsVisitor.visitPreprocessedEntitiesInRegion(); } //===----------------------------------------------------------------------===// // libclang public APIs. //===----------------------------------------------------------------------===// extern "C" { void clang_findReferencesInFile(CXCursor cursor, CXFile file, CXCursorAndRangeVisitor visitor) { LogRef Log = Logger::make(LLVM_FUNCTION_NAME); if (clang_Cursor_isNull(cursor)) { if (Log) *Log << "Null cursor"; return; } if (cursor.kind == CXCursor_NoDeclFound) { if (Log) *Log << "Got CXCursor_NoDeclFound"; return; } if (!file) { if (Log) *Log << "Null file"; return; } if (!visitor.visit) { if (Log) *Log << "Null visitor"; return; } if (Log) *Log << cursor << " @" << static_cast<const FileEntry *>(file); ASTUnit *CXXUnit = cxcursor::getCursorASTUnit(cursor); if (!CXXUnit) return; ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (cursor.kind == CXCursor_MacroDefinition || cursor.kind == CXCursor_MacroExpansion) { findMacroRefsInFile(cxcursor::getCursorTU(cursor), cursor, static_cast<const FileEntry *>(file), visitor); return; } // We are interested in semantics of identifiers so for C++ constructor exprs // prefer type references, e.g.: // // return MyStruct(); // // for 'MyStruct' we'll have a cursor pointing at the constructor decl but // we are actually interested in the type declaration. cursor = cxcursor::getTypeRefCursor(cursor); CXCursor refCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(refCursor.kind)) { if (Log) *Log << "cursor is not referencing a declaration"; return; } findIdRefsInFile(cxcursor::getCursorTU(cursor), refCursor, static_cast<const FileEntry *>(file), visitor); } static enum CXVisitorResult _visitCursorAndRange(void *context, CXCursor cursor, CXSourceRange range) { CXCursorAndRangeVisitorBlock block = (CXCursorAndRangeVisitorBlock)context; return INVOKE_BLOCK2(block, cursor, range); } void clang_findReferencesInFileWithBlock(CXCursor cursor, CXFile file, CXCursorAndRangeVisitorBlock block) { CXCursorAndRangeVisitor visitor = { block, block ? _visitCursorAndRange : 0 }; return clang_findReferencesInFile(cursor, file, visitor); } } // end: extern "C" <commit_msg>[libclang] When calling the function of CXCursorAndRangeVisitor, don't forget to stop visitation if it returns CXVisit_Break.<commit_after>//===- CIndexHigh.cpp - Higher level API functions ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CursorVisitor.h" #include "CLog.h" #include "CXCursor.h" #include "CXSourceLocation.h" #include "CXTranslationUnit.h" #include "clang/AST/DeclObjC.h" #include "clang/Frontend/ASTUnit.h" #include "llvm/Support/Compiler.h" using namespace clang; using namespace cxcursor; using namespace cxindex; static void getTopOverriddenMethods(CXTranslationUnit TU, const Decl *D, SmallVectorImpl<const Decl *> &Methods) { if (!D) return; if (!isa<ObjCMethodDecl>(D) && !isa<CXXMethodDecl>(D)) return; SmallVector<CXCursor, 8> Overridden; cxcursor::getOverriddenCursors(cxcursor::MakeCXCursor(D, TU), Overridden); if (Overridden.empty()) { Methods.push_back(D->getCanonicalDecl()); return; } for (SmallVector<CXCursor, 8>::iterator I = Overridden.begin(), E = Overridden.end(); I != E; ++I) getTopOverriddenMethods(TU, cxcursor::getCursorDecl(*I), Methods); } namespace { struct FindFileIdRefVisitData { CXTranslationUnit TU; FileID FID; const Decl *Dcl; int SelectorIdIdx; CXCursorAndRangeVisitor visitor; typedef SmallVector<const Decl *, 8> TopMethodsTy; TopMethodsTy TopMethods; FindFileIdRefVisitData(CXTranslationUnit TU, FileID FID, const Decl *D, int selectorIdIdx, CXCursorAndRangeVisitor visitor) : TU(TU), FID(FID), SelectorIdIdx(selectorIdIdx), visitor(visitor) { Dcl = getCanonical(D); getTopOverriddenMethods(TU, Dcl, TopMethods); } ASTContext &getASTContext() const { return cxtu::getASTUnit(TU)->getASTContext(); } /// \brief We are looking to find all semantically relevant identifiers, /// so the definition of "canonical" here is different than in the AST, e.g. /// /// \code /// class C { /// C() {} /// }; /// \endcode /// /// we consider the canonical decl of the constructor decl to be the class /// itself, so both 'C' can be highlighted. const Decl *getCanonical(const Decl *D) const { if (!D) return 0; D = D->getCanonicalDecl(); if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D)) { if (ImplD->getClassInterface()) return getCanonical(ImplD->getClassInterface()); } else if (const CXXConstructorDecl *CXXCtorD = dyn_cast<CXXConstructorDecl>(D)) { return getCanonical(CXXCtorD->getParent()); } return D; } bool isHit(const Decl *D) const { if (!D) return false; D = getCanonical(D); if (D == Dcl) return true; if (isa<ObjCMethodDecl>(D) || isa<CXXMethodDecl>(D)) return isOverriddingMethod(D); return false; } private: bool isOverriddingMethod(const Decl *D) const { if (std::find(TopMethods.begin(), TopMethods.end(), D) != TopMethods.end()) return true; TopMethodsTy methods; getTopOverriddenMethods(TU, D, methods); for (TopMethodsTy::iterator I = methods.begin(), E = methods.end(); I != E; ++I) { if (std::find(TopMethods.begin(), TopMethods.end(), *I) != TopMethods.end()) return true; } return false; } }; } // end anonymous namespace. /// \brief For a macro \arg Loc, returns the file spelling location and sets /// to \arg isMacroArg whether the spelling resides inside a macro definition or /// a macro argument. static SourceLocation getFileSpellingLoc(SourceManager &SM, SourceLocation Loc, bool &isMacroArg) { assert(Loc.isMacroID()); SourceLocation SpellLoc = SM.getImmediateSpellingLoc(Loc); if (SpellLoc.isMacroID()) return getFileSpellingLoc(SM, SpellLoc, isMacroArg); isMacroArg = SM.isMacroArgExpansion(Loc); return SpellLoc; } static enum CXChildVisitResult findFileIdRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { CXCursor declCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(declCursor.kind)) return CXChildVisit_Recurse; const Decl *D = cxcursor::getCursorDecl(declCursor); if (!D) return CXChildVisit_Continue; FindFileIdRefVisitData *data = (FindFileIdRefVisitData *)client_data; if (data->isHit(D)) { cursor = cxcursor::getSelectorIdentifierCursor(data->SelectorIdIdx, cursor); // We are looking for identifiers to highlight so for objc methods (and // not a parameter) we can only highlight the selector identifiers. if ((cursor.kind == CXCursor_ObjCClassMethodDecl || cursor.kind == CXCursor_ObjCInstanceMethodDecl) && cxcursor::getSelectorIdentifierIndex(cursor) == -1) return CXChildVisit_Recurse; if (clang_isExpression(cursor.kind)) { if (cursor.kind == CXCursor_DeclRefExpr || cursor.kind == CXCursor_MemberRefExpr) { // continue.. } else if (cursor.kind == CXCursor_ObjCMessageExpr && cxcursor::getSelectorIdentifierIndex(cursor) != -1) { // continue.. } else return CXChildVisit_Recurse; } SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); SourceLocation SelIdLoc = cxcursor::getSelectorIdentifierLoc(cursor); if (SelIdLoc.isValid()) Loc = SelIdLoc; ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (LocInfo.first != data->FID) return CXChildVisit_Recurse; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Recurse; } if (data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)) == CXVisit_Break) return CXChildVisit_Break; } return CXChildVisit_Recurse; } static void findIdRefsInFile(CXTranslationUnit TU, CXCursor declCursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { assert(clang_isDeclaration(declCursor.kind)); SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager(); FileID FID = SM.translateFile(File); const Decl *Dcl = cxcursor::getCursorDecl(declCursor); if (!Dcl) return; FindFileIdRefVisitData data(TU, FID, Dcl, cxcursor::getSelectorIdentifierIndex(declCursor), Visitor); if (const DeclContext *DC = Dcl->getParentFunctionOrMethod()) { clang_visitChildren(cxcursor::MakeCXCursor(cast<Decl>(DC), TU), findFileIdRefVisit, &data); return; } SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindIdRefsVisitor(TU, findFileIdRefVisit, &data, /*VisitPreprocessorLast=*/true, /*VisitIncludedEntities=*/false, Range, /*VisitDeclsOnly=*/true); FindIdRefsVisitor.visitFileRegion(); } namespace { struct FindFileMacroRefVisitData { ASTUnit &Unit; const FileEntry *File; const IdentifierInfo *Macro; CXCursorAndRangeVisitor visitor; FindFileMacroRefVisitData(ASTUnit &Unit, const FileEntry *File, const IdentifierInfo *Macro, CXCursorAndRangeVisitor visitor) : Unit(Unit), File(File), Macro(Macro), visitor(visitor) { } ASTContext &getASTContext() const { return Unit.getASTContext(); } }; } // anonymous namespace static enum CXChildVisitResult findFileMacroRefVisit(CXCursor cursor, CXCursor parent, CXClientData client_data) { const IdentifierInfo *Macro = 0; if (cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(cursor)->getName(); else if (cursor.kind == CXCursor_MacroExpansion) Macro = getCursorMacroExpansion(cursor).getName(); if (!Macro) return CXChildVisit_Continue; FindFileMacroRefVisitData *data = (FindFileMacroRefVisitData *)client_data; if (data->Macro != Macro) return CXChildVisit_Continue; SourceLocation Loc = cxloc::translateSourceLocation(clang_getCursorLocation(cursor)); ASTContext &Ctx = data->getASTContext(); SourceManager &SM = Ctx.getSourceManager(); bool isInMacroDef = false; if (Loc.isMacroID()) { bool isMacroArg; Loc = getFileSpellingLoc(SM, Loc, isMacroArg); isInMacroDef = !isMacroArg; } // We are looking for identifiers in a specific file. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (SM.getFileEntryForID(LocInfo.first) != data->File) return CXChildVisit_Continue; if (isInMacroDef) { // FIXME: For a macro definition make sure that all expansions // of it expand to the same reference before allowing to point to it. return CXChildVisit_Continue; } if (data->visitor.visit(data->visitor.context, cursor, cxloc::translateSourceRange(Ctx, Loc)) == CXVisit_Break) return CXChildVisit_Break; return CXChildVisit_Continue; } static void findMacroRefsInFile(CXTranslationUnit TU, CXCursor Cursor, const FileEntry *File, CXCursorAndRangeVisitor Visitor) { if (Cursor.kind != CXCursor_MacroDefinition && Cursor.kind != CXCursor_MacroExpansion) return; ASTUnit *Unit = cxtu::getASTUnit(TU); SourceManager &SM = Unit->getSourceManager(); FileID FID = SM.translateFile(File); const IdentifierInfo *Macro = 0; if (Cursor.kind == CXCursor_MacroDefinition) Macro = getCursorMacroDefinition(Cursor)->getName(); else Macro = getCursorMacroExpansion(Cursor).getName(); if (!Macro) return; FindFileMacroRefVisitData data(*Unit, File, Macro, Visitor); SourceRange Range(SM.getLocForStartOfFile(FID), SM.getLocForEndOfFile(FID)); CursorVisitor FindMacroRefsVisitor(TU, findFileMacroRefVisit, &data, /*VisitPreprocessorLast=*/false, /*VisitIncludedEntities=*/false, Range); FindMacroRefsVisitor.visitPreprocessedEntitiesInRegion(); } //===----------------------------------------------------------------------===// // libclang public APIs. //===----------------------------------------------------------------------===// extern "C" { void clang_findReferencesInFile(CXCursor cursor, CXFile file, CXCursorAndRangeVisitor visitor) { LogRef Log = Logger::make(LLVM_FUNCTION_NAME); if (clang_Cursor_isNull(cursor)) { if (Log) *Log << "Null cursor"; return; } if (cursor.kind == CXCursor_NoDeclFound) { if (Log) *Log << "Got CXCursor_NoDeclFound"; return; } if (!file) { if (Log) *Log << "Null file"; return; } if (!visitor.visit) { if (Log) *Log << "Null visitor"; return; } if (Log) *Log << cursor << " @" << static_cast<const FileEntry *>(file); ASTUnit *CXXUnit = cxcursor::getCursorASTUnit(cursor); if (!CXXUnit) return; ASTUnit::ConcurrencyCheck Check(*CXXUnit); if (cursor.kind == CXCursor_MacroDefinition || cursor.kind == CXCursor_MacroExpansion) { findMacroRefsInFile(cxcursor::getCursorTU(cursor), cursor, static_cast<const FileEntry *>(file), visitor); return; } // We are interested in semantics of identifiers so for C++ constructor exprs // prefer type references, e.g.: // // return MyStruct(); // // for 'MyStruct' we'll have a cursor pointing at the constructor decl but // we are actually interested in the type declaration. cursor = cxcursor::getTypeRefCursor(cursor); CXCursor refCursor = clang_getCursorReferenced(cursor); if (!clang_isDeclaration(refCursor.kind)) { if (Log) *Log << "cursor is not referencing a declaration"; return; } findIdRefsInFile(cxcursor::getCursorTU(cursor), refCursor, static_cast<const FileEntry *>(file), visitor); } static enum CXVisitorResult _visitCursorAndRange(void *context, CXCursor cursor, CXSourceRange range) { CXCursorAndRangeVisitorBlock block = (CXCursorAndRangeVisitorBlock)context; return INVOKE_BLOCK2(block, cursor, range); } void clang_findReferencesInFileWithBlock(CXCursor cursor, CXFile file, CXCursorAndRangeVisitorBlock block) { CXCursorAndRangeVisitor visitor = { block, block ? _visitCursorAndRange : 0 }; return clang_findReferencesInFile(cursor, file, visitor); } } // end: extern "C" <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ScriptProfiler.h" #include "BindingVisitors.h" #include "RetainedDOMInfo.h" #include "ScriptObject.h" #include "V8ArrayBufferView.h" #include "V8Binding.h" #include "V8DOMWindow.h" #include "V8DOMWrapper.h" #include "V8Node.h" #include "WebCoreMemoryInstrumentation.h" #include "WrapperTypeInfo.h" #include <v8-profiler.h> #include <wtf/ThreadSpecific.h> namespace WebCore { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::start(ScriptState* state, const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::HandleScope hs; v8::CpuProfiler::StartProfiling(v8String(title, state ? state->isolate() : v8::Isolate::GetCurrent()), true); } void ScriptProfiler::startForPage(Page*, const String& title) { return start(0, title); } void ScriptProfiler::startForWorkerContext(WorkerContext*, const String& title) { return start(0, title); } PassRefPtr<ScriptProfile> ScriptProfiler::stop(ScriptState* state, const String& title) { v8::HandleScope hs; const v8::CpuProfile* profile = state ? v8::CpuProfiler::StopProfiling(v8String(title, state->isolate()), state->context()->GetSecurityToken()) : v8::CpuProfiler::StopProfiling(v8String(title, v8::Isolate::GetCurrent())); if (!profile) return 0; String profileTitle = toWebCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } PassRefPtr<ScriptProfile> ScriptProfiler::stopForPage(Page*, const String& title) { // Use null script state to avoid filtering by context security token. // All functions from all iframes should be visible from Inspector UI. return stop(0, title); } PassRefPtr<ScriptProfile> ScriptProfiler::stopForWorkerContext(WorkerContext*, const String& title) { return stop(0, title); } void ScriptProfiler::collectGarbage() { v8::V8::LowMemoryNotification(); } ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned id) { // As ids are unique, it doesn't matter which HeapSnapshot owns HeapGraphNode. // We need to find first HeapSnapshot containing a node with the specified id. const v8::HeapGraphNode* node = 0; for (int i = 0, l = v8::HeapProfiler::GetSnapshotsCount(); i < l; ++i) { const v8::HeapSnapshot* snapshot = v8::HeapProfiler::GetSnapshot(i); node = snapshot->GetNodeById(id); if (node) break; } if (!node) return ScriptObject(); v8::HandleScope scope; v8::Handle<v8::Value> value = node->GetHeapValue(); if (!value->IsObject()) return ScriptObject(); v8::Handle<v8::Object> object = value.As<v8::Object>(); ScriptState* scriptState = ScriptState::forContext(object->CreationContext()); return ScriptObject(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::SnapshotObjectId id = v8::HeapProfiler::GetSnapshotObjectId(value.v8Value()); return id; } namespace { class ActivityControlAdapter : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } ControlOption ReportProgressValue(int done, int total) { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else m_progress->Worked(done); if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Handle<v8::Object> object) { if (V8DOMWrapper::isWrapperOfType(object, &V8DOMWindow::info)) { DOMWindow* window = V8DOMWindow::toNative(object); if (window) { CString url = window->document()->url().string().utf8(); m_strings.append(url); return url.data(); } } return 0; } private: Vector<CString> m_strings; }; } // namespace // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(const String& title, HeapSnapshotProgress* control) { v8::HandleScope hs; ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = v8::HeapProfiler::TakeSnapshot(v8String(title, v8::Isolate::GetCurrent()), v8::HeapSnapshot::kFull, &adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : 0; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Handle<v8::Value> wrapper) { ASSERT(classId == v8DOMNodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toNative(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::HeapProfiler::DefineWrapperClass(v8DOMNodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { v8::HandleScope scope; // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) , m_isolate(isolate) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMNodeClassId) return; UNUSED_PARAM(m_isolate); ASSERT(V8Node::HasInstance(value, m_isolate, worldType(m_isolate))); ASSERT(value->IsObject()); v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); m_visitor->visitNode(V8Node::toNative(wrapper)); } private: WrappedNodeVisitor* m_visitor; v8::Isolate* m_isolate; } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::visitExternalStrings(ExternalStringVisitor* visitor) { V8PerIsolateData::current()->visitExternalStrings(visitor); } void ScriptProfiler::visitExternalArrays(ExternalArrayVisitor* visitor) { class DOMObjectWrapperVisitor : public v8::PersistentHandleVisitor { public: explicit DOMObjectWrapperVisitor(ExternalArrayVisitor* visitor) : m_visitor(visitor) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMObjectClassId) return; ASSERT(value->IsObject()); v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); if (!toWrapperTypeInfo(wrapper)->isSubclass(&V8ArrayBufferView::info)) return; m_visitor->visitJSExternalArray(V8ArrayBufferView::toNative(wrapper)); } private: ExternalArrayVisitor* m_visitor; } wrapperVisitor(visitor); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::collectBindingMemoryInfo(MemoryInstrumentation* instrumentation) { V8PerIsolateData* data = V8PerIsolateData::current(); instrumentation->addRootObject(data); } size_t ScriptProfiler::profilerSnapshotsSize() { return v8::HeapProfiler::GetMemorySizeUsedByProfiler(); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return *map; } } // namespace WebCore <commit_msg>Use isolate-based versions of CPU and Heap profilers<commit_after>/* * Copyright (c) 2011, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ScriptProfiler.h" #include "BindingVisitors.h" #include "RetainedDOMInfo.h" #include "ScriptObject.h" #include "V8ArrayBufferView.h" #include "V8Binding.h" #include "V8DOMWindow.h" #include "V8DOMWrapper.h" #include "V8Node.h" #include "WebCoreMemoryInstrumentation.h" #include "WrapperTypeInfo.h" #include <v8-profiler.h> #include <wtf/ThreadSpecific.h> namespace WebCore { typedef HashMap<String, double> ProfileNameIdleTimeMap; void ScriptProfiler::start(ScriptState* state, const String& title) { ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); if (profileNameIdleTimeMap->contains(title)) return; profileNameIdleTimeMap->add(title, 0); v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return; v8::HandleScope handleScope(isolate); profiler->StartCpuProfiling(v8String(title, isolate), true); } void ScriptProfiler::startForPage(Page*, const String& title) { return start(0, title); } void ScriptProfiler::startForWorkerContext(WorkerContext*, const String& title) { return start(0, title); } PassRefPtr<ScriptProfile> ScriptProfiler::stop(ScriptState* state, const String& title) { v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent(); v8::CpuProfiler* profiler = isolate->GetCpuProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); v8::Handle<v8::Value> securityToken; if (state) securityToken = state->context()->GetSecurityToken(); const v8::CpuProfile* profile = profiler->StopCpuProfiling(v8String(title, isolate), securityToken); if (!profile) return 0; String profileTitle = toWebCoreString(profile->GetTitle()); double idleTime = 0.0; ProfileNameIdleTimeMap* profileNameIdleTimeMap = ScriptProfiler::currentProfileNameIdleTimeMap(); ProfileNameIdleTimeMap::iterator profileIdleTime = profileNameIdleTimeMap->find(profileTitle); if (profileIdleTime != profileNameIdleTimeMap->end()) { idleTime = profileIdleTime->value * 1000.0; profileNameIdleTimeMap->remove(profileIdleTime); } return ScriptProfile::create(profile, idleTime); } PassRefPtr<ScriptProfile> ScriptProfiler::stopForPage(Page*, const String& title) { // Use null script state to avoid filtering by context security token. // All functions from all iframes should be visible from Inspector UI. return stop(0, title); } PassRefPtr<ScriptProfile> ScriptProfiler::stopForWorkerContext(WorkerContext*, const String& title) { return stop(0, title); } void ScriptProfiler::collectGarbage() { v8::V8::LowMemoryNotification(); } ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned id) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return ScriptObject(); // As ids are unique, it doesn't matter which HeapSnapshot owns HeapGraphNode. // We need to find first HeapSnapshot containing a node with the specified id. const v8::HeapGraphNode* node = 0; for (int i = 0, l = profiler->GetSnapshotCount(); i < l; ++i) { const v8::HeapSnapshot* snapshot = profiler->GetHeapSnapshot(i); node = snapshot->GetNodeById(id); if (node) break; } if (!node) return ScriptObject(); v8::HandleScope handleScope(isolate); v8::Handle<v8::Value> value = node->GetHeapValue(); if (!value->IsObject()) return ScriptObject(); v8::Handle<v8::Object> object = value.As<v8::Object>(); ScriptState* scriptState = ScriptState::forContext(object->CreationContext()); return ScriptObject(scriptState, object); } unsigned ScriptProfiler::getHeapObjectId(const ScriptValue& value) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); v8::SnapshotObjectId id = profiler->GetObjectId(value.v8Value()); return id; } namespace { class ActivityControlAdapter : public v8::ActivityControl { public: ActivityControlAdapter(ScriptProfiler::HeapSnapshotProgress* progress) : m_progress(progress), m_firstReport(true) { } ControlOption ReportProgressValue(int done, int total) { ControlOption result = m_progress->isCanceled() ? kAbort : kContinue; if (m_firstReport) { m_firstReport = false; m_progress->Start(total); } else m_progress->Worked(done); if (done >= total) m_progress->Done(); return result; } private: ScriptProfiler::HeapSnapshotProgress* m_progress; bool m_firstReport; }; class GlobalObjectNameResolver : public v8::HeapProfiler::ObjectNameResolver { public: virtual const char* GetName(v8::Handle<v8::Object> object) { if (V8DOMWrapper::isWrapperOfType(object, &V8DOMWindow::info)) { DOMWindow* window = V8DOMWindow::toNative(object); if (window) { CString url = window->document()->url().string().utf8(); m_strings.append(url); return url.data(); } } return 0; } private: Vector<CString> m_strings; }; } // namespace // FIXME: This method should receive a ScriptState, from which we should retrieve an Isolate. PassRefPtr<ScriptHeapSnapshot> ScriptProfiler::takeHeapSnapshot(const String& title, HeapSnapshotProgress* control) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; v8::HandleScope handleScope(isolate); ASSERT(control); ActivityControlAdapter adapter(control); GlobalObjectNameResolver resolver; const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(v8String(title, isolate), &adapter, &resolver); return snapshot ? ScriptHeapSnapshot::create(snapshot) : 0; } static v8::RetainedObjectInfo* retainedDOMInfo(uint16_t classId, v8::Handle<v8::Value> wrapper) { ASSERT(classId == v8DOMNodeClassId); if (!wrapper->IsObject()) return 0; Node* node = V8Node::toNative(wrapper.As<v8::Object>()); return node ? new RetainedDOMInfo(node) : 0; } void ScriptProfiler::initialize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (profiler) profiler->SetWrapperClassInfoProvider(v8DOMNodeClassId, &retainedDOMInfo); } void ScriptProfiler::visitNodeWrappers(WrappedNodeVisitor* visitor) { // visitNodeWrappers() should receive a ScriptState and retrieve an Isolate // from the ScriptState. v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope handleScope(isolate); class DOMNodeWrapperVisitor : public v8::PersistentHandleVisitor { public: DOMNodeWrapperVisitor(WrappedNodeVisitor* visitor, v8::Isolate* isolate) : m_visitor(visitor) , m_isolate(isolate) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMNodeClassId) return; UNUSED_PARAM(m_isolate); ASSERT(V8Node::HasInstance(value, m_isolate, worldType(m_isolate))); ASSERT(value->IsObject()); v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); m_visitor->visitNode(V8Node::toNative(wrapper)); } private: WrappedNodeVisitor* m_visitor; v8::Isolate* m_isolate; } wrapperVisitor(visitor, isolate); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::visitExternalStrings(ExternalStringVisitor* visitor) { V8PerIsolateData::current()->visitExternalStrings(visitor); } void ScriptProfiler::visitExternalArrays(ExternalArrayVisitor* visitor) { class DOMObjectWrapperVisitor : public v8::PersistentHandleVisitor { public: explicit DOMObjectWrapperVisitor(ExternalArrayVisitor* visitor) : m_visitor(visitor) { } virtual void VisitPersistentHandle(v8::Persistent<v8::Value> value, uint16_t classId) OVERRIDE { if (classId != v8DOMObjectClassId) return; ASSERT(value->IsObject()); v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value); if (!toWrapperTypeInfo(wrapper)->isSubclass(&V8ArrayBufferView::info)) return; m_visitor->visitJSExternalArray(V8ArrayBufferView::toNative(wrapper)); } private: ExternalArrayVisitor* m_visitor; } wrapperVisitor(visitor); v8::V8::VisitHandlesWithClassIds(&wrapperVisitor); } void ScriptProfiler::collectBindingMemoryInfo(MemoryInstrumentation* instrumentation) { V8PerIsolateData* data = V8PerIsolateData::current(); instrumentation->addRootObject(data); } size_t ScriptProfiler::profilerSnapshotsSize() { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); if (!profiler) return 0; return profiler->GetProfilerMemorySize(); } ProfileNameIdleTimeMap* ScriptProfiler::currentProfileNameIdleTimeMap() { AtomicallyInitializedStatic(WTF::ThreadSpecific<ProfileNameIdleTimeMap>*, map = new WTF::ThreadSpecific<ProfileNameIdleTimeMap>); return *map; } } // namespace WebCore <|endoftext|>
<commit_before>/* * Copyright (c) 2017-2018 OFFIS Institute for Information Technology * Oldenburg, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "timed_stream_fixture.h" #include "print_processor.h" #include "tvs/tracing.h" #include "gtest/gtest.h" class StreamEventSemantics : public timed_stream_fixture_b { using base_type = timed_stream_fixture_b; using value_type = std::set<int>; using traits_type = tracing::timed_event_traits<value_type>; using stream_type = tracing::timed_stream<value_type, traits_type>; using printer_type = test_event_printer<int>; // special event writer to simplify event handling with std::set<T> using writer_type = tracing::timed_event_writer<int>; protected: StreamEventSemantics() : base_type() , writer("writer", tracing::STREAM_CREATE) { printer.in(writer.name()); } void expect_processor_output(std::string const& str) { std::stringstream actual; printer.print(actual); EXPECT_EQ(str, actual.str()); printer.clear(); } writer_type writer; printer_type printer; }; TEST_F(StreamEventSemantics, PushRelEvent) { // Push two events at the relative offset dur writer.push(0, dur); writer.push(10, dur); writer.commit(); expect_processor_output("@1 s: { 0, 10 }\n"); } TEST_F(StreamEventSemantics, PushAbsEvent) { // Push two events to an absolute time point tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs); writer.commit(); expect_processor_output("@1 s: { 0, 10 }\n"); } TEST_F(StreamEventSemantics, PushSemantics) { // Push two events at the relative offset dur writer.push(0, dur); writer.push(10, 2 * dur); writer.commit(); expect_processor_output("@1 s: { 0 }\n" "@2 s: { 10 }\n"); } TEST_F(StreamEventSemantics, PartialCommit) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs / 2.0); // note that we use the absolute time commit interface here writer.commit(abs / 2.0); writer.commit(abs); // a split/merge results in decaying of the old event value to the 'right' // side while the duration and an empty value is created on the 'left' side of // a split std::stringstream exp; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemantics) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs / 2.0); writer.commit(); // a split/merge results in decaying of the old event value to the 'right' // side while the duration and an empty value is created on the 'left' side of // a split std::stringstream exp; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemanticsTwo) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); writer.commit(); // we expect to have the events ordered correctly std::stringstream exp; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0, 5 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemanticsThree) { tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); // now, push again over the whole 'duration' writer.push(10, abs); writer.commit(); std::stringstream exp; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0, 5, 10 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeCommitSemantics) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); // now further split the stream by performing partial commits writer.commit(dur / 8.0); writer.commit(dur / 8.0); writer.commit(dur / 4.0); writer.commit(dur / 4.0); // the last commit should update up to the last event of the pushed events writer.commit(); // we expect to have the events ordered correctly and have the splits at the // commit boundaries std::stringstream exp; exp << "@" << dur / 8.0 << ": { - }\n"; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur * (3.0 / 4.0) << ": { - }\n"; exp << "@" << dur << ": { 0, 5 }\n"; expect_processor_output(exp.str()); } tracing::time_type operator"" _ns(unsigned long long val) { #ifdef SYSX_NO_SYSTEMC return tracing::time_type(val * 1.0 * sysx::si::nanoseconds ); #else return tracing::time_type(1.0 * val, sc_core::SC_NS); #endif } tracing::time_type operator"" _ms(unsigned long long val) { #ifdef SYSX_NO_SYSTEMC return tracing::time_type(val * 1.0 * sysx::si::milliseconds ); #else return tracing::time_type(1.0 * val, sc_core::SC_MS); #endif } TEST_F(StreamEventSemantics, RoundingErrorTests) { writer.push(0, 251_ns); writer.push(0, 46_ns); writer.push(0, 209_ns); writer.commit(); EXPECT_EQ(writer.local_time(), 251_ns); } TEST_F(StreamEventSemantics, RoundingErrorTests2) { writer.push(0, 52_ns); writer.push(0, 126_ns); writer.push(0, 248_ns); writer.push(0, 22_ns); writer.push(0, 26_ns); writer.push(0, 253_ns); writer.commit(); EXPECT_EQ(writer.local_time(), 253_ns); } <commit_msg>tests: enable rounding error tests in release mode<commit_after>/* * Copyright (c) 2017-2018 OFFIS Institute for Information Technology * Oldenburg, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "timed_stream_fixture.h" #include "print_processor.h" #include "tvs/tracing.h" #include "gtest/gtest.h" class StreamEventSemantics : public timed_stream_fixture_b { using base_type = timed_stream_fixture_b; using value_type = std::set<int>; using traits_type = tracing::timed_event_traits<value_type>; using stream_type = tracing::timed_stream<value_type, traits_type>; using printer_type = test_event_printer<int>; // special event writer to simplify event handling with std::set<T> using writer_type = tracing::timed_event_writer<int>; protected: StreamEventSemantics() : base_type() , writer("writer", tracing::STREAM_CREATE) { printer.in(writer.name()); } void expect_processor_output(std::string const& str) { std::stringstream actual; printer.print(actual); EXPECT_EQ(str, actual.str()); printer.clear(); } writer_type writer; printer_type printer; }; TEST_F(StreamEventSemantics, PushRelEvent) { // Push two events at the relative offset dur writer.push(0, dur); writer.push(10, dur); writer.commit(); expect_processor_output("@1 s: { 0, 10 }\n"); } TEST_F(StreamEventSemantics, PushAbsEvent) { // Push two events to an absolute time point tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs); writer.commit(); expect_processor_output("@1 s: { 0, 10 }\n"); } TEST_F(StreamEventSemantics, PushSemantics) { // Push two events at the relative offset dur writer.push(0, dur); writer.push(10, 2 * dur); writer.commit(); expect_processor_output("@1 s: { 0 }\n" "@2 s: { 10 }\n"); } TEST_F(StreamEventSemantics, PartialCommit) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs / 2.0); // note that we use the absolute time commit interface here writer.commit(abs / 2.0); writer.commit(abs); // a split/merge results in decaying of the old event value to the 'right' // side while the duration and an empty value is created on the 'left' side of // a split std::stringstream exp; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemantics) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(10, abs / 2.0); writer.commit(); // a split/merge results in decaying of the old event value to the 'right' // side while the duration and an empty value is created on the 'left' side of // a split std::stringstream exp; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemanticsTwo) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); writer.commit(); // we expect to have the events ordered correctly std::stringstream exp; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0, 5 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeSemanticsThree) { tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); // now, push again over the whole 'duration' writer.push(10, abs); writer.commit(); std::stringstream exp; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur << ": { 0, 5, 10 }\n"; expect_processor_output(exp.str()); } TEST_F(StreamEventSemantics, SplitMergeCommitSemantics) { // Push two events to an absolute time point which need to be 'merged' tracing::time_type abs{ dur }; writer.push(0, abs); writer.push(5, abs); writer.push(10, abs / 2.0); writer.push(10, abs / 4.0); // now further split the stream by performing partial commits writer.commit(dur / 8.0); writer.commit(dur / 8.0); writer.commit(dur / 4.0); writer.commit(dur / 4.0); // the last commit should update up to the last event of the pushed events writer.commit(); // we expect to have the events ordered correctly and have the splits at the // commit boundaries std::stringstream exp; exp << "@" << dur / 8.0 << ": { - }\n"; exp << "@" << dur / 4.0 << ": { 10 }\n"; exp << "@" << dur / 2.0 << ": { 10 }\n"; exp << "@" << dur * (3.0 / 4.0) << ": { - }\n"; exp << "@" << dur << ": { 0, 5 }\n"; expect_processor_output(exp.str()); } tracing::time_type operator"" _ns(unsigned long long val) { #ifdef SYSX_NO_SYSTEMC return tracing::time_type(val * 1.0 * sysx::si::nanoseconds ); #else return tracing::time_type(1.0 * val, sc_core::SC_NS); #endif } tracing::time_type operator"" _ms(unsigned long long val) { #ifdef SYSX_NO_SYSTEMC return tracing::time_type(val * 1.0 * sysx::si::milliseconds ); #else return tracing::time_type(1.0 * val, sc_core::SC_MS); #endif } // only in release mode #if defined(SYSX_NDEBUG) TEST_F(StreamEventSemantics, RoundingErrorTests) { writer.push(0, 251_ns); writer.push(0, 46_ns); writer.push(0, 209_ns); writer.commit(); EXPECT_EQ(writer.local_time(), 251_ns); } TEST_F(StreamEventSemantics, RoundingErrorTests2) { writer.push(0, 52_ns); writer.push(0, 126_ns); writer.push(0, 248_ns); writer.push(0, 22_ns); writer.push(0, 26_ns); writer.push(0, 253_ns); writer.commit(); EXPECT_EQ(writer.local_time(), 253_ns); } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qfxtester.h> #include <QDebug> #include <QApplication> #include <qmlview.h> #include <QFile> #include <QmlComponent> #include <QDir> #include <QCryptographicHash> #include <private/qabstractanimation_p.h> #include <private/qmlgraphicsitem_p.h> QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(Qt.VisualTest, 4,6, VisualTest, QmlGraphicsVisualTest); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Frame, QmlGraphicsVisualTestFrame); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Mouse, QmlGraphicsVisualTestMouse); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Key, QmlGraphicsVisualTestKey); QmlGraphicsTester::QmlGraphicsTester(const QString &script, QmlViewer::ScriptOptions opts, QmlView *parent) : QAbstractAnimation(parent), m_script(script), m_view(parent), filterEvents(true), options(opts), testscript(0), hasCompleted(false), hasFailed(false) { parent->viewport()->installEventFilter(this); parent->installEventFilter(this); QUnifiedTimer::instance()->setConsistentTiming(true); if (options & QmlViewer::Play) this->run(); start(); } QmlGraphicsTester::~QmlGraphicsTester() { if (!hasFailed && options & QmlViewer::Record && options & QmlViewer::SaveOnExit) save(); } int QmlGraphicsTester::duration() const { return -1; } void QmlGraphicsTester::addMouseEvent(Destination dest, QMouseEvent *me) { MouseEvent e(me); e.destination = dest; m_mouseEvents << e; } void QmlGraphicsTester::addKeyEvent(Destination dest, QKeyEvent *ke) { KeyEvent e(ke); e.destination = dest; m_keyEvents << e; } bool QmlGraphicsTester::eventFilter(QObject *o, QEvent *e) { if (!filterEvents) return false; Destination destination; if (o == m_view) { destination = View; } else if (o == m_view->viewport()) { destination = ViewPort; } else { return false; } switch (e->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: addKeyEvent(destination, (QKeyEvent *)e); return true; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseButtonDblClick: addMouseEvent(destination, (QMouseEvent *)e); return true; default: break; } return false; } void QmlGraphicsTester::executefailure() { hasFailed = true; if (options & QmlViewer::ExitOnFailure) exit(-1); } void QmlGraphicsTester::imagefailure() { hasFailed = true; if (options & QmlViewer::ExitOnFailure) exit(-1); } void QmlGraphicsTester::complete() { if ((options & QmlViewer::TestErrorProperty) && !hasFailed) { QString e = m_view->root()->property("error").toString(); if (!e.isEmpty()) { qWarning() << "Test failed:" << e; hasFailed = true; } } if (options & QmlViewer::ExitOnComplete) QApplication::exit(hasFailed?-1:0); if (hasCompleted) return; hasCompleted = true; if (options & QmlViewer::Play) qWarning("Script playback complete"); } void QmlGraphicsTester::run() { QmlComponent c(m_view->engine(), m_script + QLatin1String(".qml")); testscript = qobject_cast<QmlGraphicsVisualTest *>(c.create()); if (testscript) testscript->setParent(this); else executefailure(); testscriptidx = 0; } void QmlGraphicsTester::save() { QString filename = m_script + QLatin1String(".qml"); QFileInfo filenameInfo(filename); QDir saveDir = filenameInfo.absoluteDir(); saveDir.mkpath("."); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream ts(&file); ts << "import Qt.VisualTest 4.6\n\n"; ts << "VisualTest {\n"; int imgCount = 0; QList<KeyEvent> keyevents = m_savedKeyEvents; QList<MouseEvent> mouseevents = m_savedMouseEvents; for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) { const FrameEvent &fe = m_savedFrameEvents.at(ii); ts << " Frame {\n"; ts << " msec: " << fe.msec << "\n"; if (!fe.hash.isEmpty()) { ts << " hash: \"" << fe.hash.toHex() << "\"\n"; } else if (!fe.image.isNull()) { QString filename = filenameInfo.baseName() + "." + QString::number(imgCount) + ".png"; fe.image.save(m_script + "." + QString::number(imgCount) + ".png"); imgCount++; ts << " image: \"" << filename << "\"\n"; } ts << " }\n"; while (!mouseevents.isEmpty() && mouseevents.first().msec == fe.msec) { MouseEvent me = mouseevents.takeFirst(); ts << " Mouse {\n"; ts << " type: " << me.type << "\n"; ts << " button: " << me.button << "\n"; ts << " buttons: " << me.buttons << "\n"; ts << " x: " << me.pos.x() << "; y: " << me.pos.y() << "\n"; ts << " modifiers: " << me.modifiers << "\n"; if (me.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } while (!keyevents.isEmpty() && keyevents.first().msec == fe.msec) { KeyEvent ke = keyevents.takeFirst(); ts << " Key {\n"; ts << " type: " << ke.type << "\n"; ts << " key: " << ke.key << "\n"; ts << " modifiers: " << ke.modifiers << "\n"; ts << " text: \"" << ke.text.toUtf8().toHex() << "\"\n"; ts << " autorep: " << (ke.autorep?"true":"false") << "\n"; ts << " count: " << ke.count << "\n"; if (ke.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } } ts << "}\n"; file.close(); } void QmlGraphicsTester::updateCurrentTime(int msec) { QmlGraphicsItemPrivate::setConsistentTime(msec); QImage img(m_view->width(), m_view->height(), QImage::Format_RGB32); if (options & QmlViewer::TestImages) { img.fill(qRgb(255,255,255)); QPainter p(&img); m_view->render(&p); } FrameEvent fe; fe.msec = msec; if (msec == 0 || !(options & QmlViewer::TestImages)) { // Skip first frame, skip if not doing images } else if (0 == (m_savedFrameEvents.count() % 60)) { fe.image = img; } else { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)img.bits(), img.bytesPerLine() * img.height()); fe.hash = hash.result(); } m_savedFrameEvents.append(fe); // Deliver mouse events filterEvents = false; if (!testscript) { for (int ii = 0; ii < m_mouseEvents.count(); ++ii) { MouseEvent &me = m_mouseEvents[ii]; me.msec = msec; QMouseEvent event(me.type, me.pos, me.button, me.buttons, me.modifiers); if (me.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } for (int ii = 0; ii < m_keyEvents.count(); ++ii) { KeyEvent &ke = m_keyEvents[ii]; ke.msec = msec; QKeyEvent event(ke.type, ke.key, ke.modifiers, ke.text, ke.autorep, ke.count); if (ke.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } m_savedMouseEvents.append(m_mouseEvents); m_savedKeyEvents.append(m_keyEvents); } m_mouseEvents.clear(); m_keyEvents.clear(); // Advance test script static int imgCount = 0; while (testscript && testscript->count() > testscriptidx) { QObject *event = testscript->event(testscriptidx); if (QmlGraphicsVisualTestFrame *frame = qobject_cast<QmlGraphicsVisualTestFrame *>(event)) { if (frame->msec() < msec) { if (options & QmlViewer::TestImages && !(options & QmlViewer::Record)) { qWarning() << "QmlGraphicsTester: Extra frame. Seen:" << msec << "Expected:" << frame->msec(); imagefailure(); } } else if (frame->msec() == msec) { if (!frame->hash().isEmpty() && frame->hash().toUtf8() != fe.hash.toHex()) { if (options & QmlViewer::TestImages && !(options & QmlViewer::Record)) { qWarning() << "QmlGraphicsTester: Mismatched frame hash. Seen:" << fe.hash.toHex() << "Expected:" << frame->hash().toUtf8(); imagefailure(); } } } else if (frame->msec() > msec) { break; } if (options & QmlViewer::TestImages && !(options & QmlViewer::Record) && !frame->image().isEmpty()) { QImage goodImage(frame->image().toLocalFile()); if (goodImage != img) { QString reject(frame->image().toLocalFile() + ".reject.png"); qWarning() << "QmlGraphicsTester: Image mismatch. Reject saved to:" << reject; img.save(reject); imagefailure(); } } } else if (QmlGraphicsVisualTestMouse *mouse = qobject_cast<QmlGraphicsVisualTestMouse *>(event)) { QPoint pos(mouse->x(), mouse->y()); QPoint globalPos = m_view->mapToGlobal(QPoint(0, 0)) + pos; QMouseEvent event((QEvent::Type)mouse->type(), pos, globalPos, (Qt::MouseButton)mouse->button(), (Qt::MouseButtons)mouse->buttons(), (Qt::KeyboardModifiers)mouse->modifiers()); MouseEvent me(&event); me.msec = msec; if (!mouse->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); me.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); me.destination = ViewPort; } m_savedMouseEvents.append(me); } else if (QmlGraphicsVisualTestKey *key = qobject_cast<QmlGraphicsVisualTestKey *>(event)) { QKeyEvent event((QEvent::Type)key->type(), key->key(), (Qt::KeyboardModifiers)key->modifiers(), QString::fromUtf8(QByteArray::fromHex(key->text().toUtf8())), key->autorep(), key->count()); KeyEvent ke(&event); ke.msec = msec; if (!key->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); ke.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); ke.destination = ViewPort; } m_savedKeyEvents.append(ke); } testscriptidx++; } filterEvents = true; if (testscript && testscript->count() <= testscriptidx) complete(); } QT_END_NAMESPACE <commit_msg>Always exit on play script failure<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qfxtester.h> #include <QDebug> #include <QApplication> #include <qmlview.h> #include <QFile> #include <QmlComponent> #include <QDir> #include <QCryptographicHash> #include <private/qabstractanimation_p.h> #include <private/qmlgraphicsitem_p.h> QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(Qt.VisualTest, 4,6, VisualTest, QmlGraphicsVisualTest); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Frame, QmlGraphicsVisualTestFrame); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Mouse, QmlGraphicsVisualTestMouse); QML_DEFINE_TYPE(Qt.VisualTest, 4,6, Key, QmlGraphicsVisualTestKey); QmlGraphicsTester::QmlGraphicsTester(const QString &script, QmlViewer::ScriptOptions opts, QmlView *parent) : QAbstractAnimation(parent), m_script(script), m_view(parent), filterEvents(true), options(opts), testscript(0), hasCompleted(false), hasFailed(false) { parent->viewport()->installEventFilter(this); parent->installEventFilter(this); QUnifiedTimer::instance()->setConsistentTiming(true); if (options & QmlViewer::Play) this->run(); start(); } QmlGraphicsTester::~QmlGraphicsTester() { if (!hasFailed && options & QmlViewer::Record && options & QmlViewer::SaveOnExit) save(); } int QmlGraphicsTester::duration() const { return -1; } void QmlGraphicsTester::addMouseEvent(Destination dest, QMouseEvent *me) { MouseEvent e(me); e.destination = dest; m_mouseEvents << e; } void QmlGraphicsTester::addKeyEvent(Destination dest, QKeyEvent *ke) { KeyEvent e(ke); e.destination = dest; m_keyEvents << e; } bool QmlGraphicsTester::eventFilter(QObject *o, QEvent *e) { if (!filterEvents) return false; Destination destination; if (o == m_view) { destination = View; } else if (o == m_view->viewport()) { destination = ViewPort; } else { return false; } switch (e->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: addKeyEvent(destination, (QKeyEvent *)e); return true; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: case QEvent::MouseButtonDblClick: addMouseEvent(destination, (QMouseEvent *)e); return true; default: break; } return false; } void QmlGraphicsTester::executefailure() { hasFailed = true; if (options & QmlViewer::ExitOnFailure) exit(-1); } void QmlGraphicsTester::imagefailure() { hasFailed = true; if (options & QmlViewer::ExitOnFailure) exit(-1); } void QmlGraphicsTester::complete() { if ((options & QmlViewer::TestErrorProperty) && !hasFailed) { QString e = m_view->root()->property("error").toString(); if (!e.isEmpty()) { qWarning() << "Test failed:" << e; hasFailed = true; } } if (options & QmlViewer::ExitOnComplete) QApplication::exit(hasFailed?-1:0); if (hasCompleted) return; hasCompleted = true; if (options & QmlViewer::Play) qWarning("Script playback complete"); } void QmlGraphicsTester::run() { QmlComponent c(m_view->engine(), m_script + QLatin1String(".qml")); testscript = qobject_cast<QmlGraphicsVisualTest *>(c.create()); if (testscript) testscript->setParent(this); else { executefailure(); exit(-1); } testscriptidx = 0; } void QmlGraphicsTester::save() { QString filename = m_script + QLatin1String(".qml"); QFileInfo filenameInfo(filename); QDir saveDir = filenameInfo.absoluteDir(); saveDir.mkpath("."); QFile file(filename); file.open(QIODevice::WriteOnly); QTextStream ts(&file); ts << "import Qt.VisualTest 4.6\n\n"; ts << "VisualTest {\n"; int imgCount = 0; QList<KeyEvent> keyevents = m_savedKeyEvents; QList<MouseEvent> mouseevents = m_savedMouseEvents; for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) { const FrameEvent &fe = m_savedFrameEvents.at(ii); ts << " Frame {\n"; ts << " msec: " << fe.msec << "\n"; if (!fe.hash.isEmpty()) { ts << " hash: \"" << fe.hash.toHex() << "\"\n"; } else if (!fe.image.isNull()) { QString filename = filenameInfo.baseName() + "." + QString::number(imgCount) + ".png"; fe.image.save(m_script + "." + QString::number(imgCount) + ".png"); imgCount++; ts << " image: \"" << filename << "\"\n"; } ts << " }\n"; while (!mouseevents.isEmpty() && mouseevents.first().msec == fe.msec) { MouseEvent me = mouseevents.takeFirst(); ts << " Mouse {\n"; ts << " type: " << me.type << "\n"; ts << " button: " << me.button << "\n"; ts << " buttons: " << me.buttons << "\n"; ts << " x: " << me.pos.x() << "; y: " << me.pos.y() << "\n"; ts << " modifiers: " << me.modifiers << "\n"; if (me.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } while (!keyevents.isEmpty() && keyevents.first().msec == fe.msec) { KeyEvent ke = keyevents.takeFirst(); ts << " Key {\n"; ts << " type: " << ke.type << "\n"; ts << " key: " << ke.key << "\n"; ts << " modifiers: " << ke.modifiers << "\n"; ts << " text: \"" << ke.text.toUtf8().toHex() << "\"\n"; ts << " autorep: " << (ke.autorep?"true":"false") << "\n"; ts << " count: " << ke.count << "\n"; if (ke.destination == ViewPort) ts << " sendToViewport: true\n"; ts << " }\n"; } } ts << "}\n"; file.close(); } void QmlGraphicsTester::updateCurrentTime(int msec) { QmlGraphicsItemPrivate::setConsistentTime(msec); QImage img(m_view->width(), m_view->height(), QImage::Format_RGB32); if (options & QmlViewer::TestImages) { img.fill(qRgb(255,255,255)); QPainter p(&img); m_view->render(&p); } FrameEvent fe; fe.msec = msec; if (msec == 0 || !(options & QmlViewer::TestImages)) { // Skip first frame, skip if not doing images } else if (0 == (m_savedFrameEvents.count() % 60)) { fe.image = img; } else { QCryptographicHash hash(QCryptographicHash::Md5); hash.addData((const char *)img.bits(), img.bytesPerLine() * img.height()); fe.hash = hash.result(); } m_savedFrameEvents.append(fe); // Deliver mouse events filterEvents = false; if (!testscript) { for (int ii = 0; ii < m_mouseEvents.count(); ++ii) { MouseEvent &me = m_mouseEvents[ii]; me.msec = msec; QMouseEvent event(me.type, me.pos, me.button, me.buttons, me.modifiers); if (me.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } for (int ii = 0; ii < m_keyEvents.count(); ++ii) { KeyEvent &ke = m_keyEvents[ii]; ke.msec = msec; QKeyEvent event(ke.type, ke.key, ke.modifiers, ke.text, ke.autorep, ke.count); if (ke.destination == View) { QCoreApplication::sendEvent(m_view, &event); } else { QCoreApplication::sendEvent(m_view->viewport(), &event); } } m_savedMouseEvents.append(m_mouseEvents); m_savedKeyEvents.append(m_keyEvents); } m_mouseEvents.clear(); m_keyEvents.clear(); // Advance test script static int imgCount = 0; while (testscript && testscript->count() > testscriptidx) { QObject *event = testscript->event(testscriptidx); if (QmlGraphicsVisualTestFrame *frame = qobject_cast<QmlGraphicsVisualTestFrame *>(event)) { if (frame->msec() < msec) { if (options & QmlViewer::TestImages && !(options & QmlViewer::Record)) { qWarning() << "QmlGraphicsTester: Extra frame. Seen:" << msec << "Expected:" << frame->msec(); imagefailure(); } } else if (frame->msec() == msec) { if (!frame->hash().isEmpty() && frame->hash().toUtf8() != fe.hash.toHex()) { if (options & QmlViewer::TestImages && !(options & QmlViewer::Record)) { qWarning() << "QmlGraphicsTester: Mismatched frame hash. Seen:" << fe.hash.toHex() << "Expected:" << frame->hash().toUtf8(); imagefailure(); } } } else if (frame->msec() > msec) { break; } if (options & QmlViewer::TestImages && !(options & QmlViewer::Record) && !frame->image().isEmpty()) { QImage goodImage(frame->image().toLocalFile()); if (goodImage != img) { QString reject(frame->image().toLocalFile() + ".reject.png"); qWarning() << "QmlGraphicsTester: Image mismatch. Reject saved to:" << reject; img.save(reject); imagefailure(); } } } else if (QmlGraphicsVisualTestMouse *mouse = qobject_cast<QmlGraphicsVisualTestMouse *>(event)) { QPoint pos(mouse->x(), mouse->y()); QPoint globalPos = m_view->mapToGlobal(QPoint(0, 0)) + pos; QMouseEvent event((QEvent::Type)mouse->type(), pos, globalPos, (Qt::MouseButton)mouse->button(), (Qt::MouseButtons)mouse->buttons(), (Qt::KeyboardModifiers)mouse->modifiers()); MouseEvent me(&event); me.msec = msec; if (!mouse->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); me.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); me.destination = ViewPort; } m_savedMouseEvents.append(me); } else if (QmlGraphicsVisualTestKey *key = qobject_cast<QmlGraphicsVisualTestKey *>(event)) { QKeyEvent event((QEvent::Type)key->type(), key->key(), (Qt::KeyboardModifiers)key->modifiers(), QString::fromUtf8(QByteArray::fromHex(key->text().toUtf8())), key->autorep(), key->count()); KeyEvent ke(&event); ke.msec = msec; if (!key->sendToViewport()) { QCoreApplication::sendEvent(m_view, &event); ke.destination = View; } else { QCoreApplication::sendEvent(m_view->viewport(), &event); ke.destination = ViewPort; } m_savedKeyEvents.append(ke); } testscriptidx++; } filterEvents = true; if (testscript && testscript->count() <= testscriptidx) complete(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>#pragma once #pragma warning(push) #pragma warning(disable: 4302 4838) #include <atlbase.h> #include <atlfile.h> #include <atlcoll.h> #include <atlstr.h> #include <atlwin.h> #include <atlapp.h> #include <atlctrls.h> #include <atldlgs.h> #pragma warning(pop) #include "unzip.h" #include "resource.h" #include <shellapi.h> static HINSTANCE hInstance; static void ShowFailureDialog(const CString& mainInstruction, const CString& content = _T("")) { CTaskDialog td; td.SetMainInstructionText(mainInstruction); if (content.GetLength() != 0) td.SetContentText(content); td.SetWindowTitle(_T("Chocolatey Installer")); td.SetCommonButtons(TDCBF_CLOSE_BUTTON); td.SetMainIcon(TD_ERROR_ICON); td.ModifyFlags(0, TDF_ALLOW_DIALOG_CANCELLATION); td.DoModal(HWND_DESKTOP); } static bool ExtractZip(WORD zipResourceId, const CString& directory) { CResource zipResource; if (!zipResource.Load(_T("ZIPFILE"), zipResourceId)) return false; unsigned int dwSize = zipResource.GetSize(); if (dwSize < 0x100) return false; HZIP zipFile = OpenZip(zipResource.Lock(), dwSize, NULL); SetUnzipBaseDir(zipFile, directory.GetString()); ZRESULT zr; int index = 0; bool result = true; do { ZIPENTRY zipEntry; zr = GetZipItem(zipFile, index, &zipEntry); if (zr != ZR_MORE && zr != ZR_OK) break; CString targetFile = directory + "\\" + zipEntry.name; DeleteFile(targetFile.GetString()); ZRESULT zr_inner = UnzipItem(zipFile, index, zipEntry.name); if (zr_inner != ZR_OK) { // Sometimes ZR_FLATE can be returned incorrectly if the file being // decompressed is of zero length. (UnzipItem() cannot differentiate // between a genuine zero-size read and an error condition.) Only fail // if the size decompressed size is not actually zero. if (zr_inner == ZR_FLATE && zipEntry.unc_size != 0) { result = false; break; } } index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); return result; } #define REENTRANCY_MUTEX_NAME _T("Local\\Chocolatey Installer Reentrancy Mutex") int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE /* hPrevInstance */, LPTSTR cmdLine, INT nCmdShow) { hInstance = hInst; HANDLE hMutex = ::OpenMutex(SYNCHRONIZE, false, REENTRANCY_MUTEX_NAME); bool alreadyExists = (hMutex == NULL && GetLastError() == ERROR_FILE_NOT_FOUND); if (!alreadyExists) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_REENTRANCY); CString content; content.LoadStringW(hInstance, IDS_REENTRANCY_DESC); ShowFailureDialog(mainInstruction, content); CloseHandle(hMutex); return 1; } hMutex = ::CreateMutex(nullptr, true, REENTRANCY_MUTEX_NAME); TCHAR targetDir[MAX_PATH]; if (!::GetEnvironmentVariable(_T("TEMP"), targetDir, MAX_PATH)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_NOTEMPDIR); CString content; content.LoadStringW(hInstance, IDS_NOTEMPDIR_DESC); ShowFailureDialog(mainInstruction, content); return 1; } _tcscat_s(targetDir, _T("\\ChocolateyInstaller")); if (!::CreateDirectory(targetDir, nullptr) && ::GetLastError() != ERROR_ALREADY_EXISTS) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL); CString content; content.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL_DESC); ShowFailureDialog(mainInstruction, content); return 1; } CString outputDir = targetDir; const WORD IDR_CHOCOLATEY_NUPKG = 1, IDR_WIZARD_ZIP = 2; if (!ExtractZip(IDR_CHOCOLATEY_NUPKG, outputDir + "\\choco_nupkg")) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL); ShowFailureDialog(mainInstruction, _T("")); return 1; } if (!ExtractZip(IDR_WIZARD_ZIP, outputDir)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL); ShowFailureDialog(mainInstruction, _T("")); return 1; } CString cmd = outputDir + "\\ChocolateyInstaller.Wizard.exe"; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!CreateProcess(cmd.GetString(), _T(""), nullptr, nullptr, false, 0, nullptr, outputDir.GetString(), &si, &pi)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXECFAIL); ShowFailureDialog(mainInstruction, _T("")); return -1; } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(hMutex); return 0; }<commit_msg>Make usage of variable clearer<commit_after>#pragma once #pragma warning(push) #pragma warning(disable: 4302 4838) #include <atlbase.h> #include <atlfile.h> #include <atlcoll.h> #include <atlstr.h> #include <atlwin.h> #include <atlapp.h> #include <atlctrls.h> #include <atldlgs.h> #pragma warning(pop) #include "unzip.h" #include "resource.h" #include <shellapi.h> static HINSTANCE hInstance; static void ShowFailureDialog(const CString& mainInstruction, const CString& content = _T("")) { CTaskDialog td; td.SetMainInstructionText(mainInstruction); if (content.GetLength() != 0) td.SetContentText(content); td.SetWindowTitle(_T("Chocolatey Installer")); td.SetCommonButtons(TDCBF_CLOSE_BUTTON); td.SetMainIcon(TD_ERROR_ICON); td.ModifyFlags(0, TDF_ALLOW_DIALOG_CANCELLATION); td.DoModal(HWND_DESKTOP); } static bool ExtractZip(WORD zipResourceId, const CString& directory) { CResource zipResource; if (!zipResource.Load(_T("ZIPFILE"), zipResourceId)) return false; unsigned int dwSize = zipResource.GetSize(); if (dwSize < 0x100) return false; HZIP zipFile = OpenZip(zipResource.Lock(), dwSize, NULL); SetUnzipBaseDir(zipFile, directory.GetString()); ZRESULT zr; int index = 0; bool result = true; do { ZIPENTRY zipEntry; zr = GetZipItem(zipFile, index, &zipEntry); if (zr != ZR_MORE && zr != ZR_OK) break; CString targetFile = directory + "\\" + zipEntry.name; DeleteFile(targetFile.GetString()); ZRESULT zr_inner = UnzipItem(zipFile, index, zipEntry.name); if (zr_inner != ZR_OK) { // Sometimes ZR_FLATE can be returned incorrectly if the file being // decompressed is of zero length. (UnzipItem() cannot differentiate // between a genuine zero-size read and an error condition.) Only fail // if the size decompressed size is not actually zero. if (zr_inner == ZR_FLATE && zipEntry.unc_size != 0) { result = false; break; } } index++; } while (zr == ZR_MORE || zr == ZR_OK); CloseZip(zipFile); zipResource.Release(); return result; } #define REENTRANCY_MUTEX_NAME _T("Local\\Chocolatey Installer Reentrancy Mutex") int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE /* hPrevInstance */, LPTSTR cmdLine, INT nCmdShow) { hInstance = hInst; HANDLE hMutex = ::OpenMutex(SYNCHRONIZE, false, REENTRANCY_MUTEX_NAME); bool alreadyExists = !(hMutex == NULL && GetLastError() == ERROR_FILE_NOT_FOUND); if (alreadyExists) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_REENTRANCY); CString content; content.LoadStringW(hInstance, IDS_REENTRANCY_DESC); ShowFailureDialog(mainInstruction, content); CloseHandle(hMutex); return 1; } hMutex = ::CreateMutex(nullptr, true, REENTRANCY_MUTEX_NAME); TCHAR targetDir[MAX_PATH]; if (!::GetEnvironmentVariable(_T("TEMP"), targetDir, MAX_PATH)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_NOTEMPDIR); CString content; content.LoadStringW(hInstance, IDS_NOTEMPDIR_DESC); ShowFailureDialog(mainInstruction, content); return 1; } _tcscat_s(targetDir, _T("\\ChocolateyInstaller")); if (!::CreateDirectory(targetDir, nullptr) && ::GetLastError() != ERROR_ALREADY_EXISTS) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL); CString content; content.LoadStringW(hInstance, IDS_TEMPDIRWRITEFAIL_DESC); ShowFailureDialog(mainInstruction, content); return 1; } CString outputDir = targetDir; const WORD IDR_CHOCOLATEY_NUPKG = 1, IDR_WIZARD_ZIP = 2; if (!ExtractZip(IDR_CHOCOLATEY_NUPKG, outputDir + "\\choco_nupkg")) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL); ShowFailureDialog(mainInstruction, _T("")); return 1; } if (!ExtractZip(IDR_WIZARD_ZIP, outputDir)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXTRACTFAIL); ShowFailureDialog(mainInstruction, _T("")); return 1; } CString cmd = outputDir + "\\ChocolateyInstaller.Wizard.exe"; STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_SHOW; si.dwFlags = STARTF_USESHOWWINDOW; if (!CreateProcess(cmd.GetString(), _T(""), nullptr, nullptr, false, 0, nullptr, outputDir.GetString(), &si, &pi)) { CString mainInstruction; mainInstruction.LoadStringW(hInstance, IDS_EXECFAIL); ShowFailureDialog(mainInstruction, _T("")); return -1; } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(hMutex); return 0; }<|endoftext|>
<commit_before>#include <algorithm> #include <vector> #include <set> #include <chrono> #include <random> #include "phevaluator/phevaluator.h" #include "benchmark/benchmark.h" using namespace phevaluator; static void EvaluateAllFiveCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 48; a++) { for(int b = a + 1; b < 49; b++) { for(int c = b + 1; c < 50; c++) { for(int d = c + 1; d < 51; d++) { for(int e = d + 1; e < 52; e++) { EvaluateCards(a, b, c, d, e); } } } } } } } BENCHMARK(EvaluateAllFiveCards); static void EvaluateAllSixCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 47; a++) { for(int b = a + 1; b < 48; b++) { for(int c = b + 1; c < 49; c++) { for(int d = c + 1; d < 50; d++) { for(int e = d + 1; e < 51; e++) { for(int f = e + 1; f < 52; f++) { EvaluateCards(a, b, c, d, e, f); } } } } } } } } BENCHMARK(EvaluateAllSixCards); static void EvaluateAllSevenCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 46; a++) { for(int b = a + 1; b < 47; b++) { for(int c = b + 1; c < 48; c++) { for(int d = c + 1; d < 49; d++) { for(int e = d + 1; e < 50; e++) { for(int f = e + 1; f < 51; f++) { for(int g = f + 1; g < 52; g++) { EvaluateCards(a, b, c, d, e, f, g); } } } } } } } } } BENCHMARK(EvaluateAllSevenCards); static unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine generator(seed); static std::uniform_int_distribution<int> distribution(0, 51); static std::vector<int> RandomCardSample(int size) { std::vector<int> ret; std::set<int> sample; while (sample.size() < size) { int number = distribution(generator); if (sample.find(number) == sample.end()) { ret.push_back(number); sample.insert(number); } } return ret; } const int SIZE = 10; static void EvaluateRandomFiveCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(5)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4]); } } } BENCHMARK(EvaluateRandomFiveCards); static void EvaluateRandomSixCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(6)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5]); } } } BENCHMARK(EvaluateRandomSixCards); static void EvaluateRandomSevenCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(7)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5], hands[i][6]); } } } BENCHMARK(EvaluateRandomSevenCards); static void EvaluateRandomOmahaCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(9)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateOmahaCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5], hands[i][6], hands[i][7], hands[i][8]); } }} BENCHMARK(EvaluateRandomOmahaCards); BENCHMARK_MAIN(); <commit_msg>Try 100 samples in the benchmark<commit_after>#include <algorithm> #include <vector> #include <set> #include <chrono> #include <random> #include "phevaluator/phevaluator.h" #include "benchmark/benchmark.h" using namespace phevaluator; static void EvaluateAllFiveCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 48; a++) { for(int b = a + 1; b < 49; b++) { for(int c = b + 1; c < 50; c++) { for(int d = c + 1; d < 51; d++) { for(int e = d + 1; e < 52; e++) { EvaluateCards(a, b, c, d, e); } } } } } } } BENCHMARK(EvaluateAllFiveCards); static void EvaluateAllSixCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 47; a++) { for(int b = a + 1; b < 48; b++) { for(int c = b + 1; c < 49; c++) { for(int d = c + 1; d < 50; d++) { for(int e = d + 1; e < 51; e++) { for(int f = e + 1; f < 52; f++) { EvaluateCards(a, b, c, d, e, f); } } } } } } } } BENCHMARK(EvaluateAllSixCards); static void EvaluateAllSevenCards(benchmark::State& state) { for (auto _ : state) { for(int a = 0; a < 46; a++) { for(int b = a + 1; b < 47; b++) { for(int c = b + 1; c < 48; c++) { for(int d = c + 1; d < 49; d++) { for(int e = d + 1; e < 50; e++) { for(int f = e + 1; f < 51; f++) { for(int g = f + 1; g < 52; g++) { EvaluateCards(a, b, c, d, e, f, g); } } } } } } } } } BENCHMARK(EvaluateAllSevenCards); static unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine generator(seed); static std::uniform_int_distribution<int> distribution(0, 51); static std::vector<int> RandomCardSample(int size) { std::vector<int> ret; std::set<int> sample; while (sample.size() < size) { int number = distribution(generator); if (sample.find(number) == sample.end()) { ret.push_back(number); sample.insert(number); } } return ret; } const int SIZE = 100; static void EvaluateRandomFiveCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(5)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4]); } } } BENCHMARK(EvaluateRandomFiveCards); static void EvaluateRandomSixCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(6)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5]); } } } BENCHMARK(EvaluateRandomSixCards); static void EvaluateRandomSevenCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(7)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5], hands[i][6]); } } } BENCHMARK(EvaluateRandomSevenCards); static void EvaluateRandomOmahaCards(benchmark::State& state) { std::vector<std::vector<int>> hands; for (int i = 0; i < SIZE; i++) { hands.push_back(RandomCardSample(9)); } for (auto _ : state) { for (int i = 0; i < SIZE; i++) { EvaluateOmahaCards(hands[i][0], hands[i][1], hands[i][2], hands[i][3], hands[i][4], hands[i][5], hands[i][6], hands[i][7], hands[i][8]); } }} BENCHMARK(EvaluateRandomOmahaCards); BENCHMARK_MAIN(); <|endoftext|>
<commit_before>/* * Multiplatform Async Network Library * Copyright (c) 2007 Burlex * * Socket implementable class. * */ #include "Network.h" initialiseSingleton(SocketGarbageCollector); Socket::Socket(SOCKET fd, uint32 sendbuffersize, uint32 recvbuffersize) : m_readBufferSize(recvbuffersize), m_writeBufferSize(sendbuffersize), m_fd(fd), m_readByteCount(0), m_writeByteCount(0), m_connected(false), m_deleted(false) { // Allocate Buffers m_readBuffer = (uint8*)malloc(recvbuffersize); m_writeBuffer = (uint8*)malloc(sendbuffersize); // IOCP Member Variables #ifdef CONFIG_USE_IOCP m_writeLock = 0; m_completionPort = 0; #else m_writeLock = 0; #endif // Check for needed fd allocation. if(m_fd == 0) m_fd = SocketOps::CreateTCPFileDescriptor(); } Socket::~Socket() { // Deallocate buffers free(m_readBuffer); free(m_writeBuffer); #ifdef CONFIG_USE_IOCP /*if(m_readEvent != NULL) delete m_readEvent;*/ #endif } bool Socket::Connect(const char * Address, uint32 Port) { struct hostent * ci = gethostbyname(Address); if(ci == 0) return false; m_client.sin_family = ci->h_addrtype; m_client.sin_port = ntohs((u_short)Port); memcpy(&m_client.sin_addr.s_addr, ci->h_addr_list[0], ci->h_length); SocketOps::Blocking(m_fd); if(connect(m_fd, (const sockaddr*)&m_client, sizeof(m_client)) == -1) return false; // at this point the connection was established #ifdef CONFIG_USE_IOCP m_completionPort = sSocketMgr.GetCompletionPort(); #endif _OnConnect(); return true; } void Socket::Accept(sockaddr_in * address) { memcpy(&m_client, address, sizeof(*address)); _OnConnect(); } void Socket::_OnConnect() { // set common parameters on the file descriptor SocketOps::Nonblocking(m_fd); SocketOps::DisableBuffering(m_fd); SocketOps::SetRecvBufferSize(m_fd, m_writeBufferSize); SocketOps::SetSendBufferSize(m_fd, m_writeBufferSize); m_connected = true; // IOCP stuff #ifdef CONFIG_USE_IOCP AssignToCompletionPort(); SetupReadEvent(); #endif sSocketMgr.AddSocket(this); // Call virtual onconnect OnConnect(); } bool Socket::Send(const uint8 * Bytes, uint32 Size) { bool rv; // This is really just a wrapper for all the burst stuff. BurstBegin(); rv = BurstSend(Bytes, Size); if(rv) BurstPush(); BurstEnd(); return rv; } bool Socket::BurstSend(const uint8 * Bytes, uint32 Size) { // Check for buffer space. if((Size + m_writeByteCount) >= m_writeBufferSize) return false; // Copy into the buffer. memcpy(&m_writeBuffer[m_writeByteCount], Bytes, Size); m_writeByteCount += Size; return true; } void Socket::RemoveReadBufferBytes(uint32 size, bool lock) { if(lock) m_readMutex.Acquire(); if(m_readByteCount < size) { Disconnect(); if(lock) m_readMutex.Release(); return; } if(size == m_readByteCount) // complete erasure m_readByteCount = 0; else { memcpy(m_readBuffer, &m_readBuffer[size], m_readByteCount - size); m_readByteCount -= size; } if(lock) m_readMutex.Release(); } void Socket::RemoveWriteBufferBytes(uint32 size, bool lock) { if(lock) m_writeMutex.Acquire(); if(m_writeByteCount < size) { Disconnect(); if(lock) m_writeMutex.Release(); return; } if(size == m_writeByteCount) // complete erasure m_writeByteCount = 0; else { //memcpy(m_writeBuffer, &m_writeBuffer[size], m_writeByteCount - size); memmove(m_writeBuffer, &m_writeBuffer[size], m_writeByteCount - size); m_writeByteCount -= size; } if(lock) m_writeMutex.Release(); } string Socket::GetRemoteIP() { // inet_ntoa may leak memory, so we'll do this our own way. char * ip = (char*)inet_ntoa(m_client.sin_addr); string ret = string(ip); //free(ip); return ret; } void Socket::Disconnect() { m_connected = false; // remove from mgr sSocketMgr.RemoveSocket(this); SocketOps::CloseSocket(m_fd); // Call virtual ondisconnect OnDisconnect(); if(!m_deleted) Delete(); } void Socket::Delete() { if(m_deleted) return; m_deleted = true; if(m_connected) Disconnect(); sSocketGarbageCollector.QueueSocket(this); } void Socket::Read(uint32 size, uint8 * buffer) { assert(size <= m_readByteCount); memcpy(buffer, m_readBuffer, size); RemoveReadBufferBytes(size, false); } <commit_msg>crash fix<commit_after>/* * Multiplatform Async Network Library * Copyright (c) 2007 Burlex * * Socket implementable class. * */ #include "Network.h" initialiseSingleton(SocketGarbageCollector); Socket::Socket(SOCKET fd, uint32 sendbuffersize, uint32 recvbuffersize) : m_readBufferSize(recvbuffersize), m_writeBufferSize(sendbuffersize), m_fd(fd), m_readByteCount(0), m_writeByteCount(0), m_connected(false), m_deleted(false) { // Allocate Buffers m_readBuffer = (uint8*)malloc(recvbuffersize); m_writeBuffer = (uint8*)malloc(sendbuffersize); // IOCP Member Variables #ifdef CONFIG_USE_IOCP m_writeLock = 0; m_completionPort = 0; #else m_writeLock = 0; #endif // Check for needed fd allocation. if(m_fd == 0) m_fd = SocketOps::CreateTCPFileDescriptor(); } Socket::~Socket() { // Deallocate buffers free(m_readBuffer); free(m_writeBuffer); #ifdef CONFIG_USE_IOCP /*if(m_readEvent != NULL) delete m_readEvent;*/ #endif } bool Socket::Connect(const char * Address, uint32 Port) { struct hostent * ci = gethostbyname(Address); if(ci == 0) return false; m_client.sin_family = ci->h_addrtype; m_client.sin_port = ntohs((u_short)Port); memcpy(&m_client.sin_addr.s_addr, ci->h_addr_list[0], ci->h_length); SocketOps::Blocking(m_fd); if(connect(m_fd, (const sockaddr*)&m_client, sizeof(m_client)) == -1) return false; // at this point the connection was established #ifdef CONFIG_USE_IOCP m_completionPort = sSocketMgr.GetCompletionPort(); #endif _OnConnect(); return true; } void Socket::Accept(sockaddr_in * address) { memcpy(&m_client, address, sizeof(*address)); _OnConnect(); } void Socket::_OnConnect() { // set common parameters on the file descriptor SocketOps::Nonblocking(m_fd); SocketOps::DisableBuffering(m_fd); SocketOps::SetRecvBufferSize(m_fd, m_writeBufferSize); SocketOps::SetSendBufferSize(m_fd, m_writeBufferSize); m_connected = true; // IOCP stuff #ifdef CONFIG_USE_IOCP AssignToCompletionPort(); SetupReadEvent(); #endif sSocketMgr.AddSocket(this); // Call virtual onconnect OnConnect(); } bool Socket::Send(const uint8 * Bytes, uint32 Size) { bool rv; // This is really just a wrapper for all the burst stuff. BurstBegin(); rv = BurstSend(Bytes, Size); if(rv) BurstPush(); BurstEnd(); return rv; } bool Socket::BurstSend(const uint8 * Bytes, uint32 Size) { // Check for buffer space. if((Size + m_writeByteCount) >= m_writeBufferSize) return false; // Copy into the buffer. memcpy(&m_writeBuffer[m_writeByteCount], Bytes, Size); m_writeByteCount += Size; return true; } void Socket::RemoveReadBufferBytes(uint32 size, bool lock) { if(lock) m_readMutex.Acquire(); if(m_readByteCount < size) { Disconnect(); if(lock) m_readMutex.Release(); return; } if(size == m_readByteCount) // complete erasure m_readByteCount = 0; else { memcpy(m_readBuffer, &m_readBuffer[size], m_readByteCount - size); m_readByteCount -= size; } if(lock) m_readMutex.Release(); } void Socket::RemoveWriteBufferBytes(uint32 size, bool lock) { if(lock) m_writeMutex.Acquire(); if(m_writeByteCount < size) { Disconnect(); if(lock) m_writeMutex.Release(); return; } if(size == m_writeByteCount) // complete erasure m_writeByteCount = 0; else { //memcpy(m_writeBuffer, &m_writeBuffer[size], m_writeByteCount - size); memmove(m_writeBuffer, &m_writeBuffer[size], m_writeByteCount - size); m_writeByteCount -= size; } if(lock) m_writeMutex.Release(); } string Socket::GetRemoteIP() { char* ip = (char*)inet_ntoa( m_client.sin_addr ); if( ip != NULL ) return string( ip ); else return string( "" ); } void Socket::Disconnect() { m_connected = false; // remove from mgr sSocketMgr.RemoveSocket(this); SocketOps::CloseSocket(m_fd); // Call virtual ondisconnect OnDisconnect(); if(!m_deleted) Delete(); } void Socket::Delete() { if(m_deleted) return; m_deleted = true; if(m_connected) Disconnect(); sSocketGarbageCollector.QueueSocket(this); } void Socket::Read(uint32 size, uint8 * buffer) { assert(size <= m_readByteCount); memcpy(buffer, m_readBuffer, size); RemoveReadBufferBytes(size, false); } <|endoftext|>
<commit_before>// // MessagePack for C++ memory pool // // Copyright (C) 2008-2013 FURUHASHI Sadayuki and KONDO Takatoshi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MSGPACK_ZONE_HPP #define MSGPACK_ZONE_HPP #include <cstdlib> #include <memory> #include <vector> #include "cpp_config.hpp" #ifndef MSGPACK_ZONE_CHUNK_SIZE #define MSGPACK_ZONE_CHUNK_SIZE 8192 #endif #ifndef MSGPACK_ZONE_ALIGN #define MSGPACK_ZONE_ALIGN sizeof(int) #endif namespace msgpack { class zone { private: struct finalizer { finalizer(void (*func)(void*), void* data):func_(func), data_(data) {} void operator()() { func_(data_); } void (*func_)(void*); void* data_; }; struct finalizer_array { finalizer_array():tail_(nullptr), end_(nullptr), array_(nullptr) {} void call() { finalizer* fin = tail_; for(; fin != array_; --fin) (*(fin-1))(); } ~finalizer_array() { call(); ::free(array_); } void clear() { call(); tail_ = array_; } void push(void (*func)(void* data), void* data) { finalizer* fin = tail_; if(fin == end_) { push_expand(func, data); return; } fin->func_ = func; fin->data_ = data; ++tail_; } void push_expand(void (*func)(void*), void* data) { const size_t nused = end_ - array_; size_t nnext; if(nused == 0) { nnext = (sizeof(finalizer) < 72/2) ? 72 / sizeof(finalizer) : 8; } else { nnext = nused * 2; } finalizer* tmp = static_cast<finalizer*>(::realloc(array_, sizeof(finalizer) * nnext)); if(!tmp) { throw std::bad_alloc(); } array_ = tmp; end_ = tmp + nnext; tail_ = tmp + nused; new (tail_) finalizer(func, data); ++tail_; } finalizer* tail_; finalizer* end_; finalizer* array_; }; struct chunk { chunk* next_; }; struct chunk_list { chunk_list(size_t chunk_size) { chunk* c = static_cast<chunk*>(::malloc(sizeof(chunk) + chunk_size)); if(!c) { throw std::bad_alloc(); } head_ = c; free_ = chunk_size; ptr_ = reinterpret_cast<char*>(c) + sizeof(chunk); c->next_ = nullptr; } ~chunk_list() { chunk* c = head_; while(true) { chunk* n = c->next_; ::free(c); if(n) { c = n; } else { break; } } } void clear(size_t chunk_size) { chunk* c = head_; while(true) { chunk* n = c->next_; if(n) { ::free(c); c = n; } else { head_ = c; break; } } head_->next_ = nullptr; free_ = chunk_size; ptr_ = reinterpret_cast<char*>(head_) + sizeof(chunk); } size_t free_; char* ptr_; chunk* head_; }; size_t chunk_size_; chunk_list chunk_list_; finalizer_array finalizer_array_; public: zone(size_t chunk_size = MSGPACK_ZONE_CHUNK_SIZE) noexcept; public: static zone* create(size_t chunk_size); static void destroy(zone* zone); void* allocate_align(size_t size); void* allocate_no_align(size_t size); void push_finalizer(void (*func)(void*), void* data); template <typename T> void push_finalizer(msgpack::unique_ptr<T> obj); void clear(); void swap(zone& o); template <typename T, typename... Args> T* allocate(Args... args); private: void undo_allocate(size_t size); template <typename T> static void object_destructor(void* obj); void* allocate_expand(size_t size); }; inline zone* zone::create(size_t chunk_size) { zone* z = static_cast<zone*>(::malloc(sizeof(zone) + chunk_size)); if (!z) { return nullptr; } new (z) zone(chunk_size); return z; } inline void zone::destroy(zone* z) { z->~zone(); ::free(z); } inline zone::zone(size_t chunk_size) noexcept:chunk_size_(chunk_size), chunk_list_(chunk_size_) { } inline void* zone::allocate_align(size_t size) { return allocate_no_align( ((size)+((MSGPACK_ZONE_ALIGN)-1)) & ~((MSGPACK_ZONE_ALIGN)-1)); } inline void* zone::allocate_no_align(size_t size) { if(chunk_list_.free_ < size) { return allocate_expand(size); } char* ptr = chunk_list_.ptr_; chunk_list_.free_ -= size; chunk_list_.ptr_ += size; return ptr; } inline void* zone::allocate_expand(size_t size) { chunk_list* const cl = &chunk_list_; size_t sz = chunk_size_; while(sz < size) { sz *= 2; } chunk* c = static_cast<chunk*>(::malloc(sizeof(chunk) + sz)); char* ptr = reinterpret_cast<char*>(c) + sizeof(chunk); c->next_ = cl->head_; cl->head_ = c; cl->free_ = sz - size; cl->ptr_ = ptr + size; return ptr; } inline void zone::push_finalizer(void (*func)(void*), void* data) { finalizer_array_.push(func, data); } template <typename T> inline void zone::push_finalizer(msgpack::unique_ptr<T> obj) { finalizer_array_.push(&zone::object_destructor<T>, obj.get()); obj.release(); } inline void zone::clear() { finalizer_array_.clear(); chunk_list_.clear(chunk_size_); } inline void zone::swap(zone& o) { std::swap(*this, o); } template <typename T> void zone::object_destructor(void* obj) { reinterpret_cast<T*>(obj)->~T(); } inline void zone::undo_allocate(size_t size) { chunk_list_.ptr_ -= size; chunk_list_.free_ += size; } template <typename T, typename... Args> T* zone::allocate(Args... args) { void* x = allocate_align(sizeof(T)); try { finalizer_array_.push(&zone::object_destructor<T>, x); } catch (...) { undo_allocate(sizeof(T)); throw; } try { return new (x) T(args...); } catch (...) { --finalizer_array_.tail_; undo_allocate(sizeof(T)); throw; } } } // namespace msgpack #endif /* msgpack/zone.hpp */ <commit_msg>Added null pointer check for C++ separated code.<commit_after>// // MessagePack for C++ memory pool // // Copyright (C) 2008-2013 FURUHASHI Sadayuki and KONDO Takatoshi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MSGPACK_ZONE_HPP #define MSGPACK_ZONE_HPP #include <cstdlib> #include <memory> #include <vector> #include "cpp_config.hpp" #ifndef MSGPACK_ZONE_CHUNK_SIZE #define MSGPACK_ZONE_CHUNK_SIZE 8192 #endif #ifndef MSGPACK_ZONE_ALIGN #define MSGPACK_ZONE_ALIGN sizeof(int) #endif namespace msgpack { class zone { private: struct finalizer { finalizer(void (*func)(void*), void* data):func_(func), data_(data) {} void operator()() { func_(data_); } void (*func_)(void*); void* data_; }; struct finalizer_array { finalizer_array():tail_(nullptr), end_(nullptr), array_(nullptr) {} void call() { finalizer* fin = tail_; for(; fin != array_; --fin) (*(fin-1))(); } ~finalizer_array() { call(); ::free(array_); } void clear() { call(); tail_ = array_; } void push(void (*func)(void* data), void* data) { finalizer* fin = tail_; if(fin == end_) { push_expand(func, data); return; } fin->func_ = func; fin->data_ = data; ++tail_; } void push_expand(void (*func)(void*), void* data) { const size_t nused = end_ - array_; size_t nnext; if(nused == 0) { nnext = (sizeof(finalizer) < 72/2) ? 72 / sizeof(finalizer) : 8; } else { nnext = nused * 2; } finalizer* tmp = static_cast<finalizer*>(::realloc(array_, sizeof(finalizer) * nnext)); if(!tmp) { throw std::bad_alloc(); } array_ = tmp; end_ = tmp + nnext; tail_ = tmp + nused; new (tail_) finalizer(func, data); ++tail_; } finalizer* tail_; finalizer* end_; finalizer* array_; }; struct chunk { chunk* next_; }; struct chunk_list { chunk_list(size_t chunk_size) { chunk* c = static_cast<chunk*>(::malloc(sizeof(chunk) + chunk_size)); if(!c) { throw std::bad_alloc(); } head_ = c; free_ = chunk_size; ptr_ = reinterpret_cast<char*>(c) + sizeof(chunk); c->next_ = nullptr; } ~chunk_list() { chunk* c = head_; while(true) { chunk* n = c->next_; ::free(c); if(n) { c = n; } else { break; } } } void clear(size_t chunk_size) { chunk* c = head_; while(true) { chunk* n = c->next_; if(n) { ::free(c); c = n; } else { head_ = c; break; } } head_->next_ = nullptr; free_ = chunk_size; ptr_ = reinterpret_cast<char*>(head_) + sizeof(chunk); } size_t free_; char* ptr_; chunk* head_; }; size_t chunk_size_; chunk_list chunk_list_; finalizer_array finalizer_array_; public: zone(size_t chunk_size = MSGPACK_ZONE_CHUNK_SIZE) noexcept; public: static zone* create(size_t chunk_size); static void destroy(zone* zone); void* allocate_align(size_t size); void* allocate_no_align(size_t size); void push_finalizer(void (*func)(void*), void* data); template <typename T> void push_finalizer(msgpack::unique_ptr<T> obj); void clear(); void swap(zone& o); template <typename T, typename... Args> T* allocate(Args... args); private: void undo_allocate(size_t size); template <typename T> static void object_destructor(void* obj); void* allocate_expand(size_t size); }; inline zone* zone::create(size_t chunk_size) { zone* z = static_cast<zone*>(::malloc(sizeof(zone) + chunk_size)); if (!z) { return nullptr; } new (z) zone(chunk_size); return z; } inline void zone::destroy(zone* z) { z->~zone(); ::free(z); } inline zone::zone(size_t chunk_size) noexcept:chunk_size_(chunk_size), chunk_list_(chunk_size_) { } inline void* zone::allocate_align(size_t size) { return allocate_no_align( ((size)+((MSGPACK_ZONE_ALIGN)-1)) & ~((MSGPACK_ZONE_ALIGN)-1)); } inline void* zone::allocate_no_align(size_t size) { if(chunk_list_.free_ < size) { return allocate_expand(size); } char* ptr = chunk_list_.ptr_; chunk_list_.free_ -= size; chunk_list_.ptr_ += size; return ptr; } inline void* zone::allocate_expand(size_t size) { chunk_list* const cl = &chunk_list_; size_t sz = chunk_size_; while(sz < size) { sz *= 2; } chunk* c = static_cast<chunk*>(::malloc(sizeof(chunk) + sz)); if (!c) return nullptr; char* ptr = reinterpret_cast<char*>(c) + sizeof(chunk); if (!ptr) { ::free(c); return nullptr; } c->next_ = cl->head_; cl->head_ = c; cl->free_ = sz - size; cl->ptr_ = ptr + size; return ptr; } inline void zone::push_finalizer(void (*func)(void*), void* data) { finalizer_array_.push(func, data); } template <typename T> inline void zone::push_finalizer(msgpack::unique_ptr<T> obj) { finalizer_array_.push(&zone::object_destructor<T>, obj.get()); obj.release(); } inline void zone::clear() { finalizer_array_.clear(); chunk_list_.clear(chunk_size_); } inline void zone::swap(zone& o) { std::swap(*this, o); } template <typename T> void zone::object_destructor(void* obj) { reinterpret_cast<T*>(obj)->~T(); } inline void zone::undo_allocate(size_t size) { chunk_list_.ptr_ -= size; chunk_list_.free_ += size; } template <typename T, typename... Args> T* zone::allocate(Args... args) { void* x = allocate_align(sizeof(T)); try { finalizer_array_.push(&zone::object_destructor<T>, x); } catch (...) { undo_allocate(sizeof(T)); throw; } try { return new (x) T(args...); } catch (...) { --finalizer_array_.tail_; undo_allocate(sizeof(T)); throw; } } } // namespace msgpack #endif /* msgpack/zone.hpp */ <|endoftext|>
<commit_before>// // Copyright (c) 2016 Kimball Thurston // // 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 "plane_resize.h" #include "scanline_process.h" #include <base/cpu_features.h> //////////////////////////////////////// namespace { using namespace image; static void doResizeVertPoint( scanline &dest, int y, const plane &in, float scale ) { int srcY = static_cast<int>( ( static_cast<float>( y ) + 0.5F ) * scale ); srcY = std::min( in.height() - 1, srcY ); const float *inLine = in.line( srcY ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = inLine[x]; } static void doResizeHorizPoint( scanline &dest, const scanline &in, float scale ) { int maxS = in.width() - 1; for ( int x = 0; x < dest.width(); ++x ) { int srcX = static_cast<int>( ( static_cast<float>( x ) + 0.5F ) * scale ); srcX = std::min( maxS, srcX ); dest[x] = in[srcX]; } } //////////////////////////////////////// static void doResizeVertBilinear( scanline &dest, int y, const plane &in, float scale ) { float srcY = ( static_cast<float>( y ) + 0.5F ) * scale; int lowY = static_cast<int>( srcY ); float perc = srcY - static_cast<float>( lowY ); const float *lowLine = in.line( lowY ); const float *hiLine = lowLine; if ( ( lowY + 1 ) < in.height() ) hiLine = in.line( lowY + 1 ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = base::lerp( lowLine[x], hiLine[x], perc ); } static void doResizeHorizBilinear( scanline &dest, const scanline &in, float scale ) { for ( int x = 0; x < dest.width(); ++x ) { float srcX = ( static_cast<float>( x ) + 0.5F ) * scale; int lowX = static_cast<int>( srcX ); float perc = srcX - static_cast<float>( lowX ); int hiX = lowX + 1; if ( hiX >= dest.width() ) hiX = lowX; dest[x] = base::lerp( in[lowX], in[hiX], perc ); } } //////////////////////////////////////// static void doResizeVertBicubic( scanline &dest, int y, const plane &in, float scale ) { float srcY = ( static_cast<float>( y ) + 0.5F ) * scale; int pY = static_cast<int>( srcY ); float t = srcY - static_cast<float>( pY ); int hm1 = in.height() - 1; const float *p0 = in.line( std::max( int(0), pY - 1 ) ); const float *p1 = in.line( pY ); const float *p2 = in.line( std::min( int(hm1), pY + 1 ) ); const float *p3 = in.line( std::min( int(hm1), pY + 2 ) ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = base::cubic_interp( t, p0[x], p1[x], p2[x], p3[x] ); } static void doResizeHorizBicubic( scanline &dest, const scanline &in, float scale ) { int wm1 = in.width() - 1; for ( int x = 0; x < dest.width(); ++x ) { float srcX = ( static_cast<float>( x ) + 0.5F ) * scale; int pX = static_cast<int>( srcX ); float p0 = in[std::max( int(0), pX - 1 )]; float p1 = in[pX]; float p2 = in[std::min( int(wm1), pX + 1 )]; float p3 = in[std::min( int(wm1), pX + 2 )]; float t = srcX - static_cast<float>( pX ); dest[x] = base::cubic_interp( t, p0, p1, p2, p3 ); } } } // empty namespace //////////////////////////////////////// namespace image { //////////////////////////////////////// plane resize_horiz_point( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_point", d, p, scale ); } //////////////////////////////////////// plane resize_vert_point( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_point", d, p, scale ); } //////////////////////////////////////// plane resize_horiz_bilinear( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_bilinear", d, p, scale ); } //////////////////////////////////////// plane resize_vert_bilinear( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_bilinear", d, p, scale ); } //////////////////////////////////////// plane resize_horiz_bicubic( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_bicubic", d, p, scale ); } //////////////////////////////////////// plane resize_vert_bicubic( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_bicubic", d, p, scale ); } //////////////////////////////////////// plane resize_horiz( const plane &p, const std::string &filter, int neww ) { throw_not_yet(); } //////////////////////////////////////// plane resize_vert( const plane &p, const std::string &filter, int newh ) { throw_not_yet(); } //////////////////////////////////////// std::vector<plane> make_pyramid( const plane &in, const std::string &filter, float eta, int n ) { precondition( eta > 0.F && eta < 1.F, "Invalid eta {0} for pyramid, must be between 0 and 1", eta ); std::vector<plane> ret; int curLev = 1; ret.push_back( in ); while ( n == 0 || curLev < n ) { float curS = powf( eta, curLev ); float curWf = curS * static_cast<float>( in.width() ); float curHf = curS * static_cast<float>( in.height() ); int curW = static_cast<int>( ceilf( curWf ) ); int curH = static_cast<int>( ceilf( curHf ) ); if ( curW < 2 || curH < 2 ) { std::cout << "Terminating pyramid at level " << curLev << std::endl; break; } std::cout << "adding level " << curLev << " at " << curW << "x" << curH << std::endl; if ( filter == "bilinear" ) ret.push_back( resize_bilinear( ret.back(), curW, curH ) ); else if ( filter == "bicubic" ) ret.push_back( resize_bicubic( ret.back(), curW, curH ) ); else if ( filter == "point" || filter == "dirac" ) ret.push_back( resize_point( ret.back(), curW, curH ) ); else throw_not_yet(); ++curLev; } return ret; } //////////////////////////////////////// std::vector<image_buf> make_pyramid( const image_buf &in, const std::string &filter, float eta, int n ) { precondition( eta > 0.F && eta < 1.F, "Invalid eta {0} for pyramid, must be between 0 and 1", eta ); std::vector<image_buf> ret; int curLev = 1; ret.push_back( in ); while ( n == 0 || curLev < n ) { float curS = powf( eta, curLev ); float curWf = curS * static_cast<float>( in.width() ); float curHf = curS * static_cast<float>( in.height() ); int curW = static_cast<int>( ceilf( curWf ) ); int curH = static_cast<int>( ceilf( curHf ) ); if ( curW < 2 || curH < 2 ) { std::cout << "Terminating pyramid at level " << curLev << std::endl; break; } std::cout << "adding level " << curLev << " at " << curW << "x" << curH << std::endl; if ( filter == "bilinear" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_bilinear( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else if ( filter == "bicubic" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_bicubic( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else if ( filter == "point" || filter == "dirac" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_point( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else { throw_not_yet(); } ++curLev; } return ret; } //////////////////////////////////////// void add_resize( engine::registry &r ) { using namespace engine; r.add( op( "p.resize_vert_point", base::choose_runtime( doResizeVertPoint ), n_scanline_plane_adapter<false, decltype(doResizeVertPoint)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_point", base::choose_runtime( doResizeHorizPoint ), scanline_plane_adapter<true, decltype(doResizeHorizPoint)>(), dispatch_scan_processing, op::one_to_one ) ); r.add( op( "p.resize_vert_bilinear", base::choose_runtime( doResizeVertBilinear ), n_scanline_plane_adapter<false, decltype(doResizeVertBilinear)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_bilinear", base::choose_runtime( doResizeHorizBilinear ), scanline_plane_adapter<true, decltype(doResizeHorizBilinear)>(), dispatch_scan_processing, op::one_to_one ) ); r.add( op( "p.resize_vert_bicubic", base::choose_runtime( doResizeVertBicubic ), n_scanline_plane_adapter<false, decltype(doResizeVertBicubic)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_bicubic", base::choose_runtime( doResizeHorizBicubic ), scanline_plane_adapter<true, decltype(doResizeHorizBicubic)>(), dispatch_scan_processing, op::one_to_one ) ); // r.add( op( "p.resize_vert_generic", base::choose_runtime( doResizeVertGeneric ), n_scanline_plane_adapter<false, decltype(doResizeVertGeneric)>(), dispatch_scan_processing, op::n_to_one ) ); // r.add( op( "p.resize_horiz_generic", base::choose_runtime( doResizeHorizGeneric ), scanline_plane_adapter<true, decltype(doResizeHorizGeneric)>(), dispatch_scan_processing, op::one_to_one ) ); } //////////////////////////////////////// } // image <commit_msg>fix rounding, out of bounds access in simple resizers<commit_after>// // Copyright (c) 2016 Kimball Thurston // // 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 "plane_resize.h" #include "scanline_process.h" #include <base/cpu_features.h> //////////////////////////////////////// namespace { using namespace image; static void doResizeVertPoint( scanline &dest, int y, const plane &in, float scale ) { int srcY = static_cast<int>( ( static_cast<float>( y ) ) * scale + 0.5F ); srcY = std::min( in.height() - 1, srcY ); const float *inLine = in.line( srcY ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = inLine[x]; } static void doResizeHorizPoint( scanline &dest, const scanline &in, float scale ) { int maxS = in.width() - 1; for ( int x = 0; x < dest.width(); ++x ) { int srcX = static_cast<int>( ( static_cast<float>( x ) ) * scale + 0.5F ); srcX = std::min( maxS, srcX ); dest[x] = in[srcX]; } } //////////////////////////////////////// static void doResizeVertBilinear( scanline &dest, int y, const plane &in, float scale ) { float srcY = static_cast<float>( y ) * scale; int lowY = static_cast<int>( srcY ); float perc = srcY - static_cast<float>( lowY ); lowY = std::min( in.height() - 1, lowY ); const float *lowLine = in.line( lowY ); const float *hiLine = lowLine; if ( ( lowY + 1 ) < in.height() ) hiLine = in.line( lowY + 1 ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = base::lerp( lowLine[x], hiLine[x], perc ); } static void doResizeHorizBilinear( scanline &dest, const scanline &in, float scale ) { int maxw = in.width() - 1; for ( int x = 0; x < dest.width(); ++x ) { float srcX = static_cast<float>( x ) * scale; int lowX = static_cast<int>( srcX ); float perc = srcX - static_cast<float>( lowX ); lowX = std::min( maxw, lowX ); int hiX = std::min( maxw, lowX + 1 ); dest[x] = base::lerp( in[lowX], in[hiX], perc ); } } //////////////////////////////////////// static void doResizeVertBicubic( scanline &dest, int y, const plane &in, float scale ) { float srcY = static_cast<float>( y ) * scale; int pY = static_cast<int>( srcY ); float t = srcY - static_cast<float>( pY ); int hm1 = in.height() - 1; pY = std::min( hm1, pY ); const float *p0 = in.line( std::max( int(0), pY - 1 ) ); const float *p1 = in.line( pY ); const float *p2 = in.line( std::min( int(hm1), pY + 1 ) ); const float *p3 = in.line( std::min( int(hm1), pY + 2 ) ); for ( int x = 0; x < dest.width(); ++x ) dest[x] = base::cubic_interp( t, p0[x], p1[x], p2[x], p3[x] ); } static void doResizeHorizBicubic( scanline &dest, const scanline &in, float scale ) { int wm1 = in.width() - 1; for ( int x = 0; x < dest.width(); ++x ) { float srcX = static_cast<float>( x ) * scale; int pX = static_cast<int>( srcX ); float t = srcX - static_cast<float>( pX ); pX = std::min( wm1, pX ); float p0 = in[std::max( int(0), pX - 1 )]; float p1 = in[pX]; float p2 = in[std::min( int(wm1), pX + 1 )]; float p3 = in[std::min( int(wm1), pX + 2 )]; dest[x] = base::cubic_interp( t, p0, p1, p2, p3 ); } } } // empty namespace //////////////////////////////////////// namespace image { //////////////////////////////////////// plane resize_horiz_point( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_point", d, p, scale ); } //////////////////////////////////////// plane resize_vert_point( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_point", d, p, scale ); } //////////////////////////////////////// plane resize_horiz_bilinear( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_bilinear", d, p, scale ); } //////////////////////////////////////// plane resize_vert_bilinear( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_bilinear", d, p, scale ); } //////////////////////////////////////// plane resize_horiz_bicubic( const plane &p, int neww ) { precondition( neww > 0, "Invalid new width {0} to resize", neww ); engine::dimensions d = p.dims(); d.x = neww; float scale = static_cast<float>( p.width() ) / static_cast<float>( neww ); return plane( "p.resize_horiz_bicubic", d, p, scale ); } //////////////////////////////////////// plane resize_vert_bicubic( const plane &p, int newh ) { precondition( newh > 0, "Invalid new width {0} to resize", newh ); engine::dimensions d = p.dims(); d.y = newh; float scale = static_cast<float>( p.height() ) / static_cast<float>( newh ); return plane( "p.resize_vert_bicubic", d, p, scale ); } //////////////////////////////////////// plane resize_horiz( const plane &p, const std::string &filter, int neww ) { throw_not_yet(); } //////////////////////////////////////// plane resize_vert( const plane &p, const std::string &filter, int newh ) { throw_not_yet(); } //////////////////////////////////////// std::vector<plane> make_pyramid( const plane &in, const std::string &filter, float eta, int n ) { precondition( eta > 0.F && eta < 1.F, "Invalid eta {0} for pyramid, must be between 0 and 1", eta ); std::vector<plane> ret; int curLev = 1; ret.push_back( in ); while ( n == 0 || curLev < n ) { float curS = powf( eta, curLev ); float curWf = curS * static_cast<float>( in.width() ); float curHf = curS * static_cast<float>( in.height() ); int curW = static_cast<int>( ceilf( curWf ) ); int curH = static_cast<int>( ceilf( curHf ) ); if ( curW < 2 || curH < 2 ) { std::cout << "Terminating pyramid at level " << curLev << std::endl; break; } std::cout << "adding level " << curLev << " at " << curW << "x" << curH << std::endl; if ( filter == "bilinear" ) ret.push_back( resize_bilinear( ret.back(), curW, curH ) ); else if ( filter == "bicubic" ) ret.push_back( resize_bicubic( ret.back(), curW, curH ) ); else if ( filter == "point" || filter == "dirac" ) ret.push_back( resize_point( ret.back(), curW, curH ) ); else throw_not_yet(); ++curLev; } return ret; } //////////////////////////////////////// std::vector<image_buf> make_pyramid( const image_buf &in, const std::string &filter, float eta, int n ) { precondition( eta > 0.F && eta < 1.F, "Invalid eta {0} for pyramid, must be between 0 and 1", eta ); std::vector<image_buf> ret; int curLev = 1; ret.push_back( in ); while ( n == 0 || curLev < n ) { float curS = powf( eta, curLev ); float curWf = curS * static_cast<float>( in.width() ); float curHf = curS * static_cast<float>( in.height() ); int curW = static_cast<int>( ceilf( curWf ) ); int curH = static_cast<int>( ceilf( curHf ) ); if ( curW < 2 || curH < 2 ) { std::cout << "Terminating pyramid at level " << curLev << std::endl; break; } std::cout << "adding level " << curLev << " at " << curW << "x" << curH << std::endl; if ( filter == "bilinear" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_bilinear( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else if ( filter == "bicubic" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_bicubic( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else if ( filter == "point" || filter == "dirac" ) { image_buf tmp = ret.back(); for ( size_t p = 0; p != tmp.size(); ++p ) tmp[p] = resize_point( tmp[p], curW, curH ); ret.emplace_back( std::move( tmp ) ); } else { throw_not_yet(); } ++curLev; } return ret; } //////////////////////////////////////// void add_resize( engine::registry &r ) { using namespace engine; r.add( op( "p.resize_vert_point", base::choose_runtime( doResizeVertPoint ), n_scanline_plane_adapter<false, decltype(doResizeVertPoint)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_point", base::choose_runtime( doResizeHorizPoint ), scanline_plane_adapter<true, decltype(doResizeHorizPoint)>(), dispatch_scan_processing, op::one_to_one ) ); r.add( op( "p.resize_vert_bilinear", base::choose_runtime( doResizeVertBilinear ), n_scanline_plane_adapter<false, decltype(doResizeVertBilinear)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_bilinear", base::choose_runtime( doResizeHorizBilinear ), scanline_plane_adapter<true, decltype(doResizeHorizBilinear)>(), dispatch_scan_processing, op::one_to_one ) ); r.add( op( "p.resize_vert_bicubic", base::choose_runtime( doResizeVertBicubic ), n_scanline_plane_adapter<false, decltype(doResizeVertBicubic)>(), dispatch_scan_processing, op::n_to_one ) ); r.add( op( "p.resize_horiz_bicubic", base::choose_runtime( doResizeHorizBicubic ), scanline_plane_adapter<true, decltype(doResizeHorizBicubic)>(), dispatch_scan_processing, op::one_to_one ) ); // r.add( op( "p.resize_vert_generic", base::choose_runtime( doResizeVertGeneric ), n_scanline_plane_adapter<false, decltype(doResizeVertGeneric)>(), dispatch_scan_processing, op::n_to_one ) ); // r.add( op( "p.resize_horiz_generic", base::choose_runtime( doResizeHorizGeneric ), scanline_plane_adapter<true, decltype(doResizeHorizGeneric)>(), dispatch_scan_processing, op::one_to_one ) ); } //////////////////////////////////////// } // image <|endoftext|>
<commit_before>/** * Copyright (C) 2018 3D Repo Ltd * * This program 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. * * 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 <OdaCommon.h> #include <OdString.h> #include <toString.h> #include <DgLevelTableRecord.h> #include "geometry_dumper.h" #include "../../../../core/model/bson/repo_bson_factory.h" using namespace repo::manipulator::modelconvertor::odaHelper; void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal) { const OdGePoint3d* pVertexDataList = vertexDataList(); const OdGeVector3d* pNormals = NULL; if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) && (pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) && (pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2])) { std::vector<repo::lib::RepoVector3D64> vertices; for (int i = 0; i < 3; ++i) { vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z }); } collector->addFace(vertices); } } double GeometryDumper::deviation( const OdGiDeviationType deviationType, const OdGePoint3d& pointOnCurve) const { return 0; } VectoriseDevice* GeometryDumper::device() { return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device()); } bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable) { OdDgElementPtr pElm = OdDgElement::cast(pDrawable); OdString sClassName = toString(pElm->isA()); OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident")); std::stringstream ss; ss << sHandle; collector->setNextMeshName(ss.str()); OdGiSubEntityTraitsData traits = effectiveTraits(); OdDgElementId idLevel = traits.layer(); if (!idLevel.isNull()) { OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead); OdUInt32 iLevelEntry = pLevel->getEntryId(); std::stringstream ss; ss << pLevel->getName(); auto layerName = ss.str(); repoInfo << layerName; collector->setLayer(layerName); } return OdGsBaseMaterialView::doDraw(i, pDrawable); } OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color) { if (color.isByACI() || color.isByDgnIndex()) { return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()])); } else if (!color.isByColor()) { return OdCmEntityColor(0, 0, 0); } return color; } OdGiMaterialItemPtr GeometryDumper::fillMaterialCache( OdGiMaterialItemPtr prevCache, OdDbStub* materialId, const OdGiMaterialTraitsData & materialData ) { auto id = (OdUInt64)(OdIntPtr)materialId; OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap; OdGiMaterialColor ambientColor; OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor; double opacityPercentage; OdGiMaterialMap opacityMap; double refrIndex; OdGiMaterialMap refrMap; materialData.diffuse(diffuseColor, diffuseMap); materialData.ambient(ambientColor); materialData.specular(specularColor, specularMap, glossFactor); materialData.opacity(opacityPercentage, opacityMap); materialData.refraction(refrIndex, refrMap); OdGiMaterialMap bumpMap; materialData.bump(bumpMap); ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0); if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorDiffuse = ODTOCOLORREF(diffuseColor.color()); } else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex()); } if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorAmbient = ODTOCOLORREF(ambientColor.color()); } else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex()); } if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorSpecular = ODTOCOLORREF(specularColor.color()); } else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex()); } OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor()); repo_material_t material; // diffuse if (diffuseColor.method() == OdGiMaterialColor::kOverride) material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f }; else material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; /* TODO: texture support mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false; if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty()) { mData.bDiffuseHasTexture = true; mData.sDiffuseFileSource = diffuseMap.sourceFileName(); }*/ // specular if (specularColor.method() == OdGiMaterialColor::kOverride) material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f }; else material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; material.shininessStrength = 1 - glossFactor; material.shininess = materialData.reflectivity(); // opacity material.opacity = opacityPercentage; // refraction /*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0; mData.dRefractionIndex = materialData.reflectivity();*/ // transclucence //mData.dTranslucence = materialData.translucence(); collector->setCurrentMaterial(material); collector->stopMeshEntry(); collector->startMeshEntry(); return OdGiMaterialItemPtr(); } void GeometryDumper::init(GeometryCollector *const geoCollector) { collector = geoCollector; } void GeometryDumper::beginViewVectorization() { OdGsBaseMaterialView::beginViewVectorization(); setEyeToOutputTransform(getEyeToWorldTransform()); OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext()); output().setDestGeometry((OdGiGeometrySimplifier&)*this); } void GeometryDumper::endViewVectorization() { collector->stopMeshEntry(); OdGsBaseMaterialView::endViewVectorization(); } void GeometryDumper::setMode(OdGsView::RenderMode mode) { OdGsBaseVectorizeView::m_renderMode = kGouraudShaded; m_regenerationType = kOdGiRenderCommand; OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode; }<commit_msg>ISSUE #271 remove log<commit_after>/** * Copyright (C) 2018 3D Repo Ltd * * This program 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. * * 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 <OdaCommon.h> #include <OdString.h> #include <toString.h> #include <DgLevelTableRecord.h> #include "geometry_dumper.h" #include "../../../../core/model/bson/repo_bson_factory.h" using namespace repo::manipulator::modelconvertor::odaHelper; void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal) { const OdGePoint3d* pVertexDataList = vertexDataList(); const OdGeVector3d* pNormals = NULL; if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) && (pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) && (pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2])) { std::vector<repo::lib::RepoVector3D64> vertices; for (int i = 0; i < 3; ++i) { vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z }); } collector->addFace(vertices); } } double GeometryDumper::deviation( const OdGiDeviationType deviationType, const OdGePoint3d& pointOnCurve) const { return 0; } VectoriseDevice* GeometryDumper::device() { return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device()); } bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable) { OdDgElementPtr pElm = OdDgElement::cast(pDrawable); OdString sClassName = toString(pElm->isA()); OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident")); std::stringstream ss; ss << sHandle; collector->setNextMeshName(ss.str()); OdGiSubEntityTraitsData traits = effectiveTraits(); OdDgElementId idLevel = traits.layer(); if (!idLevel.isNull()) { OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead); OdUInt32 iLevelEntry = pLevel->getEntryId(); std::stringstream ss; ss << pLevel->getName(); auto layerName = ss.str(); collector->setLayer(layerName); } return OdGsBaseMaterialView::doDraw(i, pDrawable); } OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color) { if (color.isByACI() || color.isByDgnIndex()) { return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()])); } else if (!color.isByColor()) { return OdCmEntityColor(0, 0, 0); } return color; } OdGiMaterialItemPtr GeometryDumper::fillMaterialCache( OdGiMaterialItemPtr prevCache, OdDbStub* materialId, const OdGiMaterialTraitsData & materialData ) { auto id = (OdUInt64)(OdIntPtr)materialId; OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap; OdGiMaterialColor ambientColor; OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor; double opacityPercentage; OdGiMaterialMap opacityMap; double refrIndex; OdGiMaterialMap refrMap; materialData.diffuse(diffuseColor, diffuseMap); materialData.ambient(ambientColor); materialData.specular(specularColor, specularMap, glossFactor); materialData.opacity(opacityPercentage, opacityMap); materialData.refraction(refrIndex, refrMap); OdGiMaterialMap bumpMap; materialData.bump(bumpMap); ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0); if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorDiffuse = ODTOCOLORREF(diffuseColor.color()); } else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex()); } if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorAmbient = ODTOCOLORREF(ambientColor.color()); } else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex()); } if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor) { colorSpecular = ODTOCOLORREF(specularColor.color()); } else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI) { colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex()); } OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor()); repo_material_t material; // diffuse if (diffuseColor.method() == OdGiMaterialColor::kOverride) material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f }; else material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; /* TODO: texture support mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false; if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty()) { mData.bDiffuseHasTexture = true; mData.sDiffuseFileSource = diffuseMap.sourceFileName(); }*/ // specular if (specularColor.method() == OdGiMaterialColor::kOverride) material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f }; else material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f }; material.shininessStrength = 1 - glossFactor; material.shininess = materialData.reflectivity(); // opacity material.opacity = opacityPercentage; // refraction /*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0; mData.dRefractionIndex = materialData.reflectivity();*/ // transclucence //mData.dTranslucence = materialData.translucence(); collector->setCurrentMaterial(material); collector->stopMeshEntry(); collector->startMeshEntry(); return OdGiMaterialItemPtr(); } void GeometryDumper::init(GeometryCollector *const geoCollector) { collector = geoCollector; } void GeometryDumper::beginViewVectorization() { OdGsBaseMaterialView::beginViewVectorization(); setEyeToOutputTransform(getEyeToWorldTransform()); OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext()); output().setDestGeometry((OdGiGeometrySimplifier&)*this); } void GeometryDumper::endViewVectorization() { collector->stopMeshEntry(); OdGsBaseMaterialView::endViewVectorization(); } void GeometryDumper::setMode(OdGsView::RenderMode mode) { OdGsBaseVectorizeView::m_renderMode = kGouraudShaded; m_regenerationType = kOdGiRenderCommand; OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode; }<|endoftext|>
<commit_before>#include "common/application_info.h" #include "base/file_version_info.h" #include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" namespace brightray { std::string GetApplicationName() { auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr))); return UTF16ToUTF8(info->product_name()); } std::string GetApplicationVersion() { auto info = make_scoped_ptr(FileVersionInfo::CreateFileVersionInfoForModule(GetModuleHandle(nullptr))); return UTF16ToUTF8(info->product_version()); } } // namespace brightray <commit_msg>Fix cpplint errors in application_info_win.cc<commit_after>#include "common/application_info.h" #include "base/file_version_info.h" #include "base/memory/scoped_ptr.h" #include "base/strings/utf_string_conversions.h" namespace brightray { std::string GetApplicationName() { auto module = GetModuleHandle(nullptr); auto info = make_scoped_ptr( FileVersionInfo::CreateFileVersionInfoForModule(module)); return UTF16ToUTF8(info->product_name()); } std::string GetApplicationVersion() { auto module = GetModuleHandle(nullptr); auto info = make_scoped_ptr( FileVersionInfo::CreateFileVersionInfoForModule(module)); return UTF16ToUTF8(info->product_version()); } } // namespace brightray <|endoftext|>
<commit_before>TEveRGBAPalette *g_zdc_palette = 0; TEveGeoShape* zdc_make_shape(const Text_t* name, const Text_t* title_base, Double_t signal, const Text_t* path) { if ( ! gGeoManager->cd(path)) { Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path); return 0; } UChar_t rgb[3]; g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE); TGeoShape *gs = (TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone(); TEveGeoShape *s = new TEveGeoShape(name, Form("%s %s, E=%.3f", title_base, name, signal)); s->SetPickable(kTRUE); s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]); s->SetShape(gs); s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix()); // Scale z-dictance by 0.1 Double_t* t = s->RefMainTrans().ArrT(); t[2] *= 0.1; return s; } // ???? There are 5 towers in ESD, 4 in geom. // Not sure about assignment A/C <-> 1/2 void esd_zdc() { AliEveEventManager::AssertGeometry(); AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC(); if (g_zdc_palette == 0) { // Map values from 0, 50 on a spectrum palette. g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE); g_zdc_palette->IncRefCount(); gStyle->SetPalette(1, 0); g_zdc_palette->SetupColorArray(); } TEveElementList* l = new TEveElementList("ZDC Data", ""); gEve->AddElement(l); TEveElementList *c = 0; TEveGeoShape *s = 0; Double_t *te = 0; Text_t *tb = 0; // ZNC geometry ------------------------------------ tb = "ZNC"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZN1TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2")); // ZNA geometry tb = "ZNA"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZN2TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2")); // ZPC geometry ------------------------------------ tb = "ZPC"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZP1TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1")); // ZPA geometry tb = "ZPA"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZP2TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1")); // End - refresh screen gEve->Redraw3D(); } <commit_msg>Add display of ZDC tower centroid.<commit_after>TEveRGBAPalette *g_zdc_palette = 0; Float_t g_zdc_scale = 0.1; Float_t g_zdc_dist = 11695; Float_t g_zdc_cross = 20; TEveGeoShape* zdc_make_shape(const Text_t* name, const Text_t* title_base, Double_t signal, const Text_t* path) { if ( ! gGeoManager->cd(path)) { Warning("zdc_make_shape", "Module name=%s, path='%s' not found.\n", name, path); return 0; } UChar_t rgb[3]; g_zdc_palette->ColorFromValue(TMath::Nint(signal), rgb, kFALSE); TGeoShape *gs = (TGeoShape*) gGeoManager->GetCurrentVolume()->GetShape()->Clone(); TEveGeoShape *s = new TEveGeoShape(name, Form("%s %s, E=%.3f", title_base, name, signal)); s->SetPickable(kTRUE); s->SetMainColorRGB(rgb[0], rgb[1], rgb[2]); s->SetShape(gs); s->RefMainTrans().SetFrom(*gGeoManager->GetCurrentMatrix()); // Scale z-dictance by 0.1 Double_t* t = s->RefMainTrans().ArrT(); t[2] *= g_zdc_scale; return s; } TEveStraightLineSet* zdc_make_cross(const Text_t* name, const Text_t* title_base, Float_t x, Float_t y, Float_t z, Float_t dx, Float_t dy, Float_t dz) { TEveStraightLineSet* ls = new TEveStraightLineSet(name, Form("%s, x=%.3f, y=%.3f", title_base, x, y)); ls->SetMainColor(kYellow); ls->SetLineWidth(2); ls->RefMainTrans().SetPos(x, y, z); ls->AddLine(dx, 0, 0, -dx, 0, 0); ls->AddLine(0, dy, 0, 0, -dy, 0); ls->AddLine(0, 0, dz, 0, 0, -dz); return ls; } // ???? There are 5 towers in ESD, 4 in geom. // Not sure about assignment A/C <-> 1/2 void esd_zdc() { AliEveEventManager::AssertGeometry(); AliESDZDC *esd = AliEveEventManager::AssertESD()->GetESDZDC(); if (g_zdc_palette == 0) { // Map values from 0, 50 on a spectrum palette. g_zdc_palette = new TEveRGBAPalette(0, 50, kTRUE, kFALSE); g_zdc_palette->IncRefCount(); gStyle->SetPalette(1, 0); g_zdc_palette->SetupColorArray(); } TEveElementList* l = new TEveElementList("ZDC Data", ""); gEve->AddElement(l); TEveElementList *c = 0; TEveGeoShape *s = 0; Double_t *te = 0; Text_t *tb = 0; // ZNC geometry ------------------------------------ tb = "ZNC"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZN1TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_1/ZN1_2")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCC_1/ZNEU_1/ZNTX_2/ZN1_2")); // ZNA geometry tb = "ZNA"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZN2TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_1/ZN1_2")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCA_1/ZNEU_2/ZNTX_2/ZN1_2")); // ZPC geometry ------------------------------------ tb = "ZPC"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZP1TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_1/ZP1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_2/ZP1_1")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_3/ZP1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCC_1/ZPRO_1/ZPTX_4/ZP1_1")); // ZPA geometry tb = "ZPA"; c = new TEveElementList(tb); l->AddElement(c); te = esd->GetZP2TowerEnergy(); c->AddElement(zdc_make_shape("Tower 1", tb, te[1], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_1/ZP1_1")); c->AddElement(zdc_make_shape("Tower 2", tb, te[2], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_2/ZP1_1")); c->AddElement(zdc_make_shape("Tower 3", tb, te[3], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_3/ZP1_1")); c->AddElement(zdc_make_shape("Tower 4", tb, te[4], "ALIC_1/ZDCA_1/ZPRO_2/ZPTX_4/ZP1_1")); // Centroids TEveStraightLineSet *ls = 0; Double32_t *cNA = esd->GetZNACentroid(); ls = zdc_make_cross("ZNA Centroid", "ZNA", cNA[0], cNA[1], g_zdc_dist * g_zdc_scale, g_zdc_cross, g_zdc_cross, g_zdc_cross); l->AddElement(ls); Double32_t *cNC = esd->GetZNCCentroid(); ls = zdc_make_cross("ZNA Centroid", "ZNA", cNC[0], cNC[1], -g_zdc_dist * g_zdc_scale, g_zdc_cross, g_zdc_cross, g_zdc_cross); l->AddElement(ls); // End - refresh screen gEve->Redraw3D(); } <|endoftext|>
<commit_before> #include <config.h> #if defined(HAVE_CLOCK_GETTIME) #include <time.h> unsigned GetRunningMicroSecs() { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); unsigned usecs = ((unsigned)now.tv_nsec)/1000 + ((unsigned)now.tv_sec) * 1000000; // unsigned msecs = (now.tv_nsec / (1000*1000)) + now.tv_sec * 1000; return usecs; } #elif defined(HAVE_GETTIMEOFDAY_FUNC) #include <sys/time.h> unsigned GetRunningMicroSecs() { timeval tv; gettimeofday( &tv, 0 ); return (tv.tv_sec * 1000000) + tv.tv_usec; } #elif defined(_WIN32) #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #include <assert.h> unsigned GetRunningMicroSecs() { LARGE_INTEGER curtime; static unsigned timerFreq; // timer frequency if( !timerFreq ) { QueryPerformanceFrequency( &curtime ); timerFreq = curtime.QuadPart / 1000000; // i.e., ticks per usec assert( timerFreq ); } QueryPerformanceCounter( &curtime ); return ( curtime.LowPart / timerFreq ); } #endif <commit_msg>fix windows version of GetRunningMicroSecs()<commit_after> #include <config.h> #if defined(HAVE_CLOCK_GETTIME) #include <time.h> unsigned GetRunningMicroSecs() { struct timespec now; clock_gettime( CLOCK_MONOTONIC, &now ); unsigned usecs = ((unsigned)now.tv_nsec)/1000 + ((unsigned)now.tv_sec) * 1000000; // unsigned msecs = (now.tv_nsec / (1000*1000)) + now.tv_sec * 1000; return usecs; } #elif defined(HAVE_GETTIMEOFDAY_FUNC) #include <sys/time.h> unsigned GetRunningMicroSecs() { timeval tv; gettimeofday( &tv, 0 ); return (tv.tv_sec * 1000000) + tv.tv_usec; } #elif defined(_WIN32) #define WIN32_LEAN_AND_MEAN 1 #include <windows.h> #include <assert.h> unsigned GetRunningMicroSecs() { FILETIME now; GetSystemTimeAsFileTime( &now ); typedef unsigned long long UINT64; UINT64 t = (UINT64(now.dwHighDateTime) << 32) + now.dwLowDateTime; t /= 10; return unsigned( t ); } #if 0 // test program #include <stdio.h> int main( int argc, char** argv ) { unsigned then = GetRunningMicroSecs(); Sleep( 2000 ); // Windows Sleep( msecs ) printf( "delta: %u\n", GetRunningMicroSecs() - then ); return 0; } #endif #endif <|endoftext|>
<commit_before>// // Urho3D Engine // Copyright (c) 2008-2012 Lasse rni // // 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 "Precompiled.h" #include "Context.h" #include "DropDownList.h" #include "ListView.h" #include "UIEvents.h" #include "Window.h" #include "DebugNew.h" namespace Urho3D { OBJECTTYPESTATIC(DropDownList); DropDownList::DropDownList(Context* context) : Menu(context), resizePopup_(false) { Window* window = new Window(context_); window->SetInternal(true); SetPopup(window); // Hack: parent the popup until first shown to allow loading style from XML AddChild(window); window->SetVisible(false); listView_ = new ListView(context_); listView_->SetInternal(true); listView_->SetScrollBarsVisible(false, false); listView_->SetFocusMode(FM_NOTFOCUSABLE); popup_->SetLayout(LM_VERTICAL); popup_->AddChild(listView_); placeholder_ = CreateChild<UIElement>(); placeholder_->SetInternal(true); SubscribeToEvent(listView_, E_ITEMSELECTED, HANDLER(DropDownList, HandleItemSelected)); } DropDownList::~DropDownList() { } void DropDownList::RegisterObject(Context* context) { context->RegisterFactory<DropDownList>(); COPY_BASE_ATTRIBUTES(DropDownList, Menu); ACCESSOR_ATTRIBUTE(DropDownList, VAR_BOOL, "Resize Popup", GetResizePopup, SetResizePopup, bool, false, AM_FILE); } bool DropDownList::SaveXML(XMLElement& dest) { // Hack: parent the popup and the list items during serialization bool popupShown = popup_ && popup_->IsVisible(); if (popup_) { InsertChild(0, popup_); popup_->SetVisible(false); } while (listView_->GetNumItems()) placeholder_->AddChild(listView_->GetItem(0)); bool success = UIElement::SaveXML(dest); while (placeholder_->GetNumChildren()) listView_->AddItem(placeholder_->GetChild(0)); ShowPopup(popupShown); return success; } void DropDownList::ApplyAttributes() { // Hack: if the placeholder has any child elements defined, move them to the list while (placeholder_->GetNumChildren()) AddItem(placeholder_->GetChild(0)); } void DropDownList::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor) { Button::GetBatches(batches, quads, currentScissor); if (!placeholder_->IsVisible()) return; UIElement* selectedItem = GetSelectedItem(); if (selectedItem) { // Can not easily copy the selected item. However, it can be re-rendered on the placeholder's position const IntVector2& targetPos = placeholder_->GetScreenPosition(); const IntVector2& originalPos = selectedItem->GetScreenPosition(); IntVector2 offset = targetPos - originalPos; // GetBatches() usually resets the hover flag. Therefore get its value and then reset it for the real rendering bool hover = selectedItem->IsHovering(); selectedItem->SetHovering(false); selectedItem->GetBatchesWithOffset(offset, batches, quads, currentScissor); selectedItem->SetHovering(hover); } } void DropDownList::OnShowPopup() { // Resize the popup to match the size of the list content, and optionally match the button width UIElement* content = listView_->GetContentElement(); content->UpdateLayout(); const IntVector2& contentSize = content->GetSize(); const IntRect& border = popup_->GetLayoutBorder(); popup_->SetSize(resizePopup_ ? GetWidth() : contentSize.x_ + border.left_ + border.right_, contentSize.y_ + border.top_ + border.bottom_); listView_->SetViewPosition(IntVector2::ZERO); // Check if popup fits below the button. If not, show above instead bool showAbove = false; UIElement* root = GetRoot(); if (root) { const IntVector2& screenPos = GetScreenPosition(); if (screenPos.y_ + GetHeight() + popup_->GetHeight() > root->GetHeight() && screenPos.y_ - popup_->GetHeight() >= 0) showAbove = true; } if (!showAbove) SetPopupOffset(0, GetHeight()); else SetPopupOffset(0, -popup_->GetHeight()); } void DropDownList::AddItem(UIElement* item) { InsertItem(listView_->GetNumItems(), item); } void DropDownList::InsertItem(unsigned index, UIElement* item) { listView_->InsertItem(index, item); // If there was no selection, set to the first if (listView_->GetSelection() == M_MAX_UNSIGNED) listView_->SetSelection(0); } void DropDownList::RemoveItem(UIElement* item) { listView_->RemoveItem(item); } void DropDownList::RemoveItem(unsigned index) { listView_->RemoveItem(index); } void DropDownList::RemoveAllItems() { listView_->RemoveAllItems(); } void DropDownList::SetSelection(unsigned index) { listView_->SetSelection(index); } void DropDownList::SetResizePopup(bool enable) { resizePopup_ = enable; } unsigned DropDownList::GetNumItems() const { return listView_->GetNumItems(); } UIElement* DropDownList::GetItem(unsigned index) const { return listView_->GetItem(index); } PODVector<UIElement*> DropDownList::GetItems() const { PODVector<UIElement*> items; listView_->GetContentElement()->GetChildren(items); return items; } unsigned DropDownList::GetSelection() const { return listView_->GetSelection(); } UIElement* DropDownList::GetSelectedItem() const { return listView_->GetSelectedItem(); } void DropDownList::HandleItemSelected(StringHash eventType, VariantMap& eventData) { // Resize the selection placeholder to match the selected item UIElement* selectedItem = GetSelectedItem(); if (selectedItem) placeholder_->SetSize(selectedItem->GetSize()); // Close the popup as the selection was made if (GetShowPopup()) ShowPopup(false); // Send the event forward using namespace ItemSelected; VariantMap newEventData; newEventData[P_ELEMENT] = (void*)this; newEventData[P_SELECTION] = GetSelection(); SendEvent(E_ITEMSELECTED, newEventData); } } <commit_msg>Removed unnecessary line of code from DropDownList.<commit_after>// // Urho3D Engine // Copyright (c) 2008-2012 Lasse rni // // 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 "Precompiled.h" #include "Context.h" #include "DropDownList.h" #include "ListView.h" #include "UIEvents.h" #include "Window.h" #include "DebugNew.h" namespace Urho3D { OBJECTTYPESTATIC(DropDownList); DropDownList::DropDownList(Context* context) : Menu(context), resizePopup_(false) { Window* window = new Window(context_); window->SetInternal(true); SetPopup(window); // Hack: parent the popup until first shown to allow loading style from XML AddChild(window); window->SetVisible(false); listView_ = new ListView(context_); listView_->SetInternal(true); listView_->SetScrollBarsVisible(false, false); listView_->SetFocusMode(FM_NOTFOCUSABLE); popup_->SetLayout(LM_VERTICAL); popup_->AddChild(listView_); placeholder_ = CreateChild<UIElement>(); placeholder_->SetInternal(true); SubscribeToEvent(listView_, E_ITEMSELECTED, HANDLER(DropDownList, HandleItemSelected)); } DropDownList::~DropDownList() { } void DropDownList::RegisterObject(Context* context) { context->RegisterFactory<DropDownList>(); COPY_BASE_ATTRIBUTES(DropDownList, Menu); ACCESSOR_ATTRIBUTE(DropDownList, VAR_BOOL, "Resize Popup", GetResizePopup, SetResizePopup, bool, false, AM_FILE); } bool DropDownList::SaveXML(XMLElement& dest) { // Hack: parent the popup and the list items during serialization bool popupShown = popup_ && popup_->IsVisible(); if (popup_) { InsertChild(0, popup_); popup_->SetVisible(false); } while (listView_->GetNumItems()) placeholder_->AddChild(listView_->GetItem(0)); bool success = UIElement::SaveXML(dest); while (placeholder_->GetNumChildren()) listView_->AddItem(placeholder_->GetChild(0)); ShowPopup(popupShown); return success; } void DropDownList::ApplyAttributes() { // Hack: if the placeholder has any child elements defined, move them to the list while (placeholder_->GetNumChildren()) AddItem(placeholder_->GetChild(0)); } void DropDownList::GetBatches(PODVector<UIBatch>& batches, PODVector<UIQuad>& quads, const IntRect& currentScissor) { Button::GetBatches(batches, quads, currentScissor); if (!placeholder_->IsVisible()) return; UIElement* selectedItem = GetSelectedItem(); if (selectedItem) { // Can not easily copy the selected item. However, it can be re-rendered on the placeholder's position const IntVector2& targetPos = placeholder_->GetScreenPosition(); const IntVector2& originalPos = selectedItem->GetScreenPosition(); IntVector2 offset = targetPos - originalPos; // GetBatches() usually resets the hover flag. Therefore get its value and then reset it for the real rendering bool hover = selectedItem->IsHovering(); selectedItem->SetHovering(false); selectedItem->GetBatchesWithOffset(offset, batches, quads, currentScissor); selectedItem->SetHovering(hover); } } void DropDownList::OnShowPopup() { // Resize the popup to match the size of the list content, and optionally match the button width UIElement* content = listView_->GetContentElement(); content->UpdateLayout(); const IntVector2& contentSize = content->GetSize(); const IntRect& border = popup_->GetLayoutBorder(); popup_->SetSize(resizePopup_ ? GetWidth() : contentSize.x_ + border.left_ + border.right_, contentSize.y_ + border.top_ + border.bottom_); // Check if popup fits below the button. If not, show above instead bool showAbove = false; UIElement* root = GetRoot(); if (root) { const IntVector2& screenPos = GetScreenPosition(); if (screenPos.y_ + GetHeight() + popup_->GetHeight() > root->GetHeight() && screenPos.y_ - popup_->GetHeight() >= 0) showAbove = true; } if (!showAbove) SetPopupOffset(0, GetHeight()); else SetPopupOffset(0, -popup_->GetHeight()); } void DropDownList::AddItem(UIElement* item) { InsertItem(listView_->GetNumItems(), item); } void DropDownList::InsertItem(unsigned index, UIElement* item) { listView_->InsertItem(index, item); // If there was no selection, set to the first if (listView_->GetSelection() == M_MAX_UNSIGNED) listView_->SetSelection(0); } void DropDownList::RemoveItem(UIElement* item) { listView_->RemoveItem(item); } void DropDownList::RemoveItem(unsigned index) { listView_->RemoveItem(index); } void DropDownList::RemoveAllItems() { listView_->RemoveAllItems(); } void DropDownList::SetSelection(unsigned index) { listView_->SetSelection(index); } void DropDownList::SetResizePopup(bool enable) { resizePopup_ = enable; } unsigned DropDownList::GetNumItems() const { return listView_->GetNumItems(); } UIElement* DropDownList::GetItem(unsigned index) const { return listView_->GetItem(index); } PODVector<UIElement*> DropDownList::GetItems() const { PODVector<UIElement*> items; listView_->GetContentElement()->GetChildren(items); return items; } unsigned DropDownList::GetSelection() const { return listView_->GetSelection(); } UIElement* DropDownList::GetSelectedItem() const { return listView_->GetSelectedItem(); } void DropDownList::HandleItemSelected(StringHash eventType, VariantMap& eventData) { // Resize the selection placeholder to match the selected item UIElement* selectedItem = GetSelectedItem(); if (selectedItem) placeholder_->SetSize(selectedItem->GetSize()); // Close the popup as the selection was made if (GetShowPopup()) ShowPopup(false); // Send the event forward using namespace ItemSelected; VariantMap newEventData; newEventData[P_ELEMENT] = (void*)this; newEventData[P_SELECTION] = GetSelection(); SendEvent(E_ITEMSELECTED, newEventData); } } <|endoftext|>
<commit_before>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include "vw_cbutil.h" #include "cb_algs.h" namespace VW { float VowpalWabbitContextualBanditUtil::GetUnbiasedCost(uint32_t actionObservered, uint32_t actionTaken, float cost, float probability) { CB::cb_class observation = { cost, actionObservered, probability }; return get_unbiased_cost(&observation, actionTaken); } } <commit_msg>vw_cbutil error fix attempt<commit_after>/* Copyright (c) by respective owners including Yahoo!, Microsoft, and individual contributors. All rights reserved. Released under a BSD (revised) license as described in the file LICENSE. */ #include "vw_cbutil.h" #include "cb_algs.h" namespace VW { float VowpalWabbitContextualBanditUtil::GetUnbiasedCost(uint32_t actionObservered, uint32_t actionTaken, float cost, float probability) { CB::cb_class observation = { cost, actionObservered, probability }; return CB_ALGS::get_unbiased_cost(&observation, actionTaken); } } <|endoftext|>
<commit_before> #include <Python.h> #include <pybind11/pybind11.h> namespace py = pybind11; extern "C" PyObject* function_with_cpp_args(PyObject* self, PyObject* args, PyObject* kwargs) { static char* _keywords_[] = {"a","b",nullptr}; py::object a; py::object b; if(!PyArg_ParseTupleAndKeywords(args, kwargs, "OO", _keywords_, &(a.ptr()), &(b.ptr()))) return nullptr; a.inc_ref(); b.inc_ref(); { py::tuple args = py::make_tuple(a, b); args.inc_ref(); return args.ptr(); } } static PyMethodDef module_functions_def[] = { {"function_with_cpp_args", reinterpret_cast<PyCFunction>(function_with_cpp_args), METH_VARARGS | METH_KEYWORDS, nullptr}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef inline_module = { PyModuleDef_HEAD_INIT, "compiled_function_with_cpp_args", nullptr, -1, module_functions_def }; PyMODINIT_FUNC PyInit_compiled_function_with_cpp_args(void) { PyObject* module = PyModule_Create(&inline_module); if (module == nullptr) return nullptr; return module; } <commit_msg>Remove temporary cpp code<commit_after><|endoftext|>
<commit_before>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/Wnt/OsFileSystemWnt.h" #include "os/Wnt/OsFileWnt.h" #include "os/Wnt/OsPathWnt.h" #include "os/Wnt/OsFileInfoWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const unsigned long CopyBufLen = 32768; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileWnt::OsFileWnt(const OsPathBase& filename) : OsFileBase(filename) { } // Copy constructor OsFileWnt::OsFileWnt(const OsFileWnt& rOsFileWnt) : OsFileBase(rOsFileWnt) { OsPathWnt path; rOsFileWnt.getFileName(path); mFilename = path; mOsFileHandle = rOsFileWnt.mOsFileHandle; } // Destructor OsFileWnt::~OsFileWnt() { if (mOsFileHandle) close(); //call our close } /* ============================ MANIPULATORS ============================== */ OsStatus OsFileWnt::setLength(unsigned long newLength) { OsStatus stat = OS_SUCCESS; return stat; } OsStatus OsFileWnt::fileunlock() { OsStatus retval = OS_SUCCESS; return retval; } OsStatus OsFileWnt::filelock(const bool wait) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsFileWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; #ifdef WINCE printf( "JEP - TODO in OsFileWnt::getFileInfo( )\n" ); // JEP - TODO - implement this... #else struct stat stats; if (stat(mFilename,&stats) == 0) { ret = OS_SUCCESS; if (stats.st_mode & _S_IWRITE) fileinfo.mbIsReadOnly = FALSE; else fileinfo.mbIsReadOnly = TRUE; OsTime createTime(stats.st_ctime,0); fileinfo.mCreateTime = createTime; OsTime modifiedTime(stats.st_ctime,0); fileinfo.mCreateTime = modifiedTime; fileinfo.mSize = stats.st_size; } #endif return ret; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileWnt::isReadonly() const { UtlBoolean retval = FALSE; OsFileInfoWnt info; getFileInfo(info); return info.mbIsReadOnly; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsFileWnt& OsFileWnt::operator=(const OsFileWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Bugfix: OsFileWnt::getFileInfo() returned incorrect file modification time.<commit_after>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES // APPLICATION INCLUDES #include "os/Wnt/OsFileSystemWnt.h" #include "os/Wnt/OsFileWnt.h" #include "os/Wnt/OsPathWnt.h" #include "os/Wnt/OsFileInfoWnt.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS const unsigned long CopyBufLen = 32768; // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsFileWnt::OsFileWnt(const OsPathBase& filename) : OsFileBase(filename) { } // Copy constructor OsFileWnt::OsFileWnt(const OsFileWnt& rOsFileWnt) : OsFileBase(rOsFileWnt) { OsPathWnt path; rOsFileWnt.getFileName(path); mFilename = path; mOsFileHandle = rOsFileWnt.mOsFileHandle; } // Destructor OsFileWnt::~OsFileWnt() { if (mOsFileHandle) close(); //call our close } /* ============================ MANIPULATORS ============================== */ OsStatus OsFileWnt::setLength(unsigned long newLength) { OsStatus stat = OS_SUCCESS; return stat; } OsStatus OsFileWnt::fileunlock() { OsStatus retval = OS_SUCCESS; return retval; } OsStatus OsFileWnt::filelock(const bool wait) { OsStatus retval = OS_FAILED; return retval; } OsStatus OsFileWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; #ifdef WINCE printf( "JEP - TODO in OsFileWnt::getFileInfo( )\n" ); // JEP - TODO - implement this... #else struct stat stats; if (stat(mFilename,&stats) == 0) { ret = OS_SUCCESS; if (stats.st_mode & _S_IWRITE) fileinfo.mbIsReadOnly = FALSE; else fileinfo.mbIsReadOnly = TRUE; OsTime createTime(stats.st_ctime,0); fileinfo.mCreateTime = createTime; OsTime modifiedTime(stats.st_mtime,0); fileinfo.mModifiedTime = modifiedTime; fileinfo.mSize = stats.st_size; } #endif return ret; } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ UtlBoolean OsFileWnt::isReadonly() const { UtlBoolean retval = FALSE; OsFileInfoWnt info; getFileInfo(info); return info.mbIsReadOnly; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ // Assignment operator OsFileWnt& OsFileWnt::operator=(const OsFileWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>#include "linear_interpolate_d.hpp" #include "find_barycentric_coords.hpp" #include <algorithm> #include <map> #include <vector> typedef CGAL::Cartesian_d<double> R; typedef CGAL::Delaunay_d<R> Delaunay; typedef Delaunay::Point_d Point; typedef Delaunay::Vertex_handle Vertex_handle; // returns beta_1, ..., beta_d+1, beta_0 std::vector<double> linear_coef(size_t d, const std::vector<Point> &points, const std::vector<double> &values) { std::vector<double> a((d+1) * (d+1)); for (size_t i = 0; i <= d; ++i) { for (size_t j = 0; j < d; ++j) { a[i + j*(d+1)] = *(points[i].cartesian_begin() + j); } a[i + d*(d+1)] = 1; } std::vector<double> b(values); for (auto el : b) { if (ISNAN(el)) { return b; } } // additional variables needed for LAPACK std::vector<int> ipiv(d + 1); int info; int size_int = d + 1; int b_size = 1; // solve a*x = b // result will be in b F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0], &b[0], &size_int, &info); if (info != 0) { // error("Bad matrix"); } return b; } class LinearInterpolator_d { public: LinearInterpolator_d(int d, const double *points, const double *values, size_t npoints) : d{d}, triangulation{d}, npoints{npoints} { for (size_t i{0}; i < npoints; ++i) { Point point(d, points + i*d, points + (i + 1)*d); Vertex_handle vertex_handle = triangulation.insert(point); vertices_to_values[vertex_handle] = values[i]; } for (const auto &simplex : triangulation.all_simplices()) { if (simplex == Delaunay::Simplex_handle()) continue; std::vector<Point> vertices; std::vector<double> vertex_values; bool flag = true; for (size_t i{0}; i <= d; ++i) { auto vertex = triangulation.vertex_of_simplex(simplex, i); double vertex_val = vertices_to_values[vertex]; if (vertex == Delaunay::Vertex_handle()) { flag = false; break; } vertices.push_back(vertex->point()); vertex_values.push_back(vertex_val); } if (!flag) continue; m[simplex] = linear_coef(d, vertices, vertex_values); } } double get(const double *x) { const double double_fill_value = NA_REAL; Point point(d, x, x + d); auto simplex = triangulation.locate(point); if (!m.count(simplex)) { return double_fill_value; } auto beta = m[simplex]; return std::inner_product(x, x + d, beta.begin(), beta[d]); } double operator()(const double *x) { const double double_fill_value = NA_REAL; Point point(d, x, x + d); auto simplex = triangulation.locate(point); if (simplex == Delaunay::Simplex_handle()) { return double_fill_value; } std::vector<Point> vertices(d + 1); std::vector<double> vertex_values(d + 1); for (size_t i{0}; i <= triangulation.current_dimension(); ++i) { auto vertex = triangulation.vertex_of_simplex(simplex, i); double vertex_val = vertices_to_values[vertex]; if (ISNAN(vertex_val)) { return double_fill_value; } vertices[i] = triangulation.associated_point(vertex); vertex_values[i] = vertex_val; } auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices); return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.); } private: const int d; size_t npoints; Delaunay triangulation; std::map<Vertex_handle, double> vertices_to_values; std::map<Delaunay::Simplex_handle, std::vector<double>> m; }; SEXP linear_interpolate_d(SEXP dimentions, SEXP points, SEXP values, SEXP xi) { int d = INTEGER(dimentions)[0]; LinearInterpolator_d li(d, REAL(points), REAL(values), length(values)); int result_length = length(xi) / d; SEXP results = PROTECT(allocVector(REALSXP, result_length)); for (size_t i{0}; i < result_length; ++i) { // REAL(results)[i] = li(REAL(xi) + i*d); REAL(results)[i] = li.get(REAL(xi) + i*d); } UNPROTECT(1); return results; } <commit_msg>Drop exact coef computation staff<commit_after>#include "linear_interpolate_d.hpp" #include "find_barycentric_coords.hpp" #include <algorithm> #include <map> #include <vector> typedef CGAL::Cartesian_d<double> R; typedef CGAL::Delaunay_d<R> Delaunay; typedef Delaunay::Point_d Point; typedef Delaunay::Vertex_handle Vertex_handle; class LinearInterpolator_d { public: LinearInterpolator_d(int d, const double *points, const double *values, size_t npoints) : d{d}, triangulation{d}, npoints{npoints} { for (size_t i{0}; i < npoints; ++i) { Point point(d, points + i*d, points + (i + 1)*d); Vertex_handle vertex_handle = triangulation.insert(point); vertices_to_values[vertex_handle] = values[i]; } } double operator()(const double *x) { const double double_fill_value = NA_REAL; Point point(d, x, x + d); auto simplex = triangulation.locate(point); if (simplex == Delaunay::Simplex_handle()) { return double_fill_value; } std::vector<Point> vertices(d + 1); std::vector<double> vertex_values(d + 1); for (size_t i{0}; i <= triangulation.current_dimension(); ++i) { auto vertex = triangulation.vertex_of_simplex(simplex, i); double vertex_val = vertices_to_values[vertex]; if (ISNAN(vertex_val)) { return double_fill_value; } vertices[i] = triangulation.associated_point(vertex); vertex_values[i] = vertex_val; } auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices); return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.); } private: const int d; size_t npoints; Delaunay triangulation; std::map<Vertex_handle, double> vertices_to_values; }; SEXP linear_interpolate_d(SEXP dimentions, SEXP points, SEXP values, SEXP xi) { int d = INTEGER(dimentions)[0]; LinearInterpolator_d li(d, REAL(points), REAL(values), length(values)); int result_length = length(xi) / d; SEXP results = PROTECT(allocVector(REALSXP, result_length)); for (size_t i{0}; i < result_length; ++i) { REAL(results)[i] = li(REAL(xi) + i*d); } UNPROTECT(1); return results; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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_sal.hxx" #include <cppunit/TestFixture.h> #include <cppunit/TestAssert.h> #include <cppunit/extensions/HelperMacros.h> #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" namespace test { namespace oustringbuffer { class ToString: public CppUnit::TestFixture { private: void testToString(); CPPUNIT_TEST_SUITE(ToString); CPPUNIT_TEST(testToString); CPPUNIT_TEST_SUITE_END(); }; } } CPPUNIT_TEST_SUITE_REGISTRATION(test::oustringbuffer::ToString); void test::oustringbuffer::ToString::testToString() { rtl::OUStringBuffer sb(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test string"))); rtl::OUString str = sb.toString(); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); // returned OUString must be independent from sb sb.append('a'); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); sb.setLength(0); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix: call of overloaded 'append(char)' is ambiguous<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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_sal.hxx" #include <cppunit/TestFixture.h> #include <cppunit/TestAssert.h> #include <cppunit/extensions/HelperMacros.h> #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" namespace test { namespace oustringbuffer { class ToString: public CppUnit::TestFixture { private: void testToString(); CPPUNIT_TEST_SUITE(ToString); CPPUNIT_TEST(testToString); CPPUNIT_TEST_SUITE_END(); }; } } CPPUNIT_TEST_SUITE_REGISTRATION(test::oustringbuffer::ToString); void test::oustringbuffer::ToString::testToString() { rtl::OUStringBuffer sb(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test string"))); rtl::OUString str = sb.toString(); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); // returned OUString must be independent from sb sb.append( (sal_Unicode)'a' ); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); sb.setLength(0); CPPUNIT_ASSERT(str.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("test string"))); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file df_mpu9250_wrapper.cpp * Lightweight driver to access the MPU9250 of the DriverFramework. * * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_accel.h> #include <drivers/drv_gyro.h> #include <board_config.h> //#include <mathlib/math/filter/LowPassFilter2p.hpp> //#include <lib/conversion/rotation.h> #include <mpu9250/MPU9250.hpp> #include <DevMgr.hpp> extern "C" { __EXPORT int df_mpu9250_wrapper_main(int argc, char *argv[]); } using namespace DriverFramework; class DfMpu9250Wrapper : public MPU9250 { public: DfMpu9250Wrapper(/*enum Rotation rotation*/); ~DfMpu9250Wrapper(); /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: int _publish(struct imu_sensor_data &data); //enum Rotation _rotation; orb_advert_t _accel_topic; orb_advert_t _gyro_topic; int _accel_orb_class_instance; int _gyro_orb_class_instance; perf_counter_t _accel_sample_perf; perf_counter_t _gyro_sample_perf; }; DfMpu9250Wrapper::DfMpu9250Wrapper(/*enum Rotation rotation*/) : MPU9250(IMU_DEVICE_PATH), _accel_topic(nullptr), _gyro_topic(nullptr), _accel_orb_class_instance(-1), _gyro_orb_class_instance(-1), _accel_sample_perf(perf_alloc(PC_ELAPSED, "df_accel_read")), _gyro_sample_perf(perf_alloc(PC_ELAPSED, "df_gyro_read")) /*_rotation(rotation)*/ { } DfMpu9250Wrapper::~DfMpu9250Wrapper() { perf_free(_accel_sample_perf); perf_free(_gyro_sample_perf); } int DfMpu9250Wrapper::start() { // TODO: don't publish garbage here accel_report accel_report = {}; _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &accel_report, &_accel_orb_class_instance, ORB_PRIO_DEFAULT); if (_accel_topic == nullptr) { PX4_ERR("sensor_accel advert fail"); return -1; } // TODO: don't publish garbage here gyro_report gyro_report = {}; _gyro_topic = orb_advertise_multi(ORB_ID(sensor_gyro), &gyro_report, &_gyro_orb_class_instance, ORB_PRIO_DEFAULT); if (_gyro_topic == nullptr) { PX4_ERR("sensor_gyro advert fail"); return -1; } /* Init device and start sensor. */ int ret = init(); if (ret != 0) { PX4_ERR("MPU9250 init fail: %d", ret); return ret; } ret = MPU9250::start(); if (ret != 0) { PX4_ERR("MPU9250 start fail: %d", ret); return ret; } return 0; } int DfMpu9250Wrapper::stop() { /* Stop sensor. */ int ret = MPU9250::stop(); if (ret != 0) { PX4_ERR("MPU9250 stop fail: %d", ret); return ret; } return 0; } int DfMpu9250Wrapper::_publish(struct imu_sensor_data &data) { /* Publish accel first. */ perf_begin(_accel_sample_perf); accel_report accel_report = {}; accel_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) accel_report.x_raw = NAN; accel_report.y_raw = NAN; accel_report.z_raw = NAN; accel_report.x = data.accel_m_s2_x; accel_report.y = data.accel_m_s2_y; accel_report.z = data.accel_m_s2_z; // TODO: get these right accel_report.scaling = -1.0f; accel_report.range_m_s2 = -1.0f; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_accel_topic != nullptr) { orb_publish(ORB_ID(sensor_accel), _accel_topic, &accel_report); } } perf_end(_accel_sample_perf); /* Then publish gyro. */ perf_begin(_gyro_sample_perf); gyro_report gyro_report = {}; gyro_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) gyro_report.x_raw = NAN; gyro_report.y_raw = NAN; gyro_report.z_raw = NAN; gyro_report.x = data.gyro_rad_s_x; gyro_report.y = data.gyro_rad_s_y; gyro_report.z = data.gyro_rad_s_z; // TODO: get these right gyro_report.scaling = -1.0f; gyro_report.range_rad_s = -1.0f; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_gyro_topic != nullptr) { orb_publish(ORB_ID(sensor_gyro), _gyro_topic, &gyro_report); } } perf_end(_gyro_sample_perf); /* Notify anyone waiting for data. */ DevMgr::updateNotify(*this); return 0; }; namespace df_mpu9250_wrapper { DfMpu9250Wrapper *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfMpu9250Wrapper(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfMpu9250Wrapper object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfMpu9250Wrapper start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(IMU_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", IMU_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_mpu9250_wrapper 'start', 'info', 'stop'"); PX4_WARN("options:"); //PX4_WARN(" -R rotation"); } } // namespace df_mpu9250_wrapper int df_mpu9250_wrapper_main(int argc, char *argv[]) { int ch; // enum Rotation rotation = ROTATION_NONE; int ret = 0; int myoptind = 1; const char *myoptarg = NULL; /* jump over start/off/etc and look at options first */ while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) { switch (ch) { //case 'R': // rotation = (enum Rotation)atoi(myoptarg); // break; default: df_mpu9250_wrapper::usage(); return 0; } } if (argc <= 1) { df_mpu9250_wrapper::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_mpu9250_wrapper::start(/*rotation*/); } else if (!strcmp(verb, "stop")) { ret = df_mpu9250_wrapper::stop(); } else if (!strcmp(verb, "info")) { ret = df_mpu9250_wrapper::info(); } else { df_mpu9250_wrapper::usage(); return 1; } return ret; } <commit_msg>df_mpu9250_wrapper: astyle<commit_after>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file df_mpu9250_wrapper.cpp * Lightweight driver to access the MPU9250 of the DriverFramework. * * @author Julian Oes <julian@oes.ch> */ #include <px4_config.h> #include <sys/types.h> #include <sys/stat.h> #include <stdint.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <px4_getopt.h> #include <errno.h> #include <systemlib/perf_counter.h> #include <systemlib/err.h> #include <drivers/drv_accel.h> #include <drivers/drv_gyro.h> #include <board_config.h> //#include <mathlib/math/filter/LowPassFilter2p.hpp> //#include <lib/conversion/rotation.h> #include <mpu9250/MPU9250.hpp> #include <DevMgr.hpp> extern "C" { __EXPORT int df_mpu9250_wrapper_main(int argc, char *argv[]); } using namespace DriverFramework; class DfMpu9250Wrapper : public MPU9250 { public: DfMpu9250Wrapper(/*enum Rotation rotation*/); ~DfMpu9250Wrapper(); /** * Start automatic measurement. * * @return 0 on success */ int start(); /** * Stop automatic measurement. * * @return 0 on success */ int stop(); private: int _publish(struct imu_sensor_data &data); //enum Rotation _rotation; orb_advert_t _accel_topic; orb_advert_t _gyro_topic; int _accel_orb_class_instance; int _gyro_orb_class_instance; perf_counter_t _accel_sample_perf; perf_counter_t _gyro_sample_perf; }; DfMpu9250Wrapper::DfMpu9250Wrapper(/*enum Rotation rotation*/) : MPU9250(IMU_DEVICE_PATH), _accel_topic(nullptr), _gyro_topic(nullptr), _accel_orb_class_instance(-1), _gyro_orb_class_instance(-1), _accel_sample_perf(perf_alloc(PC_ELAPSED, "df_accel_read")), _gyro_sample_perf(perf_alloc(PC_ELAPSED, "df_gyro_read")) /*_rotation(rotation)*/ { } DfMpu9250Wrapper::~DfMpu9250Wrapper() { perf_free(_accel_sample_perf); perf_free(_gyro_sample_perf); } int DfMpu9250Wrapper::start() { // TODO: don't publish garbage here accel_report accel_report = {}; _accel_topic = orb_advertise_multi(ORB_ID(sensor_accel), &accel_report, &_accel_orb_class_instance, ORB_PRIO_DEFAULT); if (_accel_topic == nullptr) { PX4_ERR("sensor_accel advert fail"); return -1; } // TODO: don't publish garbage here gyro_report gyro_report = {}; _gyro_topic = orb_advertise_multi(ORB_ID(sensor_gyro), &gyro_report, &_gyro_orb_class_instance, ORB_PRIO_DEFAULT); if (_gyro_topic == nullptr) { PX4_ERR("sensor_gyro advert fail"); return -1; } /* Init device and start sensor. */ int ret = init(); if (ret != 0) { PX4_ERR("MPU9250 init fail: %d", ret); return ret; } ret = MPU9250::start(); if (ret != 0) { PX4_ERR("MPU9250 start fail: %d", ret); return ret; } return 0; } int DfMpu9250Wrapper::stop() { /* Stop sensor. */ int ret = MPU9250::stop(); if (ret != 0) { PX4_ERR("MPU9250 stop fail: %d", ret); return ret; } return 0; } int DfMpu9250Wrapper::_publish(struct imu_sensor_data &data) { /* Publish accel first. */ perf_begin(_accel_sample_perf); accel_report accel_report = {}; accel_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) accel_report.x_raw = NAN; accel_report.y_raw = NAN; accel_report.z_raw = NAN; accel_report.x = data.accel_m_s2_x; accel_report.y = data.accel_m_s2_y; accel_report.z = data.accel_m_s2_z; // TODO: get these right accel_report.scaling = -1.0f; accel_report.range_m_s2 = -1.0f; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_accel_topic != nullptr) { orb_publish(ORB_ID(sensor_accel), _accel_topic, &accel_report); } } perf_end(_accel_sample_perf); /* Then publish gyro. */ perf_begin(_gyro_sample_perf); gyro_report gyro_report = {}; gyro_report.timestamp = data.last_read_time_usec; // TODO: remove these (or get the values) gyro_report.x_raw = NAN; gyro_report.y_raw = NAN; gyro_report.z_raw = NAN; gyro_report.x = data.gyro_rad_s_x; gyro_report.y = data.gyro_rad_s_y; gyro_report.z = data.gyro_rad_s_z; // TODO: get these right gyro_report.scaling = -1.0f; gyro_report.range_rad_s = -1.0f; // TODO: when is this ever blocked? if (!(m_pub_blocked)) { if (_gyro_topic != nullptr) { orb_publish(ORB_ID(sensor_gyro), _gyro_topic, &gyro_report); } } perf_end(_gyro_sample_perf); /* Notify anyone waiting for data. */ DevMgr::updateNotify(*this); return 0; }; namespace df_mpu9250_wrapper { DfMpu9250Wrapper *g_dev = nullptr; int start(/* enum Rotation rotation */); int stop(); int info(); void usage(); int start(/*enum Rotation rotation*/) { g_dev = new DfMpu9250Wrapper(/*rotation*/); if (g_dev == nullptr) { PX4_ERR("failed instantiating DfMpu9250Wrapper object"); return -1; } int ret = g_dev->start(); if (ret != 0) { PX4_ERR("DfMpu9250Wrapper start failed"); return ret; } // Open the IMU sensor DevHandle h; DevMgr::getHandle(IMU_DEVICE_PATH, h); if (!h.isValid()) { DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)", IMU_DEVICE_PATH, h.getError()); return -1; } DevMgr::releaseHandle(h); return 0; } int stop() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } int ret = g_dev->stop(); if (ret != 0) { PX4_ERR("driver could not be stopped"); return ret; } delete g_dev; g_dev = nullptr; return 0; } /** * Print a little info about the driver. */ int info() { if (g_dev == nullptr) { PX4_ERR("driver not running"); return 1; } PX4_DEBUG("state @ %p", g_dev); return 0; } void usage() { PX4_WARN("Usage: df_mpu9250_wrapper 'start', 'info', 'stop'"); PX4_WARN("options:"); //PX4_WARN(" -R rotation"); } } // namespace df_mpu9250_wrapper int df_mpu9250_wrapper_main(int argc, char *argv[]) { int ch; // enum Rotation rotation = ROTATION_NONE; int ret = 0; int myoptind = 1; const char *myoptarg = NULL; /* jump over start/off/etc and look at options first */ while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) { switch (ch) { //case 'R': // rotation = (enum Rotation)atoi(myoptarg); // break; default: df_mpu9250_wrapper::usage(); return 0; } } if (argc <= 1) { df_mpu9250_wrapper::usage(); return 1; } const char *verb = argv[myoptind]; if (!strcmp(verb, "start")) { ret = df_mpu9250_wrapper::start(/*rotation*/); } else if (!strcmp(verb, "stop")) { ret = df_mpu9250_wrapper::stop(); } else if (!strcmp(verb, "info")) { ret = df_mpu9250_wrapper::info(); } else { df_mpu9250_wrapper::usage(); return 1; } return ret; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.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 "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/ThirdHeader.h" #include "llbc/common/Config.h" #include "llbc/common/Compiler.h" #include "llbc/common/Version.h" __LLBC_NS_BEGIN int LLBC_majorVersion = 1; int LLBC_minorVersion = 0; int LLBC_updateNo = 2; #ifdef LLBC_DEBUG bool LLBC_isDebugVer = true; #else bool LLBC_isDebugVer = false; #endif LLBC_String LLBC_GetVersionInfo(bool verbose) { LLBC_String desc; desc.format("%d.%d.%d_%s", LLBC_majorVersion, LLBC_minorVersion, LLBC_updateNo, LLBC_isDebugVer ? "debug" : "release"); #if LLBC_TARGET_PLATFORM_WIN32 desc.append_format("(%s", "WIN32"); #elif LLBC_TARGET_PLATFORM_LINUX desc.append_format("(%s", "LINUX"); #elif LLBC_TARGET_PLATFORM_IPHONE desc.append_format("(%s", "IPHONE"); #elif LLBC_TARGET_PLATFORM_MAC desc.append_format("(%s", "MAC"); #elif LLBC_TARGET_PLATFORM_ANDROID desc.append_format("(%s", "ANDROID"); #endif #if LLBC_CUR_COMP == LLBC_COMP_MSVC desc.append_format(", compiled with: %s, version: %d)", LLBC_CUR_COMP_DESC, LLBC_COMP_VER); #elif LLBC_CUR_COMP == LLBC_COMP_GCC desc.append_format(", compiled with: %s, version %d.%d.%d)", LLBC_CUR_COMP_DESC, LLBC_COMP_MAJOR_VER, LLBC_COMP_MINOR_VER, LLBC_COMP_PATCH_LEVEL); #else desc.append_format(", compiled with: %s)", LLBC_CUR_COMP_DESC); #endif if (!verbose) return desc; // Append core info. desc.append_format("\n"); desc.append_format("core info: \n"); desc.append_format(" thread info: \n"); desc.append_format(" max thread num: %d\n", LLBC_CFG_THREAD_MAX_THREAD_NUM); desc.append_format(" default thread stack size: %d\n", LLBC_CFG_THREAD_DFT_STACK_SIZE); desc.append_format(" miximum thread stack size: %d\n", LLBC_CFG_THREAD_MINIMUM_STACK_SIZE); desc.append_format(" message block size: %d\n", LLBC_CFG_THREAD_MSG_BLOCK_DFT_SIZE); desc.append_format(" enabled guard debug: %s\n", LLBC_CFG_THREAD_GUARD_DEBUG ? "true" : "false"); desc.append_format(" logger info: \n"); desc.append_format(" default level: %d\n", LLBC_CFG_LOG_DEFAULT_LEVEL); desc.append_format(" default asynchronous mode: %s\n", (LLBC_CFG_LOG_DEFAULT_ASYNC_MODE) ? "true" : "false"); desc.append_format(" default log to console: %s\n", (LLBC_CFG_LOG_DEFAULT_LOG_TO_CONSOLE) ? "true" : "false"); desc.append_format(" default console log pattern: %s\n", LLBC_CFG_LOG_DEFAULT_CONSOLE_LOG_PATTERN); desc.append_format(" default log to file: %s\n", (LLBC_CFG_LOG_DEFAULT_LOG_TO_FILE) ? "true" : "false"); desc.append_format(" default log file name: %s\n", LLBC_CFG_LOG_DEFAULT_LOG_FILE_NAME); desc.append_format(" default file log pattern: %s\n", LLBC_CFG_LOG_DEFAULT_FILE_LOG_PATTERN); desc.append_format(" default daily mode enabled(available in file log): %s\n", (LLBC_CFG_LOG_DEFAULT_DAILY_MODE) ? "true" : "false"); desc.append_format(" default max log file size: %d\n", LLBC_CFG_LOG_MAX_FILE_SIZE); desc.append_format(" default max backup index: %d\n", LLBC_CFG_LOG_MAX_BACKUP_INDEX); desc.append_format(" default flush interval(ms)(only available in asyn mode): %d\n", LLBC_CFG_LOG_DEFAULT_LOG_FLUSH_INTERVAL); desc.append_format(" max flush interval(ms)(only available in asyn mode): %d\n", LLBC_CFG_LOG_MAX_LOG_FLUSH_INTERVAL); desc.append_format(" default log file buffer size: %d\n", LLBC_CFG_LOG_DEFAULT_LOG_FILE_BUFFER_SIZE); desc.append_format(" take over unknown logger message?: %s\n", LLBC_CFG_LOG_ROOT_LOGGER_TAKE_OVER_UNCONFIGED ? "true" : "false"); desc.append_format(" timer info: \n"); desc.append_format(" strict timer schedule: %s\n", LLBC_CFG_CORE_TIMER_STRICT_SCHEDULE ? "true" : "false"); // Append communication info. desc.append_format("communication info: \n"); desc.append_format(" poller model: %s\n", LLBC_CFG_COMM_POLLER_MODEL); desc.append_format(" default service FPS: %d\n", LLBC_CFG_COMM_DFT_SERVICE_FPS); desc.append_format(" per thread max drive services count: %d\n", LLBC_CFG_COMM_PER_THREAD_DRIVE_MAX_SVC_COUNT); desc.append_format(" full protocol-stack support(let your program more efficient): %s\n", LLBC_CFG_COMM_USE_FULL_STACK ? "true" : "false"); desc.append_format(" enabled register status code handler support: %s\n", LLBC_CFG_COMM_ENABLE_STATUS_HANDLER ? "true" : "false"); desc.append_format(" enabled register status code describe string support: %s\n", LLBC_CFG_COMM_ENABLE_STATUS_DESC ? "true" : "false"); desc.append_format(" enabled unify pre-subscribe support: %s\n", LLBC_CFG_COMM_ENABLE_UNIFY_PRESUBSCRIBE ? "true" : "false"); desc.append_format(" sampler support: %s\n", LLBC_CFG_COMM_ENABLE_SAMPLER_SUPPORT ? "true" : "false"); // Append third-party info. // desc.append_format("3rd party info: \n"); // desc.append_format(" zlib version: %s(ver-num:%d)\n", ZLIB_VERSION, ZLIB_VERNUM); return desc; } __LLBC_NS_END #include "llbc/common/AfterIncl.h" <commit_msg>Update version to 1.0.3<commit_after>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.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 "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/ThirdHeader.h" #include "llbc/common/Config.h" #include "llbc/common/Compiler.h" #include "llbc/common/Version.h" __LLBC_NS_BEGIN int LLBC_majorVersion = 1; int LLBC_minorVersion = 0; int LLBC_updateNo = 3; #ifdef LLBC_DEBUG bool LLBC_isDebugVer = true; #else bool LLBC_isDebugVer = false; #endif LLBC_String LLBC_GetVersionInfo(bool verbose) { LLBC_String desc; desc.format("%d.%d.%d_%s", LLBC_majorVersion, LLBC_minorVersion, LLBC_updateNo, LLBC_isDebugVer ? "debug" : "release"); #if LLBC_TARGET_PLATFORM_WIN32 desc.append_format("(%s", "WIN32"); #elif LLBC_TARGET_PLATFORM_LINUX desc.append_format("(%s", "LINUX"); #elif LLBC_TARGET_PLATFORM_IPHONE desc.append_format("(%s", "IPHONE"); #elif LLBC_TARGET_PLATFORM_MAC desc.append_format("(%s", "MAC"); #elif LLBC_TARGET_PLATFORM_ANDROID desc.append_format("(%s", "ANDROID"); #endif #if LLBC_CUR_COMP == LLBC_COMP_MSVC desc.append_format(", compiled with: %s, version: %d)", LLBC_CUR_COMP_DESC, LLBC_COMP_VER); #elif LLBC_CUR_COMP == LLBC_COMP_GCC desc.append_format(", compiled with: %s, version %d.%d.%d)", LLBC_CUR_COMP_DESC, LLBC_COMP_MAJOR_VER, LLBC_COMP_MINOR_VER, LLBC_COMP_PATCH_LEVEL); #else desc.append_format(", compiled with: %s)", LLBC_CUR_COMP_DESC); #endif if (!verbose) return desc; // Append core info. desc.append_format("\n"); desc.append_format("core info: \n"); desc.append_format(" thread info: \n"); desc.append_format(" max thread num: %d\n", LLBC_CFG_THREAD_MAX_THREAD_NUM); desc.append_format(" default thread stack size: %d\n", LLBC_CFG_THREAD_DFT_STACK_SIZE); desc.append_format(" miximum thread stack size: %d\n", LLBC_CFG_THREAD_MINIMUM_STACK_SIZE); desc.append_format(" message block size: %d\n", LLBC_CFG_THREAD_MSG_BLOCK_DFT_SIZE); desc.append_format(" enabled guard debug: %s\n", LLBC_CFG_THREAD_GUARD_DEBUG ? "true" : "false"); desc.append_format(" logger info: \n"); desc.append_format(" default level: %d\n", LLBC_CFG_LOG_DEFAULT_LEVEL); desc.append_format(" default asynchronous mode: %s\n", (LLBC_CFG_LOG_DEFAULT_ASYNC_MODE) ? "true" : "false"); desc.append_format(" default log to console: %s\n", (LLBC_CFG_LOG_DEFAULT_LOG_TO_CONSOLE) ? "true" : "false"); desc.append_format(" default console log pattern: %s\n", LLBC_CFG_LOG_DEFAULT_CONSOLE_LOG_PATTERN); desc.append_format(" default log to file: %s\n", (LLBC_CFG_LOG_DEFAULT_LOG_TO_FILE) ? "true" : "false"); desc.append_format(" default log file name: %s\n", LLBC_CFG_LOG_DEFAULT_LOG_FILE_NAME); desc.append_format(" default file log pattern: %s\n", LLBC_CFG_LOG_DEFAULT_FILE_LOG_PATTERN); desc.append_format(" default daily mode enabled(available in file log): %s\n", (LLBC_CFG_LOG_DEFAULT_DAILY_MODE) ? "true" : "false"); desc.append_format(" default max log file size: %d\n", LLBC_CFG_LOG_MAX_FILE_SIZE); desc.append_format(" default max backup index: %d\n", LLBC_CFG_LOG_MAX_BACKUP_INDEX); desc.append_format(" default flush interval(ms)(only available in asyn mode): %d\n", LLBC_CFG_LOG_DEFAULT_LOG_FLUSH_INTERVAL); desc.append_format(" max flush interval(ms)(only available in asyn mode): %d\n", LLBC_CFG_LOG_MAX_LOG_FLUSH_INTERVAL); desc.append_format(" default log file buffer size: %d\n", LLBC_CFG_LOG_DEFAULT_LOG_FILE_BUFFER_SIZE); desc.append_format(" take over unknown logger message?: %s\n", LLBC_CFG_LOG_ROOT_LOGGER_TAKE_OVER_UNCONFIGED ? "true" : "false"); desc.append_format(" timer info: \n"); desc.append_format(" strict timer schedule: %s\n", LLBC_CFG_CORE_TIMER_STRICT_SCHEDULE ? "true" : "false"); // Append communication info. desc.append_format("communication info: \n"); desc.append_format(" poller model: %s\n", LLBC_CFG_COMM_POLLER_MODEL); desc.append_format(" default service FPS: %d\n", LLBC_CFG_COMM_DFT_SERVICE_FPS); desc.append_format(" per thread max drive services count: %d\n", LLBC_CFG_COMM_PER_THREAD_DRIVE_MAX_SVC_COUNT); desc.append_format(" full protocol-stack support(let your program more efficient): %s\n", LLBC_CFG_COMM_USE_FULL_STACK ? "true" : "false"); desc.append_format(" enabled register status code handler support: %s\n", LLBC_CFG_COMM_ENABLE_STATUS_HANDLER ? "true" : "false"); desc.append_format(" enabled register status code describe string support: %s\n", LLBC_CFG_COMM_ENABLE_STATUS_DESC ? "true" : "false"); desc.append_format(" enabled unify pre-subscribe support: %s\n", LLBC_CFG_COMM_ENABLE_UNIFY_PRESUBSCRIBE ? "true" : "false"); desc.append_format(" sampler support: %s\n", LLBC_CFG_COMM_ENABLE_SAMPLER_SUPPORT ? "true" : "false"); // Append third-party info. // desc.append_format("3rd party info: \n"); // desc.append_format(" zlib version: %s(ver-num:%d)\n", ZLIB_VERSION, ZLIB_VERNUM); return desc; } __LLBC_NS_END #include "llbc/common/AfterIncl.h" <|endoftext|>
<commit_before>// // Copyright (C) 2007 Jaroslav Libak // Licensed under the LGPL license. // // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <net/SipTransport.h> #include <net/Url.h> // DEFINES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // MACROS // GLOBAL VARIABLES // GLOBAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const Url& url) { return getSipTransport(url.toString()); } SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const UtlString& strUrl) { SIPXSTACK_TRANSPORT_TYPE transport = SIPXSTACK_TRANSPORT_UDP; if (strUrl.contains("sips:") || strUrl.contains("transport=tls")) { transport = SIPXSTACK_TRANSPORT_TLS; } if (strUrl.contains("transport=tcp")) { transport = SIPXSTACK_TRANSPORT_TCP; } return transport; } SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const char* szUrl) { UtlString strUrl(szUrl); return getSipTransport(strUrl); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>SipTransport now ignores case of transport=tls etc.<commit_after>// // Copyright (C) 2007 Jaroslav Libak // Licensed under the LGPL license. // // Copyright (C) 2005-2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <net/SipTransport.h> #include <net/Url.h> // DEFINES // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS // MACROS // GLOBAL VARIABLES // GLOBAL FUNCTIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ /* ============================ MANIPULATORS ============================== */ SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const Url& url) { return getSipTransport(url.toString()); } SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const UtlString& strUrl) { SIPXSTACK_TRANSPORT_TYPE transport = SIPXSTACK_TRANSPORT_UDP; UtlString lowerStrUrl(strUrl); lowerStrUrl.toLower(); if (lowerStrUrl.contains("sips:") || lowerStrUrl.contains("transport=tls")) { transport = SIPXSTACK_TRANSPORT_TLS; } if (lowerStrUrl.contains("transport=tcp")) { transport = SIPXSTACK_TRANSPORT_TCP; } return transport; } SIPXSTACK_TRANSPORT_TYPE SipTransport::getSipTransport(const char* szUrl) { UtlString strUrl(szUrl); return getSipTransport(strUrl); } /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>