text
stringlengths 54
60.6k
|
|---|
<commit_before>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"
using namespace lsh;
std::vector<bool> c(128);
vector u = vector::random(128);
vector v = vector::random(128);
BENCHMARK(vector, vector, 10000, 200) {
lsh::vector v(c);
}
BENCHMARK(vector, size, 10000, 75000) {
v.size();
}
BENCHMARK(vector, get, 10000, 18000) {
v.get(64);
}
BENCHMARK(vector, equals, 10000, 10000) {
bool f = v == u;
}
BENCHMARK(vector, dot_product, 10000, 10000) {
v * u;
}
BENCHMARK(vector, and, 10000, 500) {
v & u;
}
BENCHMARK(vector, hash, 10000, 28000) {
v.hash();
}
BENCHMARK(vector, distance, 10000, 9000) {
vector::distance(u, v);
}
BENCHMARK(vector, random, 10000, 10) {
vector::random(128);
}
<commit_msg>Increase vector bench iteration count<commit_after>#include <vector>
#include "../lib/hayai/hayai.hpp"
#include "../lib/hayai/hayai_posix_main.cpp"
#include "../src/vector.hpp"
using namespace lsh;
std::vector<bool> c(128);
vector u = vector::random(128);
vector v = vector::random(128);
BENCHMARK(vector, vector, 10000, 300) {
lsh::vector v(c);
}
BENCHMARK(vector, size, 10000, 75000) {
v.size();
}
BENCHMARK(vector, get, 10000, 18000) {
v.get(64);
}
BENCHMARK(vector, equals, 10000, 10000) {
bool f = v == u;
}
BENCHMARK(vector, dot_product, 10000, 10000) {
v * u;
}
BENCHMARK(vector, and, 10000, 500) {
v & u;
}
BENCHMARK(vector, hash, 10000, 28000) {
v.hash();
}
BENCHMARK(vector, distance, 10000, 9000) {
vector::distance(u, v);
}
BENCHMARK(vector, random, 10000, 10) {
vector::random(128);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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 <iostream>
#include <boost/shared_ptr.hpp>
#ifdef DEBUG_ELEMENT
#include "ooxmlLoggers.hxx"
#include <resourcemodel/Protocol.hxx>
#endif
#include "OOXMLFastDocumentHandler.hxx"
#include "OOXMLFastContextHandler.hxx"
#include "OOXMLFastTokens.hxx"
#include "OOXMLFactory.hxx"
namespace writerfilter {
namespace ooxml
{
using namespace ::com::sun::star;
using namespace ::std;
OOXMLFastDocumentHandler::OOXMLFastDocumentHandler
(uno::Reference< uno::XComponentContext > const & context)
: m_xContext(context)
{}
// ::com::sun::star::xml::sax::XFastContextHandler:
void SAL_CALL OOXMLFastDocumentHandler::startFastElement
(::sal_Int32
#ifdef DEBUG_CONTEXT_STACK
Element
#endif
, const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":start element:"
<< fastTokenToId(Element)
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::startUnknownElement
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
, const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
,
const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":start unknown element:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::endFastElement(::sal_Int32
#ifdef DEBUG_CONTEXT_STACK
Element
#endif
)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":end element:"
<< fastTokenToId(Element)
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::endUnknownElement
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
, const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":end unknown element:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
}
OOXMLFastContextHandler::Pointer_t
OOXMLFastDocumentHandler::getContextHandler() const
{
if (mpContextHandler == OOXMLFastContextHandler::Pointer_t())
{
mpContextHandler.reset
(new OOXMLFastContextHandler(m_xContext));
mpContextHandler->setStream(mpStream);
mpContextHandler->setDocument(mpDocument);
mpContextHandler->setXNoteId(msXNoteId);
mpContextHandler->setForwardEvents(true);
}
return mpContextHandler;
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
OOXMLFastDocumentHandler::createFastChildContext
(::sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":createFastChildContext:"
<< fastTokenToId(Element)
<< endl;
#endif
return OOXMLFactory::getInstance()->createFastChildContextFromStart(getContextHandler().get(), Element);
}
OOXMLParserState::Pointer_t OOXMLFastDocumentHandler::getParserState() const
{
OOXMLParserState::Pointer_t pParserState;
return getContextHandler()->getParserState();
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
OOXMLFastDocumentHandler::createUnknownChildContext
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
,
const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
, const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":createUnknownChildContext:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
return uno::Reference< xml::sax::XFastContextHandler >
(new OOXMLFastDocumentHandler(m_xContext));
}
void SAL_CALL OOXMLFastDocumentHandler::characters(const ::rtl::OUString & /*aChars*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
// TODO: Insert your implementation for "characters" here.
}
// ::com::sun::star::xml::sax::XFastDocumentHandler:
void SAL_CALL OOXMLFastDocumentHandler::startDocument()
throw (uno::RuntimeException, xml::sax::SAXException)
{
}
void SAL_CALL OOXMLFastDocumentHandler::endDocument()
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
OOXMLFastContextHandler::dumpOpenContexts();
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::setDocumentLocator
(const uno::Reference< xml::sax::XLocator > & /*xLocator*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
// TODO: Insert your implementation for "setDocumentLocator" here.
}
void OOXMLFastDocumentHandler::setStream(Stream * pStream)
{
#ifdef DEBUG_PROTOCOL
mpTmpStream.reset(new StreamProtocol(pStream, debug_logger));
mpStream = mpTmpStream.get();
#else
mpStream = pStream;
#endif
}
void OOXMLFastDocumentHandler::setDocument(OOXMLDocument * pDocument)
{
mpDocument = pDocument;
}
void OOXMLFastDocumentHandler::setXNoteId(const ::rtl::OUString & rXNoteId)
{
msXNoteId = rXNoteId;
}
void OOXMLFastDocumentHandler::setIsSubstream( bool bSubstream )
{
getContextHandler( )->getParserState( )->setInSectionGroup( bSubstream );
}
}}
<commit_msg>sw34bf01: #i114285#: patch by dtardon: fix build with -DEBUG_CONTEXT_STACK<commit_after>/*************************************************************************
*
* 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 <iostream>
#include <boost/shared_ptr.hpp>
#ifdef DEBUG_ELEMENT
#include "ooxmlLoggers.hxx"
#include <resourcemodel/Protocol.hxx>
#endif
#include "OOXMLFastDocumentHandler.hxx"
#include "OOXMLFastContextHandler.hxx"
#include "OOXMLFastTokens.hxx"
#include "OOXMLFactory.hxx"
namespace writerfilter {
namespace ooxml
{
using namespace ::com::sun::star;
using namespace ::std;
OOXMLFastDocumentHandler::OOXMLFastDocumentHandler
(uno::Reference< uno::XComponentContext > const & context)
: m_xContext(context)
{}
// ::com::sun::star::xml::sax::XFastContextHandler:
void SAL_CALL OOXMLFastDocumentHandler::startFastElement
(::sal_Int32
#ifdef DEBUG_CONTEXT_STACK
Element
#endif
, const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":start element:"
<< fastTokenToId(Element)
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::startUnknownElement
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
, const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
,
const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":start unknown element:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::endFastElement(::sal_Int32
#ifdef DEBUG_CONTEXT_STACK
Element
#endif
)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":end element:"
<< fastTokenToId(Element)
<< endl;
#endif
}
void SAL_CALL OOXMLFastDocumentHandler::endUnknownElement
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
, const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":end unknown element:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
}
OOXMLFastContextHandler::Pointer_t
OOXMLFastDocumentHandler::getContextHandler() const
{
if (mpContextHandler == OOXMLFastContextHandler::Pointer_t())
{
mpContextHandler.reset
(new OOXMLFastContextHandler(m_xContext));
mpContextHandler->setStream(mpStream);
mpContextHandler->setDocument(mpDocument);
mpContextHandler->setXNoteId(msXNoteId);
mpContextHandler->setForwardEvents(true);
}
return mpContextHandler;
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
OOXMLFastDocumentHandler::createFastChildContext
(::sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":createFastChildContext:"
<< fastTokenToId(Element)
<< endl;
#endif
return OOXMLFactory::getInstance()->createFastChildContextFromStart(getContextHandler().get(), Element);
}
OOXMLParserState::Pointer_t OOXMLFastDocumentHandler::getParserState() const
{
OOXMLParserState::Pointer_t pParserState;
return getContextHandler()->getParserState();
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
OOXMLFastDocumentHandler::createUnknownChildContext
(const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Namespace
#endif
,
const ::rtl::OUString &
#ifdef DEBUG_CONTEXT_STACK
Name
#endif
, const uno::Reference< xml::sax::XFastAttributeList > & /*Attribs*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
#ifdef DEBUG_CONTEXT_STACK
clog << this << ":createUnknownChildContext:"
<< OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()
<< ":"
<< OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()
<< endl;
#endif
return uno::Reference< xml::sax::XFastContextHandler >
(new OOXMLFastDocumentHandler(m_xContext));
}
void SAL_CALL OOXMLFastDocumentHandler::characters(const ::rtl::OUString & /*aChars*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
// TODO: Insert your implementation for "characters" here.
}
// ::com::sun::star::xml::sax::XFastDocumentHandler:
void SAL_CALL OOXMLFastDocumentHandler::startDocument()
throw (uno::RuntimeException, xml::sax::SAXException)
{
}
void SAL_CALL OOXMLFastDocumentHandler::endDocument()
throw (uno::RuntimeException, xml::sax::SAXException)
{
}
void SAL_CALL OOXMLFastDocumentHandler::setDocumentLocator
(const uno::Reference< xml::sax::XLocator > & /*xLocator*/)
throw (uno::RuntimeException, xml::sax::SAXException)
{
// TODO: Insert your implementation for "setDocumentLocator" here.
}
void OOXMLFastDocumentHandler::setStream(Stream * pStream)
{
#ifdef DEBUG_PROTOCOL
mpTmpStream.reset(new StreamProtocol(pStream, debug_logger));
mpStream = mpTmpStream.get();
#else
mpStream = pStream;
#endif
}
void OOXMLFastDocumentHandler::setDocument(OOXMLDocument * pDocument)
{
mpDocument = pDocument;
}
void OOXMLFastDocumentHandler::setXNoteId(const ::rtl::OUString & rXNoteId)
{
msXNoteId = rXNoteId;
}
void OOXMLFastDocumentHandler::setIsSubstream( bool bSubstream )
{
getContextHandler( )->getParserState( )->setInSectionGroup( bSubstream );
}
}}
<|endoftext|>
|
<commit_before>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the Campcaster project.
http://campcaster.campware.org/
To report bugs, send an e-mail to bugs@campware.org
Campcaster is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Campcaster 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 Campcaster; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author: fgerlits $
Version : $Revision$
Location : $URL: svn+ssh://fgerlits@code.campware.org/home/svn/repo/livesupport/trunk/livesupport/src/products/gLiveSupport/src/TransportList.cxx $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include "LiveSupport/Core/TimeConversion.h"
#include "TransportList.h"
using namespace LiveSupport::Core;
using namespace LiveSupport::StorageClient;
using namespace LiveSupport::Widgets;
using namespace LiveSupport::GLiveSupport;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
namespace {
/*------------------------------------------------------------------------------
* The localization key for the 'working' status.
*----------------------------------------------------------------------------*/
const Glib::ustring workingStatusKey = "workingStatus";
/*------------------------------------------------------------------------------
* The localization key for the 'success' status.
*----------------------------------------------------------------------------*/
const Glib::ustring successStatusKey = "successStatus";
/*------------------------------------------------------------------------------
* The localization key for the 'fault' status.
*----------------------------------------------------------------------------*/
const Glib::ustring faultStatusKey = "faultStatus";
/*------------------------------------------------------------------------------
* The name of the user preference for storing the list of transports.
*----------------------------------------------------------------------------*/
const Glib::ustring userPreferencesKeyName = "activeTransports";
/*------------------------------------------------------------------------------
* The symbol for an upload.
*----------------------------------------------------------------------------*/
const Glib::ustring uploadSymbol = "⇧";
/*------------------------------------------------------------------------------
* The symbol for a download.
*----------------------------------------------------------------------------*/
const Glib::ustring downloadSymbol = "⇩";
}
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
TransportList :: TransportList (Ptr<GLiveSupport>::Ref gLiveSupport,
Ptr<ResourceBundle>::Ref bundle)
throw ()
: LocalizedObject(bundle),
gLiveSupport(gLiveSupport)
{
Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();
// create the tree view
treeModel = Gtk::ListStore::create(modelColumns);
treeView = Gtk::manage(widgetFactory->createTreeView(treeModel));
treeView->set_enable_search(false);
// Add the TreeView's view columns:
try {
treeView->appendColumn("",
modelColumns.directionColumn, 20);
treeView->appendColumn(*getResourceUstring("titleColumnLabel"),
modelColumns.titleColumn, 300);
treeView->appendColumn(*getResourceUstring("dateColumnLabel"),
modelColumns.dateColumn, 180);
treeView->appendColumn(*getResourceUstring("statusColumnLabel"),
modelColumns.statusDisplayColumn, 50);
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
// register the signal handler for treeview entries being clicked
treeView->signal_button_press_event().connect_notify(sigc::mem_fun(*this,
&TransportList::onEntryClicked));
// create the right-click entry context menu
uploadMenu = Gtk::manage(new Gtk::Menu());
downloadMenu = Gtk::manage(new Gtk::Menu());
Gtk::Menu::MenuList& uploadMenuList = uploadMenu->items();
Gtk::Menu::MenuList& downloadMenuList = downloadMenu->items();
try{
uploadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(
*getResourceUstring("cancelUploadMenuItem"),
sigc::mem_fun(*this,
&TransportList::onCancelTransport)));
downloadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(
*getResourceUstring("cancelDownloadMenuItem"),
sigc::mem_fun(*this,
&TransportList::onCancelTransport)));
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
uploadMenu->accelerate(*this);
downloadMenu->accelerate(*this);
// add the tree view to this widget
Gtk::VBox::pack_start(*treeView);
userPreferencesKey.reset(new const Glib::ustring(userPreferencesKeyName));
}
/*------------------------------------------------------------------------------
* Add a new upload task to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: addUpload(Ptr<Playable>::Ref playable)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref token = storage->uploadToHub(sessionId,
playable->getId());
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = uploadSymbol;
row[modelColumns.titleColumn] = *playable->getTitle();
row[modelColumns.dateColumn] = *TimeConversion::nowString();
row[modelColumns.statusColumn] = workingStatusKey;
row[modelColumns.statusDisplayColumn]
= *getResourceUstring(workingStatusKey);
row[modelColumns.tokenColumn] = token;
}
/*------------------------------------------------------------------------------
* Add a new download task to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: addDownload(Ptr<Playable>::Ref playable)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref token = storage->downloadFromHub(
sessionId,
playable->getId());
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = downloadSymbol;
row[modelColumns.titleColumn] = *playable->getTitle();
row[modelColumns.dateColumn] = *TimeConversion::nowString();
row[modelColumns.statusColumn] = workingStatusKey;
row[modelColumns.statusDisplayColumn]
= *getResourceUstring(workingStatusKey);
row[modelColumns.tokenColumn] = token;
}
/*------------------------------------------------------------------------------
* Add an item with an already existing token to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: add(const Glib::ustring & title,
const Glib::ustring & date,
const Glib::ustring & token,
bool isUpload)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref tokenPtr(new Glib::ustring(token));
Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);
AsyncState state = storage->checkTransport(tokenPtr,
errorMsg);
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = isUpload ? uploadSymbol
: downloadSymbol;
row[modelColumns.titleColumn] = title;
row[modelColumns.dateColumn] = date;
row[modelColumns.tokenColumn] = tokenPtr;
setStatus(row, state, errorMsg);
}
/*------------------------------------------------------------------------------
* Remove the currently selected item from the list.
*----------------------------------------------------------------------------*/
void
TransportList :: removeSelected(void) throw (XmlRpcException)
{
Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();
Gtk::TreeIter iter = selection->get_selected();
if (!iter) {
return;
}
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
storage->cancelTransport(sessionId,
iter->get_value(modelColumns.tokenColumn));
treeModel->erase(iter);
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: updateSelected(void) throw (XmlRpcException)
{
Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();
Gtk::TreeIter iter = selection->get_selected();
if (!iter) {
return false;
} else {
return update(iter);
}
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: update(void) throw (XmlRpcException)
{
bool didSomething = false;
for (Gtk::TreeIter it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
didSomething |= update(it);
}
return didSomething;
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: updateSilently(void) throw ()
{
bool didSomething = false;
for (Gtk::TreeIter it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
try {
didSomething |= update(it);
} catch (XmlRpcException &e) {
}
}
return didSomething;
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: update(Gtk::TreeIter iter) throw (XmlRpcException)
{
if (iter->get_value(modelColumns.statusColumn) != workingStatusKey) {
return false;
}
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);
AsyncState status = storage->checkTransport(
iter->get_value(modelColumns.tokenColumn),
errorMsg);
return setStatus(iter, status, errorMsg);
}
/*------------------------------------------------------------------------------
* Set the status of the row pointed to by an iterator.
*----------------------------------------------------------------------------*/
bool
TransportList :: setStatus(Gtk::TreeIter iter,
AsyncState status,
Ptr<const Glib::ustring>::Ref errorMsg)
throw ()
{
if (status == AsyncState::pendingState) {
iter->set_value(modelColumns.statusColumn,
workingStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*getResourceUstring(workingStatusKey));
return false;
} else if (status == AsyncState::finishedState
|| status == AsyncState::closedState) {
iter->set_value(modelColumns.statusColumn,
successStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*getResourceUstring(successStatusKey));
return true;
} else if (status == AsyncState::failedState) {
iter->set_value(modelColumns.statusColumn,
faultStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*formatMessage(faultStatusKey, *errorMsg));
return false;
} else {
std::cerr << "Impossible status: '" << status
<< "' in TransportList::setStatus()."
<< std::endl;
}
return false;
}
/*------------------------------------------------------------------------------
* Return the contents of the transport list.
*----------------------------------------------------------------------------*/
Ptr<Glib::ustring>::Ref
TransportList :: getContents(void) throw ()
{
std::ostringstream contentsStream;
Gtk::TreeModel::const_iterator it;
Ptr<Glib::ustring>::Ref token;
for (it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
Gtk::TreeRow row = *it;
if (row[modelColumns.statusColumn] == workingStatusKey) {
if (row[modelColumns.directionColumn] == uploadSymbol) {
contentsStream << "up\n";
} else {
contentsStream << "down\n";
}
contentsStream << row[modelColumns.titleColumn] << '\n';
contentsStream << row[modelColumns.dateColumn] << '\n';
token = row[modelColumns.tokenColumn];
contentsStream << *token << '\n';
}
}
Ptr<Glib::ustring>::Ref contents(new Glib::ustring(
contentsStream.str() ));
return contents;
}
/*------------------------------------------------------------------------------
* Restore the contents of the transport list.
*----------------------------------------------------------------------------*/
void
TransportList :: setContents(Ptr<const Glib::ustring>::Ref contents)
throw ()
{
std::istringstream contentsStream(contents->raw());
treeModel->clear();
while (!contentsStream.eof()) {
std::string direction;
std::string title;
std::string date;
std::string token;
std::getline(contentsStream, direction);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, title);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, date);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, token);
if (contentsStream.fail()) {
break;
}
try {
add(title, date, token, (direction == "up"));
} catch (XmlRpcException &e) {
}
}
}
/*------------------------------------------------------------------------------
* Event handler for an entry being clicked in the list.
*----------------------------------------------------------------------------*/
void
TransportList :: onEntryClicked(GdkEventButton * event) throw ()
{
if (event->type == GDK_BUTTON_PRESS && event->button == 3) {
Gtk::TreePath currentPath;
Gtk::TreeViewColumn * column;
int cell_x,
cell_y;
bool foundValidRow = treeView->get_path_at_pos(
int(event->x), int(event->y),
currentPath, column,
cell_x, cell_y);
if (foundValidRow) {
Gtk::TreeIter iter = treeModel->get_iter(currentPath);
if (iter) {
Gtk::TreeRow row = *iter;
if (row[modelColumns.directionColumn] == uploadSymbol) {
uploadMenu->popup(event->button, event->time);
} else {
downloadMenu->popup(event->button, event->time);
}
}
}
}
}
/*------------------------------------------------------------------------------
* Event handler for "cancel" selected from the pop-up menu.
*----------------------------------------------------------------------------*/
void
TransportList :: onCancelTransport(void) throw ()
{
try {
removeSelected();
} catch (XmlRpcException &e) {
gLiveSupport->displayMessageWindow(formatMessage(
"cannotCancelTransportMsg",
e.what() ));
}
}
<commit_msg>fixing #1871<commit_after>/*------------------------------------------------------------------------------
Copyright (c) 2004 Media Development Loan Fund
This file is part of the Campcaster project.
http://campcaster.campware.org/
To report bugs, send an e-mail to bugs@campware.org
Campcaster is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Campcaster 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 Campcaster; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Author : $Author: fgerlits $
Version : $Revision$
Location : $URL: svn+ssh://fgerlits@code.campware.org/home/svn/repo/livesupport/trunk/livesupport/src/products/gLiveSupport/src/TransportList.cxx $
------------------------------------------------------------------------------*/
/* ============================================================ include files */
#ifdef HAVE_CONFIG_H
#include "configure.h"
#endif
#include "LiveSupport/Core/TimeConversion.h"
#include "TransportList.h"
using namespace LiveSupport::Core;
using namespace LiveSupport::StorageClient;
using namespace LiveSupport::Widgets;
using namespace LiveSupport::GLiveSupport;
/* =================================================== local data structures */
/* ================================================ local constants & macros */
namespace {
/*------------------------------------------------------------------------------
* The localization key for the 'working' status.
*----------------------------------------------------------------------------*/
const Glib::ustring workingStatusKey = "workingStatus";
/*------------------------------------------------------------------------------
* The localization key for the 'success' status.
*----------------------------------------------------------------------------*/
const Glib::ustring successStatusKey = "successStatus";
/*------------------------------------------------------------------------------
* The localization key for the 'fault' status.
*----------------------------------------------------------------------------*/
const Glib::ustring faultStatusKey = "faultStatus";
/*------------------------------------------------------------------------------
* The name of the user preference for storing the list of transports.
*----------------------------------------------------------------------------*/
const Glib::ustring userPreferencesKeyName = "activeTransports";
/*------------------------------------------------------------------------------
* The symbol for an upload.
*----------------------------------------------------------------------------*/
const Glib::ustring uploadSymbol = "⇧";
/*------------------------------------------------------------------------------
* The symbol for a download.
*----------------------------------------------------------------------------*/
const Glib::ustring downloadSymbol = "⇩";
}
/* =============================================== local function prototypes */
/* ============================================================= module code */
/*------------------------------------------------------------------------------
* Constructor.
*----------------------------------------------------------------------------*/
TransportList :: TransportList (Ptr<GLiveSupport>::Ref gLiveSupport,
Ptr<ResourceBundle>::Ref bundle)
throw ()
: LocalizedObject(bundle),
gLiveSupport(gLiveSupport)
{
Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();
// create the tree view
treeModel = Gtk::ListStore::create(modelColumns);
treeView = Gtk::manage(widgetFactory->createTreeView(treeModel));
treeView->set_enable_search(false);
// Add the TreeView's view columns:
try {
treeView->appendColumn("",
modelColumns.directionColumn, 20);
treeView->appendColumn(*getResourceUstring("titleColumnLabel"),
modelColumns.titleColumn, 300);
treeView->appendColumn(*getResourceUstring("dateColumnLabel"),
modelColumns.dateColumn, 180);
treeView->appendColumn(*getResourceUstring("statusColumnLabel"),
modelColumns.statusDisplayColumn, 50);
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
// register the signal handler for treeview entries being clicked
treeView->signal_button_press_event().connect_notify(sigc::mem_fun(*this,
&TransportList::onEntryClicked));
// create the right-click entry context menu
uploadMenu = Gtk::manage(new Gtk::Menu());
downloadMenu = Gtk::manage(new Gtk::Menu());
Gtk::Menu::MenuList& uploadMenuList = uploadMenu->items();
Gtk::Menu::MenuList& downloadMenuList = downloadMenu->items();
try{
uploadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(
*getResourceUstring("cancelUploadMenuItem"),
sigc::mem_fun(*this,
&TransportList::onCancelTransport)));
downloadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(
*getResourceUstring("cancelDownloadMenuItem"),
sigc::mem_fun(*this,
&TransportList::onCancelTransport)));
} catch (std::invalid_argument &e) {
std::cerr << e.what() << std::endl;
std::exit(1);
}
uploadMenu->accelerate(*this);
downloadMenu->accelerate(*this);
// add the tree view to this widget
Gtk::VBox::pack_start(*treeView);
userPreferencesKey.reset(new const Glib::ustring(userPreferencesKeyName));
}
/*------------------------------------------------------------------------------
* Add a new upload task to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: addUpload(Ptr<Playable>::Ref playable)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref token = storage->uploadToHub(sessionId,
playable->getId());
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = uploadSymbol;
row[modelColumns.titleColumn] = *playable->getTitle();
row[modelColumns.dateColumn] = *TimeConversion::nowString();
row[modelColumns.statusColumn] = workingStatusKey;
row[modelColumns.statusDisplayColumn]
= *getResourceUstring(workingStatusKey);
row[modelColumns.tokenColumn] = token;
}
/*------------------------------------------------------------------------------
* Add a new download task to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: addDownload(Ptr<Playable>::Ref playable)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref token = storage->downloadFromHub(
sessionId,
playable->getId());
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = downloadSymbol;
row[modelColumns.titleColumn] = *playable->getTitle();
row[modelColumns.dateColumn] = *TimeConversion::nowString();
row[modelColumns.statusColumn] = workingStatusKey;
row[modelColumns.statusDisplayColumn]
= *getResourceUstring(workingStatusKey);
row[modelColumns.tokenColumn] = token;
}
/*------------------------------------------------------------------------------
* Add an item with an already existing token to the list.
*----------------------------------------------------------------------------*/
void
TransportList :: add(const Glib::ustring & title,
const Glib::ustring & date,
const Glib::ustring & token,
bool isUpload)
throw (XmlRpcException)
{
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
Ptr<Glib::ustring>::Ref tokenPtr(new Glib::ustring(token));
Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);
AsyncState state = storage->checkTransport(tokenPtr,
errorMsg);
Gtk::TreeRow row = *treeModel->append();
row[modelColumns.directionColumn] = isUpload ? uploadSymbol
: downloadSymbol;
row[modelColumns.titleColumn] = title;
row[modelColumns.dateColumn] = date;
row[modelColumns.tokenColumn] = tokenPtr;
setStatus(row, state, errorMsg);
}
/*------------------------------------------------------------------------------
* Remove the currently selected item from the list.
*----------------------------------------------------------------------------*/
void
TransportList :: removeSelected(void) throw (XmlRpcException)
{
Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();
Gtk::TreeIter iter = selection->get_selected();
if (!iter) {
return;
}
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();
storage->cancelTransport(sessionId,
iter->get_value(modelColumns.tokenColumn));
treeModel->erase(iter);
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: updateSelected(void) throw (XmlRpcException)
{
Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();
Gtk::TreeIter iter = selection->get_selected();
if (!iter) {
return false;
} else {
return update(iter);
}
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: update(void) throw (XmlRpcException)
{
bool didSomething = false;
for (Gtk::TreeIter it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
didSomething |= update(it);
}
return didSomething;
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: updateSilently(void) throw ()
{
bool didSomething = false;
for (Gtk::TreeIter it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
try {
didSomething |= update(it);
} catch (XmlRpcException &e) {
}
}
return didSomething;
}
/*------------------------------------------------------------------------------
* Query the storage server about the status of the pending transport.
*----------------------------------------------------------------------------*/
bool
TransportList :: update(Gtk::TreeIter iter) throw (XmlRpcException)
{
if (iter->get_value(modelColumns.statusColumn) != workingStatusKey) {
return false;
}
Ptr<StorageClientInterface>::Ref
storage = gLiveSupport->getStorageClient();
Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);
AsyncState status = storage->checkTransport(
iter->get_value(modelColumns.tokenColumn),
errorMsg);
return setStatus(iter, status, errorMsg);
}
/*------------------------------------------------------------------------------
* Set the status of the row pointed to by an iterator.
*----------------------------------------------------------------------------*/
bool
TransportList :: setStatus(Gtk::TreeIter iter,
AsyncState status,
Ptr<const Glib::ustring>::Ref errorMsg)
throw ()
{
if (status == AsyncState::initState
|| status == AsyncState::pendingState) {
iter->set_value(modelColumns.statusColumn,
workingStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*getResourceUstring(workingStatusKey));
return false;
} else if (status == AsyncState::finishedState
|| status == AsyncState::closedState) {
iter->set_value(modelColumns.statusColumn,
successStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*getResourceUstring(successStatusKey));
return true;
} else if (status == AsyncState::failedState) {
iter->set_value(modelColumns.statusColumn,
faultStatusKey);
iter->set_value(modelColumns.statusDisplayColumn,
*formatMessage(faultStatusKey, *errorMsg));
return false;
} else {
std::cerr << "Impossible status: '" << status
<< "' in TransportList::setStatus()."
<< std::endl;
}
return false;
}
/*------------------------------------------------------------------------------
* Return the contents of the transport list.
*----------------------------------------------------------------------------*/
Ptr<Glib::ustring>::Ref
TransportList :: getContents(void) throw ()
{
std::ostringstream contentsStream;
Gtk::TreeModel::const_iterator it;
Ptr<Glib::ustring>::Ref token;
for (it = treeModel->children().begin();
it != treeModel->children().end(); ++it) {
Gtk::TreeRow row = *it;
if (row[modelColumns.statusColumn] == workingStatusKey) {
if (row[modelColumns.directionColumn] == uploadSymbol) {
contentsStream << "up\n";
} else {
contentsStream << "down\n";
}
contentsStream << row[modelColumns.titleColumn] << '\n';
contentsStream << row[modelColumns.dateColumn] << '\n';
token = row[modelColumns.tokenColumn];
contentsStream << *token << '\n';
}
}
Ptr<Glib::ustring>::Ref contents(new Glib::ustring(
contentsStream.str() ));
return contents;
}
/*------------------------------------------------------------------------------
* Restore the contents of the transport list.
*----------------------------------------------------------------------------*/
void
TransportList :: setContents(Ptr<const Glib::ustring>::Ref contents)
throw ()
{
std::istringstream contentsStream(contents->raw());
treeModel->clear();
while (!contentsStream.eof()) {
std::string direction;
std::string title;
std::string date;
std::string token;
std::getline(contentsStream, direction);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, title);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, date);
if (contentsStream.fail()) {
break;
}
std::getline(contentsStream, token);
if (contentsStream.fail()) {
break;
}
try {
add(title, date, token, (direction == "up"));
} catch (XmlRpcException &e) {
}
}
}
/*------------------------------------------------------------------------------
* Event handler for an entry being clicked in the list.
*----------------------------------------------------------------------------*/
void
TransportList :: onEntryClicked(GdkEventButton * event) throw ()
{
if (event->type == GDK_BUTTON_PRESS && event->button == 3) {
Gtk::TreePath currentPath;
Gtk::TreeViewColumn * column;
int cell_x,
cell_y;
bool foundValidRow = treeView->get_path_at_pos(
int(event->x), int(event->y),
currentPath, column,
cell_x, cell_y);
if (foundValidRow) {
Gtk::TreeIter iter = treeModel->get_iter(currentPath);
if (iter) {
Gtk::TreeRow row = *iter;
if (row[modelColumns.directionColumn] == uploadSymbol) {
uploadMenu->popup(event->button, event->time);
} else {
downloadMenu->popup(event->button, event->time);
}
}
}
}
}
/*------------------------------------------------------------------------------
* Event handler for "cancel" selected from the pop-up menu.
*----------------------------------------------------------------------------*/
void
TransportList :: onCancelTransport(void) throw ()
{
try {
removeSelected();
} catch (XmlRpcException &e) {
gLiveSupport->displayMessageWindow(formatMessage(
"cannotCancelTransportMsg",
e.what() ));
}
}
<|endoftext|>
|
<commit_before><commit_msg>tdf#89381 Revert "vcl: SalGraphics::mirror() - always use GetGraphicsWidth()"<commit_after><|endoftext|>
|
<commit_before><commit_msg>Signed-off-by: xsmart <xsmart@veyesys.com><commit_after><|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_ALGORITHM_VOLUME_HPP
#define VIENNAGRID_ALGORITHM_VOLUME_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "viennagrid/forwards.h"
#include "viennagrid/topology/all.hpp"
#include "viennagrid/algorithm/norm.hpp"
#include "viennagrid/algorithm/spanned_volume.hpp"
/** @file volume.hpp
@brief Computes the volume of different cell types as well as domains and segments
*/
namespace viennagrid
{
namespace detail
{
/** @brief Computes the volume of topologically zero-dimensional elements (vertices). Degenerate case, returns 1 */
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::point_tag)
{
return typename ElementType::config_type::numeric_type(1);
}
/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-simplex).*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::simplex_tag<1>)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
return norm(p0 - p1);
}
/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-hypercube).*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::hypercube_tag<1>)
{
return volume_impl(cell, viennagrid::simplex_tag<1>());
}
//topologically two-dimensional elements
/** @brief Computes the two-dimensional volume of a triangle.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::triangle_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
return spanned_volume(p0, p1, p2);
}
/** @brief Computes the two-dimensional volume of a quadrilateral.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::quadrilateral_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
return spanned_volume(p0, p1, p3) + spanned_volume(p1, p2, p3); //sum up the two triangular parts
}
//topologically three-dimensional elements
/** @brief Computes the three-dimensional volume of a tetrahedron.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::tetrahedron_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
return spanned_volume(p0, p1, p2, p3);
}
/** @brief Computes the three-dimensional volume of a hexahedron.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::hexahedron_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
PointType const & p4 = ncells<0>(cell)[4].point();
PointType const & p5 = ncells<0>(cell)[5].point();
PointType const & p6 = ncells<0>(cell)[6].point();
PointType const & p7 = ncells<0>(cell)[7].point();
//decompose hexahedron into six tetrahedra
return spanned_volume(p0, p1, p3, p4)
+ spanned_volume(p4, p1, p3, p7)
+ spanned_volume(p4, p1, p7, p5)
+ spanned_volume(p1, p2, p3, p7)
+ spanned_volume(p1, p2, p7, p5)
+ spanned_volume(p5, p2, p7, p6);
}
//
/** @brief Dispatched function for computing the volume of a domain or segment.*/
template <typename ContainerType>
typename ContainerType::config_type::numeric_type
volume_domainsegment(ContainerType const & d)
{
typedef ContainerType DomainType;
typedef typename ContainerType::config_type::cell_tag CellTag;
typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type CellContainer;
typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typename ContainerType::config_type::numeric_type new_volume = 0;
CellContainer new_cells = viennagrid::ncells<CellTag::dim>(d);
for (CellIterator new_cit = new_cells.begin();
new_cit != new_cells.end();
++new_cit)
{
new_volume += volume(*new_cit);
}
return new_volume;
}
} //namespace detail
//
// The public interface functions
//
/** @brief Returns the n-dimensional volume of a n-cell */
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume(ElementType const & cell)
{
return detail::volume_impl(cell, typename ElementType::tag());
}
//special case: domain
/** @brief Returns the N-dimensional volume of a domain, where the cell type has topological dimension N. */
template <typename ConfigType>
typename ConfigType::numeric_type
volume(domain_t<ConfigType> const & d)
{
return detail::volume_domainsegment(d);
}
//special case: segment
/** @brief Returns the N-dimensional volume of a segment, where the cell type has topological dimension N. */
template <typename ConfigType>
typename ConfigType::numeric_type
volume(segment_t<ConfigType> const & d)
{
return detail::volume_domainsegment(d);
}
} //namespace viennagrid
#endif
<commit_msg>added volume algorithm for polygon<commit_after>#ifndef VIENNAGRID_ALGORITHM_VOLUME_HPP
#define VIENNAGRID_ALGORITHM_VOLUME_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp rupp@iue.tuwien.ac.at
Josef Weinbub weinbub@iue.tuwien.ac.at
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "viennagrid/forwards.h"
#include "viennagrid/topology/all.hpp"
#include "viennagrid/algorithm/norm.hpp"
#include "viennagrid/algorithm/spanned_volume.hpp"
/** @file volume.hpp
@brief Computes the volume of different cell types as well as domains and segments
*/
namespace viennagrid
{
namespace detail
{
/** @brief Computes the volume of topologically zero-dimensional elements (vertices). Degenerate case, returns 1 */
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::point_tag)
{
return typename ElementType::config_type::numeric_type(1);
}
/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-simplex).*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::simplex_tag<1>)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
return norm(p0 - p1);
}
/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-hypercube).*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::hypercube_tag<1>)
{
return volume_impl(cell, viennagrid::simplex_tag<1>());
}
//topologically two-dimensional elements
/** @brief Computes the two-dimensional volume of a triangle.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::triangle_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
return spanned_volume(p0, p1, p2);
}
/** @brief Computes the two-dimensional volume of a quadrilateral.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::quadrilateral_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
return spanned_volume(p0, p1, p3) + spanned_volume(p1, p2, p3); //sum up the two triangular parts
}
/** @brief Computes the two-dimensional volume of a polygon.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::polygon_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename ElementType::config_type::numeric_type NumericType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
typedef typename viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;
VertexOnCellContainer range = viennagrid::ncells<0>( cell );
if (range.size() < 3) return 0;
VertexOnCellIterator it1 = range.begin();
VertexOnCellIterator it2 = it1; ++it2;
PointType origin = it1->point();
NumericType volume = 0;
for (; it2 != range.end(); ++it1, ++it2)
volume += signed_spanned_volume(origin, it1->point(), it2->point());
it1 = range.end(); --it1;
volume += signed_spanned_volume( origin, it1->point(), range.begin()->point());
return std::abs(volume);
}
//topologically three-dimensional elements
/** @brief Computes the three-dimensional volume of a tetrahedron.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::tetrahedron_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
return spanned_volume(p0, p1, p2, p3);
}
/** @brief Computes the three-dimensional volume of a hexahedron.*/
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume_impl(ElementType const & cell, viennagrid::hexahedron_tag)
{
typedef typename ElementType::config_type ConfigType;
typedef typename viennagrid::result_of::point<ConfigType>::type PointType;
typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;
PointType const & p0 = ncells<0>(cell)[0].point();
PointType const & p1 = ncells<0>(cell)[1].point();
PointType const & p2 = ncells<0>(cell)[2].point();
PointType const & p3 = ncells<0>(cell)[3].point();
PointType const & p4 = ncells<0>(cell)[4].point();
PointType const & p5 = ncells<0>(cell)[5].point();
PointType const & p6 = ncells<0>(cell)[6].point();
PointType const & p7 = ncells<0>(cell)[7].point();
//decompose hexahedron into six tetrahedra
return spanned_volume(p0, p1, p3, p4)
+ spanned_volume(p4, p1, p3, p7)
+ spanned_volume(p4, p1, p7, p5)
+ spanned_volume(p1, p2, p3, p7)
+ spanned_volume(p1, p2, p7, p5)
+ spanned_volume(p5, p2, p7, p6);
}
//
/** @brief Dispatched function for computing the volume of a domain or segment.*/
template <typename ContainerType>
typename ContainerType::config_type::numeric_type
volume_domainsegment(ContainerType const & d)
{
typedef ContainerType DomainType;
typedef typename ContainerType::config_type::cell_tag CellTag;
typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type CellContainer;
typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;
typename ContainerType::config_type::numeric_type new_volume = 0;
CellContainer new_cells = viennagrid::ncells<CellTag::dim>(d);
for (CellIterator new_cit = new_cells.begin();
new_cit != new_cells.end();
++new_cit)
{
new_volume += volume(*new_cit);
}
return new_volume;
}
} //namespace detail
//
// The public interface functions
//
/** @brief Returns the n-dimensional volume of a n-cell */
template <typename ElementType>
typename ElementType::config_type::numeric_type
volume(ElementType const & cell)
{
return detail::volume_impl(cell, typename ElementType::tag());
}
//special case: domain
/** @brief Returns the N-dimensional volume of a domain, where the cell type has topological dimension N. */
template <typename ConfigType>
typename ConfigType::numeric_type
volume(domain_t<ConfigType> const & d)
{
return detail::volume_domainsegment(d);
}
//special case: segment
/** @brief Returns the N-dimensional volume of a segment, where the cell type has topological dimension N. */
template <typename ConfigType>
typename ConfigType::numeric_type
volume(segment_t<ConfigType> const & d)
{
return detail::volume_domainsegment(d);
}
} //namespace viennagrid
#endif
<|endoftext|>
|
<commit_before>/************************************************************************/
/* */
/* Copyright 2009 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyfilters_PyArray_API
//#define NO_IMPORT_ARRAY
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <vigra/nonlineardiffusion.hxx>
#include <vigra/symmetry.hxx>
#include <vigra/tv_filter.hxx>
#include <vigra/shockfilter.hxx>
namespace python = boost::python;
namespace vigra
{
/**
python::tuple
pythonGetAnisotropy2D(
const NumpyArray<2, double> & image,
const double alpha_par,
const double beta_par,
const double sigma_par,
const double rho_par,
const double K_par,
NumpyArray<2, double> phi,
NumpyArray<2, double> alpha,
NumpyArray<2, double> beta
)
{
res.reshapeIfEmpty(image.taggedShape(),
"getAnisotropy2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
}
return ;
}
**/
template <class InValue, class OutValue>
NumpyAnyArray
pythonShockFilter(NumpyArray<3, Multiband<InValue> > image,
float sigma,
float rho,
float upwind_factor_h,
unsigned int iterations,
NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())
{
res.reshapeIfEmpty(image.taggedShape(),
"nonlinearDiffusion2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
for(int k=0; k<image.shape(2); ++k)
{
MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);
MultiArrayView<2, InValue, StridedArrayTag> bimage = image.bindOuter(k);
shockFilter(bimage,bres, sigma,
rho, upwind_factor_h, iterations);
}
}
return res;
}
template <class InValue, class OutValue>
NumpyAnyArray
pythonNonlinearDiffusion2D(NumpyArray<3, Multiband<InValue> > image,
double edgeThreshold, double scale,
NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())
{
res.reshapeIfEmpty(image.taggedShape(),
"nonlinearDiffusion2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
for(int k=0; k<image.shape(2); ++k)
{
MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);
nonlinearDiffusion(srcImageRange(image.bindOuter(k)),
destImage(bres),
DiffusivityFunctor< double >(edgeThreshold), scale);
}
}
return res;
}
template <class InValue, class OutValue>
NumpyAnyArray
pythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,
double alpha, int steps, double eps = 0,
NumpyArray<2, Singleband<OutValue> > res = python::object())
{
std::string description("totalVariationFilter, alpha, steps, eps=");
description += asString(eps);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"totalVariationFilter(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
totalVariationFilter(image, res, alpha, steps, eps);
}
return res;
}
template <class InValue, class InValue2, class OutValue>
NumpyAnyArray
pythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,
NumpyArray<2, Singleband<InValue2> > weight,
double alpha, int steps, double eps = 0,
NumpyArray<2, Singleband<OutValue> > res = python::object())
{
std::string description("totalVariationFilter, weight, alpha, steps, eps=");
description += asString(eps);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"totalVariationFilter(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
totalVariationFilter(image, weight, res, alpha, steps, eps);
}
return res;
}
template < class SrcPixelType >
NumpyAnyArray
pythonRadialSymmetryTransform2D(NumpyArray<2, Singleband<SrcPixelType> > image,
double scale = 1.0,
NumpyArray<2, Singleband<SrcPixelType> > res = python::object())
{
std::string description("radial symmetry transform, scale=");
description += asString(scale);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"radialSymmetryTransform2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
radialSymmetryTransform(srcImageRange(image), destImage(res), scale);
}
return res;
}
void defineFilters2D()
{
using namespace python;
docstring_options doc_options(true, true, false);
def("nonlinearDiffusion",
registerConverters(&pythonNonlinearDiffusion2D<float, float>),
(arg("image"), arg("edgeThreshold"), arg("scale"), arg("out")=python::object()),
"Perform edge-preserving smoothing at the given scale."
"\n\n"
"For details see nonlinearDiffusion_ in the vigra C++ documentation.\n");
def("shockFilter",
registerConverters(&pythonShockFilter<float, float>),
(
arg("image"),
arg("sigma"),
arg("rho"),
arg("updwindFactorH") ,
arg("iterations"),
arg("out")=python::object()
),
"Perform edge-preserving smoothing at the given scale."
"\n\n"
"For details see shockFilter_ in the vigra C++ documentation.\n");
def("totalVariationFilter",
registerConverters(&pythonTotalVariationFilter2D<double,double>),
(arg("image"), arg("alpha"), arg("steps"), arg("eps"), arg("out")=python::object()),
"Perform total variation filter on 2D single band images."
"\n\n"
"For details see totalVariationFilter in the vigra C++ documentation.\n");
def("totalVariationFilter",
registerConverters(&pythonTotalVariationFilter2D<double,double,double>),
(arg("image"), arg("weight"), arg("alpha"), arg("steps"), arg("eps"), arg("out")=python::object()),
"Perform weighted total variation filter on 2D single band images."
"\n\n"
"For details see totalVariationFilter in the vigra C++ documentation.\n");
def("radialSymmetryTransform2D",
registerConverters(&pythonRadialSymmetryTransform2D<float>),
(arg("image"), arg("scale"),arg("out")=python::object()),
"Find centers of radial symmetry in an 2D image.\n\n"
"This algorithm implements the Fast Radial Symmetry Transform according to "
"[G. Loy, A. Zelinsky: \"A Fast Radial Symmetry Transform for Detecting Points of Interest\", "
"in: A. Heyden et al. (Eds.): Proc. of 7th European Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002]\n\n"
"For details see radialSymmetryTransform_ in the vigra C++ documentation.\n");
}
void defineKernels();
void defineConvolutionFunctions();
void defineMorphology();
void defineTensor();
void defineNonLocalMean();
} // namespace vigra
using namespace vigra;
using namespace boost::python;
BOOST_PYTHON_MODULE_INIT(filters)
{
import_vigranumpy();
defineFilters2D();
defineKernels();
defineConvolutionFunctions();
defineMorphology();
defineTensor();
defineNonLocalMean();
}
<commit_msg>formated code<commit_after>/************************************************************************/
/* */
/* Copyright 2009 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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. */
/* */
/************************************************************************/
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyfilters_PyArray_API
//#define NO_IMPORT_ARRAY
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
#include <vigra/nonlineardiffusion.hxx>
#include <vigra/symmetry.hxx>
#include <vigra/tv_filter.hxx>
#include <vigra/shockfilter.hxx>
namespace python = boost::python;
namespace vigra
{
template <class InValue, class OutValue>
NumpyAnyArray
pythonShockFilter(NumpyArray<3, Multiband<InValue> > image,
float sigma,
float rho,
float upwind_factor_h,
unsigned int iterations,
NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())
{
res.reshapeIfEmpty(image.taggedShape(),
"nonlinearDiffusion2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
for(int k=0; k<image.shape(2); ++k)
{
MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);
MultiArrayView<2, InValue, StridedArrayTag> bimage = image.bindOuter(k);
shockFilter(bimage,bres, sigma,
rho, upwind_factor_h, iterations);
}
}
return res;
}
template <class InValue, class OutValue>
NumpyAnyArray
pythonNonlinearDiffusion2D(NumpyArray<3, Multiband<InValue> > image,
double edgeThreshold, double scale,
NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())
{
res.reshapeIfEmpty(image.taggedShape(),
"nonlinearDiffusion2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
for(int k=0; k<image.shape(2); ++k)
{
MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);
nonlinearDiffusion(srcImageRange(image.bindOuter(k)),
destImage(bres),
DiffusivityFunctor< double >(edgeThreshold), scale);
}
}
return res;
}
template <class InValue, class OutValue>
NumpyAnyArray
pythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,
double alpha, int steps, double eps = 0,
NumpyArray<2, Singleband<OutValue> > res = python::object())
{
std::string description("totalVariationFilter, alpha, steps, eps=");
description += asString(eps);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"totalVariationFilter(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
totalVariationFilter(image, res, alpha, steps, eps);
}
return res;
}
template <class InValue, class InValue2, class OutValue>
NumpyAnyArray
pythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,
NumpyArray<2, Singleband<InValue2> > weight,
double alpha, int steps, double eps = 0,
NumpyArray<2, Singleband<OutValue> > res = python::object())
{
std::string description("totalVariationFilter, weight, alpha, steps, eps=");
description += asString(eps);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"totalVariationFilter(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
totalVariationFilter(image, weight, res, alpha, steps, eps);
}
return res;
}
template < class SrcPixelType >
NumpyAnyArray
pythonRadialSymmetryTransform2D(NumpyArray<2, Singleband<SrcPixelType> > image,
double scale = 1.0,
NumpyArray<2, Singleband<SrcPixelType> > res = python::object())
{
std::string description("radial symmetry transform, scale=");
description += asString(scale);
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"radialSymmetryTransform2D(): Output array has wrong shape.");
{
PyAllowThreads _pythread;
radialSymmetryTransform(srcImageRange(image), destImage(res), scale);
}
return res;
}
void defineFilters2D()
{
using namespace python;
docstring_options doc_options(true, true, false);
def("nonlinearDiffusion",
registerConverters(&pythonNonlinearDiffusion2D<float, float>),
(arg("image"), arg("edgeThreshold"), arg("scale"), arg("out")=python::object()),
"Perform edge-preserving smoothing at the given scale."
"\n\n"
"For details see nonlinearDiffusion_ in the vigra C++ documentation.\n");
def("shockFilter",
registerConverters(&pythonShockFilter<float, float>),
(
arg("image"),
arg("sigma"),
arg("rho"),
arg("updwindFactorH") ,
arg("iterations"),
arg("out")=python::object()
),
"Perform edge-preserving smoothing at the given scale."
"\n\n"
"For details see shockFilter_ in the vigra C++ documentation.\n");
def("totalVariationFilter",
registerConverters(&pythonTotalVariationFilter2D<double,double>),
(arg("image"), arg("alpha"), arg("steps"), arg("eps"), arg("out")=python::object()),
"Perform total variation filter on 2D single band images."
"\n\n"
"For details see totalVariationFilter in the vigra C++ documentation.\n");
def("totalVariationFilter",
registerConverters(&pythonTotalVariationFilter2D<double,double,double>),
(arg("image"), arg("weight"), arg("alpha"), arg("steps"), arg("eps"), arg("out")=python::object()),
"Perform weighted total variation filter on 2D single band images."
"\n\n"
"For details see totalVariationFilter in the vigra C++ documentation.\n");
def("radialSymmetryTransform2D",
registerConverters(&pythonRadialSymmetryTransform2D<float>),
(arg("image"), arg("scale"),arg("out")=python::object()),
"Find centers of radial symmetry in an 2D image.\n\n"
"This algorithm implements the Fast Radial Symmetry Transform according to "
"[G. Loy, A. Zelinsky: \"A Fast Radial Symmetry Transform for Detecting Points of Interest\", "
"in: A. Heyden et al. (Eds.): Proc. of 7th European Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002]\n\n"
"For details see radialSymmetryTransform_ in the vigra C++ documentation.\n");
}
void defineKernels();
void defineConvolutionFunctions();
void defineMorphology();
void defineTensor();
void defineNonLocalMean();
} // namespace vigra
using namespace vigra;
using namespace boost::python;
BOOST_PYTHON_MODULE_INIT(filters)
{
import_vigranumpy();
defineFilters2D();
defineKernels();
defineConvolutionFunctions();
defineMorphology();
defineTensor();
defineNonLocalMean();
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <pc.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
bool inGraphics = true;
namespace PC {
const unsigned W = 320, H = 200;
unsigned ImageBuffer[W * H];
int selector;
void Init() {
__dpmi_regs r;
r.x.ax = 0x13;
__dpmi_int(0x10, &r);
outp(0x03c8, 0);
for ( int r = 0; r < 4; ++r ) {
for ( int g = 0; g < 4; ++g ) {
for ( int b = 0; b < 4; ++b ) {
outp(0x03c9, (r * 85));
outp(0x03c9, (g * 85));
outp(0x03c9, (b * 85));
}
}
}
}
void renderPalette() {
_farsetsel(_dos_ds);
int offset = 0;
int fullSize = 320 * 200;
for (int r = 0; r < 255; ++r) {
for (int x = 0; x < 50; ++x) {
int shade = 0;
int origin = r << 16;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + r, shade);
}
}
for (int g = 0; g < 255; ++g) {
for (int x = 50; x < 100; ++x) {
int shade = 0;
int origin = g << 8;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + g, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 100; x < 150; ++x) {
int shade = 0;
int origin = b;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + b, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 150; x < 200; ++x) {
_farnspokeb(0xA0000 + (320 * x) + b, b);
}
}
std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);
}
void Render() {
_farsetsel(_dos_ds);
auto pixelData = (*gunState)->getPixelData();
int offset = 0;
int fullSize = 320 * 200;
for (int y = 100; y < 200; ++y) {
for (int x = 80; x < 240; ++x) {
offset = (320 * y) + x;
auto origin = ImageBuffer[offset];
offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160);
if (pixelData[offset] & 0xFF000000) {
origin = pixelData[offset];
}
int shade = 0;
shade += (((((origin & 0x0000FF) ) ) / 85 ) );
shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2;
shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4;
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
}
}
std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
void setGraphics() {
inGraphics = true;
PC::Init();
}
void setTextMode() {
inGraphics = false;
__dpmi_regs r;
r.x.ax = 3;
__dpmi_int(0x10, &r);
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
if ( inGraphics ) {
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
}
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case '1':
setGraphics();
break;
case '2':
setTextMode();
break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'h':
interact();
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<commit_msg>Paint the gun of the 3D image, depending on the state of the shooting sequence<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <osmesa.h>
#include <conio.h> // For kbhit, getch, textmode (console access)
#include <dpmi.h> // For __dpmi_int (mouse access)
#include <go32.h> // For _dos_ds (VRAM access)
#include <sys/movedata.h> // For movedata (VRAM access)
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <GL/glu.h> // GLU = OpenGL utility library
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <cstdio>
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <memory>
#include <iostream>
#include <map>
#include <array>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <pc.h>
#include "NativeBitmap.h"
#include "SoundClip.h"
#include "SoundUtils.h"
#include "SoundListener.h"
#include "SoundEmitter.h"
#include "IFileLoaderDelegate.h"
#include "Vec2i.h"
#include "NativeBitmap.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "CMap.h"
#include "IRenderer.h"
#include "NoudarDungeonSnapshot.h"
#include "GameNativeAPI.h"
#include "WindowOperations.h"
#include "Common.h"
#include "LoadPNG.h"
bool inGraphics = true;
std::vector<std::shared_ptr<odb::NativeBitmap>> gunStates;
std::vector<std::shared_ptr<odb::NativeBitmap>>::iterator gunState;
namespace PC {
const unsigned W = 320, H = 200;
unsigned ImageBuffer[W * H];
int selector;
void Init() {
__dpmi_regs r;
r.x.ax = 0x13;
__dpmi_int(0x10, &r);
outp(0x03c8, 0);
for ( int r = 0; r < 4; ++r ) {
for ( int g = 0; g < 4; ++g ) {
for ( int b = 0; b < 4; ++b ) {
outp(0x03c9, (r * 85));
outp(0x03c9, (g * 85));
outp(0x03c9, (b * 85));
}
}
}
}
void renderPalette() {
_farsetsel(_dos_ds);
int offset = 0;
int fullSize = 320 * 200;
for (int r = 0; r < 255; ++r) {
for (int x = 0; x < 50; ++x) {
int shade = 0;
int origin = r << 16;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + r, shade);
}
}
for (int g = 0; g < 255; ++g) {
for (int x = 50; x < 100; ++x) {
int shade = 0;
int origin = g << 8;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + g, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 100; x < 150; ++x) {
int shade = 0;
int origin = b;
shade += (((((origin & 0x0000FF))) / 85));
shade += (((((origin & 0x00FF00) >> 8)) / 85)) << 2;
shade += (((((origin & 0xFF0000) >> 16)) / 85)) << 4;
_farnspokeb(0xA0000 + (320 * x) + b, shade);
}
}
for (int b = 0; b < 255; ++b) {
for (int x = 150; x < 200; ++x) {
_farnspokeb(0xA0000 + (320 * x) + b, b);
}
}
std::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);
}
void Render() {
_farsetsel(_dos_ds);
auto pixelData = (*gunState)->getPixelData();
int offset = 0;
int fullSize = 320 * 200;
for (int y = 100; y < 200; ++y) {
for (int x = 80; x < 240; ++x) {
offset = (320 * y) + x;
auto origin = ImageBuffer[offset];
offset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) / 160);
if (pixelData[offset] & 0xFF000000) {
origin = pixelData[offset];
}
int shade = 0;
shade += (((((origin & 0x0000FF) ) ) / 85 ) );
shade += (((((origin & 0x00FF00) >> 8 ) ) / 85 ) ) << 2;
shade += (((((origin & 0xFF0000) >> 16) ) / 85 ) ) << 4;
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);
_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);
}
}
std::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);
}
void Close() // End graphics
{
textmode(C80); // Set textmode again.
}
}
void setGraphics() {
inGraphics = true;
PC::Init();
}
void setTextMode() {
inGraphics = false;
__dpmi_regs r;
r.x.ax = 3;
__dpmi_int(0x10, &r);
}
const int winWidth = 320, winHeight = 200;
bool done = false;
bool isActive = false;
std::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {
std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;
toReturn.push_back( loadPNG( "res/grass.ppm") );
toReturn.push_back( loadPNG( "res/stonef1.ppm") );
toReturn.push_back( loadPNG( "res/bricks.ppm") );
toReturn.push_back( loadPNG( "res/arch.ppm") );
toReturn.push_back( loadPNG( "res/bars.ppm") );
toReturn.push_back( loadPNG( "res/begin.ppm") );
toReturn.push_back( loadPNG( "res/exit.ppm") );
toReturn.push_back( loadPNG( "res/bricks2.ppm") );
toReturn.push_back( loadPNG( "res/bricks3.ppm") );
toReturn.push_back( loadPNG( "res/foe0.ppm") );
toReturn.push_back( loadPNG( "res/foe1.ppm") );
toReturn.push_back( loadPNG( "res/foe2.ppm") );
toReturn.push_back( loadPNG( "res/foe3.ppm") );
toReturn.push_back( loadPNG( "res/foe4.ppm") );
toReturn.push_back( loadPNG( "res/foe5.ppm") );
toReturn.push_back( loadPNG( "res/crusad0.ppm") );
toReturn.push_back( loadPNG( "res/crusad1.ppm") );
toReturn.push_back( loadPNG( "res/crusad2.ppm") );
toReturn.push_back( loadPNG( "res/shadow.ppm") );
toReturn.push_back( loadPNG( "res/ceilin.ppm") );
toReturn.push_back( loadPNG( "res/ceigdr.ppm") );
toReturn.push_back( loadPNG( "res/ceigbgn.ppm") );
toReturn.push_back( loadPNG( "res/ceilend.ppm") );
toReturn.push_back( loadPNG( "res/splat0.ppm") );
toReturn.push_back( loadPNG( "res/splat1.ppm") );
toReturn.push_back( loadPNG( "res/splat2.ppm") );
toReturn.push_back( loadPNG( "res/ceilbar.ppm") );
toReturn.push_back( loadPNG( "res/clouds.ppm"));
toReturn.push_back( loadPNG( "res/stngrsf.ppm"));
toReturn.push_back( loadPNG( "res/grsstnf.ppm"));
toReturn.push_back( loadPNG( "res/stngrsn.ppm"));
toReturn.push_back( loadPNG( "res/grsstnn.ppm"));
toReturn.push_back( loadPNG( "res/cross.ppm"));
return toReturn;
}
void initWindow() {
auto textures = loadTextures();
gunStates.push_back( loadPNG( "res/shotgun0.ppm", 320, 200) );
gunStates.push_back( loadPNG( "res/shotgun1.ppm", 320, 200) );
gunState = std::begin( gunStates );
OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);
OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);
PC::Init();
auto gVertexShader = "";
auto gFragmentShader = "";
setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);
auto soundListener = std::make_shared<odb::SoundListener>();
std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;
std::string filenames[] {
"res/grasssteps.wav",
"res/stepsstones.wav",
"res/bgnoise.wav",
"res/monsterdamage.wav",
"res/monsterdead.wav",
"res/playerdamage.wav",
"res/playerdead.wav",
"res/swing.wav"
};
for ( auto filename : filenames ) {
FILE *file = fopen( filename.c_str(), "r");
auto soundClip = odb::makeSoundClipFrom( file );
sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );
}
setSoundEmitters( sounds, soundListener );
}
void tick() {
//if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined
if ( inGraphics ) {
gameLoopTick( 250 );
renderFrame( 250 );
PC::Render();
if ( gunState != std::begin( gunStates ) ) {
gunState = std::prev( gunState );
}
}
}
void setMainLoop() {
while ( !done ) {
while(kbhit())
switch(getch()) {
case 27: done = true; break;
case '1':
setGraphics();
break;
case '2':
setTextMode();
break;
case 'w':
moveUp();
break;
case 's':
moveDown();
break;
case 'd':
moveRight();
break;
case 'a':
moveLeft();
break;
case 'h':
interact();
gunState = std::prev(std::end(gunStates));
break;
case 'e':
rotateCameraRight();
break;
case 'q':
rotateCameraLeft();
break;
}
tick();
}
}
void destroyWindow() {
shutdown();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: DanielssonDistanceMapImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software 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.
=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{DanielssonDistanceMapImageFilter}. This filter generates a
// distance map from the input image using the algorithm developed by
// Danielsson \cite{Danielsson1980}. As secondary outputs, a Voronoi
// partition of the input elements is produced, as well as a vector image
// with the components of the distance vector to the closest point. The input
// to the map is assumed to be a set of points on the input image. Each
// point/pixel is considered to be a separate entity even if they share the
// same graylevel value.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Instantiation}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Header}
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkDanielssonDistanceMapImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
int main( int argc, char * argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImageFile outputDistanceMapImageFile ";
std::cerr << " outputVoronoiMapImageFilter ";
std::cerr << " outputVectorMapImageFilter ";
std::cerr << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel types to use for the input and output
// images. Since the output will contain distances measured in pixels, the
// pixel type should be able to represent at least the width of the image,
// or said in $N-D$ terms, the maximum extension along all the dimensions.
// The input and output image types are now defined using their respective
// pixel type and dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputPixelType;
typedef unsigned short OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The filter type can be instantiated using the input and output image
// types defined above. A filter object is created with the \code{New()}
// method.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!instantiation}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!New()}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::DanielssonDistanceMapImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
typedef itk::RescaleIntensityImageFilter<
OutputImageType, OutputImageType > RescalerType;
RescalerType::Pointer scaler = RescalerType::New();
//
// Reader and Writer types are instantiated.
//
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// The input to the filter is taken from a reader and its output is passed
// to a \doxygen{RescaleIntensityImageFilter} and then to a writer.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!SetInput()}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!GetOutput()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
scaler->SetInput( filter->GetOutput() );
writer->SetInput( scaler->GetOutput() );
// Software Guide : EndCodeSnippet
scaler->SetOutputMaximum( 65535L );
scaler->SetOutputMinimum( 0L );
// Software Guide : BeginLatex
//
// The type of input image has to be specified. In this case, a binary
// image is selected.
//
// \index{itk::Danielsson\-Distance\-MapImage\-Filter!InputIsBinaryOn()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->InputIsBinaryOn();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.32\textwidth]{FivePoints.eps}
// \includegraphics[width=0.32\textwidth]{DanielssonDistanceMapImageFilterOutput1.eps}
// \includegraphics[width=0.32\textwidth]{DanielssonDistanceMapImageFilterOutput2.eps}
// \itkcaption[DanielssonDistanceMapImageFilter
// output]{DanielssonDistanceMapImageFilter output. Set of pixels, distance
// map and Voronoi partition.}
// \label{fig:DanielssonDistanceMapImageFilterInputOutput}
// \end{figure}
//
// Figure \ref{fig:DanielssonDistanceMapImageFilterInputOutput} illustrates
// the effect of this filter on a binary image with a set of points. The
// input image is shown at left, the distance map at the center and the
// Voronoi partition at right. This filter computes distance maps in
// N-dimensions and is therefore capable of producing $N-D$ Voronoi
// partitions.
//
// \index{Voronoi partitions}
// \index{Voronoi partitions!itk::Danielsson\-Distance\-Map\-Image\-Filter}
//
// Software Guide : EndLatex
writer->Update();
const char * voronoiMapFileName = argv[3];
// Software Guide : BeginLatex
//
// The Voronoi map is obtained with the \code{GetVoronoiMap()} method. In
// the lines below we connect this output to the intensity rescaler and
// save the result in a file.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!GetVoronoiMap()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
scaler->SetInput( filter->GetVoronoiMap() );
writer->SetFileName( voronoiMapFileName );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The distance filter also produces an image of \doxygen{Offset} pixels
// representing the vectorial distance to the closest object in the scene.
// The type of this output image is defined by the VectorImageType
// trait of the filter type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef FilterType::VectorImageType OffsetImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can use this type for instantiating an \doxygen{ImageFileWriter} type
// and creating an object of this class in the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ImageFileWriter< OffsetImageType > WriterOffsetType;
WriterOffsetType::Pointer offsetWriter = WriterOffsetType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of the distance filter can be connected as input to the
// writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
offsetWriter->SetInput( filter->GetVectorDistanceMap() );
// Software Guide : EndCodeSnippet
offsetWriter->SetFileName( argv[4] );
// Software Guide : BeginLatex
//
// Execution of the writer is triggered by the invocation of the
// \code{Update()} method. Since this method can potentially throw
// exceptions it must be placed in a \code{try/catch} block.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
offsetWriter->Update();
}
catch( itk::ExceptionObject exp )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << exp << std::endl;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that only the \doxygen{MetaImageIO} class supports reading and
// writing images of pixel type \doxygen{Offset}.
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>ENH: Command line tags for automatic generation of figures in Software guide<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: DanielssonDistanceMapImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software 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.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {FivePoints.png}
// OUTPUTS: {DanielssonDistanceMapImageFilterOutput1.png}
// OUTPUTS: {DanielssonDistanceMapImageFilterOutput2.png}
// OUTPUTS: {DanielssonDistanceMapImageFilterOutput3.mhd}
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{DanielssonDistanceMapImageFilter}. This filter generates a
// distance map from the input image using the algorithm developed by
// Danielsson \cite{Danielsson1980}. As secondary outputs, a Voronoi
// partition of the input elements is produced, as well as a vector image
// with the components of the distance vector to the closest point. The input
// to the map is assumed to be a set of points on the input image. Each
// point/pixel is considered to be a separate entity even if they share the
// same graylevel value.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Instantiation}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Header}
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkDanielssonDistanceMapImageFilter.h"
// Software Guide : EndCodeSnippet
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
int main( int argc, char * argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImageFile outputDistanceMapImageFile ";
std::cerr << " outputVoronoiMapImageFilter ";
std::cerr << " outputVectorMapImageFilter ";
std::cerr << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel types to use for the input and output
// images. Since the output will contain distances measured in pixels, the
// pixel type should be able to represent at least the width of the image,
// or said in $N-D$ terms, the maximum extension along all the dimensions.
// The input and output image types are now defined using their respective
// pixel type and dimension.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputPixelType;
typedef unsigned short OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The filter type can be instantiated using the input and output image
// types defined above. A filter object is created with the \code{New()}
// method.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!instantiation}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!New()}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::DanielssonDistanceMapImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
typedef itk::RescaleIntensityImageFilter<
OutputImageType, OutputImageType > RescalerType;
RescalerType::Pointer scaler = RescalerType::New();
//
// Reader and Writer types are instantiated.
//
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// The input to the filter is taken from a reader and its output is passed
// to a \doxygen{RescaleIntensityImageFilter} and then to a writer.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!SetInput()}
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!GetOutput()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
scaler->SetInput( filter->GetOutput() );
writer->SetInput( scaler->GetOutput() );
// Software Guide : EndCodeSnippet
scaler->SetOutputMaximum( 65535L );
scaler->SetOutputMinimum( 0L );
// Software Guide : BeginLatex
//
// The type of input image has to be specified. In this case, a binary
// image is selected.
//
// \index{itk::Danielsson\-Distance\-MapImage\-Filter!InputIsBinaryOn()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->InputIsBinaryOn();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.32\textwidth]{FivePoints.eps}
// \includegraphics[width=0.32\textwidth]{DanielssonDistanceMapImageFilterOutput1.eps}
// \includegraphics[width=0.32\textwidth]{DanielssonDistanceMapImageFilterOutput2.eps}
// \itkcaption[DanielssonDistanceMapImageFilter
// output]{DanielssonDistanceMapImageFilter output. Set of pixels, distance
// map and Voronoi partition.}
// \label{fig:DanielssonDistanceMapImageFilterInputOutput}
// \end{figure}
//
// Figure \ref{fig:DanielssonDistanceMapImageFilterInputOutput} illustrates
// the effect of this filter on a binary image with a set of points. The
// input image is shown at left, the distance map at the center and the
// Voronoi partition at right. This filter computes distance maps in
// N-dimensions and is therefore capable of producing $N-D$ Voronoi
// partitions.
//
// \index{Voronoi partitions}
// \index{Voronoi partitions!itk::Danielsson\-Distance\-Map\-Image\-Filter}
//
// Software Guide : EndLatex
writer->Update();
const char * voronoiMapFileName = argv[3];
// Software Guide : BeginLatex
//
// The Voronoi map is obtained with the \code{GetVoronoiMap()} method. In
// the lines below we connect this output to the intensity rescaler and
// save the result in a file.
//
// \index{itk::Danielsson\-Distance\-Map\-Image\-Filter!GetVoronoiMap()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
scaler->SetInput( filter->GetVoronoiMap() );
writer->SetFileName( voronoiMapFileName );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The distance filter also produces an image of \doxygen{Offset} pixels
// representing the vectorial distance to the closest object in the scene.
// The type of this output image is defined by the VectorImageType
// trait of the filter type.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef FilterType::VectorImageType OffsetImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can use this type for instantiating an \doxygen{ImageFileWriter} type
// and creating an object of this class in the following lines.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::ImageFileWriter< OffsetImageType > WriterOffsetType;
WriterOffsetType::Pointer offsetWriter = WriterOffsetType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The output of the distance filter can be connected as input to the
// writer.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
offsetWriter->SetInput( filter->GetVectorDistanceMap() );
// Software Guide : EndCodeSnippet
offsetWriter->SetFileName( argv[4] );
// Software Guide : BeginLatex
//
// Execution of the writer is triggered by the invocation of the
// \code{Update()} method. Since this method can potentially throw
// exceptions it must be placed in a \code{try/catch} block.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
try
{
offsetWriter->Update();
}
catch( itk::ExceptionObject exp )
{
std::cerr << "Exception caught !" << std::endl;
std::cerr << exp << std::endl;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that only the \doxygen{MetaImageIO} class supports reading and
// writing images of pixel type \doxygen{Offset}.
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef ElastixFilter_hxx
#define ElastixFilter_hxx
namespace selx {
template< typename TFixedImage, typename TMovingImage >
ElastixFilter< TFixedImage, TMovingImage >
::ElastixFilter( void )
{
this->AddRequiredInputName( "FixedImage" );
this->AddRequiredInputName( "MovingImage" );
this->AddRequiredInputName( "ParameterObject");
this->SetPrimaryInputName( "FixedImage" );
this->SetPrimaryOutputName( "ResultImage" );
this->m_FixedImageContainer = DataObjectContainerType::New();
this->m_MovingImageContainer = DataObjectContainerType::New();
this->m_FixedMeshFileName = std::string();
this->m_MovingMeshFileName = std::string();
this->m_OutputDirectory = std::string();
this->m_LogFileName = std::string();
this->LogToConsoleOff();
this->LogToFileOff();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::GenerateData( void )
{
// Initialize variables here so they don't go out of scope between iterations of the main loop
ElastixMainObjectPointer transform = 0;
DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer fixedMaskContainer = 0;
DataObjectContainerPointer movingMaskContainer = 0;
DataObjectContainerPointer resultImageContainer = 0;
ParameterMapListType TransformParameterMapList;
FlatDirectionCosinesType fixedImageOriginalDirection;
// Split input images into two seperate fixed and moving image containers
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if( this->IsFixedImage( inputNames[ i ] ) )
{
fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
if( this->IsMovingImage( inputNames[ i ] ) )
{
movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
}
// Fixed mask (optional)
if( this->HasInput( "FixedMask" ) )
{
fixedMaskContainer = DataObjectContainerType::New();
fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( "FixedMask" );
}
// Moving mask (optional)
if( this->HasInput( "MovingMask" ) )
{
movingMaskContainer = DataObjectContainerType::New();
movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( "MovingMask" );
}
ArgumentMapType argumentMap;
if( this->GetOutputDirectory().empty() ) {
// There must be an "-out", this is checked later in the code
argumentMap.insert( ArgumentMapEntryType( "-out", "output_path_not_set" ) );
}
else
{
argumentMap.insert( ArgumentMapEntryType( "-out", this->GetOutputDirectory() ) );
}
// Fixed mesh (optional)
if( !this->m_FixedMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-fp", std::string( this->m_FixedMeshFileName ) ) );
}
// Moving mesh (optional)
if( !this->m_MovingMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-mp", std::string( this->m_MovingMeshFileName ) ) );
}
// Setup xout
std::string logFileName;
if( this->GetLogToFile() )
{
if( this->GetOutputDirectory().empty() )
{
itkExceptionMacro( "LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().")
}
if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )
{
itkExceptionMacro( "Output directory \"" << this->GetOutputDirectory() << "\" does not exist." )
}
if( this->GetOutputDirectory().back() != '/' || this->GetOutputDirectory().back() != '\\' )
{
this->SetOutputDirectory( this->GetOutputDirectory() + "/" );
}
if( this->GetLogFileName().empty() )
{
logFileName = this->GetOutputDirectory() + "transformix.log";
}
else
{
logFileName = this->GetOutputDirectory() + this->GetLogFileName();
}
}
if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )
{
itkExceptionMacro( "ERROR while setting up xout" );
}
// Get ParameterMap
ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( "ParameterObject" ) );
ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();
// Run the (possibly multiple) registration(s)
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
// Create another instance of ElastixMain
ElastixMainPointer elastix = ElastixMainType::New();
// Set the current elastix-level
elastix->SetElastixLevel( i );
elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );
// Set stuff we get from a previous registration
elastix->SetInitialTransform( transform );
elastix->SetFixedImageContainer( fixedImageContainer );
elastix->SetMovingImageContainer( movingImageContainer );
elastix->SetFixedMaskContainer( fixedMaskContainer );
elastix->SetMovingMaskContainer( movingMaskContainer );
elastix->SetResultImageContainer( resultImageContainer );
elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );
// Start registration
unsigned int isError = 0;
try
{
unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );
}
catch( itk::ExceptionObject &e )
{
itkExceptionMacro( << "Errors occurred during registration: " << e.what() );
}
if( isError == -2 )
{
itkExceptionMacro( << "Errors occurred during registration: Output directory does not exist." );
}
if( isError != 0 )
{
itkExceptionMacro( << "Uncought errors occurred during registration." );
}
// Get the transform, the fixedImage and the movingImage
// in order to put it in the next registration
transform = elastix->GetFinalTransform();
fixedImageContainer = elastix->GetFixedImageContainer();
movingImageContainer = elastix->GetMovingImageContainer();
fixedMaskContainer = elastix->GetFixedMaskContainer();
movingMaskContainer = elastix->GetMovingMaskContainer();
resultImageContainer = elastix->GetResultImageContainer();
fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();
TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );
// Set initial transform to an index number instead of a parameter filename
if( i > 0 )
{
std::stringstream index;
index << ( i - 1 );
TransformParameterMapList[ i ][ "InitialTransformParametersFileName" ][ 0 ] = index.str();
}
} // End loop over registrations
// Save result image
if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )
{
this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );
}
// Save parameter map
ParameterObject::Pointer TransformParameters = ParameterObject::New();
TransformParameters->SetParameterMapList( TransformParameterMapList );
this->SetOutput( "TransformParameterObject", static_cast< itk::DataObject* >( TransformParameters ) );
// Close the modules
ElastixMainType::UnloadComponents();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetParameterObject( ParameterObjectPointer parameterObject )
{
this->SetInput( "ParameterObject", static_cast< itk::DataObject* >( parameterObject ) );
}
template< typename TFixedImage, typename TMovingImage >
typename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer
ElastixFilter< TFixedImage, TMovingImage >
::GetTransformParameters( void )
{
// Make sure the transform parameters are up to date
this->Update();
return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( "TransformParameterObject" ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( FixedImagePointer fixedImage )
{
// Free references to fixed images that has already been set
this->RemoveFixedImages();
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( DataObjectContainerPointer fixedImages )
{
if( fixedImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set fixed images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveFixedImages();
// "FixedImage" is a required input that needs to be set
this->SetInput( "FixedImage" , fixedImages->ElementAt( 0 ) );
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// fixed images for elastix fixed image container at a later stage
DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();
++fixedImageIterator;
while( fixedImageIterator != fixedImages->End() )
{
this->AddInputAutoIncrementName( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddFixedImage( FixedImagePointer fixedImage )
{
if( !this->HasInput( "FixedImage") )
{
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
else
{
this->AddInputAutoIncrementName( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( MovingImagePointer movingImage )
{
// Free references to moving images that has already been set
this->RemoveMovingImages();
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( DataObjectContainerPointer movingImages )
{
if( movingImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set moving images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveMovingImages();
// "MovingImage" is a required input that needs to be set
this->SetInput( "MovingImage" , movingImages->ElementAt( 0 ) );
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// moving images for elastix moving image container at a later stage
DataObjectContainerIterator movingImageIterator = movingImages->Begin();
++movingImageIterator;
while( movingImageIterator != movingImages->End() )
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );
++movingImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddMovingImage( MovingImagePointer movingImage )
{
if( !this->HasInput( "MovingImage") )
{
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
else
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedMask( FixedImagePointer fixedMask )
{
this->SetInput( "FixedMask", static_cast< itk::DataObject* >( fixedMask ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingMask( MovingImagePointer movingMask )
{
this->SetInput( "MovingMask", static_cast< itk::DataObject* >( movingMask ) );
}
/*
* Adds a named input to the first null position in the input list
* Expands the list memory if necessary
*/
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )
{
for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )
{
if ( !this->GetInput( idx ) )
{
key += this->MakeNameFromInputIndex( idx );
this->SetInput( key, input );
return;
}
}
key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );
this->SetInput( key, input );
return;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsFixedImage( DataObjectIdentifierType key )
{
return std::strncmp( "FixedImage", key.c_str(), 10 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsMovingImage( DataObjectIdentifierType key )
{
return std::strncmp( "MovingImage", key.c_str(), 11 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveFixedImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsFixedImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveMovingImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsMovingImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
} // namespace selx
#endif // ElastixFilter_hxx<commit_msg>ENH: Refactor setting multiple fixed and moving images<commit_after>#ifndef ElastixFilter_hxx
#define ElastixFilter_hxx
namespace selx {
template< typename TFixedImage, typename TMovingImage >
ElastixFilter< TFixedImage, TMovingImage >
::ElastixFilter( void )
{
this->AddRequiredInputName( "FixedImage" );
this->AddRequiredInputName( "MovingImage" );
this->AddRequiredInputName( "ParameterObject");
this->SetPrimaryInputName( "FixedImage" );
this->SetPrimaryOutputName( "ResultImage" );
this->m_FixedImageContainer = DataObjectContainerType::New();
this->m_MovingImageContainer = DataObjectContainerType::New();
this->m_FixedMeshFileName = std::string();
this->m_MovingMeshFileName = std::string();
this->m_OutputDirectory = std::string();
this->m_LogFileName = std::string();
this->LogToConsoleOff();
this->LogToFileOff();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::GenerateData( void )
{
// Initialize variables here so they don't go out of scope between iterations of the main loop
ElastixMainObjectPointer transform = 0;
DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();
DataObjectContainerPointer fixedMaskContainer = 0;
DataObjectContainerPointer movingMaskContainer = 0;
DataObjectContainerPointer resultImageContainer = 0;
ParameterMapListType TransformParameterMapList;
FlatDirectionCosinesType fixedImageOriginalDirection;
// Split input images into two seperate fixed and moving image containers
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if( this->IsFixedImage( inputNames[ i ] ) )
{
fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
if( this->IsMovingImage( inputNames[ i ] ) )
{
movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );
}
}
// Fixed mask (optional)
if( this->HasInput( "FixedMask" ) )
{
fixedMaskContainer = DataObjectContainerType::New();
fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( "FixedMask" );
}
// Moving mask (optional)
if( this->HasInput( "MovingMask" ) )
{
movingMaskContainer = DataObjectContainerType::New();
movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( "MovingMask" );
}
ArgumentMapType argumentMap;
if( this->GetOutputDirectory().empty() ) {
// There must be an "-out", this is checked later in the code
argumentMap.insert( ArgumentMapEntryType( "-out", "output_path_not_set" ) );
}
else
{
argumentMap.insert( ArgumentMapEntryType( "-out", this->GetOutputDirectory() ) );
}
// Fixed mesh (optional)
if( !this->m_FixedMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-fp", std::string( this->m_FixedMeshFileName ) ) );
}
// Moving mesh (optional)
if( !this->m_MovingMeshFileName.empty() )
{
argumentMap.insert( ArgumentMapEntryType( "-mp", std::string( this->m_MovingMeshFileName ) ) );
}
// Setup xout
std::string logFileName;
if( this->GetLogToFile() )
{
if( this->GetOutputDirectory().empty() )
{
itkExceptionMacro( "LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().")
}
if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )
{
itkExceptionMacro( "Output directory \"" << this->GetOutputDirectory() << "\" does not exist." )
}
if( this->GetOutputDirectory().back() != '/' || this->GetOutputDirectory().back() != '\\' )
{
this->SetOutputDirectory( this->GetOutputDirectory() + "/" );
}
if( this->GetLogFileName().empty() )
{
logFileName = this->GetOutputDirectory() + "transformix.log";
}
else
{
logFileName = this->GetOutputDirectory() + this->GetLogFileName();
}
}
if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )
{
itkExceptionMacro( "ERROR while setting up xout" );
}
// Get ParameterMap
ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( "ParameterObject" ) );
ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();
// Run the (possibly multiple) registration(s)
for( unsigned int i = 0; i < parameterMapList.size(); ++i )
{
// Create another instance of ElastixMain
ElastixMainPointer elastix = ElastixMainType::New();
// Set the current elastix-level
elastix->SetElastixLevel( i );
elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );
// Set stuff we get from a previous registration
elastix->SetInitialTransform( transform );
elastix->SetFixedImageContainer( fixedImageContainer );
elastix->SetMovingImageContainer( movingImageContainer );
elastix->SetFixedMaskContainer( fixedMaskContainer );
elastix->SetMovingMaskContainer( movingMaskContainer );
elastix->SetResultImageContainer( resultImageContainer );
elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );
// Start registration
unsigned int isError = 0;
try
{
unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );
}
catch( itk::ExceptionObject &e )
{
itkExceptionMacro( << "Errors occurred during registration: " << e.what() );
}
if( isError == -2 )
{
itkExceptionMacro( << "Errors occurred during registration: Output directory does not exist." );
}
if( isError != 0 )
{
itkExceptionMacro( << "Uncought errors occurred during registration." );
}
// Get the transform, the fixedImage and the movingImage
// in order to put it in the next registration
transform = elastix->GetFinalTransform();
fixedImageContainer = elastix->GetFixedImageContainer();
movingImageContainer = elastix->GetMovingImageContainer();
fixedMaskContainer = elastix->GetFixedMaskContainer();
movingMaskContainer = elastix->GetMovingMaskContainer();
resultImageContainer = elastix->GetResultImageContainer();
fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();
TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );
// Set initial transform to an index number instead of a parameter filename
if( i > 0 )
{
std::stringstream index;
index << ( i - 1 );
TransformParameterMapList[ i ][ "InitialTransformParametersFileName" ][ 0 ] = index.str();
}
} // End loop over registrations
// Save result image
if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )
{
this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );
}
// Save parameter map
ParameterObject::Pointer TransformParameters = ParameterObject::New();
TransformParameters->SetParameterMapList( TransformParameterMapList );
this->SetOutput( "TransformParameterObject", static_cast< itk::DataObject* >( TransformParameters ) );
// Close the modules
ElastixMainType::UnloadComponents();
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetParameterObject( ParameterObjectPointer parameterObject )
{
this->SetInput( "ParameterObject", static_cast< itk::DataObject* >( parameterObject ) );
}
template< typename TFixedImage, typename TMovingImage >
typename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer
ElastixFilter< TFixedImage, TMovingImage >
::GetTransformParameters( void )
{
// Make sure the transform parameters are up to date
this->Update();
return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( "TransformParameterObject" ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( FixedImagePointer fixedImage )
{
// Free references to fixed images that has already been set
this->RemoveFixedImages();
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedImage( DataObjectContainerPointer fixedImages )
{
if( fixedImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set fixed images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveFixedImages();
// The first image will be used as the "FixedImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// fixed images for elastix fixed image container at a later stage
DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();
this->SetInput( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
while( fixedImageIterator != fixedImages->End() )
{
this->AddInputAutoIncrementName( "FixedImage", fixedImageIterator->Value() );
++fixedImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddFixedImage( FixedImagePointer fixedImage )
{
if( !this->HasInput( "FixedImage") )
{
this->SetInput( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
else
{
this->AddInputAutoIncrementName( "FixedImage", static_cast< itk::DataObject* >( fixedImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( MovingImagePointer movingImage )
{
// Free references to moving images that has already been set
this->RemoveMovingImages();
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingImage( DataObjectContainerPointer movingImages )
{
if( movingImages->Size() == 0 )
{
itkExceptionMacro( "Cannot set moving images from empty container.")
}
// Free references to fixed images that has already been set
this->RemoveMovingImages();
// The first image will be used as the "MovingImage" required input.
// The rest of the images will be appended to the input container
// suffixed with _1, _2, etc. This allows us to read out only the
// moving images for elastix moving image container at a later stage
DataObjectContainerIterator movingImageIterator = movingImages->Begin();
this->SetInput( "MovingImage", movingImageIterator->Value() );
++movingImageIterator;
while( movingImageIterator != movingImages->End() )
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );
++movingImageIterator;
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddMovingImage( MovingImagePointer movingImage )
{
if( !this->HasInput( "MovingImage") )
{
this->SetInput( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
else
{
this->AddInputAutoIncrementName( "MovingImage", static_cast< itk::DataObject* >( movingImage ) );
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetFixedMask( FixedImagePointer fixedMask )
{
this->SetInput( "FixedMask", static_cast< itk::DataObject* >( fixedMask ) );
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::SetMovingMask( MovingImagePointer movingMask )
{
this->SetInput( "MovingMask", static_cast< itk::DataObject* >( movingMask ) );
}
/*
* Adds a named input to the first null position in the input list
* Expands the list memory if necessary
*/
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )
{
for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )
{
if ( !this->GetInput( idx ) )
{
key += this->MakeNameFromInputIndex( idx );
this->SetInput( key, input );
return;
}
}
key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );
this->SetInput( key, input );
return;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsFixedImage( DataObjectIdentifierType key )
{
return std::strncmp( "FixedImage", key.c_str(), 10 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
bool
ElastixFilter< TFixedImage, TMovingImage >
::IsMovingImage( DataObjectIdentifierType key )
{
return std::strncmp( "MovingImage", key.c_str(), 11 ) == 0;
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveFixedImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsFixedImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
template< typename TFixedImage, typename TMovingImage >
void
ElastixFilter< TFixedImage, TMovingImage >
::RemoveMovingImages( void )
{
// Free references to fixed images that has already been set
InputNameArrayType inputNames = this->GetInputNames();
for( unsigned int i = 0; i < inputNames.size(); ++i )
{
if ( this->IsMovingImage( inputNames[ i ] ) )
{
this->RemoveInput( inputNames[ i ] );
}
}
}
} // namespace selx
#endif // ElastixFilter_hxx<|endoftext|>
|
<commit_before>//
// Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadupubdir.cpp
// Gadu-Gadu Public directory contains people data, using it you can search friends
// different criteria
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
#include "gadupubdir.h"
#include <qpushbutton.h>
#include <qtextedit.h>
#include <qwidgetstack.h>
#include <qlistview.h>
#include <qptrlist.h>
#include <qradiobutton.h>
#include <kapplication.h>
#include <kdatewidget.h>
#include <klineedit.h>
#include <klocale.h>
#include <kurllabel.h>
#include <klistview.h>
GaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent, const char* name )
: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )
{
mAccount = account;
createWidget();
initConnections();
show();
}
GaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent, const char* name )
: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )
{
mAccount = account;
createWidget();
initConnections();
kdDebug( 14100 ) << "search for Uin: " << searchFor << endl;
mMainWidget->listFound->clear();
show();
mMainWidget->pubsearch->raiseWidget( 1 );
mMainWidget->radioByUin->setChecked( true );
setButtonText( User2, i18n( "Search &More..." ) );
showButton( User3, true );
showButton( User1, true );
enableButton( User3, false );
enableButton( User2, false );
// now it is time to switch to Right Page(tm)
fName = fSurname = fNick = fCity = QString::null;
fUin = searchFor;
fOnlyOnline= false;
fGender = fAgeFrom = fAgeTo = 0;
mAccount->pubDirSearch( fName, fSurname, fNick,
fUin, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );
}
void
GaduPublicDir::createWidget()
{
setCaption( i18n( "Gadu-Gadu Public Directory" ) );
mMainWidget = new GaduPublicDirectory( this );
setMainWidget( mMainWidget );
mMainWidget->UIN->setValidChars( "1234567890" );
setButtonText( User1, i18n( "&New Search" ) );
setButtonText( User2, i18n( "S&earch" ) );
setButtonText( User3, i18n( "&Add User..." ) );
setButtonText( Cancel, i18n( "&Close" ) );
showButton( User1, false );
showButton( User3, false );
enableButton( User2, false );
mMainWidget->radioByData->setChecked( true );
mAccount->pubDirSearchClose();
}
void
GaduPublicDir::initConnections()
{
connect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) );
connect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) );
connect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult& ) ),
SLOT( slotSearchResult( const SearchResult& ) ) );
connect( mMainWidget->nameS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->surname, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->nick, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->UIN, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->cityS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->gender, SIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->ageFrom, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->ageTo, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->radioByData, SIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) );
}
void
GaduPublicDir::inputChanged( bool )
{
inputChanged( QString::null );
}
void
GaduPublicDir::inputChanged( const QString& )
{
if ( validateData() == false ) {
enableButton( User2, false );
}
else {
enableButton( User2, true );
}
}
void
GaduPublicDir::getData()
{
fName = mMainWidget->nameS->text();
fSurname = mMainWidget->surname->text();
fNick = mMainWidget->nick->text();
fUin = mMainWidget->UIN->text().toInt();
fGender = mMainWidget->gender->currentItem();
fOnlyOnline= mMainWidget->onlyOnline->isChecked();
fAgeFrom = mMainWidget->ageFrom->value();
fAgeTo = mMainWidget->ageTo->value();
fCity = mMainWidget->cityS->text();
}
// return true if not empty
#define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } }
#define CHECK_INT(A) { if ( A ) { return true; } }
bool
GaduPublicDir::validateData()
{
getData();
if ( mMainWidget->radioByData->isChecked() ) {
CHECK_STRING( fCity );
CHECK_STRING( fName );
CHECK_STRING( fSurname );
CHECK_STRING( fNick );
CHECK_INT( fGender );
CHECK_INT( fAgeFrom );
CHECK_INT( fAgeTo );
}
else {
CHECK_INT( fUin );
}
return false;
}
// Move to GaduProtocol someday
QPixmap
GaduPublicDir::iconForStatus( uint status )
{
QPixmap n;
if ( GaduProtocol::protocol() ) {
return GaduProtocol::protocol()->convertStatus( status ).protocolIcon();
}
return n;
}
void
GaduPublicDir::slotSearchResult( const SearchResult& result )
{
QListView* list = mMainWidget->listFound;
int i;
kdDebug(14100) << "searchResults(" << result.count() <<")" << endl;
// if not found anything, obviously we don't want to search for more
// if we are looking just for one UIN, don't allow search more - it is pointless
if ( result.count() && fUin==0 ) {
enableButton( User2, true );
}
enableButton( User1, true );
QListViewItem* sl;
SearchResult::const_iterator r;
for ( r = result.begin(); r != result.end() ; ++r ){
kdDebug(14100) << "adding" << (*r).uin << endl;
sl= new QListViewItem(
list, QString::fromAscii(""),
(*r).firstname.latin1(),
(*r).nickname.latin1(),
(*r).age.latin1(),
(*r).city.latin1(),
(*r).uin.latin1()
);
sl->setPixmap( 0, iconForStatus( (*r).status ) );
}
}
void
GaduPublicDir::slotNewSearch()
{
mMainWidget->pubsearch->raiseWidget( 0 );
setButtonText( User2, i18n( "S&earch" ) );
showButton( User1, false );
showButton( User3, false );
enableButton( User2, false );
inputChanged( QString::null );
mAccount->pubDirSearchClose();
}
void
GaduPublicDir::slotSearch()
{
mMainWidget->listFound->clear();
QString empty;
// search more, or search ?
if ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) {
kdDebug(14100) << "start search... " << endl;
getData();
// validate data
if ( validateData() == false ) {
return;
}
// go on
mMainWidget->pubsearch->raiseWidget( 1 );
}
else{
kdDebug(14100) << "search more... " << endl;
// Search for more
}
setButtonText( User2, i18n( "Search &More..." ) );
showButton( User3, true );
showButton( User1, true );
enableButton( User3, false );
enableButton( User2, false );
if ( mMainWidget->radioByData->isChecked() ) {
mAccount->pubDirSearch( fName, fSurname, fNick,
0, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );
}
else {
mAccount->pubDirSearch( empty, empty, empty,
fUin, empty, 0, 0, 0, fOnlyOnline );
}
}
#include "gadupubdir.moc"
<commit_msg>This was a pointless change, could only fsck encoding<commit_after>//
// Copyright (C) 2003 Grzegorz Jaskiewicz <gj at pointblue.com.pl>
//
// gadupubdir.cpp
// Gadu-Gadu Public directory contains people data, using it you can search friends
// different criteria
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
#include "gadupubdir.h"
#include <qpushbutton.h>
#include <qtextedit.h>
#include <qwidgetstack.h>
#include <qlistview.h>
#include <qptrlist.h>
#include <qradiobutton.h>
#include <kapplication.h>
#include <kdatewidget.h>
#include <klineedit.h>
#include <klocale.h>
#include <kurllabel.h>
#include <klistview.h>
GaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent, const char* name )
: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )
{
mAccount = account;
createWidget();
initConnections();
show();
}
GaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent, const char* name )
: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )
{
mAccount = account;
createWidget();
initConnections();
kdDebug( 14100 ) << "search for Uin: " << searchFor << endl;
mMainWidget->listFound->clear();
show();
mMainWidget->pubsearch->raiseWidget( 1 );
mMainWidget->radioByUin->setChecked( true );
setButtonText( User2, i18n( "Search &More..." ) );
showButton( User3, true );
showButton( User1, true );
enableButton( User3, false );
enableButton( User2, false );
// now it is time to switch to Right Page(tm)
fName = fSurname = fNick = fCity = QString::null;
fUin = searchFor;
fOnlyOnline= false;
fGender = fAgeFrom = fAgeTo = 0;
mAccount->pubDirSearch( fName, fSurname, fNick,
fUin, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );
}
void
GaduPublicDir::createWidget()
{
setCaption( i18n( "Gadu-Gadu Public Directory" ) );
mMainWidget = new GaduPublicDirectory( this );
setMainWidget( mMainWidget );
mMainWidget->UIN->setValidChars( "1234567890" );
setButtonText( User1, i18n( "&New Search" ) );
setButtonText( User2, i18n( "S&earch" ) );
setButtonText( User3, i18n( "&Add User..." ) );
setButtonText( Cancel, i18n( "&Close" ) );
showButton( User1, false );
showButton( User3, false );
enableButton( User2, false );
mMainWidget->radioByData->setChecked( true );
mAccount->pubDirSearchClose();
}
void
GaduPublicDir::initConnections()
{
connect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) );
connect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) );
connect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult& ) ),
SLOT( slotSearchResult( const SearchResult& ) ) );
connect( mMainWidget->nameS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->surname, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->nick, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->UIN, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->cityS, SIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->gender, SIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->ageFrom, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->ageTo, SIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );
connect( mMainWidget->radioByData, SIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) );
}
void
GaduPublicDir::inputChanged( bool )
{
inputChanged( QString::null );
}
void
GaduPublicDir::inputChanged( const QString& )
{
if ( validateData() == false ) {
enableButton( User2, false );
}
else {
enableButton( User2, true );
}
}
void
GaduPublicDir::getData()
{
fName = mMainWidget->nameS->text();
fSurname = mMainWidget->surname->text();
fNick = mMainWidget->nick->text();
fUin = mMainWidget->UIN->text().toInt();
fGender = mMainWidget->gender->currentItem();
fOnlyOnline= mMainWidget->onlyOnline->isChecked();
fAgeFrom = mMainWidget->ageFrom->value();
fAgeTo = mMainWidget->ageTo->value();
fCity = mMainWidget->cityS->text();
}
// return true if not empty
#define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } }
#define CHECK_INT(A) { if ( A ) { return true; } }
bool
GaduPublicDir::validateData()
{
getData();
if ( mMainWidget->radioByData->isChecked() ) {
CHECK_STRING( fCity );
CHECK_STRING( fName );
CHECK_STRING( fSurname );
CHECK_STRING( fNick );
CHECK_INT( fGender );
CHECK_INT( fAgeFrom );
CHECK_INT( fAgeTo );
}
else {
CHECK_INT( fUin );
}
return false;
}
// Move to GaduProtocol someday
QPixmap
GaduPublicDir::iconForStatus( uint status )
{
QPixmap n;
if ( GaduProtocol::protocol() ) {
return GaduProtocol::protocol()->convertStatus( status ).protocolIcon();
}
return n;
}
void
GaduPublicDir::slotSearchResult( const SearchResult& result )
{
QListView* list = mMainWidget->listFound;
int i;
kdDebug(14100) << "searchResults(" << result.count() <<")" << endl;
// if not found anything, obviously we don't want to search for more
// if we are looking just for one UIN, don't allow search more - it is pointless
if ( result.count() && fUin==0 ) {
enableButton( User2, true );
}
enableButton( User1, true );
QListViewItem* sl;
SearchResult::const_iterator r;
for ( r = result.begin(); r != result.end() ; ++r ){
kdDebug(14100) << "adding" << (*r).uin << endl;
sl= new QListViewItem(
list, QString::fromAscii(""),
(*r).firstname,
(*r).nickname,
(*r).age,
(*r).city,
(*r).uin
);
sl->setPixmap( 0, iconForStatus( (*r).status ) );
}
}
void
GaduPublicDir::slotNewSearch()
{
mMainWidget->pubsearch->raiseWidget( 0 );
setButtonText( User2, i18n( "S&earch" ) );
showButton( User1, false );
showButton( User3, false );
enableButton( User2, false );
inputChanged( QString::null );
mAccount->pubDirSearchClose();
}
void
GaduPublicDir::slotSearch()
{
mMainWidget->listFound->clear();
QString empty;
// search more, or search ?
if ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) {
kdDebug(14100) << "start search... " << endl;
getData();
// validate data
if ( validateData() == false ) {
return;
}
// go on
mMainWidget->pubsearch->raiseWidget( 1 );
}
else{
kdDebug(14100) << "search more... " << endl;
// Search for more
}
setButtonText( User2, i18n( "Search &More..." ) );
showButton( User3, true );
showButton( User1, true );
enableButton( User3, false );
enableButton( User2, false );
if ( mMainWidget->radioByData->isChecked() ) {
mAccount->pubDirSearch( fName, fSurname, fNick,
0, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );
}
else {
mAccount->pubDirSearch( empty, empty, empty,
fUin, empty, 0, 0, 0, fOnlyOnline );
}
}
#include "gadupubdir.moc"
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Aggregate
*
* 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 "pch.h"
#include "handlers.h"
namespace FastCGI { namespace app { namespace reader {
class LoginPageHandler: public PageHandler
{
public:
std::string name() const
{
return "Login";
}
protected:
virtual bool restrictedPage() { return false; }
const char* getPageTitle(PageTranslation& tr) { return tr(lng::LNG_LOGIN_TITLE); }
void render(SessionPtr session, Request& request, PageTranslation& tr)
{
fcgi::param_t QUERY_STRING = request.getParam("QUERY_STRING");
if (!QUERY_STRING || !*QUERY_STRING)
{
request <<
"łotewah";
request.die();
}
request << "<h1>Reading...</h1>";
request << "<p>Done</p>";
}
};
}}} // FastCGI::app::reader
REGISTER_HANDLER("/auth/login", FastCGI::app::reader::LoginPageHandler);
<commit_msg>Login form<commit_after>/*
* Copyright (C) 2013 Aggregate
*
* 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 "pch.h"
#include "handlers.h"
#include "forms.h"
#include "crypt.hpp"
namespace FastCGI { namespace app { namespace reader {
class AuthPageHandler: public PageHandler
{
protected:
void onAuthFinished(Request& request)
{
param_t _continue = request.getVariable("continue");
if (_continue != nullptr)
request.redirectUrl(_continue);
request.redirect("/");
}
virtual bool restrictedPage() { return false; }
};
class Message: public Control
{
public:
Message(const std::string& name, const std::string&, const std::string& hint)
: Control(name, std::string(), hint)
{
}
virtual void getControlString(Request& request)
{
if (!m_value.empty())
request << "<td></td><td><span class='message'>" << m_value << "</span></td>";
}
void bindUI() {}
};
typedef std::tr1::shared_ptr<Message> MessagePtr;
struct UserInfo
{
long long m_id;
std::string m_name;
std::string m_email;
std::string m_hash;
static UserInfo fromDB(db::ConnectionPtr db, const char* email)
{
UserInfo out;
db::StatementPtr query = db->prepare(
"SELECT _id, name, passphrase "
"FROM user "
"WHERE email=?"
);
if (query.get() && query->bind(0, email))
{
db::CursorPtr c = query->query();
if (c.get() && c->next())
{
out.m_id = c->getLongLong(0);
out.m_name = c->getText(1);
out.m_email = email;
out.m_hash = c->getText(2);
}
}
return out;
}
bool passwordValid(const char* pass)
{
return crypt::verify(pass, m_hash.c_str());
}
};
class LoginPageHandler: public AuthPageHandler
{
public:
std::string name() const
{
return "Login";
}
protected:
virtual bool restrictedPage() { return false; }
void prerender(SessionPtr session, Request& request, PageTranslation& tr)
{
if (request.getVariable("reset") != nullptr)
request.redirect("/auth/reset");
FormPtr content(new (std::nothrow) Form(tr(lng::LNG_LOGIN_TITLE)));
request.setContent(content);
content->hidden("continue");
content->submit("submit", tr(lng::LNG_NAV_SIGNIN));
content->submit("reset", tr(lng::LNG_LOGIN_FORGOT));
Section& section = content->section(std::string());
auto message = section.control<Message>("message");
auto email = section.text("email", tr(lng::LNG_LOGIN_USERNAME), false, tr(lng::LNG_LOGIN_USERNAME_HINT));
auto password = section.text("password", tr(lng::LNG_LOGIN_PASSWORD), true);
auto cookie = section.checkbox("long_cookie", tr(lng::LNG_LOGIN_STAY));
content->bind(request);
bool set_cookie = cookie->isChecked();
if (email->hasUserData() || password->hasUserData())
{
if (!email->hasUserData() || !password->hasUserData())
content->setError(tr(lng::LNG_LOGIN_ERROR_ONE_MISSING));
else
{
UserInfo info = UserInfo::fromDB(request.dbConn(), email->getData().c_str());
if (!info.passwordValid(password->getData().c_str()))
content->setError(tr(lng::LNG_LOGIN_ERROR_MISMATCHED));
else
{
SessionPtr session = request.startSession(set_cookie, email->getData().c_str());
if (session.get())
onAuthFinished(request);
else
request.on500();
}
}
}
else if (request.getVariable("posted") != nullptr)
{
content->setError(tr(lng::LNG_LOGIN_ERROR_ONE_MISSING));
}
else
{
Strings data;
if (session.get())
data["email"] = session->getEmail();
data["message"] = tr(lng::LNG_LOGIN_UI_STALE);
message->bind(request, data);
email->bind(request, data);
}
}
};
}}} // FastCGI::app::reader
REGISTER_HANDLER("/auth/login", FastCGI::app::reader::LoginPageHandler);
<|endoftext|>
|
<commit_before>/*
* Unix Command Execution
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/unix_cmd.h>
#include <botan/parsing.h>
#include <botan/exceptn.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
namespace Botan {
namespace {
/**
* Attempt to execute the command
*/
void do_exec(const std::vector<std::string>& arg_list,
const std::vector<std::string>& paths)
{
const u32bit args = arg_list.size() - 1;
const char* arg1 = (args >= 1) ? arg_list[1].c_str() : 0;
const char* arg2 = (args >= 2) ? arg_list[2].c_str() : 0;
const char* arg3 = (args >= 3) ? arg_list[3].c_str() : 0;
const char* arg4 = (args >= 4) ? arg_list[4].c_str() : 0;
for(u32bit j = 0; j != paths.size(); j++)
{
const std::string full_path = paths[j] + "/" + arg_list[0];
const char* fsname = full_path.c_str();
::execl(fsname, fsname, arg1, arg2, arg3, arg4, NULL);
}
}
}
/**
* Local information about the pipe
*/
struct pipe_wrapper
{
int fd;
pid_t pid;
pipe_wrapper() { fd = -1; pid = 0; }
};
/**
* Read from the pipe
*/
u32bit DataSource_Command::read(byte buf[], u32bit length)
{
if(end_of_data())
return 0;
fd_set set;
FD_ZERO(&set);
FD_SET(pipe->fd, &set);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = MAX_BLOCK_USECS;
ssize_t got = 0;
if(::select(pipe->fd + 1, &set, 0, 0, &tv) == 1)
{
if(FD_ISSET(pipe->fd, &set))
got = ::read(pipe->fd, buf, length);
}
if(got <= 0)
{
shutdown_pipe();
return 0;
}
return static_cast<u32bit>(got);
}
/**
* Peek at the pipe contents
*/
u32bit DataSource_Command::peek(byte[], u32bit, u32bit) const
{
if(end_of_data())
throw Invalid_State("DataSource_Command: Cannot peek when out of data");
throw Stream_IO_Error("Cannot peek/seek on a command pipe");
}
/**
* Check if we reached EOF
*/
bool DataSource_Command::end_of_data() const
{
return (pipe) ? false : true;
}
/**
* Return the Unix file descriptor of the pipe
*/
int DataSource_Command::fd() const
{
if(!pipe)
return -1;
return pipe->fd;
}
/**
* Return a human-readable ID for this stream
*/
std::string DataSource_Command::id() const
{
return "Unix command: " + arg_list[0];
}
/**
* Create the pipe
*/
void DataSource_Command::create_pipe(const std::vector<std::string>& paths)
{
bool found_something = false;
for(u32bit j = 0; j != paths.size(); j++)
{
const std::string full_path = paths[j] + "/" + arg_list[0];
if(::access(full_path.c_str(), X_OK) == 0)
{
found_something = true;
break;
}
}
if(!found_something)
return;
int pipe_fd[2];
if(::pipe(pipe_fd) != 0)
return;
pid_t pid = ::fork();
if(pid == -1)
{
::close(pipe_fd[0]);
::close(pipe_fd[1]);
}
else if(pid > 0)
{
pipe = new pipe_wrapper;
pipe->fd = pipe_fd[0];
pipe->pid = pid;
::close(pipe_fd[1]);
}
else
{
if(dup2(pipe_fd[1], STDOUT_FILENO) == -1)
::exit(127);
if(close(pipe_fd[0]) != 0 || close(pipe_fd[1]) != 0)
::exit(127);
if(close(STDERR_FILENO) != 0)
::exit(127);
do_exec(arg_list, paths);
::exit(127);
}
}
/**
* Shutdown the pipe
*/
void DataSource_Command::shutdown_pipe()
{
if(pipe)
{
pid_t reaped = waitpid(pipe->pid, 0, WNOHANG);
if(reaped == 0)
{
kill(pipe->pid, SIGTERM);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = KILL_WAIT;
select(0, 0, 0, 0, &tv);
reaped = ::waitpid(pipe->pid, 0, WNOHANG);
if(reaped == 0)
{
::kill(pipe->pid, SIGKILL);
do
reaped = ::waitpid(pipe->pid, 0, 0);
while(reaped == -1);
}
}
::close(pipe->fd);
delete pipe;
pipe = 0;
}
}
/**
* DataSource_Command Constructor
*/
DataSource_Command::DataSource_Command(const std::string& prog_and_args,
const std::vector<std::string>& paths) :
MAX_BLOCK_USECS(100000), KILL_WAIT(10000)
{
arg_list = split_on(prog_and_args, ' ');
if(arg_list.size() == 0)
throw Invalid_Argument("DataSource_Command: No command given");
if(arg_list.size() > 5)
throw Invalid_Argument("DataSource_Command: Too many args");
pipe = 0;
create_pipe(paths);
}
/**
* DataSource_Command Destructor
*/
DataSource_Command::~DataSource_Command()
{
if(!end_of_data())
shutdown_pipe();
}
}
<commit_msg>Add constructor and destructor for pipe_wrapper to handle init and close<commit_after>/*
* Unix Command Execution
* (C) 1999-2007 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/internal/unix_cmd.h>
#include <botan/parsing.h>
#include <botan/exceptn.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
namespace Botan {
namespace {
/**
* Attempt to execute the command
*/
void do_exec(const std::vector<std::string>& arg_list,
const std::vector<std::string>& paths)
{
const u32bit args = arg_list.size() - 1;
const char* arg1 = (args >= 1) ? arg_list[1].c_str() : 0;
const char* arg2 = (args >= 2) ? arg_list[2].c_str() : 0;
const char* arg3 = (args >= 3) ? arg_list[3].c_str() : 0;
const char* arg4 = (args >= 4) ? arg_list[4].c_str() : 0;
for(u32bit j = 0; j != paths.size(); j++)
{
const std::string full_path = paths[j] + "/" + arg_list[0];
const char* fsname = full_path.c_str();
::execl(fsname, fsname, arg1, arg2, arg3, arg4, NULL);
}
}
}
/**
* Local information about the pipe
*/
struct pipe_wrapper
{
int fd;
pid_t pid;
pipe_wrapper(int f, pid_t p) : fd(f), pid(p) {}
~pipe_wrapper() { ::close(fd); }
};
/**
* Read from the pipe
*/
u32bit DataSource_Command::read(byte buf[], u32bit length)
{
if(end_of_data())
return 0;
fd_set set;
FD_ZERO(&set);
FD_SET(pipe->fd, &set);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = MAX_BLOCK_USECS;
ssize_t got = 0;
if(::select(pipe->fd + 1, &set, 0, 0, &tv) == 1)
{
if(FD_ISSET(pipe->fd, &set))
got = ::read(pipe->fd, buf, length);
}
if(got <= 0)
{
shutdown_pipe();
return 0;
}
return static_cast<u32bit>(got);
}
/**
* Peek at the pipe contents
*/
u32bit DataSource_Command::peek(byte[], u32bit, u32bit) const
{
if(end_of_data())
throw Invalid_State("DataSource_Command: Cannot peek when out of data");
throw Stream_IO_Error("Cannot peek/seek on a command pipe");
}
/**
* Check if we reached EOF
*/
bool DataSource_Command::end_of_data() const
{
return (pipe) ? false : true;
}
/**
* Return the Unix file descriptor of the pipe
*/
int DataSource_Command::fd() const
{
if(!pipe)
return -1;
return pipe->fd;
}
/**
* Return a human-readable ID for this stream
*/
std::string DataSource_Command::id() const
{
return "Unix command: " + arg_list[0];
}
/**
* Create the pipe
*/
void DataSource_Command::create_pipe(const std::vector<std::string>& paths)
{
bool found_something = false;
for(u32bit j = 0; j != paths.size(); j++)
{
const std::string full_path = paths[j] + "/" + arg_list[0];
if(::access(full_path.c_str(), X_OK) == 0)
{
found_something = true;
break;
}
}
if(!found_something)
return;
int pipe_fd[2];
if(::pipe(pipe_fd) != 0)
return;
pid_t pid = ::fork();
if(pid == -1)
{
::close(pipe_fd[0]);
::close(pipe_fd[1]);
}
else if(pid > 0)
{
pipe = new pipe_wrapper(pipe_fd[0], pid);
::close(pipe_fd[1]);
}
else
{
if(dup2(pipe_fd[1], STDOUT_FILENO) == -1)
::exit(127);
if(close(pipe_fd[0]) != 0 || close(pipe_fd[1]) != 0)
::exit(127);
if(close(STDERR_FILENO) != 0)
::exit(127);
do_exec(arg_list, paths);
::exit(127);
}
}
/**
* Shutdown the pipe
*/
void DataSource_Command::shutdown_pipe()
{
if(pipe)
{
pid_t reaped = waitpid(pipe->pid, 0, WNOHANG);
if(reaped == 0)
{
kill(pipe->pid, SIGTERM);
struct ::timeval tv;
tv.tv_sec = 0;
tv.tv_usec = KILL_WAIT;
select(0, 0, 0, 0, &tv);
reaped = ::waitpid(pipe->pid, 0, WNOHANG);
if(reaped == 0)
{
::kill(pipe->pid, SIGKILL);
do
reaped = ::waitpid(pipe->pid, 0, 0);
while(reaped == -1);
}
}
delete pipe;
pipe = 0;
}
}
/**
* DataSource_Command Constructor
*/
DataSource_Command::DataSource_Command(const std::string& prog_and_args,
const std::vector<std::string>& paths) :
MAX_BLOCK_USECS(100000), KILL_WAIT(10000)
{
arg_list = split_on(prog_and_args, ' ');
if(arg_list.size() == 0)
throw Invalid_Argument("DataSource_Command: No command given");
if(arg_list.size() > 5)
throw Invalid_Argument("DataSource_Command: Too many args");
pipe = 0;
create_pipe(paths);
}
/**
* DataSource_Command Destructor
*/
DataSource_Command::~DataSource_Command()
{
if(!end_of_data())
shutdown_pipe();
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
test_map_random.cpp - description
-------------------
begin : Mon Feb 14 2005
copyright : (C) 2005 by Thomas Nowak
email : t.nowak@imail.de
fixed by : Roman Dementiev (01.03.2006)
***************************************************************************/
//! \file containers/test_map_random.cpp
//! \brief File for testing functionality of stxxl::map.
#include <stxxl>
#include "map_test_handlers.h"
//! \example containers/map/test_map_random.cpp
//! This is an example of use of \c stxxl::map container.
typedef int key_type;
typedef int data_type;
struct cmp2 : public std::less<int>
{
static int max_value() { return (std::numeric_limits<int>::max)(); }
};
#define DATA_NODE_BLOCK_SIZE (4096)
#define DATA_LEAF_BLOCK_SIZE (4096)
typedef std::map<key_type,data_type,cmp2> std_map_type;
typedef stxxl::map<key_type,data_type,cmp2,
DATA_NODE_BLOCK_SIZE,DATA_LEAF_BLOCK_SIZE > xxl_map_type;
#define PERCENT_CLEAR 1
#define PERCENT_ERASE_BULK 9
#define PERCENT_ERASE_KEY 90
#define PERCENT_ERASE_ITERATOR 100
#define PERCENT_INSERT_PAIR 100
#define PERCENT_INSERT_BULK 100
#define PERCENT_SIZING 100
#define PERCENT_LOWER 100
#define PERCENT_UPPER 200
#define PERCENT_FIND 100
#define PERCENT_ITERATOR 100
//#define MAX_KEY 1000
#define MAX_KEY 10000
//#define MAX_STEP 0x0001000
#define NODE_BLOCK_SIZE xxl_map_type::node_block_type::raw_size
#define LEAF_BLOCK_SIZE xxl_map_type::leaf_block_type::raw_size
#define NODE_MELEMENTS xxl_map_type::node_block_type::size
#define LEAF_MELEMENTS xxl_map_type::leaf_block_type::size
int main( int argc, char* argv[] )
{
#ifdef NDEBUG
STXXL_MSG("Program is compiled with NDEBUG option, which makes the testing wrong.")
return 1;
#endif
typedef std::vector<std::pair<key_type,data_type> > vector_type;
STXXL_MSG("Node block size: "<<NODE_BLOCK_SIZE<<" bytes")
STXXL_MSG("Leaf block size: "<<LEAF_BLOCK_SIZE<<" bytes")
STXXL_MSG("Node max elements: "<<NODE_MELEMENTS)
STXXL_MSG("Leaf max elements: "<<LEAF_MELEMENTS)
stxxl::random_number32 rnd;
//stxxl::ran32State = 1141225706;
STXXL_MSG("Init random seed: "<<stxxl::ran32State)
int a = (PERCENT_CLEAR +
PERCENT_SIZING +
PERCENT_ERASE_BULK +
PERCENT_ERASE_KEY +
PERCENT_ERASE_ITERATOR +
PERCENT_INSERT_PAIR +
PERCENT_INSERT_BULK +
PERCENT_LOWER +
PERCENT_UPPER +
PERCENT_FIND +
PERCENT_ITERATOR);
assert(a == 1000);
if(argc < 2)
{
STXXL_MSG("Usage: "<<argv[0]<<" STEP ")
STXXL_MSG("Note, that STEP must be > 1000")
return 0;
}
stxxl::uint64 MAX_STEP = atoi( argv[1] );
assert(MAX_STEP > 1000);
std_map_type stdmap;
xxl_map_type xxlmap(NODE_BLOCK_SIZE*4,LEAF_BLOCK_SIZE*3);
for( stxxl::uint64 i = 0; i < MAX_STEP; i++ )
{
// ***************************************************
// A random number is created to determine which kind
// of operation we will be called.
// ***************************************************
long step = rnd() % 1000;
int percent = 0;
if( i % (MAX_STEP/1000) == 0 )
{
STXXL_MSG( "*****************************************************" );
STXXL_MSG( "Step=" << i << " (" << (unsigned) stdmap.size() << ")" );
}
// *********************************************************
// The clear function will be called
// *********************************************************
if( step < (percent += PERCENT_CLEAR) )
{
if( (unsigned) rand() % 1000 < stdmap.size() )
{
stdmap.clear();
xxlmap.clear();
assert( stdmap.empty() );
assert( xxlmap.empty() );
}
}
// *********************************************************
// The size function will be called
// *********************************************************
else if ( step < (percent += PERCENT_SIZING) )
{
std_map_type::size_type size1 = stdmap.size();
xxl_map_type::size_type size2 = xxlmap.size();
assert( size1 == size2 );
}
// *********************************************************
// The erase range function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_BULK) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
stdmap.erase( stdmap.lower_bound(key1), stdmap.upper_bound(key2) );
xxlmap.erase( xxlmap.lower_bound(key1), xxlmap.upper_bound(key2) );
assert(stdmap.size() == xxlmap.size());
assert( stdmap.lower_bound( key1 ) == stdmap.end() ||
stdmap.lower_bound( key1 ) == stdmap.upper_bound(key2) );
assert( xxlmap.lower_bound( key1 ) == xxlmap.end() ||
xxlmap.lower_bound( key1 ) == xxlmap.upper_bound(key2) );
}
// *********************************************************
// The erase a key function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_KEY) )
{
key_type key = rnd() % MAX_KEY;
stdmap.erase( key );
xxlmap.erase( key );
assert( not_there( stdmap, key ));
assert( not_there( xxlmap, key ));
}
// *********************************************************
// The erase function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_ITERATOR) )
{
key_type key = rnd() % MAX_KEY;
std_map_type::iterator stditer = stdmap.find( key );
xxl_map_type::iterator xxliter = xxlmap.find( key );
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if( stditer != stdmap.end() ) stdmap.erase( stditer );
if( xxliter != xxlmap.end() ) xxlmap.erase( xxliter );
assert( not_there( stdmap, key ));
assert( not_there( xxlmap, key ));
}
// *********************************************************
// The insert function will be called
// *********************************************************
else if ( step < (percent += PERCENT_INSERT_PAIR) )
{
key_type key = rnd() % MAX_KEY;
stdmap.insert( std::pair<key_type,data_type>( key, 2*key ) );
xxlmap.insert( std::pair<key_type,data_type>( key, 2*key ) );
assert( there( stdmap, key, 2*key ));
assert( there( xxlmap, key, 2*key ));
}
// *********************************************************
// The bulk insert function will be called
// *********************************************************
else if ( step < (percent += PERCENT_INSERT_BULK) )
{
unsigned lower = rnd() % MAX_KEY;
unsigned upper = rnd() % MAX_KEY;
if( lower > upper )
std::swap(lower,upper);
vector_type v2( upper-lower );
for( unsigned j = 0; j < (unsigned)(upper - lower); j++)
{
v2[j].first = lower + j;
v2[j].second = 2*v2[j].first;
}
stdmap.insert( v2.begin(), v2.end() );
xxlmap.insert( v2.begin(), v2.end() );
for( unsigned i = lower; i < upper; i++ ) assert( there( stdmap, i, 2*i ));
for( unsigned i = lower; i < upper; i++ ) assert( there( xxlmap, i, 2*i ));
}
// *********************************************************
// The lower_bound function will be called
// *********************************************************
else if ( step < (percent += PERCENT_LOWER) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.lower_bound(key1);
xxl_map_type::iterator xxliter = xxlmap.lower_bound(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert(is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The upper_bound function will be called
// *********************************************************
else if ( step < (percent += PERCENT_UPPER) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.upper_bound(key1);
xxl_map_type::iterator xxliter = xxlmap.upper_bound(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The find function will be called
// *********************************************************
else if ( step < (percent += PERCENT_FIND) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.find(key1);
xxl_map_type::iterator xxliter = xxlmap.find(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The iterate functions will be called
// *********************************************************
else if ( step < (percent += PERCENT_ITERATOR) )
{
std_map_type::const_iterator siter1 = stdmap.begin();
xxl_map_type::const_iterator xiter1 = xxlmap.begin();
std_map_type::const_iterator siter2 = siter1;
xxl_map_type::const_iterator xiter2 = xiter1;
while( siter1 != stdmap.end() )
{
assert( xiter1 != xxlmap.end() );
assert( is_same( *(siter1++), *(xiter1++) ) );
if(siter1 != stdmap.end()) { assert( !is_same( *siter1, *siter2 ) ); }
if(xiter1 != xxlmap.end()) { assert( !is_same( *xiter1, *xiter2 ) ); }
}
assert( xiter1 == xxlmap.end() );
assert( siter2 == stdmap.begin() );
assert( xiter2 == xxlmap.begin() );
}
}
return 0;
}
<commit_msg>test file names in doxy are changed<commit_after>/***************************************************************************
test_map_random.cpp - description
-------------------
begin : Mon Feb 14 2005
copyright : (C) 2005 by Thomas Nowak
email : t.nowak@imail.de
fixed by : Roman Dementiev (01.03.2006)
***************************************************************************/
//! \file containers/test_map_random.cpp
//! \brief File for testing functionality of stxxl::map.
#include <stxxl>
#include "map_test_handlers.h"
//! \example containers/test_map_random.cpp
//! This is an example of use of \c stxxl::map container.
typedef int key_type;
typedef int data_type;
struct cmp2 : public std::less<int>
{
static int max_value() { return (std::numeric_limits<int>::max)(); }
};
#define DATA_NODE_BLOCK_SIZE (4096)
#define DATA_LEAF_BLOCK_SIZE (4096)
typedef std::map<key_type,data_type,cmp2> std_map_type;
typedef stxxl::map<key_type,data_type,cmp2,
DATA_NODE_BLOCK_SIZE,DATA_LEAF_BLOCK_SIZE > xxl_map_type;
#define PERCENT_CLEAR 1
#define PERCENT_ERASE_BULK 9
#define PERCENT_ERASE_KEY 90
#define PERCENT_ERASE_ITERATOR 100
#define PERCENT_INSERT_PAIR 100
#define PERCENT_INSERT_BULK 100
#define PERCENT_SIZING 100
#define PERCENT_LOWER 100
#define PERCENT_UPPER 200
#define PERCENT_FIND 100
#define PERCENT_ITERATOR 100
//#define MAX_KEY 1000
#define MAX_KEY 10000
//#define MAX_STEP 0x0001000
#define NODE_BLOCK_SIZE xxl_map_type::node_block_type::raw_size
#define LEAF_BLOCK_SIZE xxl_map_type::leaf_block_type::raw_size
#define NODE_MELEMENTS xxl_map_type::node_block_type::size
#define LEAF_MELEMENTS xxl_map_type::leaf_block_type::size
int main( int argc, char* argv[] )
{
#ifdef NDEBUG
STXXL_MSG("Program is compiled with NDEBUG option, which makes the testing wrong.")
return 1;
#endif
typedef std::vector<std::pair<key_type,data_type> > vector_type;
STXXL_MSG("Node block size: "<<NODE_BLOCK_SIZE<<" bytes")
STXXL_MSG("Leaf block size: "<<LEAF_BLOCK_SIZE<<" bytes")
STXXL_MSG("Node max elements: "<<NODE_MELEMENTS)
STXXL_MSG("Leaf max elements: "<<LEAF_MELEMENTS)
stxxl::random_number32 rnd;
//stxxl::ran32State = 1141225706;
STXXL_MSG("Init random seed: "<<stxxl::ran32State)
int a = (PERCENT_CLEAR +
PERCENT_SIZING +
PERCENT_ERASE_BULK +
PERCENT_ERASE_KEY +
PERCENT_ERASE_ITERATOR +
PERCENT_INSERT_PAIR +
PERCENT_INSERT_BULK +
PERCENT_LOWER +
PERCENT_UPPER +
PERCENT_FIND +
PERCENT_ITERATOR);
assert(a == 1000);
if(argc < 2)
{
STXXL_MSG("Usage: "<<argv[0]<<" STEP ")
STXXL_MSG("Note, that STEP must be > 1000")
return 0;
}
stxxl::uint64 MAX_STEP = atoi( argv[1] );
assert(MAX_STEP > 1000);
std_map_type stdmap;
xxl_map_type xxlmap(NODE_BLOCK_SIZE*4,LEAF_BLOCK_SIZE*3);
for( stxxl::uint64 i = 0; i < MAX_STEP; i++ )
{
// ***************************************************
// A random number is created to determine which kind
// of operation we will be called.
// ***************************************************
long step = rnd() % 1000;
int percent = 0;
if( i % (MAX_STEP/1000) == 0 )
{
STXXL_MSG( "*****************************************************" );
STXXL_MSG( "Step=" << i << " (" << (unsigned) stdmap.size() << ")" );
}
// *********************************************************
// The clear function will be called
// *********************************************************
if( step < (percent += PERCENT_CLEAR) )
{
if( (unsigned) rand() % 1000 < stdmap.size() )
{
stdmap.clear();
xxlmap.clear();
assert( stdmap.empty() );
assert( xxlmap.empty() );
}
}
// *********************************************************
// The size function will be called
// *********************************************************
else if ( step < (percent += PERCENT_SIZING) )
{
std_map_type::size_type size1 = stdmap.size();
xxl_map_type::size_type size2 = xxlmap.size();
assert( size1 == size2 );
}
// *********************************************************
// The erase range function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_BULK) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
stdmap.erase( stdmap.lower_bound(key1), stdmap.upper_bound(key2) );
xxlmap.erase( xxlmap.lower_bound(key1), xxlmap.upper_bound(key2) );
assert(stdmap.size() == xxlmap.size());
assert( stdmap.lower_bound( key1 ) == stdmap.end() ||
stdmap.lower_bound( key1 ) == stdmap.upper_bound(key2) );
assert( xxlmap.lower_bound( key1 ) == xxlmap.end() ||
xxlmap.lower_bound( key1 ) == xxlmap.upper_bound(key2) );
}
// *********************************************************
// The erase a key function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_KEY) )
{
key_type key = rnd() % MAX_KEY;
stdmap.erase( key );
xxlmap.erase( key );
assert( not_there( stdmap, key ));
assert( not_there( xxlmap, key ));
}
// *********************************************************
// The erase function will be called
// *********************************************************
else if ( step < (percent += PERCENT_ERASE_ITERATOR) )
{
key_type key = rnd() % MAX_KEY;
std_map_type::iterator stditer = stdmap.find( key );
xxl_map_type::iterator xxliter = xxlmap.find( key );
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if( stditer != stdmap.end() ) stdmap.erase( stditer );
if( xxliter != xxlmap.end() ) xxlmap.erase( xxliter );
assert( not_there( stdmap, key ));
assert( not_there( xxlmap, key ));
}
// *********************************************************
// The insert function will be called
// *********************************************************
else if ( step < (percent += PERCENT_INSERT_PAIR) )
{
key_type key = rnd() % MAX_KEY;
stdmap.insert( std::pair<key_type,data_type>( key, 2*key ) );
xxlmap.insert( std::pair<key_type,data_type>( key, 2*key ) );
assert( there( stdmap, key, 2*key ));
assert( there( xxlmap, key, 2*key ));
}
// *********************************************************
// The bulk insert function will be called
// *********************************************************
else if ( step < (percent += PERCENT_INSERT_BULK) )
{
unsigned lower = rnd() % MAX_KEY;
unsigned upper = rnd() % MAX_KEY;
if( lower > upper )
std::swap(lower,upper);
vector_type v2( upper-lower );
for( unsigned j = 0; j < (unsigned)(upper - lower); j++)
{
v2[j].first = lower + j;
v2[j].second = 2*v2[j].first;
}
stdmap.insert( v2.begin(), v2.end() );
xxlmap.insert( v2.begin(), v2.end() );
for( unsigned i = lower; i < upper; i++ ) assert( there( stdmap, i, 2*i ));
for( unsigned i = lower; i < upper; i++ ) assert( there( xxlmap, i, 2*i ));
}
// *********************************************************
// The lower_bound function will be called
// *********************************************************
else if ( step < (percent += PERCENT_LOWER) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.lower_bound(key1);
xxl_map_type::iterator xxliter = xxlmap.lower_bound(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert(is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The upper_bound function will be called
// *********************************************************
else if ( step < (percent += PERCENT_UPPER) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.upper_bound(key1);
xxl_map_type::iterator xxliter = xxlmap.upper_bound(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The find function will be called
// *********************************************************
else if ( step < (percent += PERCENT_FIND) )
{
key_type key1 = rand() % MAX_KEY;
key_type key2 = rand() % MAX_KEY;
if( key1 > key2 )
{
std::swap(key1,key2);
}
while( key1 < key2 )
{
std_map_type::iterator stditer = stdmap.find(key1);
xxl_map_type::iterator xxliter = xxlmap.find(key1);
assert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));
if(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }
key1++;
}
}
// *********************************************************
// The iterate functions will be called
// *********************************************************
else if ( step < (percent += PERCENT_ITERATOR) )
{
std_map_type::const_iterator siter1 = stdmap.begin();
xxl_map_type::const_iterator xiter1 = xxlmap.begin();
std_map_type::const_iterator siter2 = siter1;
xxl_map_type::const_iterator xiter2 = xiter1;
while( siter1 != stdmap.end() )
{
assert( xiter1 != xxlmap.end() );
assert( is_same( *(siter1++), *(xiter1++) ) );
if(siter1 != stdmap.end()) { assert( !is_same( *siter1, *siter2 ) ); }
if(xiter1 != xxlmap.end()) { assert( !is_same( *xiter1, *xiter2 ) ); }
}
assert( xiter1 == xxlmap.end() );
assert( siter2 == stdmap.begin() );
assert( xiter2 == xxlmap.begin() );
}
}
return 0;
}
<|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 <boost/algorithm/string.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include "postgis.hpp"
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::trim;
using std::string;
postgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs,
std::string const& encoding,
unsigned num_attrs=0)
: rs_(rs),
num_attrs_(num_attrs),
totalGeomSize_(0),
tr_(new transcoder(encoding)),
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==25 || oid==1042 || oid==1043) // text or bpchar or varchar
{
std::string str(buf);
trim(str);
std::wstring wstr = tr_->transcode(str);
boost::put(*feature,name,wstr);
}
else
{
#ifdef MAPNIK_DEBUG
std::clog << "uknown OID = " << oid << " FIXME \n";
#endif
//boost::put(*feature,name,0);
}
}
++count_;
}
return feature;
}
else
{
rs_->close();
return feature_ptr();
}
}
postgis_featureset::~postgis_featureset()
{
rs_->close();
}
<commit_msg>corrected members init order<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 <boost/algorithm/string.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include "postgis.hpp"
using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::trim;
using std::string;
postgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs,
std::string const& encoding,
unsigned num_attrs=0)
: rs_(rs),
num_attrs_(num_attrs),
tr_(new transcoder(encoding)),
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==25 || oid==1042 || oid==1043) // text or bpchar or varchar
{
std::string str(buf);
trim(str);
std::wstring wstr = tr_->transcode(str);
boost::put(*feature,name,wstr);
}
else
{
#ifdef MAPNIK_DEBUG
std::clog << "uknown OID = " << oid << " FIXME \n";
#endif
//boost::put(*feature,name,0);
}
}
++count_;
}
return feature;
}
else
{
rs_->close();
return feature_ptr();
}
}
postgis_featureset::~postgis_featureset()
{
rs_->close();
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2011 Intel Corporation
*
* 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.
*/
/* This file declares stripped-down versions of functions that
* normally exist outside of the glsl folder, so that they can be used
* when running the GLSL compiler standalone (for unit testing or
* compiling builtins).
*/
#include "standalone_scaffolding.h"
#include <assert.h>
#include <string.h>
#include <limits.h>
#include "util/ralloc.h"
void
_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
struct gl_shader *sh)
{
(void) ctx;
*ptr = sh;
}
void
_mesa_shader_debug(struct gl_context *, GLenum, GLuint *id,
const char *, int)
{
}
extern "C" void
_mesa_error_no_memory(const char *caller)
{
}
struct gl_shader *
_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)
{
struct gl_shader *shader;
(void) ctx;
assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);
shader = rzalloc(NULL, struct gl_shader);
if (shader) {
shader->Type = type;
shader->Stage = _mesa_shader_enum_to_shader_stage(type);
shader->Name = name;
shader->RefCount = 1;
}
return shader;
}
void initialize_context_to_defaults(struct gl_context *ctx, gl_api api)
{
memset(ctx, 0, sizeof(*ctx));
ctx->API = api;
ctx->Extensions.dummy_false = false;
ctx->Extensions.dummy_true = true;
ctx->Extensions.ARB_compute_shader = true;
ctx->Extensions.ARB_conservative_depth = true;
ctx->Extensions.ARB_draw_instanced = true;
ctx->Extensions.ARB_ES2_compatibility = true;
ctx->Extensions.ARB_ES3_compatibility = true;
ctx->Extensions.ARB_explicit_attrib_location = true;
ctx->Extensions.ARB_fragment_coord_conventions = true;
ctx->Extensions.ARB_fragment_layer_viewport = true;
ctx->Extensions.ARB_gpu_shader5 = true;
ctx->Extensions.ARB_sample_shading = true;
ctx->Extensions.ARB_shader_bit_encoding = true;
ctx->Extensions.ARB_shader_stencil_export = true;
ctx->Extensions.ARB_shader_texture_lod = true;
ctx->Extensions.ARB_shading_language_420pack = true;
ctx->Extensions.ARB_shading_language_packing = true;
ctx->Extensions.ARB_texture_cube_map_array = true;
ctx->Extensions.ARB_texture_gather = true;
ctx->Extensions.ARB_texture_multisample = true;
ctx->Extensions.ARB_texture_query_levels = true;
ctx->Extensions.ARB_texture_query_lod = true;
ctx->Extensions.ARB_uniform_buffer_object = true;
ctx->Extensions.ARB_viewport_array = true;
ctx->Extensions.OES_EGL_image_external = true;
ctx->Extensions.OES_standard_derivatives = true;
ctx->Extensions.EXT_shader_integer_mix = true;
ctx->Extensions.EXT_texture3D = true;
ctx->Extensions.EXT_texture_array = true;
ctx->Extensions.EXT_draw_buffers = true;
ctx->Extensions.NV_texture_rectangle = true;
ctx->Const.GLSLVersion = 120;
/* 1.20 minimums. */
ctx->Const.MaxLights = 8;
ctx->Const.MaxClipPlanes = 6;
ctx->Const.MaxTextureUnits = 2;
ctx->Const.MaxTextureCoordUnits = 2;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs = 16;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents = 512;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 32;
ctx->Const.MaxVarying = 8; /* == gl_MaxVaryingFloats / 4 */
ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = 0;
ctx->Const.MaxCombinedTextureImageUnits = 2;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = 2;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents = 64;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 32;
ctx->Const.MaxDrawBuffers = 1;
ctx->Const.MaxComputeWorkGroupCount[0] = 65535;
ctx->Const.MaxComputeWorkGroupCount[1] = 65535;
ctx->Const.MaxComputeWorkGroupCount[2] = 65535;
ctx->Const.MaxComputeWorkGroupSize[0] = 1024;
ctx->Const.MaxComputeWorkGroupSize[1] = 1024;
ctx->Const.MaxComputeWorkGroupSize[2] = 64;
ctx->Const.MaxComputeWorkGroupInvocations = 1024;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits = 16;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents = 1024;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxInputComponents = 0; /* not used */
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxOutputComponents = 0; /* not used */
/* Set up default shader compiler options. */
struct gl_shader_compiler_options options;
memset(&options, 0, sizeof(options));
options.MaxUnrollIterations = 32;
options.MaxIfDepth = UINT_MAX;
/* Default pragma settings */
options.DefaultPragmas.Optimize = true;
for (int sh = 0; sh < MESA_SHADER_STAGES; ++sh)
memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
}
<commit_msg>postmerge: temporarily revert max unroll iterations to previous default value (8)<commit_after>/*
* Copyright © 2011 Intel Corporation
*
* 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.
*/
/* This file declares stripped-down versions of functions that
* normally exist outside of the glsl folder, so that they can be used
* when running the GLSL compiler standalone (for unit testing or
* compiling builtins).
*/
#include "standalone_scaffolding.h"
#include <assert.h>
#include <string.h>
#include <limits.h>
#include "util/ralloc.h"
void
_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
struct gl_shader *sh)
{
(void) ctx;
*ptr = sh;
}
void
_mesa_shader_debug(struct gl_context *, GLenum, GLuint *id,
const char *, int)
{
}
extern "C" void
_mesa_error_no_memory(const char *caller)
{
}
struct gl_shader *
_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)
{
struct gl_shader *shader;
(void) ctx;
assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);
shader = rzalloc(NULL, struct gl_shader);
if (shader) {
shader->Type = type;
shader->Stage = _mesa_shader_enum_to_shader_stage(type);
shader->Name = name;
shader->RefCount = 1;
}
return shader;
}
void initialize_context_to_defaults(struct gl_context *ctx, gl_api api)
{
memset(ctx, 0, sizeof(*ctx));
ctx->API = api;
ctx->Extensions.dummy_false = false;
ctx->Extensions.dummy_true = true;
ctx->Extensions.ARB_compute_shader = true;
ctx->Extensions.ARB_conservative_depth = true;
ctx->Extensions.ARB_draw_instanced = true;
ctx->Extensions.ARB_ES2_compatibility = true;
ctx->Extensions.ARB_ES3_compatibility = true;
ctx->Extensions.ARB_explicit_attrib_location = true;
ctx->Extensions.ARB_fragment_coord_conventions = true;
ctx->Extensions.ARB_fragment_layer_viewport = true;
ctx->Extensions.ARB_gpu_shader5 = true;
ctx->Extensions.ARB_sample_shading = true;
ctx->Extensions.ARB_shader_bit_encoding = true;
ctx->Extensions.ARB_shader_stencil_export = true;
ctx->Extensions.ARB_shader_texture_lod = true;
ctx->Extensions.ARB_shading_language_420pack = true;
ctx->Extensions.ARB_shading_language_packing = true;
ctx->Extensions.ARB_texture_cube_map_array = true;
ctx->Extensions.ARB_texture_gather = true;
ctx->Extensions.ARB_texture_multisample = true;
ctx->Extensions.ARB_texture_query_levels = true;
ctx->Extensions.ARB_texture_query_lod = true;
ctx->Extensions.ARB_uniform_buffer_object = true;
ctx->Extensions.ARB_viewport_array = true;
ctx->Extensions.OES_EGL_image_external = true;
ctx->Extensions.OES_standard_derivatives = true;
ctx->Extensions.EXT_shader_integer_mix = true;
ctx->Extensions.EXT_texture3D = true;
ctx->Extensions.EXT_texture_array = true;
ctx->Extensions.EXT_draw_buffers = true;
ctx->Extensions.NV_texture_rectangle = true;
ctx->Const.GLSLVersion = 120;
/* 1.20 minimums. */
ctx->Const.MaxLights = 8;
ctx->Const.MaxClipPlanes = 6;
ctx->Const.MaxTextureUnits = 2;
ctx->Const.MaxTextureCoordUnits = 2;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs = 16;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents = 512;
ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 32;
ctx->Const.MaxVarying = 8; /* == gl_MaxVaryingFloats / 4 */
ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = 0;
ctx->Const.MaxCombinedTextureImageUnits = 2;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = 2;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents = 64;
ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 32;
ctx->Const.MaxDrawBuffers = 1;
ctx->Const.MaxComputeWorkGroupCount[0] = 65535;
ctx->Const.MaxComputeWorkGroupCount[1] = 65535;
ctx->Const.MaxComputeWorkGroupCount[2] = 65535;
ctx->Const.MaxComputeWorkGroupSize[0] = 1024;
ctx->Const.MaxComputeWorkGroupSize[1] = 1024;
ctx->Const.MaxComputeWorkGroupSize[2] = 64;
ctx->Const.MaxComputeWorkGroupInvocations = 1024;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits = 16;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents = 1024;
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxInputComponents = 0; /* not used */
ctx->Const.Program[MESA_SHADER_COMPUTE].MaxOutputComponents = 0; /* not used */
/* Set up default shader compiler options. */
struct gl_shader_compiler_options options;
memset(&options, 0, sizeof(options));
options.MaxUnrollIterations = 8;
options.MaxIfDepth = UINT_MAX;
/* Default pragma settings */
options.DefaultPragmas.Optimize = true;
for (int sh = 0; sh < MESA_SHADER_STAGES; ++sh)
memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2019, Wolfgang Merkt
// 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 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 <exotica_quadrotor_dynamics_solver/quadrotor_dynamics_solver.h>
REGISTER_DYNAMICS_SOLVER_TYPE("QuadrotorDynamicsSolver", exotica::QuadrotorDynamicsSolver)
namespace exotica
{
QuadrotorDynamicsSolver::QuadrotorDynamicsSolver()
{
num_positions_ = 6;
num_velocities_ = 6;
num_controls_ = 4;
J_.setZero();
J_.diagonal() = Eigen::Vector3d(0.0023, 0.0023, 0.004);
J_inv_.setZero();
J_inv_.diagonal() = Eigen::Vector3d(1. / 0.0023, 1. / 0.0023, 1. / 0.0040);
}
void QuadrotorDynamicsSolver::AssignScene(ScenePtr scene_in)
{
const int num_positions_in = scene_in->GetKinematicTree().GetNumControlledJoints();
// TODO: This is a terrible check (not against name etc.), but can stop _some_ mismatches between URDF/model and dynamics
if ((num_positions_in) != 6 || scene_in->GetKinematicTree().GetControlledBaseType() != BaseType::FLOATING)
ThrowPretty("Robot model may not be a quadrotor.");
}
Eigen::VectorXd QuadrotorDynamicsSolver::f(const StateVector& x, const ControlVector& u)
{
const Eigen::Vector3d& translation = x.topRows<3>();
const Eigen::Vector3d& rpy = x.middleRows<3>(3);
const Eigen::Vector3d& v = x.middleRows<3>(6);
const Eigen::Vector3d& omega = x.bottomRows<3>();
// Create quaternion from rpy
const Eigen::Quaterniond quaternion = Eigen::AngleAxisd(rpy(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(rpy(1), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(rpy(2), Eigen::Vector3d::UnitZ());
const double F_1 = k_f_ * u(0);
const double F_2 = k_f_ * u(1);
const double F_3 = k_f_ * u(2);
const double F_4 = k_f_ * u(3);
const Eigen::Vector3d F(0, 0, F_1 + F_2 + F_3 + F_4); // total rotor force in body frame
const double M_1 = k_m_ * u(0);
const double M_2 = k_m_ * u(1);
const double M_3 = k_m_ * u(2);
const double M_4 = k_m_ * u(3);
const Eigen::Vector3d tau(L_ * (F_2 - F_4), L_ * (F_3 - F_1), (M_1 - M_2 + M_3 - M_4)); // total rotor torque in body frame
const Eigen::Quaterniond dquaternion = (quaternion * Eigen::Quaterniond(0, omega(0), omega(1), omega(2)));
const Eigen::Vector3d rpy_dot = dquaternion.toRotationMatrix().eulerAngles(0, 1, 2);
StateVector x_dot;
x_dot.topRows<3>() = v; // velocity in world frame
x_dot.middleRows<3>(3) = rpy_dot; // via quaternion derivative
x_dot.middleRows<3>(6) = Eigen::Vector3d(0, 0, -g_) + (1. / mass_) * (quaternion * F); // acceleration in world frame
x_dot.middleRows<3>(9) = J_inv_ * (tau - omega.cross(J_ * omega)); // Euler's equation : I* ω + ω x I* ω = constraint_decrease_ratio
return x_dot;
}
Eigen::MatrixXd QuadrotorDynamicsSolver::fx(const StateVector& x, const ControlVector& u)
{
// TODO
}
Eigen::MatrixXd QuadrotorDynamicsSolver::fu(const StateVector& x, const ControlVector& u)
{
// TODO
}
} // namespace exotica
<commit_msg>[exotica_quadrotor_dynamics_solver] Fix RPY example<commit_after>//
// Copyright (c) 2019, Wolfgang Merkt
// 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 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 <exotica_quadrotor_dynamics_solver/quadrotor_dynamics_solver.h>
REGISTER_DYNAMICS_SOLVER_TYPE("QuadrotorDynamicsSolver", exotica::QuadrotorDynamicsSolver)
namespace exotica
{
QuadrotorDynamicsSolver::QuadrotorDynamicsSolver()
{
num_positions_ = 6;
num_velocities_ = 6;
num_controls_ = 4;
J_.setZero();
J_.diagonal() = Eigen::Vector3d(0.0023, 0.0023, 0.004);
J_inv_.setZero();
J_inv_.diagonal() = Eigen::Vector3d(1. / 0.0023, 1. / 0.0023, 1. / 0.0040);
}
void QuadrotorDynamicsSolver::AssignScene(ScenePtr scene_in)
{
const int num_positions_in = scene_in->GetKinematicTree().GetNumControlledJoints();
// TODO: This is a terrible check (not against name etc.), but can stop _some_ mismatches between URDF/model and dynamics
if ((num_positions_in) != 6 || scene_in->GetKinematicTree().GetControlledBaseType() != BaseType::FLOATING)
ThrowPretty("Robot model may not be a quadrotor.");
}
Eigen::VectorXd QuadrotorDynamicsSolver::f(const StateVector& x, const ControlVector& u)
{
const Eigen::Vector3d translation = x.head<3>();
const Eigen::Vector3d rpy = x.segment<3>(3);
const Eigen::Vector3d v = x.segment<3>(6);
const Eigen::Vector3d omega = x.tail<3>();
// Create quaternion from rpy
const Eigen::Quaterniond quaternion = Eigen::AngleAxisd(rpy(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(rpy(1), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(rpy(2), Eigen::Vector3d::UnitZ());
const double F_1 = k_f_ * u(0);
const double F_2 = k_f_ * u(1);
const double F_3 = k_f_ * u(2);
const double F_4 = k_f_ * u(3);
const Eigen::Vector3d F(0, 0, F_1 + F_2 + F_3 + F_4); // total rotor force in body frame
const double M_1 = k_m_ * u(0);
const double M_2 = k_m_ * u(1);
const double M_3 = k_m_ * u(2);
const double M_4 = k_m_ * u(3);
const Eigen::Vector3d tau(L_ * (F_2 - F_4), L_ * (F_3 - F_1), (M_1 - M_2 + M_3 - M_4)); // total rotor torque in body frame
const Eigen::Quaterniond dquaternion = (quaternion * Eigen::Quaterniond(0, omega(0), omega(1), omega(2)));
const Eigen::Vector3d rpy_dot = dquaternion.toRotationMatrix().eulerAngles(0, 1, 2);
StateVector x_dot(12);
x_dot.head<3>() = v; // velocity in world frame
x_dot.segment<3>(3) = rpy_dot; // via quaternion derivative
x_dot.segment<3>(6) = Eigen::Vector3d(0, 0, -g_) + (1. / mass_) * (quaternion * F); // acceleration in world frame
x_dot.segment<3>(9) = J_inv_ * (tau - omega.cross(J_ * omega)); // Euler's equation : I* ω + ω x I* ω = constraint_decrease_ratio
return x_dot;
}
Eigen::MatrixXd QuadrotorDynamicsSolver::fx(const StateVector& x, const ControlVector& u)
{
// TODO
}
Eigen::MatrixXd QuadrotorDynamicsSolver::fu(const StateVector& x, const ControlVector& u)
{
// TODO
}
} // namespace exotica
<|endoftext|>
|
<commit_before>/* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermín Galán Márquez
*/
#include "logMsg/traceLevels.h"
#include "logMsg/logMsg.h"
#include "common/statistics.h"
#include "common/limits.h"
#include "common/globals.h"
#include "common/logTracing.h"
#include "alarmMgr/alarmMgr.h"
#include "rest/httpRequestSend.h"
#include "ngsiNotify/senderThread.h"
#include "cache/subCache.h"
/* ****************************************************************************
*
* startSenderThread -
*/
void* startSenderThread(void* p)
{
std::vector<SenderThreadParams*>* paramsV = (std::vector<SenderThreadParams*>*) p;
for (unsigned ix = 0; ix < paramsV->size(); ix++)
{
SenderThreadParams* params = (SenderThreadParams*) (*paramsV)[ix];
char portV[STRING_SIZE_FOR_INT];
std::string url;
snprintf(portV, sizeof(portV), "%d", params->port);
url = params->ip + ":" + portV + params->resource;
strncpy(transactionId, params->transactionId, sizeof(transactionId));
LM_T(LmtNotifier, ("sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s",
params->ip.c_str(),
params->port,
params->verb.c_str(),
params->tenant.c_str(),
params->servicePath.c_str(),
params->xauthToken.c_str(),
params->resource.c_str(),
params->content_type.c_str()));
long long statusCode = -1;
std::string out;
if (!simulatedNotification)
{
int r;
r = httpRequestSend(params->from,
params->ip,
params->port,
params->protocol,
params->verb,
params->tenant,
params->servicePath,
params->xauthToken,
params->resource,
params->content_type,
params->content,
params->fiwareCorrelator,
params->renderFormat,
&out,
&statusCode,
params->extraHeaders);
if (r == 0)
{
statisticsUpdate(NotifyContextSent, params->mimeType);
alarmMgr.forwardingErrorReset(url);
if (params->registration == false)
{
subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, "");
}
}
else
{
alarmMgr.forwardingError(url, "forwarding error: " + out);
if (params->registration == false)
{
subNotificationErrorStatus(params->tenant, params->subscriptionId, -1, -1, out);
}
}
}
else
{
LM_T(LmtNotifier, ("simulatedNotification is 'true', skipping outgoing request"));
__sync_fetch_and_add(&noOfSimulatedNotifications, 1);
}
// Add notificacion result summary in log INFO level
if (statusCode != -1)
{
logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);
}
else
{
logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());
}
// End transaction
lmTransactionEnd();
/* Delete the parameters after using them */
delete params;
}
/* Delete the parameters vector after using it */
delete paramsV;
pthread_exit(NULL);
return NULL;
}
<commit_msg>Update senderThread.cpp<commit_after>/* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker 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.
*
* Orion Context Broker 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 Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Fermín Galán Márquez
*/
#include "logMsg/traceLevels.h"
#include "logMsg/logMsg.h"
#include "common/statistics.h"
#include "common/limits.h"
#include "common/globals.h"
#include "common/logTracing.h"
#include "alarmMgr/alarmMgr.h"
#include "rest/httpRequestSend.h"
#include "ngsiNotify/senderThread.h"
#include "cache/subCache.h"
/* ****************************************************************************
*
* startSenderThread -
*/
void* startSenderThread(void* p)
{
std::vector<SenderThreadParams*>* paramsV = (std::vector<SenderThreadParams*>*) p;
for (unsigned ix = 0; ix < paramsV->size(); ix++)
{
SenderThreadParams* params = (SenderThreadParams*) (*paramsV)[ix];
char portV[STRING_SIZE_FOR_INT];
std::string url;
snprintf(portV, sizeof(portV), "%d", params->port);
url = params->ip + ":" + portV + params->resource;
strncpy(transactionId, params->transactionId, sizeof(transactionId));
LM_T(LmtNotifier, ("sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s",
params->ip.c_str(),
params->port,
params->verb.c_str(),
params->tenant.c_str(),
params->servicePath.c_str(),
params->xauthToken.c_str(),
params->resource.c_str(),
params->content_type.c_str()));
long long statusCode = -1;
std::string out;
if (!simulatedNotification)
{
int r;
r = httpRequestSend(params->from,
params->ip,
params->port,
params->protocol,
params->verb,
params->tenant,
params->servicePath,
params->xauthToken,
params->resource,
params->content_type,
params->content,
params->fiwareCorrelator,
params->renderFormat,
&out,
&statusCode,
params->extraHeaders);
if (r == 0)
{
statisticsUpdate(NotifyContextSent, params->mimeType);
alarmMgr.notificationErrorReset(url);
alarmMgr.forwardingErrorReset(url);
if (params->registration == false)
{
subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, "");
}
}
else
{
alarmMgr.notificationError(url, "notification failure for sender-thread: " + out);
alarmMgr.forwardingError(url, "forwarding failure for sender-thread: " + out);
if (params->registration == false)
{
subNotificationErrorStatus(params->tenant, params->subscriptionId, -1, -1, out);
}
}
}
else
{
LM_T(LmtNotifier, ("simulatedNotification is 'true', skipping outgoing request"));
__sync_fetch_and_add(&noOfSimulatedNotifications, 1);
}
// Add notificacion result summary in log INFO level
if (statusCode != -1)
{
logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);
}
else
{
logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());
}
// End transaction
lmTransactionEnd();
/* Delete the parameters after using them */
delete params;
}
/* Delete the parameters vector after using it */
delete paramsV;
pthread_exit(NULL);
return NULL;
}
<|endoftext|>
|
<commit_before>#include "packettrain.h"
#include <QDebug>
PacketTrain::PacketTrain(QObject *parent)
: isInitialized(false)
, packetCounter(0)
, running(false)
{
connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
connect(&timeouter, SIGNAL(timeout()), this, SLOT(stop()));
timer.setInterval(10);
timeouter.setInterval(2000);
timeouter.setSingleShot(true);
}
PacketTrain::~PacketTrain()
{
}
QString PacketTrain::name() const
{
return "packettrain";
}
bool PacketTrain::isMaster() const
{
return master;
}
bool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)
{
if ( isInitialized )
return false;
if ( peers.isEmpty() ) {
qDebug() << "Peer list is empty, can't initialize packettrain test";
return false;
}
this->peers = peers;
this->master = master;
this->socket = socket;
return (isInitialized=true);
}
void PacketTrain::uninitialize()
{
}
bool PacketTrain::start()
{
qDebug() << Q_FUNC_INFO;
running = true;
timeouter.start();
// Master waits for incoming packets
if ( master ) {
return true;
}
// Clients start sending data now
timer.start();
return true;
}
bool PacketTrain::stop()
{
qDebug() << Q_FUNC_INFO;
running = false;
timer.stop();
return true;
}
bool PacketTrain::isFinished() const
{
return running;
if ( master )
return packetCounter >= 100;
else
return !timer.isActive();
}
void PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{
if ( master ) {
emit packetCountChanged(packetCounter++);
}
timeouter.start();
//qDebug() << Q_FUNC_INFO << host.toString() << port << packetCounter << "asdfff";
}
QVariant PacketTrain::data(int role) const
{
Q_UNUSED(role)
return QVariant();
}
QVariant PacketTrain::result() const
{
QVariantMap values;
values.insert("received-packets", packetCounter);
return values;
}
void PacketTrain::timeout()
{
emit packetCountChanged(packetCounter);
if ( packetCounter++ >= 100 ) {
stop();
return;
}
QByteArray data;
data.resize(512);
data.fill('X');
foreach(const Peer& peer, peers) {
socket->writeDatagram(data, peer.host, peer.port);
}
}
<commit_msg>PacketTrain forgot to derive from AbstractTest.<commit_after>#include "packettrain.h"
#include <QDebug>
PacketTrain::PacketTrain(QObject *parent)
: AbstractTest(parent)
, isInitialized(false)
, packetCounter(0)
, running(false)
{
connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
connect(&timeouter, SIGNAL(timeout()), this, SLOT(stop()));
timer.setInterval(10);
timeouter.setInterval(2000);
timeouter.setSingleShot(true);
}
PacketTrain::~PacketTrain()
{
}
QString PacketTrain::name() const
{
return "packettrain";
}
bool PacketTrain::isMaster() const
{
return master;
}
bool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)
{
if ( isInitialized )
return false;
if ( peers.isEmpty() ) {
qDebug() << "Peer list is empty, can't initialize packettrain test";
return false;
}
this->peers = peers;
this->master = master;
this->socket = socket;
return (isInitialized=true);
}
void PacketTrain::uninitialize()
{
}
bool PacketTrain::start()
{
qDebug() << Q_FUNC_INFO;
running = true;
timeouter.start();
// Master waits for incoming packets
if ( master ) {
return true;
}
// Clients start sending data now
timer.start();
return true;
}
bool PacketTrain::stop()
{
qDebug() << Q_FUNC_INFO;
running = false;
timer.stop();
return true;
}
bool PacketTrain::isFinished() const
{
return running;
if ( master )
return packetCounter >= 100;
else
return !timer.isActive();
}
void PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{
if ( master ) {
emit packetCountChanged(packetCounter++);
}
timeouter.start();
//qDebug() << Q_FUNC_INFO << host.toString() << port << packetCounter << "asdfff";
}
QVariant PacketTrain::data(int role) const
{
Q_UNUSED(role)
return QVariant();
}
QVariant PacketTrain::result() const
{
QVariantMap values;
values.insert("received-packets", packetCounter);
return values;
}
void PacketTrain::timeout()
{
emit packetCountChanged(packetCounter);
if ( packetCounter++ >= 100 ) {
stop();
return;
}
QByteArray data;
data.resize(512);
data.fill('X');
foreach(const Peer& peer, peers) {
socket->writeDatagram(data, peer.host, peer.port);
}
}
<|endoftext|>
|
<commit_before>#include "Control.h"
#include <sstream>
Control::Control() {
}
Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
_hWnd = GetDlgItem(parent, id);
}
Control::~Control() {
}
RECT Control::ScreenDimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
return r;
}
RECT Control::ClientDimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
int width = r.right - r.left;
int height = r.bottom - r.top;
POINT p = { r.left, r.top };
int ret = ScreenToClient(_parent, &p);
r.left = p.x;
r.top = p.y;
r.right = r.left + width;
r.bottom = r.top + height;
return r;
}
void Control::Enable() {
EnableWindow(_hWnd, TRUE);
}
void Control::Disable() {
EnableWindow(_hWnd, FALSE);
}
bool Control::Enabled() {
return (IsWindowEnabled(_hWnd) == TRUE);
}
void Control::Enabled(bool enabled) {
if (enabled == true) {
Enable();
} else {
Disable();
}
}
int Control::EmSize() {
/* Determine the width of the text */
HDC dc = GetDC(_hWnd);
SIZE sz = { 0 };
GetTextExtentPoint32(dc, L"M", 1, &sz);
return sz.cx;
}
void Control::Move(int x, int y) {
RECT r = ClientDimensions();
MoveWindow(_hWnd, x, y, r.right - r.left, r.bottom - r.top, TRUE);
}
void Control::PlaceRightOf(Control &control) {
RECT otherRect = control.ClientDimensions();
CLOG(L"Other dims: %d %d %d %d", otherRect.top, otherRect.right, otherRect.bottom, otherRect.left);
int x = otherRect.right;
int y = ClientDimensions().top;
Move(x, y);
}
bool Control::Text(std::wstring text) {
return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}
bool Control::Text(int value) {
return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;
}
std::wstring Control::Text() {
wchar_t text[MAX_EDITSTR];
GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
return std::wstring(text);
}
int Control::TextAsInt() {
std::wstring str = Text();
int num;
std::wistringstream wistr(str);
wistr >> num;
return num;
}
bool Control::Visible() {
return IsWindowVisible(_hWnd) != FALSE;
}
void Control::Visible(bool visible) {
ShowWindow(_hWnd, visible ? SW_SHOW : SW_HIDE);
}
void Control::AddWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs |= exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
void Control::RemoveWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs &= ~exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
DLGPROC Control::Command(unsigned short nCode) {
/* By default, indicate that we did not process the message: */
return FALSE;
}
DLGPROC Control::Notification(NMHDR *nHdr) {
/* By default, indicate that we did not process the message: */
return FALSE;
}
<commit_msg>Vertically center controls placed to the right and use a 1-em gap between the target control<commit_after>#include "Control.h"
#include <sstream>
Control::Control() {
}
Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
_hWnd = GetDlgItem(parent, id);
}
Control::~Control() {
}
RECT Control::ScreenDimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
return r;
}
RECT Control::ClientDimensions() {
RECT r;
GetWindowRect(_hWnd, &r);
int width = r.right - r.left;
int height = r.bottom - r.top;
POINT p = { r.left, r.top };
int ret = ScreenToClient(_parent, &p);
r.left = p.x;
r.top = p.y;
r.right = r.left + width;
r.bottom = r.top + height;
return r;
}
void Control::Enable() {
EnableWindow(_hWnd, TRUE);
}
void Control::Disable() {
EnableWindow(_hWnd, FALSE);
}
bool Control::Enabled() {
return (IsWindowEnabled(_hWnd) == TRUE);
}
void Control::Enabled(bool enabled) {
if (enabled == true) {
Enable();
} else {
Disable();
}
}
int Control::EmSize() {
/* Determine the width of the text */
HDC dc = GetDC(_hWnd);
SIZE sz = { 0 };
GetTextExtentPoint32(dc, L"M", 1, &sz);
return sz.cx;
}
void Control::Move(int x, int y) {
RECT r = ClientDimensions();
MoveWindow(_hWnd, x, y, r.right - r.left, r.bottom - r.top, TRUE);
}
void Control::PlaceRightOf(Control &control) {
RECT otherRect = control.ClientDimensions();
int otherHeight = otherRect.bottom - otherRect.top;
/* Vertical center point of the other control: */
int vCenter = otherRect.top + otherHeight / 2;
RECT myRect = ClientDimensions();
int myHeight = myRect.bottom - myRect.top;
int x = otherRect.right + EmSize();
int y = vCenter - myHeight / 2;
Move(x, y);
}
bool Control::Text(std::wstring text) {
return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}
bool Control::Text(int value) {
return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;
}
std::wstring Control::Text() {
wchar_t text[MAX_EDITSTR];
GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
return std::wstring(text);
}
int Control::TextAsInt() {
std::wstring str = Text();
int num;
std::wistringstream wistr(str);
wistr >> num;
return num;
}
bool Control::Visible() {
return IsWindowVisible(_hWnd) != FALSE;
}
void Control::Visible(bool visible) {
ShowWindow(_hWnd, visible ? SW_SHOW : SW_HIDE);
}
void Control::AddWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs |= exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
void Control::RemoveWindowExStyle(long exStyle) {
long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
exs &= ~exStyle;
SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}
DLGPROC Control::Command(unsigned short nCode) {
/* By default, indicate that we did not process the message: */
return FALSE;
}
DLGPROC Control::Notification(NMHDR *nHdr) {
/* By default, indicate that we did not process the message: */
return FALSE;
}
<|endoftext|>
|
<commit_before>/*
* nt loader
*
* Copyright 2006-2008 Mike McCormack
*
* 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
*/
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <poll.h>
#include <signal.h>
#include <execinfo.h>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "debug.h"
#include "mem.h"
#include "object.h"
#include "objdir.h"
#include "ntcall.h"
#include "section.h"
#include "timer.h"
#include "unicode.h"
#include "fiber.h"
#include "file.h"
#include "event.h"
#include "symlink.h"
process_list_t processes;
thread_t *current;
object_t *ntdll_section;
int option_debug = 0;
ULONG KiIntSystemCall = 0;
bool forced_quit;
class default_sleeper_t : public sleeper_t
{
public:
virtual bool sleep_timeout( LARGE_INTEGER& timeout );
virtual ~default_sleeper_t() {}
};
int sleeper_t::get_int_timeout( LARGE_INTEGER& timeout )
{
timeout.QuadPart = (timeout.QuadPart+9999)/10000;
int t = INT_MAX;
if (timeout.QuadPart < t)
t = timeout.QuadPart;
return t;
}
bool default_sleeper_t::sleep_timeout( LARGE_INTEGER& timeout )
{
int t = get_int_timeout( timeout );
int r = poll( 0, 0, t );
if (r >= 0)
return false;
if (errno != EINTR)
die("poll failed %d\n", errno);
return false;
}
default_sleeper_t default_sleeper;
sleeper_t* sleeper = &default_sleeper;
int schedule(void)
{
/* while there's still a thread running */
while (processes.head())
{
// check if any timers have expired
LARGE_INTEGER timeout;
timeout_t::check_timers(timeout);
// other fibers are active... schedule run them
if (!fiber_t::last_fiber())
{
fiber_t::yield();
continue;
}
// there's still processes but no active threads ... sleep
if (timeout_t::check_timers(timeout))
{
if (sleeper->sleep_timeout(timeout))
break;
}
else if (fiber_t::last_fiber())
break;
}
return 0;
}
NTSTATUS create_initial_process( thread_t **t, UNICODE_STRING& us )
{
BYTE *pstack;
const unsigned int stack_size = 0x100 * PAGE_SIZE;
process_t *p = NULL;
CONTEXT ctx;
INITIAL_TEB init_teb;
CLIENT_ID id;
object_t *section = NULL;
file_t *file = 0;
int r;
r = open_file( file, us );
if (r < STATUS_SUCCESS)
return r;
/* load the executable and ntdll */
r = create_section( §ion, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );
release( file );
if (r < STATUS_SUCCESS)
return r;
/* create the initial process */
r = create_process( &p, section );
release( section );
section = NULL;
if (r < STATUS_SUCCESS)
return r;
PPEB ppeb = (PPEB) p->peb_section->get_kernel_address();
p->create_exe_ppb( &ppeb->ProcessParameters, us );
/* map the stack */
pstack = NULL;
r = p->vm->allocate_virtual_memory( &pstack, 0, stack_size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
if (r < STATUS_SUCCESS)
return r;
/* teb initialization data */
memset( &init_teb, 0, sizeof init_teb );
init_teb.StackReserved = pstack;
init_teb.StackCommit = (BYTE*)init_teb.StackReserved + stack_size;
init_teb.StackCommitMax = (BYTE*)init_teb.StackCommit - PAGE_SIZE;
/* initialize the first thread's context */
p->vm->init_context( ctx );
ctx.Eip = (DWORD) get_entry_point( p );
ctx.Esp = (DWORD) pstack + stack_size - 8;
dprintf("entry point = %08lx\n", ctx.Eip);
/* when starting nt processes, make the PEB the first arg of NtProcessStartup */
r = p->vm->copy_to_user( (BYTE*) ctx.Esp + 4, &p->PebBaseAddress, sizeof p->PebBaseAddress );
if (r == STATUS_SUCCESS)
r = create_thread( t, p, &id, &ctx, &init_teb, FALSE );
release( p );
return r;
}
NTSTATUS init_ntdll( void )
{
WCHAR ntdll[] = {
'\\','?','?','\\','c',':','\\','w','i','n','n','t','\\',
's','y','s','t','e','m','3','2','\\','n','t','d','l','l','.','d','l','l',0 };
unicode_string_t us;
file_t *file = 0;
NTSTATUS r;
us.set( ntdll );
r = open_file( file, us );
if (r < STATUS_SUCCESS)
die("failed to open ntdll\n");
r = create_section( &ntdll_section, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );
if (r < STATUS_SUCCESS)
die("failed to map ntdll\n");
KiIntSystemCall = get_proc_address( ntdll_section, "KiIntSystemCall" );
dprintf("KiIntSystemCall = %08lx\n", KiIntSystemCall);
init_syscalls(KiIntSystemCall != 0);
release( file );
return r;
}
void free_ntdll( void )
{
release( ntdll_section );
ntdll_section = NULL;
}
void do_cleanup( void )
{
int num_threads = 0, num_processes = 0;
for ( process_iter_t pi(processes); pi; pi.next() )
{
process_t *p = pi;
if (p->is_signalled())
continue;
num_processes++;
fprintf(stderr, "process %04lx\n", p->id);
for ( sibling_iter_t ti(p->threads); ti; ti.next() )
{
thread_t *t = ti;
if (t->is_signalled())
continue;
fprintf(stderr, "\tthread %04lx\n", t->trace_id());
num_threads++;
}
}
if (num_threads || num_processes)
fprintf(stderr, "%d threads %d processes left\n", num_threads, num_processes);
}
int usage( const char *prog )
{
fprintf(stderr, "%s [-d] [-t] [-m] [-q] native.exe\n", prog );
fprintf(stderr, " [-d] break into debugger on exceptions\n");
fprintf(stderr, " [-m] memory reference counting\n");
fprintf(stderr, " [-t] trace syscall entry and exit\n");
fprintf(stderr, " [-q] quiet, suppress debug messages\n");
return 0;
}
static void segv_handler(int)
{
const int max_frames = 20;
void *bt[max_frames];
char **names;
int n=0, size;
ULONG id = 0;
if (current)
id = current->trace_id();
size = backtrace(bt, max_frames);
names = backtrace_symbols(bt, size);
fprintf(stderr, "%04lx: caught kernel SEGV (%d frames):\n", id, size);
for (n=0; n<size; n++)
{
fprintf(stderr, "%d: %s\n", n, names[n]);
}
exit(1);
}
bool init_skas();
bool init_tt();
bool option_skas = 1;
int main(int argc, char **argv)
{
unicode_string_t us;
thread_t *initial_thread = NULL;
int r, n;
// enable backtraces
signal(SIGSEGV, segv_handler);
for (n=1; n<argc; n++)
{
if (argv[n][0] != '-')
break;
switch (argv[n][1])
{
case 'd':
option_debug = 1;
break;
case 't':
option_trace = 1;
break;
case 'q':
option_quiet = 1;
break;
case 's':
option_skas = 0;
break;
default:
return usage( argv[0] );
}
}
if (n == argc)
return usage( argv[0] );
(option_skas && init_skas()) || init_tt();
if (!pcreate_address_space)
die("no way to manage address spaces found\n");
// initialize boottime
SYSTEM_TIME_OF_DAY_INFORMATION dummy;
get_system_time_of_day( dummy );
init_registry();
fiber_t::fibers_init();
init_root();
create_directory_object( (PWSTR) L"\\" );
create_directory_object( (PWSTR) L"\\??" );
unicode_string_t link_name, link_target;
link_name.set( L"\\DosDevices" );
link_target.copy( L"\\??" );
create_symlink( link_name, link_target );
create_directory_object( (PWSTR) L"\\Device" );
create_directory_object( (PWSTR) L"\\Device\\MailSlot" );
create_directory_object( (PWSTR) L"\\Security" );
//create_directory_object( (PWSTR) L"\\DosDevices" );
create_directory_object( (PWSTR) L"\\BaseNamedObjects" );
create_sync_event( (PWSTR) L"\\Security\\LSA_AUTHENTICATION_INITIALIZED" );
create_sync_event( (PWSTR) L"\\SeLsaInitEvent" );
init_random();
init_pipe_device();
// XP
create_directory_object( (PWSTR) L"\\KernelObjects" );
create_sync_event( (PWSTR) L"\\KernelObjects\\CritSecOutOfMemoryEvent" );
init_drives();
init_ntdll();
create_kthread();
us.copy( argv[n] );
r = create_initial_process( &initial_thread, us );
if (r < STATUS_SUCCESS)
die("create_initial_process() failed (%08x)\n", r);
// run the main loop
schedule();
ntgdi_fini();
r = initial_thread->process->ExitStatus;
//fprintf(stderr, "process exited (%08x)\n", r);
release( initial_thread );
shutdown_kthread();
do_cleanup();
free_root();
fiber_t::fibers_finish();
free_registry();
free_ntdll();
return r;
}
<commit_msg>Use getopt_long to parse options<commit_after>/*
* nt loader
*
* Copyright 2006-2008 Mike McCormack
*
* 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
*/
#include "config.h"
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <poll.h>
#include <signal.h>
#include <execinfo.h>
#include <getopt.h>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "debug.h"
#include "mem.h"
#include "object.h"
#include "objdir.h"
#include "ntcall.h"
#include "section.h"
#include "timer.h"
#include "unicode.h"
#include "fiber.h"
#include "file.h"
#include "event.h"
#include "symlink.h"
process_list_t processes;
thread_t *current;
object_t *ntdll_section;
int option_debug = 0;
ULONG KiIntSystemCall = 0;
bool forced_quit;
class default_sleeper_t : public sleeper_t
{
public:
virtual bool sleep_timeout( LARGE_INTEGER& timeout );
virtual ~default_sleeper_t() {}
};
int sleeper_t::get_int_timeout( LARGE_INTEGER& timeout )
{
timeout.QuadPart = (timeout.QuadPart+9999)/10000;
int t = INT_MAX;
if (timeout.QuadPart < t)
t = timeout.QuadPart;
return t;
}
bool default_sleeper_t::sleep_timeout( LARGE_INTEGER& timeout )
{
int t = get_int_timeout( timeout );
int r = poll( 0, 0, t );
if (r >= 0)
return false;
if (errno != EINTR)
die("poll failed %d\n", errno);
return false;
}
default_sleeper_t default_sleeper;
sleeper_t* sleeper = &default_sleeper;
int schedule(void)
{
/* while there's still a thread running */
while (processes.head())
{
// check if any timers have expired
LARGE_INTEGER timeout;
timeout_t::check_timers(timeout);
// other fibers are active... schedule run them
if (!fiber_t::last_fiber())
{
fiber_t::yield();
continue;
}
// there's still processes but no active threads ... sleep
if (timeout_t::check_timers(timeout))
{
if (sleeper->sleep_timeout(timeout))
break;
}
else if (fiber_t::last_fiber())
break;
}
return 0;
}
NTSTATUS create_initial_process( thread_t **t, UNICODE_STRING& us )
{
BYTE *pstack;
const unsigned int stack_size = 0x100 * PAGE_SIZE;
process_t *p = NULL;
CONTEXT ctx;
INITIAL_TEB init_teb;
CLIENT_ID id;
object_t *section = NULL;
file_t *file = 0;
int r;
r = open_file( file, us );
if (r < STATUS_SUCCESS)
return r;
/* load the executable and ntdll */
r = create_section( §ion, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );
release( file );
if (r < STATUS_SUCCESS)
return r;
/* create the initial process */
r = create_process( &p, section );
release( section );
section = NULL;
if (r < STATUS_SUCCESS)
return r;
PPEB ppeb = (PPEB) p->peb_section->get_kernel_address();
p->create_exe_ppb( &ppeb->ProcessParameters, us );
/* map the stack */
pstack = NULL;
r = p->vm->allocate_virtual_memory( &pstack, 0, stack_size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
if (r < STATUS_SUCCESS)
return r;
/* teb initialization data */
memset( &init_teb, 0, sizeof init_teb );
init_teb.StackReserved = pstack;
init_teb.StackCommit = (BYTE*)init_teb.StackReserved + stack_size;
init_teb.StackCommitMax = (BYTE*)init_teb.StackCommit - PAGE_SIZE;
/* initialize the first thread's context */
p->vm->init_context( ctx );
ctx.Eip = (DWORD) get_entry_point( p );
ctx.Esp = (DWORD) pstack + stack_size - 8;
dprintf("entry point = %08lx\n", ctx.Eip);
/* when starting nt processes, make the PEB the first arg of NtProcessStartup */
r = p->vm->copy_to_user( (BYTE*) ctx.Esp + 4, &p->PebBaseAddress, sizeof p->PebBaseAddress );
if (r == STATUS_SUCCESS)
r = create_thread( t, p, &id, &ctx, &init_teb, FALSE );
release( p );
return r;
}
NTSTATUS init_ntdll( void )
{
WCHAR ntdll[] = {
'\\','?','?','\\','c',':','\\','w','i','n','n','t','\\',
's','y','s','t','e','m','3','2','\\','n','t','d','l','l','.','d','l','l',0 };
unicode_string_t us;
file_t *file = 0;
NTSTATUS r;
us.set( ntdll );
r = open_file( file, us );
if (r < STATUS_SUCCESS)
die("failed to open ntdll\n");
r = create_section( &ntdll_section, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );
if (r < STATUS_SUCCESS)
die("failed to map ntdll\n");
KiIntSystemCall = get_proc_address( ntdll_section, "KiIntSystemCall" );
dprintf("KiIntSystemCall = %08lx\n", KiIntSystemCall);
init_syscalls(KiIntSystemCall != 0);
release( file );
return r;
}
void free_ntdll( void )
{
release( ntdll_section );
ntdll_section = NULL;
}
void do_cleanup( void )
{
int num_threads = 0, num_processes = 0;
for ( process_iter_t pi(processes); pi; pi.next() )
{
process_t *p = pi;
if (p->is_signalled())
continue;
num_processes++;
fprintf(stderr, "process %04lx\n", p->id);
for ( sibling_iter_t ti(p->threads); ti; ti.next() )
{
thread_t *t = ti;
if (t->is_signalled())
continue;
fprintf(stderr, "\tthread %04lx\n", t->trace_id());
num_threads++;
}
}
if (num_threads || num_processes)
fprintf(stderr, "%d threads %d processes left\n", num_threads, num_processes);
}
static void segv_handler(int)
{
const int max_frames = 20;
void *bt[max_frames];
char **names;
int n=0, size;
ULONG id = 0;
if (current)
id = current->trace_id();
size = backtrace(bt, max_frames);
names = backtrace_symbols(bt, size);
fprintf(stderr, "%04lx: caught kernel SEGV (%d frames):\n", id, size);
for (n=0; n<size; n++)
{
fprintf(stderr, "%d: %s\n", n, names[n]);
}
exit(1);
}
bool init_skas();
bool init_tt();
void usage( void )
{
const char usage[] =
"Usage: %s [options] [native.exe]\n"
"Options:\n"
" -d,--debug break into debugger on exceptions\n"
" -h,--help print this message\n"
" -q,--quiet quiet, suppress debug messages\n"
" -t,--trace trace syscall entry and exit\n"
" -v,--version print version\n\n"
" smss.exe is started by default\n\n";
printf( usage, PACKAGE_NAME );
exit(0);
}
void version( void )
{
const char version[] = "%s\n"
"Copyright (C) 2008 Mike McCormack\n"
"Licence LGPL\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n\n";
printf( version, PACKAGE_STRING );
exit(0);
}
void parse_options(int argc, char **argv)
{
while (1)
{
int option_index;
static struct option long_options[] = {
{"debug", 0, &option_debug, 1 },
{"help", 0, 0, 'h' },
{"quiet", 0, &option_quiet, 1 },
{"trace", 0, &option_trace, 1 },
{"version", 0, 0, 'v' },
{NULL, 0, 0, 0 },
};
int ch = getopt_long(argc, argv, "dhtqv", long_options, &option_index );
if (ch == -1)
break;
switch (ch)
{
case 'd':
option_debug = 1;
break;
case 'h':
usage();
break;
case 'q':
option_quiet = 1;
break;
case 't':
option_trace = 1;
break;
case 'v':
version();
}
}
}
int main(int argc, char **argv)
{
unicode_string_t us;
thread_t *initial_thread = NULL;
const char *exename;
parse_options( argc, argv );
if (optind == argc)
{
// default to starting smss.exe
exename = "\\??\\c:\\winnt\\system32\\smss.exe";
}
else
{
exename = argv[optind];
}
// the skas3 patch is deprecated...
if (0) init_skas();
init_tt();
if (!pcreate_address_space)
die("no way to manage address spaces found\n");
// enable backtraces
signal(SIGSEGV, segv_handler);
// initialize boottime
SYSTEM_TIME_OF_DAY_INFORMATION dummy;
get_system_time_of_day( dummy );
init_registry();
fiber_t::fibers_init();
init_root();
create_directory_object( (PWSTR) L"\\" );
create_directory_object( (PWSTR) L"\\??" );
unicode_string_t link_name, link_target;
link_name.set( L"\\DosDevices" );
link_target.copy( L"\\??" );
create_symlink( link_name, link_target );
create_directory_object( (PWSTR) L"\\Device" );
create_directory_object( (PWSTR) L"\\Device\\MailSlot" );
create_directory_object( (PWSTR) L"\\Security" );
//create_directory_object( (PWSTR) L"\\DosDevices" );
create_directory_object( (PWSTR) L"\\BaseNamedObjects" );
create_sync_event( (PWSTR) L"\\Security\\LSA_AUTHENTICATION_INITIALIZED" );
create_sync_event( (PWSTR) L"\\SeLsaInitEvent" );
init_random();
init_pipe_device();
// XP
create_directory_object( (PWSTR) L"\\KernelObjects" );
create_sync_event( (PWSTR) L"\\KernelObjects\\CritSecOutOfMemoryEvent" );
init_drives();
init_ntdll();
create_kthread();
us.copy( exename );
int r = create_initial_process( &initial_thread, us );
if (r < STATUS_SUCCESS)
die("create_initial_process() failed (%08x)\n", r);
// run the main loop
schedule();
ntgdi_fini();
r = initial_thread->process->ExitStatus;
//fprintf(stderr, "process exited (%08x)\n", r);
release( initial_thread );
shutdown_kthread();
do_cleanup();
free_root();
fiber_t::fibers_finish();
free_registry();
free_ntdll();
return r;
}
<|endoftext|>
|
<commit_before>
#include "pch.h"
#include "D2DWindow.h"
#include "Win32Defs.h"
using namespace std;
using namespace D2D1;
#pragma comment (lib, "d2d1.lib")
#pragma comment (lib, "dwrite.lib")
#pragma comment (lib, "D3D11.lib")
#pragma comment (lib, "Dxgi.lib")
static ATOM WndClassAtom;
static const wchar_t WndClassName[] = L"D2DWindow-{175802BE-0628-45C0-BC8A-3D27C6F4F0BE}";
D2DWindow::D2DWindow (HINSTANCE hInstance, DWORD exStyle, DWORD style, const RECT& rect, HWND hWndParent, HMENU hMenuOrControlId, IDWriteFactory* dWriteFactory)
: base(hInstance, WndClassName, exStyle, style, rect, hWndParent, hMenuOrControlId)
, _dWriteFactory(dWriteFactory)
{
auto hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, IID_PPV_ARGS(&_d2dFactory));
ThrowIfFailed(hr);
CreateD2DDeviceContext();
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
_clientSizeDips.width = GetClientWidthPixels() * 96.0f / dpiX;
_clientSizeDips.height = GetClientHeightPixels() * 96.0f / dpiY;
}
void D2DWindow::CreateD2DDeviceContext()
{
D2D1_RENDER_TARGET_PROPERTIES props = {};
props.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
props.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
props.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
_d2dFactory->GetDesktopDpi (&props.dpiX, &props.dpiY);
props.usage = D2D1_RENDER_TARGET_USAGE_NONE;
props.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
D2D1_HWND_RENDER_TARGET_PROPERTIES hwndrtprops = { };
hwndrtprops.hwnd = GetHWnd();
hwndrtprops.pixelSize = { (UINT32) GetClientWidthPixels(), (UINT32) GetClientHeightPixels() };
auto hr = _d2dFactory->CreateHwndRenderTarget(&props, &hwndrtprops, &_renderTarget);
ThrowIfFailed(hr);
}
std::optional<LRESULT> D2DWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
auto resultBaseClass = base::WindowProc(hwnd, uMsg, wParam, lParam);
if (uMsg == WM_SIZE)
{
_renderTarget = nullptr;
CreateD2DDeviceContext();
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
_clientSizeDips.width = GetClientWidthPixels() * 96.0f / dpiX;
_clientSizeDips.height = GetClientHeightPixels() * 96.0f / dpiY;
return 0;
}
if (uMsg == WM_ERASEBKGND)
return 0; // 0 means the window remains marked for erasing, so the fErase member of the PAINTSTRUCT structure will be TRUE.
if (uMsg == WM_PAINT)
{
ProcessWmPaint(hwnd);
return 0;
}
return std::nullopt;
}
void D2DWindow::ProcessWmPaint (HWND hwnd)
{
if (_painting)
{
// We get here when we're called recursively. The only such case I've seen so far is when
// an assertion fails in code called from this function. We don't want to restart painting
// cause we'll end up with a stack overflow, so let's return without attempting anything "smart".
return;
}
HRESULT hr;
// Call this before calculating the update rects, to allow derived classed to invalidate stuff.
this->OnBeforeRender();
// -------------------------------------------------
// draw the stuff
// Problem: If an assertion fails in code called from this function, the C++ runtime will try to display
// the assertion message box. It seems that Windows, while processing WM_PAINT, displays message boxes
// only if the application has called BeginPaint; if the application has not called BeginPaint, Windows
// will not display the message box, will make sounds when clicking on the application window, and will
// wait for the user to press Alt before finally displaying it (go figure!)
PAINTSTRUCT ps;
::BeginPaint(hwnd, &ps); // this will also hide the caret, if shown.
_painting = true;
_renderTarget->BeginDraw();
_renderTarget->SetTransform(IdentityMatrix());
this->Render(_renderTarget);
hr = _renderTarget->EndDraw(); ThrowIfFailed(hr);
::EndPaint(hwnd, &ps); // this will show the caret in case BeginPaint above hid it.
this->OnAfterRender();
assert(_painting);
_painting = false;
}
D2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(POINT p) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_POINT_2F{ p.x * 96.0f / dpiX, p.y * 96.0f / dpiY };
}
D2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(float xPixels, float yPixels) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_POINT_2F{ xPixels * 96.0f / dpiX, yPixels * 96.0f / dpiY };
}
POINT D2DWindow::GetPixelLocationFromDipLocation(D2D1_POINT_2F locationDips) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return POINT{ (int)roundf(locationDips.x / 96.0f * dpiX), (int)roundf(locationDips.y / 96.0f * dpiY) };
}
D2D1_SIZE_F D2DWindow::GetDipSizeFromPixelSize(SIZE sz) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_SIZE_F{ sz.cx * 96.0f / dpiX, sz.cy * 96.0f / dpiY };
}
SIZE D2DWindow::GetPixelSizeFromDipSize(D2D1_SIZE_F sizeDips) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return SIZE{ (int)(sizeDips.width / 96.0f * dpiX), (int)(sizeDips.height / 96.0f * dpiY) };
}
ColorF GetD2DSystemColor (int sysColorIndex)
{
DWORD brg = GetSysColor (sysColorIndex);
DWORD rgb = ((brg & 0xff0000) >> 16) | (brg & 0xff00) | ((brg & 0xff) << 16);
return ColorF (rgb);
}
TextLayout TextLayout::Create (IDWriteFactory* dWriteFactory, IDWriteTextFormat* format, const wchar_t* str, float maxWidth)
{
IDWriteTextLayoutPtr tl;
auto hr = dWriteFactory->CreateTextLayout(str, (UINT32) wcslen(str), format, (maxWidth != 0) ? maxWidth : 10000, 10000, &tl); ThrowIfFailed(hr);
DWRITE_TEXT_METRICS metrics;
hr = tl->GetMetrics(&metrics); ThrowIfFailed(hr);
return TextLayout { move(tl), metrics };
}
<commit_msg>Cleanup of unused libs.<commit_after>
#include "pch.h"
#include "D2DWindow.h"
#include "Win32Defs.h"
using namespace std;
using namespace D2D1;
#pragma comment (lib, "d2d1.lib")
#pragma comment (lib, "dwrite.lib")
static ATOM WndClassAtom;
static const wchar_t WndClassName[] = L"D2DWindow-{175802BE-0628-45C0-BC8A-3D27C6F4F0BE}";
D2DWindow::D2DWindow (HINSTANCE hInstance, DWORD exStyle, DWORD style, const RECT& rect, HWND hWndParent, HMENU hMenuOrControlId, IDWriteFactory* dWriteFactory)
: base(hInstance, WndClassName, exStyle, style, rect, hWndParent, hMenuOrControlId)
, _dWriteFactory(dWriteFactory)
{
auto hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, IID_PPV_ARGS(&_d2dFactory));
ThrowIfFailed(hr);
CreateD2DDeviceContext();
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
_clientSizeDips.width = GetClientWidthPixels() * 96.0f / dpiX;
_clientSizeDips.height = GetClientHeightPixels() * 96.0f / dpiY;
}
void D2DWindow::CreateD2DDeviceContext()
{
D2D1_RENDER_TARGET_PROPERTIES props = {};
props.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;
props.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;
props.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;
_d2dFactory->GetDesktopDpi (&props.dpiX, &props.dpiY);
props.usage = D2D1_RENDER_TARGET_USAGE_NONE;
props.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
D2D1_HWND_RENDER_TARGET_PROPERTIES hwndrtprops = { };
hwndrtprops.hwnd = GetHWnd();
hwndrtprops.pixelSize = { (UINT32) GetClientWidthPixels(), (UINT32) GetClientHeightPixels() };
auto hr = _d2dFactory->CreateHwndRenderTarget(&props, &hwndrtprops, &_renderTarget);
ThrowIfFailed(hr);
}
std::optional<LRESULT> D2DWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
auto resultBaseClass = base::WindowProc(hwnd, uMsg, wParam, lParam);
if (uMsg == WM_SIZE)
{
_renderTarget = nullptr;
CreateD2DDeviceContext();
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
_clientSizeDips.width = GetClientWidthPixels() * 96.0f / dpiX;
_clientSizeDips.height = GetClientHeightPixels() * 96.0f / dpiY;
return 0;
}
if (uMsg == WM_ERASEBKGND)
return 0; // 0 means the window remains marked for erasing, so the fErase member of the PAINTSTRUCT structure will be TRUE.
if (uMsg == WM_PAINT)
{
ProcessWmPaint(hwnd);
return 0;
}
return std::nullopt;
}
void D2DWindow::ProcessWmPaint (HWND hwnd)
{
if (_painting)
{
// We get here when we're called recursively. The only such case I've seen so far is when
// an assertion fails in code called from this function. We don't want to restart painting
// cause we'll end up with a stack overflow, so let's return without attempting anything "smart".
return;
}
HRESULT hr;
// Call this before calculating the update rects, to allow derived classed to invalidate stuff.
this->OnBeforeRender();
// -------------------------------------------------
// draw the stuff
// Problem: If an assertion fails in code called from this function, the C++ runtime will try to display
// the assertion message box. It seems that Windows, while processing WM_PAINT, displays message boxes
// only if the application has called BeginPaint; if the application has not called BeginPaint, Windows
// will not display the message box, will make sounds when clicking on the application window, and will
// wait for the user to press Alt before finally displaying it (go figure!)
PAINTSTRUCT ps;
::BeginPaint(hwnd, &ps); // this will also hide the caret, if shown.
_painting = true;
_renderTarget->BeginDraw();
_renderTarget->SetTransform(IdentityMatrix());
this->Render(_renderTarget);
hr = _renderTarget->EndDraw(); ThrowIfFailed(hr);
::EndPaint(hwnd, &ps); // this will show the caret in case BeginPaint above hid it.
this->OnAfterRender();
assert(_painting);
_painting = false;
}
D2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(POINT p) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_POINT_2F{ p.x * 96.0f / dpiX, p.y * 96.0f / dpiY };
}
D2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(float xPixels, float yPixels) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_POINT_2F{ xPixels * 96.0f / dpiX, yPixels * 96.0f / dpiY };
}
POINT D2DWindow::GetPixelLocationFromDipLocation(D2D1_POINT_2F locationDips) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return POINT{ (int)roundf(locationDips.x / 96.0f * dpiX), (int)roundf(locationDips.y / 96.0f * dpiY) };
}
D2D1_SIZE_F D2DWindow::GetDipSizeFromPixelSize(SIZE sz) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return D2D1_SIZE_F{ sz.cx * 96.0f / dpiX, sz.cy * 96.0f / dpiY };
}
SIZE D2DWindow::GetPixelSizeFromDipSize(D2D1_SIZE_F sizeDips) const
{
float dpiX, dpiY;
_renderTarget->GetDpi(&dpiX, &dpiY);
return SIZE{ (int)(sizeDips.width / 96.0f * dpiX), (int)(sizeDips.height / 96.0f * dpiY) };
}
ColorF GetD2DSystemColor (int sysColorIndex)
{
DWORD brg = GetSysColor (sysColorIndex);
DWORD rgb = ((brg & 0xff0000) >> 16) | (brg & 0xff00) | ((brg & 0xff) << 16);
return ColorF (rgb);
}
TextLayout TextLayout::Create (IDWriteFactory* dWriteFactory, IDWriteTextFormat* format, const wchar_t* str, float maxWidth)
{
IDWriteTextLayoutPtr tl;
auto hr = dWriteFactory->CreateTextLayout(str, (UINT32) wcslen(str), format, (maxWidth != 0) ? maxWidth : 10000, 10000, &tl); ThrowIfFailed(hr);
DWRITE_TEXT_METRICS metrics;
hr = tl->GetMetrics(&metrics); ThrowIfFailed(hr);
return TextLayout { move(tl), metrics };
}
<|endoftext|>
|
<commit_before>#include <assert.h>
#include <iostream>
#include <memory>
#include <vector>
#include "common/simhubdeviceplugin.h"
#include "main.h"
// -- public C FFI
extern "C" {
int simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)
{
*plugin_instance = new SimSourcePluginStateManager(logger);
return 0;
}
int simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));
}
int simplug_preflight_complete(SPHANDLE plugin_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();
}
void simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)
{
static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);
}
int simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)
{
return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);
}
void simplug_cease_eventing(SPHANDLE plugin_instance)
{
static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();
}
void simplug_release(SPHANDLE plugin_instance)
{
assert(plugin_instance);
delete static_cast<PluginStateManager *>(plugin_instance);
}
}
// -- internal implementation
SimSourcePluginStateManager *SimSourcePluginStateManager::_StateManagerInstance = NULL;
void SimSourcePluginStateManager::AllocBuffer(uv_handle_t *handle, size_t size, uv_buf_t *buf)
{
*buf = SimSourcePluginStateManager::StateManagerInstance()->_readBuffer;
}
//! static getter for singleton instance of our class
SimSourcePluginStateManager *SimSourcePluginStateManager::StateManagerInstance(void)
{
return _StateManagerInstance;
}
SimSourcePluginStateManager::SimSourcePluginStateManager(LoggingFunctionCB logger)
: PluginStateManager(logger)
{
// enforce singleton pre-condition
assert(!_StateManagerInstance);
_StateManagerInstance = this;
_processedElementCount = 0;
if (!(_rawBuffer = (char *)malloc(BUFFER_LEN))) {
printf("Unable to allocate buffer of size %d", BUFFER_LEN);
}
else {
_readBuffer = ::uv_buf_init(_rawBuffer, BUFFER_LEN);
}
}
SimSourcePluginStateManager::~SimSourcePluginStateManager(void)
{
// TODO: enable once shtudown implemented
if (_pluginThread != NULL) {
if (_pluginThread->joinable()) {
ceaseEventing();
_pluginThread->join();
}
delete _pluginThread;
}
if (_rawBuffer != NULL)
free(_rawBuffer);
}
int SimSourcePluginStateManager::preflightComplete(void)
{
int retVal = PREFLIGHT_OK;
int port = 8091;
libconfig::Setting *devicesConfiguraiton = NULL;
std::string type = "";
std::string ipAddress = "";
try {
devicesConfiguraiton = &_config->lookup("configuration");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {
if (iter->exists("ipAddress")) {
iter->lookupValue("ipAddress", ipAddress);
}
else {
ipAddress = "127.0.0.1";
}
if (iter->exists("port")) {
iter->lookupValue("port", port);
}
}
struct sockaddr_in req_addr;
_eventLoop = uv_default_loop();
check_uv(uv_loop_init(_eventLoop));
check_uv(uv_tcp_init(_eventLoop, &_tcpClient));
uv_tcp_keepalive(&_tcpClient, 1, 60);
uv_ip4_addr(ipAddress.c_str(), port, &req_addr);
int connectErr = uv_tcp_connect(&_connectReq, &_tcpClient, (struct sockaddr *)&req_addr, &SimSourcePluginStateManager::OnConnect);
if (connectErr < 0) {
retVal = PREFLIGHT_FAIL;
}
return retVal;
}
void SimSourcePluginStateManager::OnConnect(uv_connect_t *req, int status)
{
assert(SimSourcePluginStateManager::StateManagerInstance());
if (status == SIM_CONNECT_NOT_FOUND) {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_ERROR, " - Failed to connect to simulator");
}
else {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - Connected to simulator %d", status);
SimSourcePluginStateManager::StateManagerInstance()->instanceConnectionHandler(req, status);
}
}
void SimSourcePluginStateManager::OnRead(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)
{
SimSourcePluginStateManager::StateManagerInstance()->instanceReadHandler(server, nread, buf);
}
void SimSourcePluginStateManager::OnClose(uv_handle_t *handle)
{
assert(SimSourcePluginStateManager::StateManagerInstance());
SimSourcePluginStateManager::StateManagerInstance()->instanceCloseHandler(handle);
}
void SimSourcePluginStateManager::instanceConnectionHandler(uv_connect_t *req, int status)
{
if (uv_is_readable(req->handle)) {
uv_read_start(req->handle, &SimSourcePluginStateManager::AllocBuffer, &SimSourcePluginStateManager::OnRead);
}
else {
printf("not readable\n");
}
}
void SimSourcePluginStateManager::instanceReadHandler(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)
{
if (nread > 0) {
uv_buf_t buffer = uv_buf_init((char *)malloc(nread), nread);
memcpy(buffer.base, buf->base, nread);
buffer.base[nread - 1] = '\0';
processData(buffer.base, nread);
free(buffer.base);
}
else if (nread < 0) {
if (nread == UV_EOF) {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - Stopping prepare3d ingest loop");
ceaseEventing();
}
else {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - %s", uv_strerror(nread));
uv_close((uv_handle_t *)server, &SimSourcePluginStateManager::OnClose);
}
}
}
void SimSourcePluginStateManager::processData(char *data, int len)
{
if (len > 2) {
int elementCount = 0;
char *p = strtok(data, "\n");
char *array[MAX_ELEMENTS_PER_UPDATE];
while (p != NULL) {
size_t len = strlen(p);
if (len > 2) {
char *buffer = (char *)malloc(BUFFER_LEN);
memset(buffer, 0, BUFFER_LEN);
strncpy(buffer, p, len);
buffer[len - 1] = '\0';
array[elementCount++] = buffer;
}
p = strtok(NULL, "\n");
}
for (int i = 0; i < elementCount; ++i) {
processElement(array[i]);
free(array[i]);
}
}
}
void SimSourcePluginStateManager::processElement(char *element)
{
char *name = strtok(element, "=");
char *value = strtok(NULL, "=");
if (value == NULL)
return;
char *type = getElementDataType(name[0]);
if (type != NULL) {
// SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, "%s %s %s", name, value, type);
simElement el;
el.name = name;
if (strncmp(type, "float", sizeof(&type)) == 0) {
el.type = CONFIG_FLOAT;
el.value.float_value = atof(value);
el.length = sizeof(float);
}
else if (strncmp(type, "char", sizeof(&type)) == 0) {
el.type = CONFIG_STRING;
el.value.string_value = value;
el.length = strlen(value);
}
else if (strncmp(type, "integer", sizeof(&type)) == 0) {
el.type = CONFIG_INT;
el.value.int_value = atoi(value);
el.length = sizeof(int);
}
else if (strncmp(type, "bool", sizeof(&type)) == 0) {
el.type = CONFIG_BOOL;
el.length = sizeof(int);
if (strncmp(value, "OFF", sizeof(el.value)) == 0)
el.value.bool_value = 0;
else
el.value.bool_value = 1;
}
_enqueueCallback(this, (void *)&el, _callbackArg);
_processedElementCount++;
}
}
char *SimSourcePluginStateManager::getElementDataType(char identifier)
{
switch (identifier) {
case GAUGE_IDENTIFIER:
return (char *)"float";
break;
case NUMBER_IDENTIFIER:
return (char *)"float";
break;
case INDICATOR_IDENTIFIER:
return (char *)"bool";
break;
case VALUE_IDENTIFIER:
return (char *)"uint";
break;
case ANALOG_IDENTIFIER:
return (char *)"char";
break;
case ROTARY_IDENTIFIER:
return (char *)"char";
break;
case BOOLEAN_IDENTIFIER:
return (char *)"bool";
break;
default:
return NULL;
}
return NULL;
}
void SimSourcePluginStateManager::instanceCloseHandler(uv_handle_t *handle)
{
if (!_eventLoop->active_handles) {
uv_stop(_eventLoop);
}
}
void SimSourcePluginStateManager::ceaseEventing(void)
{
uv_stop(_eventLoop);
}
void SimSourcePluginStateManager::commenceEventing(EnqueueEventHandler enqueueCallback, void *arg)
{
_enqueueCallback = enqueueCallback;
_callbackArg = arg;
// this is wrong in a number of ways - it needs to be cancel-able being its chief sin
// TODO: unbreak
_pluginThread = new std::thread([=] { check_uv(uv_run(_eventLoop, UV_RUN_DEFAULT)); });
}
<commit_msg>more fixing of data element parsing<commit_after>#include <assert.h>
#include <iostream>
#include <memory>
#include <vector>
#include "common/simhubdeviceplugin.h"
#include "main.h"
// -- public C FFI
extern "C" {
int simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)
{
*plugin_instance = new SimSourcePluginStateManager(logger);
return 0;
}
int simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));
}
int simplug_preflight_complete(SPHANDLE plugin_instance)
{
return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();
}
void simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)
{
static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);
}
int simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)
{
return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);
}
void simplug_cease_eventing(SPHANDLE plugin_instance)
{
static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();
}
void simplug_release(SPHANDLE plugin_instance)
{
assert(plugin_instance);
delete static_cast<PluginStateManager *>(plugin_instance);
}
}
// -- internal implementation
SimSourcePluginStateManager *SimSourcePluginStateManager::_StateManagerInstance = NULL;
void SimSourcePluginStateManager::AllocBuffer(uv_handle_t *handle, size_t size, uv_buf_t *buf)
{
*buf = SimSourcePluginStateManager::StateManagerInstance()->_readBuffer;
}
//! static getter for singleton instance of our class
SimSourcePluginStateManager *SimSourcePluginStateManager::StateManagerInstance(void)
{
return _StateManagerInstance;
}
SimSourcePluginStateManager::SimSourcePluginStateManager(LoggingFunctionCB logger)
: PluginStateManager(logger)
{
// enforce singleton pre-condition
assert(!_StateManagerInstance);
_StateManagerInstance = this;
_processedElementCount = 0;
if (!(_rawBuffer = (char *)malloc(BUFFER_LEN))) {
printf("Unable to allocate buffer of size %d", BUFFER_LEN);
}
else {
_readBuffer = ::uv_buf_init(_rawBuffer, BUFFER_LEN);
}
}
SimSourcePluginStateManager::~SimSourcePluginStateManager(void)
{
// TODO: enable once shtudown implemented
if (_pluginThread != NULL) {
if (_pluginThread->joinable()) {
ceaseEventing();
_pluginThread->join();
}
delete _pluginThread;
}
if (_rawBuffer != NULL)
free(_rawBuffer);
}
int SimSourcePluginStateManager::preflightComplete(void)
{
int retVal = PREFLIGHT_OK;
int port = 8091;
libconfig::Setting *devicesConfiguraiton = NULL;
std::string type = "";
std::string ipAddress = "";
try {
devicesConfiguraiton = &_config->lookup("configuration");
}
catch (const libconfig::SettingNotFoundException &nfex) {
_logger(LOG_ERROR, "Config file parse error at %s. Skipping....", nfex.getPath());
}
for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {
if (iter->exists("ipAddress")) {
iter->lookupValue("ipAddress", ipAddress);
}
else {
ipAddress = "127.0.0.1";
}
if (iter->exists("port")) {
iter->lookupValue("port", port);
}
}
struct sockaddr_in req_addr;
_eventLoop = uv_default_loop();
check_uv(uv_loop_init(_eventLoop));
check_uv(uv_tcp_init(_eventLoop, &_tcpClient));
uv_tcp_keepalive(&_tcpClient, 1, 60);
uv_ip4_addr(ipAddress.c_str(), port, &req_addr);
int connectErr = uv_tcp_connect(&_connectReq, &_tcpClient, (struct sockaddr *)&req_addr, &SimSourcePluginStateManager::OnConnect);
if (connectErr < 0) {
retVal = PREFLIGHT_FAIL;
}
return retVal;
}
void SimSourcePluginStateManager::OnConnect(uv_connect_t *req, int status)
{
assert(SimSourcePluginStateManager::StateManagerInstance());
if (status == SIM_CONNECT_NOT_FOUND) {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_ERROR, " - Failed to connect to simulator");
}
else {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - Connected to simulator %d", status);
SimSourcePluginStateManager::StateManagerInstance()->instanceConnectionHandler(req, status);
}
}
void SimSourcePluginStateManager::OnRead(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)
{
SimSourcePluginStateManager::StateManagerInstance()->instanceReadHandler(server, nread, buf);
}
void SimSourcePluginStateManager::OnClose(uv_handle_t *handle)
{
assert(SimSourcePluginStateManager::StateManagerInstance());
SimSourcePluginStateManager::StateManagerInstance()->instanceCloseHandler(handle);
}
void SimSourcePluginStateManager::instanceConnectionHandler(uv_connect_t *req, int status)
{
if (uv_is_readable(req->handle)) {
uv_read_start(req->handle, &SimSourcePluginStateManager::AllocBuffer, &SimSourcePluginStateManager::OnRead);
}
else {
printf("not readable\n");
}
}
void SimSourcePluginStateManager::instanceReadHandler(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)
{
if (nread > 0) {
uv_buf_t buffer = uv_buf_init((char *)malloc(nread), nread);
memcpy(buffer.base, buf->base, nread);
buffer.base[nread - 1] = '\0';
processData(buffer.base, nread);
free(buffer.base);
}
else if (nread < 0) {
if (nread == UV_EOF) {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - Stopping prepare3d ingest loop");
ceaseEventing();
}
else {
SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, " - %s", uv_strerror(nread));
uv_close((uv_handle_t *)server, &SimSourcePluginStateManager::OnClose);
}
}
}
void SimSourcePluginStateManager::processData(char *data, int len)
{
if (len > 2) {
int elementCount = 0;
char *p = strtok(data, "\n");
char *array[MAX_ELEMENTS_PER_UPDATE];
while (p != NULL) {
size_t len = strlen(p);
if (len > 2) {
char *buffer = (char *)malloc(BUFFER_LEN);
memset(buffer, 0, BUFFER_LEN);
strncpy(buffer, p, len);
buffer[len - 1] = '\0';
array[elementCount++] = buffer;
}
p = strtok(NULL, "\n");
}
for (int i = 0; i < elementCount; ++i) {
processElement(array[i]);
free(array[i]);
}
}
}
void SimSourcePluginStateManager::processElement(char *element)
{
char *name = strtok(element, "=");
char *value = strtok(NULL, " =");
name[strlen(name) - 1] = '\0';
if (value == NULL)
return;
char *type = getElementDataType(name[0]);
if (type != NULL) {
simElement el;
el.name = name;
if (strncmp(type, "float", sizeof(&type)) == 0) {
el.type = CONFIG_FLOAT;
el.value.float_value = atof(value);
el.length = sizeof(float);
}
else if (strncmp(type, "char", sizeof(&type)) == 0) {
el.type = CONFIG_STRING;
el.value.string_value = value;
el.length = strlen(value);
}
else if (strncmp(type, "integer", sizeof(&type)) == 0) {
el.type = CONFIG_INT;
el.value.int_value = atoi(value);
el.length = sizeof(int);
}
else if (strncmp(type, "bool", sizeof(&type)) == 0) {
el.type = CONFIG_BOOL;
el.length = sizeof(int);
if (strncmp(value, "OFF", sizeof(el.value)) == 0)
el.value.bool_value = 0;
else
el.value.bool_value = 1;
}
_enqueueCallback(this, (void *)&el, _callbackArg);
_processedElementCount++;
}
}
char *SimSourcePluginStateManager::getElementDataType(char identifier)
{
switch (identifier) {
case GAUGE_IDENTIFIER:
return (char *)"float";
break;
case NUMBER_IDENTIFIER:
return (char *)"float";
break;
case INDICATOR_IDENTIFIER:
return (char *)"bool";
break;
case VALUE_IDENTIFIER:
return (char *)"uint";
break;
case ANALOG_IDENTIFIER:
return (char *)"char";
break;
case ROTARY_IDENTIFIER:
return (char *)"char";
break;
case BOOLEAN_IDENTIFIER:
return (char *)"bool";
break;
default:
return NULL;
}
return NULL;
}
void SimSourcePluginStateManager::instanceCloseHandler(uv_handle_t *handle)
{
if (!_eventLoop->active_handles) {
uv_stop(_eventLoop);
}
}
void SimSourcePluginStateManager::ceaseEventing(void)
{
uv_stop(_eventLoop);
}
void SimSourcePluginStateManager::commenceEventing(EnqueueEventHandler enqueueCallback, void *arg)
{
_enqueueCallback = enqueueCallback;
_callbackArg = arg;
// this is wrong in a number of ways - it needs to be cancel-able being its chief sin
// TODO: unbreak
_pluginThread = new std::thread([=] { check_uv(uv_run(_eventLoop, UV_RUN_DEFAULT)); });
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "historycompleter.h"
#include "fancylineedit.h"
#include "qtcassert.h"
#include <QSettings>
#include <QItemDelegate>
#include <QKeyEvent>
#include <QListView>
#include <QPainter>
namespace Utils {
namespace Internal {
static QSettings *theSettings = 0;
class HistoryCompleterPrivate : public QAbstractListModel
{
public:
HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
void clearHistory();
void saveEntry(const QString &str);
QStringList list;
QString historyKey;
int maxLines;
FancyLineEdit *lineEdit;
};
class HistoryLineDelegate : public QItemDelegate
{
public:
HistoryLineDelegate(QObject *parent)
: QItemDelegate(parent)
, pixmap(QLatin1String(":/core/images/editclear.png"))
{}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QItemDelegate::paint(painter,option,index);
QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);
painter->drawPixmap(r, pixmap);
}
QPixmap pixmap;
};
class HistoryLineView : public QListView
{
public:
HistoryLineView(HistoryCompleterPrivate *model_)
: model(model_)
{
HistoryLineDelegate *delegate = new HistoryLineDelegate(this);
pixmapWidth = delegate->pixmap.width();
setItemDelegate(delegate);
}
private:
void mousePressEvent(QMouseEvent *event)
{
int rr= event->x();
if (layoutDirection() == Qt::LeftToRight)
rr = viewport()->width() - event->x();
if (rr < pixmapWidth) {
model->removeRow(indexAt(event->pos()).row());
return;
}
QListView::mousePressEvent(event);
}
HistoryCompleterPrivate *model;
int pixmapWidth;
};
} // namespace Internal
using namespace Internal;
int HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : list.count();
}
QVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const
{
if (index.row() >= list.count() || index.column() != 0)
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
return list.at(index.row());
return QVariant();
}
bool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)
{
QTC_ASSERT(theSettings, return false);
if (row + count > list.count())
return false;
beginRemoveRows(parent, row, row + count -1);
for (int i = 0; i < count; ++i)
list.removeAt(row);
theSettings->setValue(historyKey, list);
endRemoveRows();
return true;
}
void HistoryCompleterPrivate::clearHistory()
{
beginResetModel();
list.clear();
endResetModel();
}
void HistoryCompleterPrivate::saveEntry(const QString &str)
{
QTC_ASSERT(theSettings, return);
const QString &entry = str.trimmed();
int removeIndex = list.indexOf(entry);
if (removeIndex != -1)
removeRow(removeIndex);
beginInsertRows (QModelIndex(), list.count(), list.count());
list.prepend(entry);
list = list.mid(0, maxLines);
endInsertRows();
theSettings->setValue(historyKey, list);
}
HistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)
: QCompleter(parent),
d(new HistoryCompleterPrivate)
{
QTC_ASSERT(lineEdit, return);
QTC_ASSERT(!historyKey.isEmpty(), return);
QTC_ASSERT(theSettings, return);
d->historyKey = QLatin1String("CompleterHistory/") + historyKey;
d->list = theSettings->value(d->historyKey).toStringList();
d->lineEdit = lineEdit;
if (d->list.count())
lineEdit->setText(d->list.at(0));
setModel(d);
setPopup(new HistoryLineView(d));
connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));
}
bool HistoryCompleter::removeHistoryItem(int index)
{
return d->removeRow(index);
}
HistoryCompleter::~HistoryCompleter()
{
delete d;
}
int HistoryCompleter::historySize() const
{
return d->rowCount();
}
int HistoryCompleter::maximalHistorySize() const
{
return d->maxLines;
}
void HistoryCompleter::setMaximalHistorySize(int numberOfEntries)
{
d->maxLines = numberOfEntries;
}
void HistoryCompleter::clearHistory()
{
d->clearHistory();
}
void HistoryCompleter::saveHistory()
{
d->saveEntry(d->lineEdit->text());
}
void HistoryCompleter::setSettings(QSettings *settings)
{
Internal::theSettings = settings;
}
} // namespace Utils
<commit_msg>HistoryCompleter: Do not overwrite text in the FancyLineEdit<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "historycompleter.h"
#include "fancylineedit.h"
#include "qtcassert.h"
#include <QSettings>
#include <QItemDelegate>
#include <QKeyEvent>
#include <QListView>
#include <QPainter>
namespace Utils {
namespace Internal {
static QSettings *theSettings = 0;
class HistoryCompleterPrivate : public QAbstractListModel
{
public:
HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());
void clearHistory();
void saveEntry(const QString &str);
QStringList list;
QString historyKey;
int maxLines;
FancyLineEdit *lineEdit;
};
class HistoryLineDelegate : public QItemDelegate
{
public:
HistoryLineDelegate(QObject *parent)
: QItemDelegate(parent)
, pixmap(QLatin1String(":/core/images/editclear.png"))
{}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QItemDelegate::paint(painter,option,index);
QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);
painter->drawPixmap(r, pixmap);
}
QPixmap pixmap;
};
class HistoryLineView : public QListView
{
public:
HistoryLineView(HistoryCompleterPrivate *model_)
: model(model_)
{
HistoryLineDelegate *delegate = new HistoryLineDelegate(this);
pixmapWidth = delegate->pixmap.width();
setItemDelegate(delegate);
}
private:
void mousePressEvent(QMouseEvent *event)
{
int rr= event->x();
if (layoutDirection() == Qt::LeftToRight)
rr = viewport()->width() - event->x();
if (rr < pixmapWidth) {
model->removeRow(indexAt(event->pos()).row());
return;
}
QListView::mousePressEvent(event);
}
HistoryCompleterPrivate *model;
int pixmapWidth;
};
} // namespace Internal
using namespace Internal;
int HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : list.count();
}
QVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const
{
if (index.row() >= list.count() || index.column() != 0)
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
return list.at(index.row());
return QVariant();
}
bool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)
{
QTC_ASSERT(theSettings, return false);
if (row + count > list.count())
return false;
beginRemoveRows(parent, row, row + count -1);
for (int i = 0; i < count; ++i)
list.removeAt(row);
theSettings->setValue(historyKey, list);
endRemoveRows();
return true;
}
void HistoryCompleterPrivate::clearHistory()
{
beginResetModel();
list.clear();
endResetModel();
}
void HistoryCompleterPrivate::saveEntry(const QString &str)
{
QTC_ASSERT(theSettings, return);
const QString &entry = str.trimmed();
int removeIndex = list.indexOf(entry);
if (removeIndex != -1)
removeRow(removeIndex);
beginInsertRows (QModelIndex(), list.count(), list.count());
list.prepend(entry);
list = list.mid(0, maxLines);
endInsertRows();
theSettings->setValue(historyKey, list);
}
HistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)
: QCompleter(parent),
d(new HistoryCompleterPrivate)
{
QTC_ASSERT(lineEdit, return);
QTC_ASSERT(!historyKey.isEmpty(), return);
QTC_ASSERT(theSettings, return);
d->historyKey = QLatin1String("CompleterHistory/") + historyKey;
d->list = theSettings->value(d->historyKey).toStringList();
d->lineEdit = lineEdit;
if (d->list.count() && lineEdit->text().isEmpty())
lineEdit->setText(d->list.at(0));
setModel(d);
setPopup(new HistoryLineView(d));
connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));
}
bool HistoryCompleter::removeHistoryItem(int index)
{
return d->removeRow(index);
}
HistoryCompleter::~HistoryCompleter()
{
delete d;
}
int HistoryCompleter::historySize() const
{
return d->rowCount();
}
int HistoryCompleter::maximalHistorySize() const
{
return d->maxLines;
}
void HistoryCompleter::setMaximalHistorySize(int numberOfEntries)
{
d->maxLines = numberOfEntries;
}
void HistoryCompleter::clearHistory()
{
d->clearHistory();
}
void HistoryCompleter::saveHistory()
{
d->saveEntry(d->lineEdit->text());
}
void HistoryCompleter::setSettings(QSettings *settings)
{
Internal::theSettings = settings;
}
} // namespace Utils
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
#include "line_utilities.h"
#include "../control.h"
#include "line_simplification.h"
using namespace std;
using namespace cv;
void LineFollowing::detect_lines(Mat &original_frame) {
Mat hsv;
Mat mask;
width = original_frame.cols;
height = original_frame.rows;
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
// printf("Adding in %d lines\n", (int) lines.size());
vector<Vec2f> tmp = condense_lines(lines, true);
sort(tmp.begin(), tmp.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
if (tmp.size() > 0) {
found_lines = tmp;
}
draw_lines(original_frame, found_lines, Scalar(255, 255, 255));
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
minH = 50;
minS = 20;
minV = 150;
maxH = 125;
maxS = 100;
maxV = 255;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
int center_x = 0 + (control_ptr->image.cols / 2);
int center_y = 0 + (control_ptr->image.rows / 2);
Point center_point = cvPoint(center_x, center_y);
int tolerance = 10;
line_options categorization;
Point intersection_point;
double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image);
if (found_lines.size() < 1) return;
if (found_lines.size() == 1) {
categorization.vertical = found_lines[0];
calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
control_ptr->image.cols, control_ptr->image.rows);
calculated_distance_from_horizontal = 0;
intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);
} else if (found_lines.size() == 2) {
//TODO maybe this is a very bad assumption to make, that [0] is the vertical line
categorization.vertical = found_lines[0];
categorization.horizontal = found_lines[1];
calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
control_ptr->image.cols, control_ptr->image.rows);
calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],
categorization.horizontal[0],
control_ptr->image.cols, control_ptr->image.rows);
intersection_point = find_intersection(categorization.vertical, categorization.horizontal);
}
if (found_lines.size() < 3) {
//For 1 or 2 lines
line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); // draw the line to the center
//draw a cross at the intersection
line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),
cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);
line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),
cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);
// I need to snap myself to the line
if (categorization.vertical[0] >= deg2rad(5)) {
control_ptr->velocities.vr = -.2;
// printf("Turning Right\n");
} else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {
control_ptr->velocities.vr = .2;
// printf("Turning Left\n");
} else {
// printf("Checking Distance\n");
// printf("Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\n", offset,
// (double) control_ptr->image.cols, (control_ptr->image.cols / 2.0));
if (-100 >= calculated_distance_from_vertical && calculated_distance_from_vertical >= 100) {
if (calculated_distance_from_vertical < 0) {
//we are to the right of the line
//we need to move left
control_ptr->velocities.vy = 1;
// printf("Move left\n");
} else {
//we need to move right
control_ptr->velocities.vy = -1;
// printf("Move right\n");
}
}
if (-100 >= calculated_distance_from_horizontal && calculated_distance_from_horizontal >= 100) {
//todo move up or down the line
if (calculated_distance_from_horizontal > 0) {
// we are above the line
// so we need to move backwards
// I think
// todo check this
control_ptr->velocities.vx = -1;
} else {
control_ptr->velocities.vx = 1;
}
}
}
} else {
for (int i = 0; i < found_lines.size(); ++i) {
float angle = abs(found_lines[i][0]);
if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {
categorization.vertical = found_lines[i];
}
if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {
categorization.horizontal = found_lines[i];
}
if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {
categorization.sloped = found_lines[i];
if (found_lines[i][0] < 0) {
categorization.d = direction::right;
} else if (found_lines[i][0] > 0) {
categorization.d = direction::left;
}
}
}
}
if (found_lines.size() > 3) {
//print out the points of all 4+ lines
for (int j = 0; j < (int) found_lines.size(); j++) {
printf("(%5.1f, %5.0f) ", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);
}
printf("\n");
}
//Draw all the lines
if (categorization.horizontal != Vec2f()) {
draw_line(control_ptr->image, categorization.horizontal, color_green);
}
if (categorization.vertical != Vec2f()) {
draw_line(control_ptr->image, categorization.vertical, color_blue);
}
if (categorization.sloped != Vec2f()) {
draw_line(control_ptr->image, categorization.sloped, color_red);
}
return;
}
cv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {
Point rv;
bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);
if (!do_intersect) {
printf("No intersection!\n");
}
return rv;
}
<commit_msg>tweaks<commit_after>/*
*/
#include "lineFollowing.h"
#include "line_utilities.h"
#include "../control.h"
#include "line_simplification.h"
using namespace std;
using namespace cv;
void LineFollowing::detect_lines(Mat &original_frame) {
Mat hsv;
Mat mask;
width = original_frame.cols;
height = original_frame.rows;
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
// printf("Adding in %d lines\n", (int) lines.size());
vector<Vec2f> tmp = condense_lines(lines, true);
sort(tmp.begin(), tmp.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
if (tmp.size() > 0) {
found_lines = tmp;
}
draw_lines(original_frame, found_lines, Scalar(255, 255, 255));
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
minH = 50;
minS = 20;
minV = 150;
maxH = 125;
maxS = 100;
maxV = 255;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
int center_x = 0 + (control_ptr->image.cols / 2);
int center_y = 0 + (control_ptr->image.rows / 2);
Point center_point = cvPoint(center_x, center_y);
int tolerance = 10;
line_options categorization;
Point intersection_point;
double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image);
if (found_lines.size() < 1) return;
if (found_lines.size() == 1) {
categorization.vertical = found_lines[0];
calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
control_ptr->image.cols, control_ptr->image.rows);
calculated_distance_from_horizontal = 0;
intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);
if (true) {
printf("Width of %7.1f with (%5.1f, %5.1f)\n", calculated_distance_from_vertical, categorization.vertical[0],
categorization.vertical[1]);
}
} else if (found_lines.size() == 2) {
//TODO maybe this is a very bad assumption to make, that [0] is the vertical line
categorization.vertical = found_lines[1];
categorization.horizontal = found_lines[0];
calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],
control_ptr->image.cols, control_ptr->image.rows);
calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],
categorization.horizontal[0],
control_ptr->image.cols, control_ptr->image.rows);
intersection_point = find_intersection(categorization.vertical, categorization.horizontal);
}
if (found_lines.size() < 3) {
//For 1 or 2 lines
line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); // draw the line to the center
//draw a cross at the intersection
line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),
cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);
line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),
cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);
// I need to snap myself to the line
if (categorization.vertical[0] >= deg2rad(5)) {
control_ptr->velocities.vr = -.2;
// printf("Turning Right\n");
} else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {
control_ptr->velocities.vr = .2;
// printf("Turning Left\n");
} else {
// printf("Checking Distance\n");
// printf("Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\n", offset,
// (double) control_ptr->image.cols, (control_ptr->image.cols / 2.0));
int vertical_tolerance = 50;
int horizontal_tolerance = 100;
if (-1 * vertical_tolerance >= calculated_distance_from_vertical &&
calculated_distance_from_vertical >= vertical_tolerance) {
if (calculated_distance_from_vertical < 0) {
//we are to the right of the line
//we need to move left
control_ptr->velocities.vy = 1;
// printf("Move left\n");
} else {
//we need to move right
control_ptr->velocities.vy = -1;
// printf("Move right\n");
}
}
if (-1 * horizontal_tolerance >= calculated_distance_from_horizontal &&
calculated_distance_from_horizontal >= horizontal_tolerance) {
//todo move up or down the line
if (calculated_distance_from_horizontal > 0) {
// we are above the line
// so we need to move backwards
// I think
// todo check this
control_ptr->velocities.vx = -1;
} else {
control_ptr->velocities.vx = 1;
}
}
}
} else {
for (int i = 0; i < found_lines.size(); ++i) {
float angle = abs(found_lines[i][0]);
if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {
categorization.vertical = found_lines[i];
}
if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {
categorization.horizontal = found_lines[i];
}
if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {
categorization.sloped = found_lines[i];
if (found_lines[i][0] < 0) {
categorization.d = direction::right;
} else if (found_lines[i][0] > 0) {
categorization.d = direction::left;
}
}
}
}
if (found_lines.size() > 3) {
//print out the points of all 4+ lines
for (int j = 0; j < (int) found_lines.size(); j++) {
printf("(%5.1f, %5.0f) ", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);
}
printf("\n");
}
//Draw all the lines
if (categorization.horizontal != Vec2f()) {
draw_line(control_ptr->image, categorization.horizontal, color_green);
}
if (categorization.vertical != Vec2f()) {
draw_line(control_ptr->image, categorization.vertical, color_blue);
}
if (categorization.sloped != Vec2f()) {
draw_line(control_ptr->image, categorization.sloped, color_red);
}
return;
}
cv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {
Point rv;
bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);
if (!do_intersect) {
printf("No intersection!\n");
}
return rv;
}
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
// printf("Hello, this is Caleb\n");
VideoCapture cap("../../tests/videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
namedWindow("edges", CV_WINDOW_NORMAL);
// Mat edges;
for (; ;) {
Mat mask;
Mat frame, hsv;
cap >> frame; // get a new frame from camera
cvtColor(frame, hsv, CV_BGR2HSV);
double minH = 30;
double minS = 0;
double minV = 240;
double maxH = 80;
double maxS = 70;
double maxV = 255;
cv::Scalar lower(minH, minS, minV);
cv::Scalar upper(maxH, maxS, maxV);
cv::inRange(hsv, lower, upper, mask);
// bitwise_and(frame, frame, frame, mask);
// medianBlur(mask, mask, 5);
erode(mask, mask, Mat(), Point(-1,-1), 20);
vector <Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);
printf("Adding in %d lines\n", (int) lines.size());
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
// break;
}
// if (lines.size() < 1) continue;
imshow("edges", mask);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
<commit_msg>messing with erode<commit_after>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
// printf("Hello, this is Caleb\n");
VideoCapture cap("../../tests/videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
namedWindow("edges", CV_WINDOW_NORMAL);
// Mat edges;
for (; ;) {
Mat mask;
Mat frame, hsv;
cap >> frame; // get a new frame from camera
cvtColor(frame, hsv, CV_BGR2HSV);
double minH = 30;
double minS = 0;
double minV = 240;
double maxH = 80;
double maxS = 70;
double maxV = 255;
cv::Scalar lower(minH, minS, minV);
cv::Scalar upper(maxH, maxS, maxV);
cv::inRange(hsv, lower, upper, mask);
// bitwise_and(frame, frame, frame, mask);
// medianBlur(mask, mask, 5);
erode(mask, mask, Mat(), Point(-1,-1), 12);
vector <Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);
printf("Adding in %d lines\n", (int) lines.size());
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
// break;
}
// if (lines.size() < 1) continue;
imshow("edges", mask);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
void detect_lines(Mat &original_frame, double scale_factor);
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
// printf("Hello, this is Caleb\n");
// no this is patric
VideoCapture cap("../../tests/videos/top_down_1.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
// Mat edges;
for (; ;) {
Mat frame;
cap >> frame; // get a new frame from camera
detect_lines(frame, .2);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
#pragma clang diagnostic pop
void detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame
cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV
double minH = 50;
double minS = 20;
double minV = 150;
double maxH = 125;
double maxS = 100;
double maxV = 255;
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
vector<Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image
printf("Adding in %d lines\n", (int) lines.size());
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
// break;
}
// if (lines.size() < 1) continue;
// imshow("line_window", image);
original_frame = image;
}
void LineFollowing::initialize() {
namedWindow("line_window", CV_WINDOW_NORMAL);
return;
}
void LineFollowing::close() {
return;
}
ControlMovements LineFollowing::fly(cv::Mat *image) {
ControlMovements velocities;
velocities.vx = 0;
velocities.vy = 0;
velocities.vz = 0;
velocities.vr = 0;
detect_lines(*image, .3);
return velocities;
}
<commit_msg>shows lines on the main screen<commit_after>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
void detect_lines(Mat &original_frame, double scale_factor);
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
// printf("Hello, this is Caleb\n");
// no this is patric
VideoCapture cap("../../tests/videos/top_down_1.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
// Mat edges;
for (; ;) {
Mat frame;
cap >> frame; // get a new frame from camera
detect_lines(frame, .2);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
#pragma clang diagnostic pop
void detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame
cvtColor(image, hsv, CV_BGR2HSV); // Image is now HSV
double minH = 50;
double minS = 20;
double minV = 150;
double maxH = 125;
double maxS = 100;
double maxV = 255;
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
vector<Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image
printf("Adding in %d lines\n", (int) lines.size());
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);
// break;
}
// if (lines.size() < 1) continue;
// imshow("line_window", image);
resize(image, original_frame, Size(), 1/scale_factor, 1/scale_factor);
}
void LineFollowing::initialize() {
namedWindow("line_window", CV_WINDOW_NORMAL);
return;
}
void LineFollowing::close() {
return;
}
ControlMovements LineFollowing::fly(cv::Mat *image) {
ControlMovements velocities;
velocities.vx = 0;
velocities.vy = 0;
velocities.vz = 0;
velocities.vr = 0;
detect_lines(*image, .3);
return velocities;
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Connections class in C++
*/
#ifndef NTA_CONNECTIONS_HPP
#define NTA_CONNECTIONS_HPP
#include <vector>
#include <utility>
#include <nta/types/Types.hpp>
#include <nta/math/Math.hpp>
namespace nta
{
namespace algorithms
{
namespace connections
{
typedef UInt32 CellIdx;
typedef unsigned char SegmentIdx;
typedef unsigned char SynapseIdx;
typedef Real32 Permanence;
/**
* Cell class used in Connections.
*
* @b Description
* The Cell class is a data structure that points to a particular cell.
*
* @param idx Index of cell.
*
*/
struct Cell
{
CellIdx idx;
Cell(CellIdx idx) : idx(idx) {}
Cell() {}
bool operator==(const Cell &other) const;
bool operator<=(const Cell &other) const;
bool operator<(const Cell &other) const;
bool operator>=(const Cell &other) const;
bool operator>(const Cell &other) const;
};
/**
* Segment class used in Connections.
*
* @b Description
* The Segment class is a data structure that points to a particular
* segment on a particular cell.
*
* @param idx Index of segment.
* @param cellIdx Index of cell.
*
*/
struct Segment
{
SegmentIdx idx;
Cell cell;
Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}
Segment() {}
bool operator==(const Segment &other) const;
bool operator<=(const Segment &other) const;
bool operator<(const Segment &other) const;
bool operator>=(const Segment &other) const;
bool operator>(const Segment &other) const;
};
/**
* Synapse class used in Connections.
*
* @b Description
* The Synapse class is a data structure that points to a particular
* synapse on a particular segment on a particular cell.
*
* @param idx Index of synapse in segment.
* @param segmentIdx Index of segment in cell.
* @param cellIdx Index of cell.
*
*/
struct Synapse
{
SynapseIdx idx;
Segment segment;
Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}
Synapse() {}
bool operator==(const Synapse &other) const;
};
/**
* SynapseData class used in Connections.
*
* @b Description
* The SynapseData class is a data structure that contains the data for a
* synapse on a segment.
*
* @param presynapticCellIdx Cell that this synapse gets input from.
* @param permanence Permanence of synapse.
*
*/
struct SynapseData
{
Cell presynapticCell;
Permanence permanence;
};
/**
* SegmentData class used in Connections.
*
* @b Description
* The SegmentData class is a data structure that contains the data for a
* segment on a cell.
*
* @param synapses Data for synapses that this segment contains.
*
*/
struct SegmentData
{
std::vector<SynapseData> synapses;
};
/**
* CellData class used in Connections.
*
* @b Description
* The CellData class is a data structure that contains the data for a
* cell.
*
* @param segments Data for segments that this cell contains.
*
*/
struct CellData
{
std::vector<SegmentData> segments;
};
/**
* Activity class used in Connections.
*
* @b Description
* The Activity class is a data structure that represents the
* activity of a collection of cells, as computed by propagating
* input through connections.
*
*/
struct Activity
{
std::map< Cell, std::vector<Segment> > activeSegmentsForCell;
std::map<Segment, UInt> numActiveSynapsesForSegment;
};
/**
* Connections implementation in C++.
*
* @b Description
* The Connections class is a data structure that represents the
* connections of a collection of cells. It is used in the HTM
* learning algorithms to store and access data related to the
* connectivity of cells.
*
* It's main utility is to provide a common, optimized data structure
* that all HTM learning algorithms can use. It is flexible enough to
* support any learning algorithm that operates on a collection of cells.
*
* Each type of connection (proximal, distal, apical) should be
* represented by a different instantiation of this class. This class
* will help compute the activity along those connections due to active
* input cells. The responsibility for what effect that activity has on
* the cells and connections lies in the user of this class.
*
* This class is optimized to store connections between cells, and
* compute the activity of cells due to input over the connections.
*
*/
class Connections
{
public:
Connections(CellIdx numCells);
virtual ~Connections() {}
/**
Creates a segment on the specified cell.
@param cell Cell to create segment on.
@retval Created segment.
*/
Segment createSegment(const Cell& cell);
/**
Creates a synapse on the specified segment.
@param segment Segment to create synapse on.
@param presynapticCell Cell to synapse on.
@param permanence Initial permanence of new synapse.
@reval Created synapse.
*/
Synapse createSynapse(const Segment& segment,
const Cell& presynapticCell,
Permanence permanence);
/**
Updates a synapse's permanence.
@param synapse Synapse to update.
@param permanence New permanence.
*/
void updateSynapsePermanence(const Synapse& synapse,
Permanence permanence);
/**
Gets the segments for a cell.
@param cell Cell to get segments for.
@retval Segments on cell.
*/
std::vector<Segment> segmentsForCell(const Cell& cell);
/**
Gets the synapses for a segment.
@param segment Segment to get synapses for.
@retval Synapses on segment.
*/
std::vector<Synapse> synapsesForSegment(const Segment& segment);
/**
Gets the data for a synapse.
@param synapse Synapse to get data for.
@retval Synapse data.
*/
SynapseData dataForSynapse(const Synapse& synapse) const;
/**
Gets the segment with the most active synapses due to given input,
from among all the segments on all the given cells.
@param cells Cells to look among.
@param input Active cells in the input.
@param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
@param segment Segment to return.
@retval Segment found?
*/
bool mostActiveSegmentForCells(const std::vector<Cell>& cells,
std::vector<Cell> input,
UInt synapseThreshold,
Segment& retSegment) const;
/**
Forward-propagates input to synapses, dendrites, and cells, to
compute their activity.
@param input Active cells in the input.
@param permanenceThreshold Only consider synapses with permanences greater than this threshold.
@param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
@retval Activity to return.
*/
Activity computeActivity(const std::vector<Cell>& input,
Permanence permanenceThreshold,
UInt synapseThreshold) const;
/**
Gets the active segments from activity.
@param activity Activity.
@retval Active segments.
*/
std::vector<Segment> activeSegments(const Activity& activity);
/**
Gets the active cells from activity.
@param activity Activity.
@retval Active cells.
*/
std::vector<Cell> activeCells(const Activity& activity);
// Debugging
/**
Gets the number of segments.
@retval Number of segments.
*/
UInt numSegments() const;
/**
Gets the number of synapses.
@retval Number of synapses.
*/
UInt numSynapses() const;
private:
std::vector<CellData> cells_;
// Mapping (presynaptic cell => synapses) used in forward propagation
std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;
}; // end class Connections
} // end namespace connections
} // end namespace algorithms
} // end namespace nta
#endif // NTA_CONNECTIONS_HPP
<commit_msg>Formatting of documentation<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Connections class in C++
*/
#ifndef NTA_CONNECTIONS_HPP
#define NTA_CONNECTIONS_HPP
#include <vector>
#include <utility>
#include <nta/types/Types.hpp>
#include <nta/math/Math.hpp>
namespace nta
{
namespace algorithms
{
namespace connections
{
typedef UInt32 CellIdx;
typedef unsigned char SegmentIdx;
typedef unsigned char SynapseIdx;
typedef Real32 Permanence;
/**
* Cell class used in Connections.
*
* @b Description
* The Cell class is a data structure that points to a particular cell.
*
* @param idx Index of cell.
*
*/
struct Cell
{
CellIdx idx;
Cell(CellIdx idx) : idx(idx) {}
Cell() {}
bool operator==(const Cell &other) const;
bool operator<=(const Cell &other) const;
bool operator<(const Cell &other) const;
bool operator>=(const Cell &other) const;
bool operator>(const Cell &other) const;
};
/**
* Segment class used in Connections.
*
* @b Description
* The Segment class is a data structure that points to a particular
* segment on a particular cell.
*
* @param idx Index of segment.
* @param cellIdx Index of cell.
*
*/
struct Segment
{
SegmentIdx idx;
Cell cell;
Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}
Segment() {}
bool operator==(const Segment &other) const;
bool operator<=(const Segment &other) const;
bool operator<(const Segment &other) const;
bool operator>=(const Segment &other) const;
bool operator>(const Segment &other) const;
};
/**
* Synapse class used in Connections.
*
* @b Description
* The Synapse class is a data structure that points to a particular
* synapse on a particular segment on a particular cell.
*
* @param idx Index of synapse in segment.
* @param segmentIdx Index of segment in cell.
* @param cellIdx Index of cell.
*
*/
struct Synapse
{
SynapseIdx idx;
Segment segment;
Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}
Synapse() {}
bool operator==(const Synapse &other) const;
};
/**
* SynapseData class used in Connections.
*
* @b Description
* The SynapseData class is a data structure that contains the data for a
* synapse on a segment.
*
* @param presynapticCellIdx Cell that this synapse gets input from.
* @param permanence Permanence of synapse.
*
*/
struct SynapseData
{
Cell presynapticCell;
Permanence permanence;
};
/**
* SegmentData class used in Connections.
*
* @b Description
* The SegmentData class is a data structure that contains the data for a
* segment on a cell.
*
* @param synapses Data for synapses that this segment contains.
*
*/
struct SegmentData
{
std::vector<SynapseData> synapses;
};
/**
* CellData class used in Connections.
*
* @b Description
* The CellData class is a data structure that contains the data for a
* cell.
*
* @param segments Data for segments that this cell contains.
*
*/
struct CellData
{
std::vector<SegmentData> segments;
};
/**
* Activity class used in Connections.
*
* @b Description
* The Activity class is a data structure that represents the
* activity of a collection of cells, as computed by propagating
* input through connections.
*
*/
struct Activity
{
std::map< Cell, std::vector<Segment> > activeSegmentsForCell;
std::map<Segment, UInt> numActiveSynapsesForSegment;
};
/**
* Connections implementation in C++.
*
* @b Description
* The Connections class is a data structure that represents the
* connections of a collection of cells. It is used in the HTM
* learning algorithms to store and access data related to the
* connectivity of cells.
*
* It's main utility is to provide a common, optimized data structure
* that all HTM learning algorithms can use. It is flexible enough to
* support any learning algorithm that operates on a collection of cells.
*
* Each type of connection (proximal, distal, apical) should be
* represented by a different instantiation of this class. This class
* will help compute the activity along those connections due to active
* input cells. The responsibility for what effect that activity has on
* the cells and connections lies in the user of this class.
*
* This class is optimized to store connections between cells, and
* compute the activity of cells due to input over the connections.
*
*/
class Connections
{
public:
Connections(CellIdx numCells);
virtual ~Connections() {}
/**
* Creates a segment on the specified cell.
*
* @param cell Cell to create segment on.
*
* @retval Created segment.
*/
Segment createSegment(const Cell& cell);
/**
* Creates a synapse on the specified segment.
*
* @param segment Segment to create synapse on.
* @param presynapticCell Cell to synapse on.
* @param permanence Initial permanence of new synapse.
*
* @reval Created synapse.
*/
Synapse createSynapse(const Segment& segment,
const Cell& presynapticCell,
Permanence permanence);
/**
* Updates a synapse's permanence.
*
* @param synapse Synapse to update.
* @param permanence New permanence.
*/
void updateSynapsePermanence(const Synapse& synapse,
Permanence permanence);
/**
* Gets the segments for a cell.
*
* @param cell Cell to get segments for.
*
* @retval Segments on cell.
*/
std::vector<Segment> segmentsForCell(const Cell& cell);
/**
* Gets the synapses for a segment.
*
* @param segment Segment to get synapses for.
*
* @retval Synapses on segment.
*/
std::vector<Synapse> synapsesForSegment(const Segment& segment);
/**
* Gets the data for a synapse.
*
* @param synapse Synapse to get data for.
*
* @retval Synapse data.
*/
SynapseData dataForSynapse(const Synapse& synapse) const;
/**
* Gets the segment with the most active synapses due to given input,
* from among all the segments on all the given cells.
*
* @param cells Cells to look among.
* @param input Active cells in the input.
* @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
* @param segment Segment to return.
*
* @retval Segment found?
*/
bool mostActiveSegmentForCells(const std::vector<Cell>& cells,
std::vector<Cell> input,
UInt synapseThreshold,
Segment& retSegment) const;
/**
* Forward-propagates input to synapses, dendrites, and cells, to
* compute their activity.
*
* @param input Active cells in the input.
* @param permanenceThreshold Only consider synapses with permanences greater than this threshold.
* @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.
*
* @retval Activity to return.
*/
Activity computeActivity(const std::vector<Cell>& input,
Permanence permanenceThreshold,
UInt synapseThreshold) const;
/**
* Gets the active segments from activity.
*
* @param activity Activity.
*
* @retval Active segments.
*/
std::vector<Segment> activeSegments(const Activity& activity);
/**
* Gets the active cells from activity.
*
* @param activity Activity.
*
* @retval Active cells.
*/
std::vector<Cell> activeCells(const Activity& activity);
// Debugging
/**
* Gets the number of segments.
*
* @retval Number of segments.
*/
UInt numSegments() const;
/**
* Gets the number of synapses.
*
* @retval Number of synapses.
*/
UInt numSynapses() const;
private:
std::vector<CellData> cells_;
// Mapping (presynaptic cell => synapses) used in forward propagation
std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;
}; // end class Connections
} // end namespace connections
} // end namespace algorithms
} // end namespace nta
#endif // NTA_CONNECTIONS_HPP
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
// @brief: lane_post_processing_subnode source file
#include "modules/perception/obstacle/onboard/lane_post_processing_subnode.h"
#include <unordered_map>
#include <cfloat>
#include "Eigen/Dense"
#include "opencv2/opencv.hpp"
#include "yaml-cpp/yaml.h"
#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/common/time/time_util.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/camera/lane_post_process/cc_lane_post_processor/cc_lane_post_processor.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/types.h"
#include "modules/perception/proto/perception_obstacle.pb.h"
namespace apollo {
namespace perception {
using std::string;
using std::unordered_map;
using std::shared_ptr;
using apollo::common::Status;
using apollo::common::ErrorCode;
using apollo::common::time::Timer;
bool LanePostProcessingSubnode::InitInternal() {
// get Subnode config in DAG streaming
unordered_map<string, string> fields;
SubnodeHelper::ParseReserveField(reserve_, &fields);
if (fields.count("publish") && stoi(fields["publish"]) != 0) {
publish_ = true;
}
// init shared data
if (!InitSharedData()) {
AERROR << "failed to init shared data.";
return false;
}
RegistAllAlgorithms();
// init plugins
if (!InitAlgorithmPlugin()) {
AERROR << "failed to init algorithm plugins.";
return false;
}
AINFO << "init LanePostProcessing subnode successfully.";
return true;
}
bool LanePostProcessingSubnode::InitSharedData() {
if (shared_data_manager_ == nullptr) {
AERROR << "shared data manager is a null pointer.";
return false;
}
// init preprocess_data
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AERROR << "failed to get shared data instance: CameraObjectData ";
return false;
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AERROR << "failed to get shared data instance: LaneSharedData ";
return false;
}
AINFO << "init shared data successfully, data: "
<< camera_object_data_->name() << " and " << lane_shared_data_->name();
return true;
}
void LanePostProcessingSubnode::RegistAllAlgorithms() {
RegisterFactoryCCLanePostProcessor();
}
bool LanePostProcessingSubnode::InitAlgorithmPlugin() {
// init lane post-processer
lane_post_processor_.reset(
BaseCameraLanePostProcessorRegisterer::GetInstanceByName(
FLAGS_onboard_lane_post_processor));
if (!lane_post_processor_) {
AERROR << "failed to get instance: " << FLAGS_onboard_lane_post_processor;
return false;
}
if (!lane_post_processor_->Init()) {
AERROR << "failed to init lane post-processor: "
<< lane_post_processor_->name();
return false;
}
AINFO << "init alg pulgins successfully\n"
<< " lane post-processer: " << FLAGS_onboard_lane_post_processor;
return true;
}
bool LanePostProcessingSubnode::InitWorkRoot() {
ConfigManager *config_manager = ConfigManager::instance();
if (config_manager == NULL) {
AERROR << "failed to get ConfigManager instance.";
return false;
}
if (!config_manager->Init()) {
AERROR << "failed to init ConfigManager";
return false;
}
return true;
}
bool LanePostProcessingSubnode::GetSharedData(const Event &event,
shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
string device_id = event.reserve;
device_id_ = device_id;
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;
}
if (!camera_object_data_->Get(data_key, objs)) {
AERROR << "failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
void LanePostProcessingSubnode::PublishDataAndEvent(
const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {
string key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
AERROR << "failed to produce shared key. time: "
<< GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
return;
}
if (!lane_shared_data_->Add(key, lane_objects)) {
AWARN << "failed to add LaneSharedData. key: " << key
<< " num_detected_objects: " << lane_objects->size();
return;
}
// pub events
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
AINFO << "succeed to publish data and event.";
}
Status LanePostProcessingSubnode::ProcEvents() {
// fusion output subnode only subcribe the fusion subnode
CHECK_EQ(sub_meta_events_.size(), 1u) << "only subcribe one event.";
const EventMeta &event_meta = sub_meta_events_[0];
Event event;
event_manager_->Subscribe(event_meta.event_id, &event);
++seq_num_;
shared_ptr<SensorObjects> objs;
if (!GetSharedData(event, &objs)) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
}
Timer timer;
timer.Start();
cv::Mat lane_map = objs->camera_frame_supplement->lane_map;
if (lane_map.empty()) {
AERROR << "Get NULL lane_map from camera frame supplement";
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
}
LaneObjectsPtr lane_objects(new LaneObjects());
CameraLanePostProcessOptions options;
options.timestamp = event.timestamp;
timestamp_ns_ = event.timestamp * 1e9;
lane_post_processor_->Process(lane_map, options, &lane_objects);
for (size_t i = 0; i < lane_objects->size(); ++i) {
(*lane_objects)[i].timestamp = event.timestamp;
(*lane_objects)[i].seq_num = seq_num_;
}
AINFO << "Before publish lane objects, objects num: "
<< lane_objects->size();
uint64_t t = timer.End("lane post-processing");
min_processing_time_ = std::min(min_processing_time_, t);
max_processing_time_ = std::max(max_processing_time_, t);
tot_processing_time_ += t;
AINFO << "Lane Post Processing Runtime: "
<< "MIN (" << min_processing_time_ << " ms), "
<< "MAX (" << max_processing_time_ << " ms), "
<< "AVE (" << tot_processing_time_ / seq_num_ << " ms).";
PublishDataAndEvent(event.timestamp, lane_objects);
if (publish_) {
PublishPerceptionPb(lane_objects);
}
AINFO << "Successfully finished lane post processing";
return Status::OK();
}
void LanePostProcessingSubnode::PublishPerceptionPb(
const LaneObjectsPtr &lane_objects) {
ADEBUG << "Lane post-processor publish lane object pb data";
PerceptionObstacles obstacles;
// Header
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
"perception_obstacle", &obstacles);
common::Header *header = obstacles.mutable_header();
header->set_lidar_timestamp(0);
header->set_camera_timestamp(timestamp_ns_);
header->set_radar_timestamp(0);
// generate lane marker protobuf messages
LaneMarkers* lane_markers = obstacles.mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
ADEBUG << "Lane Markers: " << obstacles.ShortDebugString();
ADEBUG << "Succeed to publish lane object pb data.";
}
} // namespace perception
} // namespace apollo
<commit_msg>fix lint issue<commit_after>/******************************************************************************
* Copyright 2018 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.
*****************************************************************************/
// @brief: lane_post_processing_subnode source file
#include "modules/perception/obstacle/onboard/lane_post_processing_subnode.h"
#include <unordered_map>
#include <cfloat>
#include <algorithm>
#include "Eigen/Dense"
#include "opencv2/opencv.hpp"
#include "yaml-cpp/yaml.h"
#include "modules/common/log.h"
#include "modules/common/time/timer.h"
#include "modules/common/time/time_util.h"
#include "modules/perception/common/perception_gflags.h"
#include "modules/perception/lib/config_manager/config_manager.h"
#include "modules/perception/obstacle/camera/lane_post_process/cc_lane_post_processor/cc_lane_post_processor.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/types.h"
#include "modules/perception/proto/perception_obstacle.pb.h"
namespace apollo {
namespace perception {
using std::string;
using std::unordered_map;
using std::shared_ptr;
using apollo::common::Status;
using apollo::common::ErrorCode;
using apollo::common::time::Timer;
bool LanePostProcessingSubnode::InitInternal() {
// get Subnode config in DAG streaming
unordered_map<string, string> fields;
SubnodeHelper::ParseReserveField(reserve_, &fields);
if (fields.count("publish") && stoi(fields["publish"]) != 0) {
publish_ = true;
}
// init shared data
if (!InitSharedData()) {
AERROR << "failed to init shared data.";
return false;
}
RegistAllAlgorithms();
// init plugins
if (!InitAlgorithmPlugin()) {
AERROR << "failed to init algorithm plugins.";
return false;
}
AINFO << "init LanePostProcessing subnode successfully.";
return true;
}
bool LanePostProcessingSubnode::InitSharedData() {
if (shared_data_manager_ == nullptr) {
AERROR << "shared data manager is a null pointer.";
return false;
}
// init preprocess_data
camera_object_data_ = dynamic_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
if (camera_object_data_ == nullptr) {
AERROR << "failed to get shared data instance: CameraObjectData ";
return false;
}
lane_shared_data_ = dynamic_cast<LaneSharedData *>(
shared_data_manager_->GetSharedData("LaneSharedData"));
if (lane_shared_data_ == nullptr) {
AERROR << "failed to get shared data instance: LaneSharedData ";
return false;
}
AINFO << "init shared data successfully, data: "
<< camera_object_data_->name() << " and " << lane_shared_data_->name();
return true;
}
void LanePostProcessingSubnode::RegistAllAlgorithms() {
RegisterFactoryCCLanePostProcessor();
}
bool LanePostProcessingSubnode::InitAlgorithmPlugin() {
// init lane post-processer
lane_post_processor_.reset(
BaseCameraLanePostProcessorRegisterer::GetInstanceByName(
FLAGS_onboard_lane_post_processor));
if (!lane_post_processor_) {
AERROR << "failed to get instance: " << FLAGS_onboard_lane_post_processor;
return false;
}
if (!lane_post_processor_->Init()) {
AERROR << "failed to init lane post-processor: "
<< lane_post_processor_->name();
return false;
}
AINFO << "init alg pulgins successfully\n"
<< " lane post-processer: " << FLAGS_onboard_lane_post_processor;
return true;
}
bool LanePostProcessingSubnode::InitWorkRoot() {
ConfigManager *config_manager = ConfigManager::instance();
if (config_manager == NULL) {
AERROR << "failed to get ConfigManager instance.";
return false;
}
if (!config_manager->Init()) {
AERROR << "failed to init ConfigManager";
return false;
}
return true;
}
bool LanePostProcessingSubnode::GetSharedData(const Event &event,
shared_ptr<SensorObjects> *objs) {
double timestamp = event.timestamp;
string device_id = event.reserve;
device_id_ = device_id;
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;
}
if (!camera_object_data_->Get(data_key, objs)) {
AERROR << "failed to get shared data. event:" << event.to_string();
return false;
}
return true;
}
void LanePostProcessingSubnode::PublishDataAndEvent(
const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {
string key;
if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {
AERROR << "failed to produce shared key. time: "
<< GLOG_TIMESTAMP(timestamp) << ", device_id: " << device_id_;
return;
}
if (!lane_shared_data_->Add(key, lane_objects)) {
AWARN << "failed to add LaneSharedData. key: " << key
<< " num_detected_objects: " << lane_objects->size();
return;
}
// pub events
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
AINFO << "succeed to publish data and event.";
}
Status LanePostProcessingSubnode::ProcEvents() {
// fusion output subnode only subcribe the fusion subnode
CHECK_EQ(sub_meta_events_.size(), 1u) << "only subcribe one event.";
const EventMeta &event_meta = sub_meta_events_[0];
Event event;
event_manager_->Subscribe(event_meta.event_id, &event);
++seq_num_;
shared_ptr<SensorObjects> objs;
if (!GetSharedData(event, &objs)) {
AERROR << "Failed to get shared data. event:" << event.to_string();
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
}
Timer timer;
timer.Start();
cv::Mat lane_map = objs->camera_frame_supplement->lane_map;
if (lane_map.empty()) {
AERROR << "Get NULL lane_map from camera frame supplement";
return Status(ErrorCode::PERCEPTION_ERROR, "Failed to proc events.");
}
LaneObjectsPtr lane_objects(new LaneObjects());
CameraLanePostProcessOptions options;
options.timestamp = event.timestamp;
timestamp_ns_ = event.timestamp * 1e9;
lane_post_processor_->Process(lane_map, options, &lane_objects);
for (size_t i = 0; i < lane_objects->size(); ++i) {
(*lane_objects)[i].timestamp = event.timestamp;
(*lane_objects)[i].seq_num = seq_num_;
}
AINFO << "Before publish lane objects, objects num: "
<< lane_objects->size();
uint64_t t = timer.End("lane post-processing");
min_processing_time_ = std::min(min_processing_time_, t);
max_processing_time_ = std::max(max_processing_time_, t);
tot_processing_time_ += t;
AINFO << "Lane Post Processing Runtime: "
<< "MIN (" << min_processing_time_ << " ms), "
<< "MAX (" << max_processing_time_ << " ms), "
<< "AVE (" << tot_processing_time_ / seq_num_ << " ms).";
PublishDataAndEvent(event.timestamp, lane_objects);
if (publish_) {
PublishPerceptionPb(lane_objects);
}
AINFO << "Successfully finished lane post processing";
return Status::OK();
}
void LanePostProcessingSubnode::PublishPerceptionPb(
const LaneObjectsPtr &lane_objects) {
ADEBUG << "Lane post-processor publish lane object pb data";
PerceptionObstacles obstacles;
// Header
common::adapter::AdapterManager::FillPerceptionObstaclesHeader(
"perception_obstacle", &obstacles);
common::Header *header = obstacles.mutable_header();
header->set_lidar_timestamp(0);
header->set_camera_timestamp(timestamp_ns_);
header->set_radar_timestamp(0);
// generate lane marker protobuf messages
LaneMarkers* lane_markers = obstacles.mutable_lane_marker();
LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);
common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);
ADEBUG << "Lane Markers: " << obstacles.ShortDebugString();
ADEBUG << "Succeed to publish lane object pb data.";
}
} // namespace perception
} // namespace apollo
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LConnection.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 05:43:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_
#include "LConnection.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_
#include "LDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_
#include "LCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _CONNECTIVITY_MODULECONTEXT_HXX_
#include "ModuleContext.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_
#include "LPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_
#include "LStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX
#include "LDebug.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace vos;
typedef connectivity::file::OConnection OConnection_B;
//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )
{
::rtl::OUString aExceptionType = aExceptionType_;
if( aExceptionType.getLength() == 0 )
aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) );
::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) );
aTypeLine += aExceptionType;
::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) );
aMessageLine += ::rtl::OUString( e.Message );
::rtl::OUString aMsg(aTypeLine);
aMsg += aMessageLine;
return aMsg;
}
// Exception type unknown
::rtl::OUString implGetExceptionMsg( Exception& e )
{
::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );
return aMsg;
}
// --------------------------------------------------------------------------------
OEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver)
,m_bHeaderLine(sal_True)
,m_cFieldDelimiter(',')
,m_cStringDelimiter('"')
,m_cDecimalDelimiter('.')
,m_cThousandDelimiter(' ')
{
// Initialise m_aColumnAlias.
m_aColumnAlias.setAlias(_pDriver->getFactory());
}
//-----------------------------------------------------------------------------
OEvoabConnection::~OEvoabConnection()
{
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection")
//-----------------------------------------------------------------------------
void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)
{
osl_incrementInterlockedCount( &m_refCount );
EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url );
::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();
::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();
::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());
::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());
aArg2 += aWorkingDirPath;
aArg2 += getDriver()->getEvoFolderListFileName();
OArgumentList aArgs(2,&aArg1,&aArg2);
EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand );
EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath );
EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 );
EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 );
OProcess aApp( aCLICommand,aWorkingDirPath);
OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);
DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards");
Sequence<PropertyValue> aDriverParam;
::std::vector<PropertyValue> aParam;
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE));
::dbtools::OCharsetMap aLookupIanaName;
::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0,
makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));
// build a new parameter sequence from the original parameters, appended by the new parameters from above
PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];
aDriverParam = ::comphelper::concatSequences(
info,
Sequence< PropertyValue >( pParams, aParam.size() )
);
// transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..."
//
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aAddrbookURI(url.copy(nLen+1));
// Get Scheme
nLen = aAddrbookURI.indexOf(':');
::rtl::OUString aAddrbookScheme;
if ( nLen == -1 )
{
// There isn't any subschema: - but could be just subschema
if ( aAddrbookURI.getLength() > 0 )
{
aAddrbookScheme= aAddrbookURI;
}
else
{
OSL_TRACE( "No subschema given!!!\n");
::dbtools::throwGenericSQLException(
::rtl::OUString::createFromAscii("No subschema provided"),NULL);
}
}
else
{
aAddrbookScheme = aAddrbookURI.copy(0, nLen);
}
EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI );
EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme );
//
// Now we have a URI convert it to a Evolution CLI flat file URI
//
// The Mapping being used is:
//
// * for Evolution
// "sdbc:address:evolution:" -> "sdbc:flat:file:///(file path generated)
rtl::OUString aEvoFlatURI;
if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )
{
aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" ));
}
aEvoFlatURI += getDriver()->getWorkingDirURL();
EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI );
//setURL(aEvoFlatURI);
m_aEvoFlatURI = aEvoFlatURI;
osl_decrementInterlockedCount( &m_refCount );
OConnection::construct(aEvoFlatURI,aDriverParam);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OEvoabDatabaseMetaData(this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
OEvoabCatalog *pCat = new OEvoabCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
OEvoabStatement* pStmt = new OEvoabStatement(this);
Reference< XStatement > xStmt = pStmt;
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);
Reference< XPreparedStatement > xStmt = pStmt;
pStmt->construct(sql);
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
return NULL;
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba203a (1.7.76); FILE MERGED 2006/03/20 13:11:15 fs 1.7.76.1: #i10000#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: LConnection.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-03-29 12:15:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_
#include "LConnection.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_
#include "LDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_
#include "LCatalog.hxx"
#endif
#ifndef _CONNECTIVITY_RESOURCE_HRC_
#include "Resource.hrc"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _URLOBJ_HXX //autogen wg. INetURLObject
#include <tools/urlobj.hxx>
#endif
#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_
#include "LPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_
#include "LStatement.hxx"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include <connectivity/dbexception.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _VOS_PROCESS_HXX_
#include <vos/process.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX
#include "LDebug.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
using namespace connectivity::evoab;
using namespace connectivity::file;
using namespace vos;
typedef connectivity::file::OConnection OConnection_B;
//------------------------------------------------------------------------------
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::lang;
::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )
{
::rtl::OUString aExceptionType = aExceptionType_;
if( aExceptionType.getLength() == 0 )
aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii("Unknown" ) );
::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii("\nType: " ) );
aTypeLine += aExceptionType;
::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii("\nMessage: " ) );
aMessageLine += ::rtl::OUString( e.Message );
::rtl::OUString aMsg(aTypeLine);
aMsg += aMessageLine;
return aMsg;
}
// Exception type unknown
::rtl::OUString implGetExceptionMsg( Exception& e )
{
::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );
return aMsg;
}
// --------------------------------------------------------------------------------
OEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver)
,m_bHeaderLine(sal_True)
,m_cFieldDelimiter(',')
,m_cStringDelimiter('"')
,m_cDecimalDelimiter('.')
,m_cThousandDelimiter(' ')
{
// Initialise m_aColumnAlias.
m_aColumnAlias.setAlias(_pDriver->getFactory());
}
//-----------------------------------------------------------------------------
OEvoabConnection::~OEvoabConnection()
{
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OEvoabConnection, "com.sun.star.sdbc.drivers.evoab.Connection", "com.sun.star.sdbc.Connection")
//-----------------------------------------------------------------------------
void OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)
{
osl_incrementInterlockedCount( &m_refCount );
EVO_TRACE_STRING("OEvoabConnection::construct()::url = %s\n", url );
::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();
::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();
::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());
::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());
aArg2 += aWorkingDirPath;
aArg2 += getDriver()->getEvoFolderListFileName();
OArgumentList aArgs(2,&aArg1,&aArg2);
EVO_TRACE_STRING("OEvoabConnection::construct()::aCLICommand = %s\n", aCLICommand );
EVO_TRACE_STRING("OEvoabConnection::construct()::aWorkingDirPath = %s\n", aWorkingDirPath );
EVO_TRACE_STRING("OEvoabConnection::construct()::aArg1 = %s\n", aArg1 );
EVO_TRACE_STRING("OEvoabConnection::construct()::aArg2 = %s\n", aArg2 );
OProcess aApp( aCLICommand,aWorkingDirPath);
OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);
DBG_ASSERT(eError == OProcess::E_None,"Error at execute evolution-addressbook-export to get VCards");
Sequence<PropertyValue> aDriverParam;
::std::vector<PropertyValue> aParam;
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("EnableSQL92Check"), 0, Any(), PropertyState_DIRECT_VALUE));
::dbtools::OCharsetMap aLookupIanaName;
::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("CharSet"), 0,
makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("Extension"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("HeaderLine"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("FieldDelimiter"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("StringDelimiter"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("DecimalDelimiter"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));
aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii("ThousandDelimiter"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));
// build a new parameter sequence from the original parameters, appended by the new parameters from above
PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];
aDriverParam = ::comphelper::concatSequences(
info,
Sequence< PropertyValue >( pParams, aParam.size() )
);
// transform "sdbc:address:evolution" part of URL to "sdbc:flat:file:///..."
//
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aAddrbookURI(url.copy(nLen+1));
// Get Scheme
nLen = aAddrbookURI.indexOf(':');
::rtl::OUString aAddrbookScheme;
if ( nLen == -1 )
{
// There isn't any subschema: - but could be just subschema
if ( aAddrbookURI.getLength() > 0 )
{
aAddrbookScheme= aAddrbookURI;
}
else
{
OSL_TRACE( "No subschema given!!!\n");
::dbtools::throwGenericSQLException(
::rtl::OUString::createFromAscii("No subschema provided"),NULL);
}
}
else
{
aAddrbookScheme = aAddrbookURI.copy(0, nLen);
}
EVO_TRACE_STRING("OEvoabConnection::construct()::URI = %s\n", aAddrbookURI );
EVO_TRACE_STRING("OEvoabConnection::construct()::Scheme = %s\n", aAddrbookScheme );
//
// Now we have a URI convert it to a Evolution CLI flat file URI
//
// The Mapping being used is:
//
// * for Evolution
// "sdbc:address:evolution:" -> "sdbc:flat:file:///(file path generated)
rtl::OUString aEvoFlatURI;
if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )
{
aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "sdbc:flat:" ));
}
aEvoFlatURI += getDriver()->getWorkingDirURL();
EVO_TRACE_STRING("OEvoabConnection::construct()::m_aEvoFlatURI = %s\n", aEvoFlatURI );
//setURL(aEvoFlatURI);
m_aEvoFlatURI = aEvoFlatURI;
osl_decrementInterlockedCount( &m_refCount );
OConnection::construct(aEvoFlatURI,aDriverParam);
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OEvoabDatabaseMetaData(this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
//------------------------------------------------------------------------------
::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
OEvoabCatalog *pCat = new OEvoabCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
OEvoabStatement* pStmt = new OEvoabStatement(this);
Reference< XStatement > xStmt = pStmt;
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);
Reference< XPreparedStatement > xStmt = pStmt;
pStmt->construct(sql);
m_aStatements.push_back(WeakReferenceHelper(*pStmt));
return xStmt;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_B::rBHelper.bDisposed);
return NULL;
}
// -------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ENoException.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2003-09-04 08:26:47 $
*
* 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 _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif
using namespace connectivity;
using namespace connectivity::flat;
//------------------------------------------------------------------
xub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const
{
if ( !Len() )
return 0;
xub_StrLen nTokCount = 1;
BOOL bStart = TRUE; // Stehen wir auf dem ersten Zeichen im Token?
BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String?
// Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
for( xub_StrLen i = 0; i < Len(); i++ )
{
if (bStart)
{
bStart = FALSE;
// Erstes Zeichen ein String-Delimiter?
if ((*this).GetChar(i) == cStrDel)
{
bInString = TRUE; // dann sind wir jetzt INNERHALB des Strings!
continue; // dieses Zeichen ueberlesen!
}
}
if (bInString) {
// Wenn jetzt das String-Delimiter-Zeichen auftritt ...
if ( (*this).GetChar(i) == cStrDel )
{
if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))
{
// Verdoppeltes String-Delimiter-Zeichen:
i++; // kein String-Ende, naechstes Zeichen ueberlesen.
}
else
{
// String-Ende
bInString = FALSE;
}
}
} else {
// Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount
if ( (*this).GetChar(i) == cTok )
{
nTokCount++;
bStart = TRUE;
}
}
}
return nTokCount;
}
//------------------------------------------------------------------
void OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const
{
_rStr.Erase();
xub_StrLen nLen = Len();
if ( nLen )
{
BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String?
// Erstes Zeichen ein String-Delimiter?
if (bInString )
++nStartPos; // dieses Zeichen ueberlesen!
// Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
xub_StrLen i = nStartPos;
for( ; i < nLen; ++i )
{
if (bInString)
{
// Wenn jetzt das String-Delimiter-Zeichen auftritt ...
if ( (*this).GetChar(i) == cStrDel )
{
if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))
{
// Verdoppeltes String-Delimiter-Zeichen:
++i; // kein String-Ende, naechstes Zeichen ueberlesen.
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
else
{
// String-Ende
bInString = FALSE;
}
}
else
{
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
}
else
{
// Stimmt das Tokenzeichen ueberein, dann erhoehe nTok
if ( (*this).GetChar(i) == cTok )
{
// Vorzeitiger Abbruch der Schleife moeglich, denn
// wir haben, was wir wollten.
nStartPos = i+1;
break;
}
else
{
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
}
}
if ( i == nLen && nStartPos < i )
nStartPos = nLen;
}
}
// -----------------------------------------------------------------------------
sal_Bool OFlatTable::checkHeaderLine()
{
if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())
{
BOOL bRead2;
do
{
bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());
}
while(bRead2 && !m_aCurrentLine.Len());
m_nFilePos = m_pFileStream->Tell();
if (m_pFileStream->IsEof())
return sal_False;
}
return sal_True;
}
//------------------------------------------------------------------
sal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
{
if ( !m_pFileStream )
return sal_False;
OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;
// ----------------------------------------------------------
// Positionierung vorbereiten:
sal_uInt32 nTempPos = m_nFilePos;
m_nFilePos = nCurPos;
switch(eCursorPosition)
{
case IResultSetHelper::FIRST:
m_nFilePos = 0;
m_nRowPos = 1;
// run through
case IResultSetHelper::NEXT:
if(eCursorPosition != IResultSetHelper::FIRST)
++m_nRowPos;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
{
m_nMaxRowCount = m_nRowPos;
return sal_False;
}
m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
{
m_nMaxRowCount = m_nRowPos;
return sal_False;
}
nCurPos = m_pFileStream->Tell();
break;
case IResultSetHelper::PRIOR:
--m_nRowPos;
if(m_nRowPos > 0)
{
m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else
m_nRowPos = 0;
break;
break;
case IResultSetHelper::LAST:
if(m_nMaxRowCount)
{
m_nFilePos = m_aRowToFilePos.rbegin()->second;
m_nRowPos = m_aRowToFilePos.rbegin()->first;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else
{
while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row
// now I know all
seekRow(IResultSetHelper::PRIOR,1,nCurPos);
}
break;
case IResultSetHelper::RELATIVE:
if(nOffset > 0)
{
for(sal_Int32 i = 0;i<nOffset;++i)
seekRow(IResultSetHelper::NEXT,1,nCurPos);
}
else if(nOffset < 0)
{
for(sal_Int32 i = nOffset;i;++i)
seekRow(IResultSetHelper::PRIOR,1,nCurPos);
}
break;
case IResultSetHelper::ABSOLUTE:
{
if(nOffset < 0)
nOffset = m_nRowPos + nOffset;
::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);
if(aIter != m_aRowToFilePos.end())
{
m_nFilePos = aIter->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table
{
m_nRowPos = m_nMaxRowCount;
return sal_False;
}
else
{
aIter = m_aRowToFilePos.upper_bound(nOffset);
if(aIter == m_aRowToFilePos.end())
{
m_nRowPos = m_aRowToFilePos.rbegin()->first;
nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;
while(m_nRowPos != nOffset)
seekRow(IResultSetHelper::NEXT,1,nCurPos);
}
else
{
--aIter;
m_nRowPos = aIter->first;
m_nFilePos = aIter->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
}
}
break;
case IResultSetHelper::BOOKMARK:
m_pFileStream->Seek(nOffset);
if (m_pFileStream->IsEof())
return sal_False;
m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG)
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
break;
}
return sal_True;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.198); FILE MERGED 2005/09/05 17:23:54 rt 1.6.198.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ENoException.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-08 06:00:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif
using namespace connectivity;
using namespace connectivity::flat;
//------------------------------------------------------------------
xub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const
{
if ( !Len() )
return 0;
xub_StrLen nTokCount = 1;
BOOL bStart = TRUE; // Stehen wir auf dem ersten Zeichen im Token?
BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String?
// Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
for( xub_StrLen i = 0; i < Len(); i++ )
{
if (bStart)
{
bStart = FALSE;
// Erstes Zeichen ein String-Delimiter?
if ((*this).GetChar(i) == cStrDel)
{
bInString = TRUE; // dann sind wir jetzt INNERHALB des Strings!
continue; // dieses Zeichen ueberlesen!
}
}
if (bInString) {
// Wenn jetzt das String-Delimiter-Zeichen auftritt ...
if ( (*this).GetChar(i) == cStrDel )
{
if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))
{
// Verdoppeltes String-Delimiter-Zeichen:
i++; // kein String-Ende, naechstes Zeichen ueberlesen.
}
else
{
// String-Ende
bInString = FALSE;
}
}
} else {
// Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount
if ( (*this).GetChar(i) == cTok )
{
nTokCount++;
bStart = TRUE;
}
}
}
return nTokCount;
}
//------------------------------------------------------------------
void OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const
{
_rStr.Erase();
xub_StrLen nLen = Len();
if ( nLen )
{
BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String?
// Erstes Zeichen ein String-Delimiter?
if (bInString )
++nStartPos; // dieses Zeichen ueberlesen!
// Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
xub_StrLen i = nStartPos;
for( ; i < nLen; ++i )
{
if (bInString)
{
// Wenn jetzt das String-Delimiter-Zeichen auftritt ...
if ( (*this).GetChar(i) == cStrDel )
{
if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))
{
// Verdoppeltes String-Delimiter-Zeichen:
++i; // kein String-Ende, naechstes Zeichen ueberlesen.
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
else
{
// String-Ende
bInString = FALSE;
}
}
else
{
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
}
else
{
// Stimmt das Tokenzeichen ueberein, dann erhoehe nTok
if ( (*this).GetChar(i) == cTok )
{
// Vorzeitiger Abbruch der Schleife moeglich, denn
// wir haben, was wir wollten.
nStartPos = i+1;
break;
}
else
{
_rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String
}
}
}
if ( i == nLen && nStartPos < i )
nStartPos = nLen;
}
}
// -----------------------------------------------------------------------------
sal_Bool OFlatTable::checkHeaderLine()
{
if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())
{
BOOL bRead2;
do
{
bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());
}
while(bRead2 && !m_aCurrentLine.Len());
m_nFilePos = m_pFileStream->Tell();
if (m_pFileStream->IsEof())
return sal_False;
}
return sal_True;
}
//------------------------------------------------------------------
sal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
{
if ( !m_pFileStream )
return sal_False;
OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;
// ----------------------------------------------------------
// Positionierung vorbereiten:
sal_uInt32 nTempPos = m_nFilePos;
m_nFilePos = nCurPos;
switch(eCursorPosition)
{
case IResultSetHelper::FIRST:
m_nFilePos = 0;
m_nRowPos = 1;
// run through
case IResultSetHelper::NEXT:
if(eCursorPosition != IResultSetHelper::FIRST)
++m_nRowPos;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
{
m_nMaxRowCount = m_nRowPos;
return sal_False;
}
m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
{
m_nMaxRowCount = m_nRowPos;
return sal_False;
}
nCurPos = m_pFileStream->Tell();
break;
case IResultSetHelper::PRIOR:
--m_nRowPos;
if(m_nRowPos > 0)
{
m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else
m_nRowPos = 0;
break;
break;
case IResultSetHelper::LAST:
if(m_nMaxRowCount)
{
m_nFilePos = m_aRowToFilePos.rbegin()->second;
m_nRowPos = m_aRowToFilePos.rbegin()->first;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else
{
while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row
// now I know all
seekRow(IResultSetHelper::PRIOR,1,nCurPos);
}
break;
case IResultSetHelper::RELATIVE:
if(nOffset > 0)
{
for(sal_Int32 i = 0;i<nOffset;++i)
seekRow(IResultSetHelper::NEXT,1,nCurPos);
}
else if(nOffset < 0)
{
for(sal_Int32 i = nOffset;i;++i)
seekRow(IResultSetHelper::PRIOR,1,nCurPos);
}
break;
case IResultSetHelper::ABSOLUTE:
{
if(nOffset < 0)
nOffset = m_nRowPos + nOffset;
::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);
if(aIter != m_aRowToFilePos.end())
{
m_nFilePos = aIter->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table
{
m_nRowPos = m_nMaxRowCount;
return sal_False;
}
else
{
aIter = m_aRowToFilePos.upper_bound(nOffset);
if(aIter == m_aRowToFilePos.end())
{
m_nRowPos = m_aRowToFilePos.rbegin()->first;
nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;
while(m_nRowPos != nOffset)
seekRow(IResultSetHelper::NEXT,1,nCurPos);
}
else
{
--aIter;
m_nRowPos = aIter->first;
m_nFilePos = aIter->second;
m_pFileStream->Seek(m_nFilePos);
if (m_pFileStream->IsEof() || !checkHeaderLine())
return sal_False;
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
}
}
}
break;
case IResultSetHelper::BOOKMARK:
m_pFileStream->Seek(nOffset);
if (m_pFileStream->IsEof())
return sal_False;
m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG)
m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
if (m_pFileStream->IsEof())
return sal_False;
nCurPos = m_pFileStream->Tell();
break;
}
return sal_True;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MacabHeader.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ihi $ $Date: 2007-09-13 17:52:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "MacabHeader.hxx"
#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_
#include "MacabRecord.hxx"
#endif
#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_
#include "macabutilities.hxx"
#endif
#include <math.h>
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
using namespace connectivity::macab;
using namespace com::sun::star::sdbc;
// -------------------------------------------------------------------------
MacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)
{
sal_Int32 i;
size = _size;
fields = new macabfield *[size];
for(i = 0; i < size; i++)
{
if(_fields[i] == NULL)
{
fields[i] = NULL;
}
else
{
/* The constructor duplicates the macabfields it gets because they
* are either deleted later or used for other purposes.
*/
fields[i] = new macabfield;
fields[i]->type = _fields[i]->type;
fields[i]->value = _fields[i]->value;
CFRetain(fields[i]->value);
}
}
}
// -------------------------------------------------------------------------
MacabHeader::MacabHeader()
{
size = 0;
fields = NULL;
}
// -------------------------------------------------------------------------
MacabHeader::~MacabHeader()
{
}
// -------------------------------------------------------------------------
void MacabHeader::operator+= (const MacabHeader *r)
{
/* Add one MacabHeader to another. Anything not already in the header is
* added to the end of it.
*/
sal_Int32 rSize = r->getSize();
if(rSize != 0) // If the new header does actually have fields
{
/* If our header is currently empty, just copy all of the fields from
* the new header to this one.
*/
if(size == 0)
{
sal_Int32 i;
size = rSize;
fields = new macabfield *[size];
for(i = 0; i < size; i++)
{
fields[i] = r->copy(i);
}
}
/* Otherwise, only add the duplicates. We do this with a two-pass
* approach. First, find out how many fields to add, then reallocate
* the size of the fields array and add the old ones at the end.
* (More precisely, we create a _new_ fields array with the new length
* allocated to it, then get all of the fields from the current
* fields array to it, then copy the non-duplicates from the new
* header to the end.)
*/
else
{
sal_Int32 i;
sal_Int32 numToAdd = 0, numAdded = 0;
macabfield **newFields;
for( i = 0; i < rSize; i++)
{
if(!contains(r->get(i)))
{
numToAdd++;
}
}
newFields = new macabfield *[size+numToAdd];
for(i = 0; i < size; i++)
{
newFields[i] = copy(i);
}
for( i = 0; i < rSize; i++)
{
if(!contains(r->get(i)))
{
newFields[size+numAdded] = r->copy(i);
numAdded++;
if(numAdded == numToAdd)
break;
}
}
releaseFields();
delete [] fields;
size += numAdded;
fields = newFields;
}
}
}
// -------------------------------------------------------------------------
::rtl::OUString MacabHeader::getString(const sal_Int32 i) const
{
::rtl::OUString nRet;
if(i < size)
{
if(fields[i] == NULL)
return ::rtl::OUString();
try
{
nRet = CFStringToOUString( (CFStringRef) fields[i]->value);
}
catch(...){ }
}
return nRet;
}
// -------------------------------------------------------------------------
void MacabHeader::sortRecord()
{
sortRecord(0,size);
}
// -------------------------------------------------------------------------
macabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)
{
/* Sort using mergesort. Because it uses mergesort, it is recursive and
* not in place (so it creates a new array at every step of the
* recursion), so if you prefer to use a different sort, please feel
* free to implement it.
*/
macabfield** sorted = new macabfield *[_length];
if(_length <= 2)
{
if(_length == 2)
{
if(compareFields(fields[_start], fields[_start+1]) > 0)
{
sorted[0] = get(_start+1);
sorted[1] = get(_start);
}
else
{
sorted[0] = get(_start);
sorted[1] = get(_start+1);
}
}
else if(_length == 1)
{
sorted[0] = get(_start);
}
}
else
{
sal_Int32 halfLength = floor(_length/2);
sal_Int32 fp = 0, lp = 0;
sal_Int32 i;
macabfield **firstHalf = new macabfield *[halfLength];
macabfield **lastHalf = new macabfield *[_length - halfLength];
firstHalf = sortRecord(_start, halfLength);
lastHalf = sortRecord(_start+halfLength, _length-halfLength);
for(i = 0; i < _length; i++)
{
if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)
{
sorted[i] = firstHalf[fp++];
if(fp == halfLength)
{
for( i++; i < _length; i++)
{
sorted[i] = lastHalf[lp++];
}
break;
}
}
else
{
sorted[i] = lastHalf[lp++];
if(lp == _length - halfLength)
{
for( i++; i < _length; i++)
{
sorted[i] = firstHalf[fp++];
}
break;
}
}
}
if(_length == size)
{
fields = sorted;
}
}
return sorted;
}
sal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)
{
/* Comparing two fields in a MacabHeader is different than comparing two
* fields in a MacabRecord. It starts in the same way (if one of the two
* fields is NULL, it belongs after the other, so it is considered
* "greater"). But, then, all headers are CFStrings, no matter what
* type they claim to be (since they actually hold the expected type for
* the records with that header). That being said, all we have to do is
* the built-in CFStringCompare.
*/
if(_field1 == _field2)
return 0;
if(_field1 == NULL)
return 1;
if(_field2 == NULL)
return -1;
CFComparisonResult result = CFStringCompare(
(CFStringRef) _field1->value,
(CFStringRef) _field2->value,
0); // 0 = no options (like ignore case)
return (sal_Int32) result;
}
// -------------------------------------------------------------------------
sal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const
{
sal_Int32 i;
for(i = 0; i < size; i++)
{
if(getString(i) == s)
break;
}
if(i == size)
i = -1;
return i;
}
// -------------------------------------------------------------------------
MacabHeader *MacabHeader::begin()
{
return this;
}
// -------------------------------------------------------------------------
MacabHeader::iterator::iterator ()
{
}
// -------------------------------------------------------------------------
MacabHeader::iterator::~iterator ()
{
}
void MacabHeader::iterator::operator= (MacabHeader *_record)
{
id = 0;
record = _record;
}
// -------------------------------------------------------------------------
void MacabHeader::iterator::operator++ ()
{
id++;
}
// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const
{
return(id != i);
}
// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const
{
return(id == i);
}
// -------------------------------------------------------------------------
macabfield *MacabHeader::iterator::operator* () const
{
return record->get(id);
}
// -------------------------------------------------------------------------
sal_Int32 MacabHeader::end() const
{
return size;
}
<commit_msg>INTEGRATION: CWS aquavcl05_DEV300 (1.2.74); FILE MERGED 2008/01/29 09:17:56 ericb 1.2.74.2: #i83707# cosmetic 2008/01/29 09:09:40 ericb 1.2.74.1: #i83707# fix potential crash. Fixes proposed by P. Luby<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: MacabHeader.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-05 16:38:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "MacabHeader.hxx"
#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_
#include "MacabRecord.hxx"
#endif
#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_
#include "macabutilities.hxx"
#endif
#include <math.h>
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif
using namespace connectivity::macab;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::util;
using namespace ::dbtools;
// -------------------------------------------------------------------------
MacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)
{
sal_Int32 i;
size = _size;
fields = new macabfield *[size];
for(i = 0; i < size; i++)
{
if(_fields[i] == NULL)
{
fields[i] = NULL;
}
else
{
/* The constructor duplicates the macabfields it gets because they
* are either deleted later or used for other purposes.
*/
fields[i] = new macabfield;
fields[i]->type = _fields[i]->type;
fields[i]->value = _fields[i]->value;
if (fields[i]->value)
CFRetain(fields[i]->value);
}
}
}
// -------------------------------------------------------------------------
MacabHeader::MacabHeader()
{
size = 0;
fields = NULL;
}
// -------------------------------------------------------------------------
MacabHeader::~MacabHeader()
{
}
// -------------------------------------------------------------------------
void MacabHeader::operator+= (const MacabHeader *r)
{
/* Add one MacabHeader to another. Anything not already in the header is
* added to the end of it.
*/
sal_Int32 rSize = r->getSize();
if(rSize != 0) // If the new header does actually have fields
{
/* If our header is currently empty, just copy all of the fields from
* the new header to this one.
*/
if(size == 0)
{
sal_Int32 i;
size = rSize;
fields = new macabfield *[size];
for(i = 0; i < size; i++)
{
fields[i] = r->copy(i);
}
}
/* Otherwise, only add the duplicates. We do this with a two-pass
* approach. First, find out how many fields to add, then reallocate
* the size of the fields array and add the old ones at the end.
* (More precisely, we create a _new_ fields array with the new length
* allocated to it, then get all of the fields from the current
* fields array to it, then copy the non-duplicates from the new
* header to the end.)
*/
else
{
sal_Int32 i;
sal_Int32 numToAdd = 0, numAdded = 0;
macabfield **newFields;
for( i = 0; i < rSize; i++)
{
if(!contains(r->get(i)))
{
numToAdd++;
}
}
newFields = new macabfield *[size+numToAdd];
for(i = 0; i < size; i++)
{
newFields[i] = copy(i);
}
for( i = 0; i < rSize; i++)
{
if(!contains(r->get(i)))
{
newFields[size+numAdded] = r->copy(i);
numAdded++;
if(numAdded == numToAdd)
break;
}
}
releaseFields();
delete [] fields;
size += numAdded;
fields = newFields;
}
}
}
// -------------------------------------------------------------------------
::rtl::OUString MacabHeader::getString(const sal_Int32 i) const
{
::rtl::OUString nRet;
if(i < size)
{
if(fields[i] == NULL || fields[i]->value == NULL || CFGetTypeID(fields[i]->value) != CFStringGetTypeID())
return ::rtl::OUString();
try
{
nRet = CFStringToOUString( (CFStringRef) fields[i]->value);
}
catch(...){ }
}
return nRet;
}
// -------------------------------------------------------------------------
void MacabHeader::sortRecord()
{
sortRecord(0,size);
}
// -------------------------------------------------------------------------
macabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)
{
/* Sort using mergesort. Because it uses mergesort, it is recursive and
* not in place (so it creates a new array at every step of the
* recursion), so if you prefer to use a different sort, please feel
* free to implement it.
*/
macabfield** sorted = new macabfield *[_length];
if(_length <= 2)
{
if(_length == 2)
{
if(compareFields(fields[_start], fields[_start+1]) > 0)
{
sorted[0] = get(_start+1);
sorted[1] = get(_start);
}
else
{
sorted[0] = get(_start);
sorted[1] = get(_start+1);
}
}
else if(_length == 1)
{
sorted[0] = get(_start);
}
}
else
{
sal_Int32 halfLength = floor(_length/2);
sal_Int32 fp = 0, lp = 0;
sal_Int32 i;
macabfield **firstHalf = new macabfield *[halfLength];
macabfield **lastHalf = new macabfield *[_length - halfLength];
firstHalf = sortRecord(_start, halfLength);
lastHalf = sortRecord(_start+halfLength, _length-halfLength);
for(i = 0; i < _length; i++)
{
if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)
{
sorted[i] = firstHalf[fp++];
if(fp == halfLength)
{
for( i++; i < _length; i++)
{
sorted[i] = lastHalf[lp++];
}
break;
}
}
else
{
sorted[i] = lastHalf[lp++];
if(lp == _length - halfLength)
{
for( i++; i < _length; i++)
{
sorted[i] = firstHalf[fp++];
}
break;
}
}
}
if(_length == size)
{
fields = sorted;
}
}
return sorted;
}
sal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)
{
/* Comparing two fields in a MacabHeader is different than comparing two
* fields in a MacabRecord. It starts in the same way (if one of the two
* fields is NULL, it belongs after the other, so it is considered
* "greater"). But, then, all headers are CFStrings, no matter what
* type they claim to be (since they actually hold the expected type for
* the records with that header). That being said, all we have to do is
* the built-in CFStringCompare.
*/
if(_field1 == _field2)
return 0;
if(_field1 == NULL)
return 1;
if(_field2 == NULL)
return -1;
CFComparisonResult result = CFStringCompare(
(CFStringRef) _field1->value,
(CFStringRef) _field2->value,
0); // 0 = no options (like ignore case)
return (sal_Int32) result;
}
// -------------------------------------------------------------------------
sal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const
{
sal_Int32 i;
for(i = 0; i < size; i++)
{
if(getString(i) == s)
break;
}
if(i == size)
i = -1;
return i;
}
// -------------------------------------------------------------------------
MacabHeader *MacabHeader::begin()
{
return this;
}
// -------------------------------------------------------------------------
MacabHeader::iterator::iterator ()
{
}
// -------------------------------------------------------------------------
MacabHeader::iterator::~iterator ()
{
}
void MacabHeader::iterator::operator= (MacabHeader *_record)
{
id = 0;
record = _record;
}
// -------------------------------------------------------------------------
void MacabHeader::iterator::operator++ ()
{
id++;
}
// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const
{
return(id != i);
}
// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const
{
return(id == i);
}
// -------------------------------------------------------------------------
macabfield *MacabHeader::iterator::operator* () const
{
return record->get(id);
}
// -------------------------------------------------------------------------
sal_Int32 MacabHeader::end() const
{
return size;
}
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project
Copyright (C) 2008 Matthias Kretz <kretz@kde.org>
This program 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) version 3.
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 <QtCore/QCoreApplication>
#include <QtCore/QtDebug>
#include <QtCore/QMutableListIterator>
#include <QtCore/QList>
#include "../qsettingsgroup_p.h"
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kconfiggroup.h>
using Phonon::QSettingsGroup;
Q_DECLARE_METATYPE(QList<int>)
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
KComponentData cData("phonon device preference update");
KConfig kconfig("phonondevicesrc", KConfig::NoGlobals);
KConfigGroup globalGroup(&kconfig, "Globals");
int newIndexForZero = 0;
foreach (const QString &group, kconfig.groupList()) {
KConfigGroup configGroup(&kconfig, group);
int index = configGroup.readEntry("index", -1);
if (index == 0) {
newIndexForZero = globalGroup.readEntry("nextIndex", 0);
configGroup.writeEntry("index", newIndexForZero);
globalGroup.writeEntry("nextIndex", newIndexForZero + 1);
break;
}
}
qDebug() << newIndexForZero;
qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>");
QSettings qconfig(QLatin1String("kde.org"), QLatin1String("libphonon"));
QSettingsGroup outputGroup(&qconfig, QLatin1String("AudioOutputDevice"));
for (int i = -1; i < 10; ++i) {
const QString oldKey = QLatin1String("Category") + QString::number(i);
const QString newKey = QLatin1String("Category_") + QString::number(i);
qDebug() << oldKey << newKey;
if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {
QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());
QMutableListIterator<int> index(deviceIndexes);
while (index.hasNext()) {
index.next();
if (index.value() < 10000 && index.value() >= 0) {
qDebug() << "changing index" << index.value();
if (index.value() == 0) {
Q_ASSERT(newIndexForZero);
index.setValue(-newIndexForZero);
} else {
index.setValue(-index.value());
}
}
}
outputGroup.setValue(newKey, deviceIndexes);
outputGroup.removeEntry(oldKey);
}
}
return 0;
}
<commit_msg>remove debug output<commit_after>/* This file is part of the KDE project
Copyright (C) 2008 Matthias Kretz <kretz@kde.org>
This program 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) version 3.
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 <QtCore/QCoreApplication>
#include <QtCore/QMutableListIterator>
#include <QtCore/QList>
#include "../qsettingsgroup_p.h"
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kconfiggroup.h>
using Phonon::QSettingsGroup;
Q_DECLARE_METATYPE(QList<int>)
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
KComponentData cData("phonon device preference update");
KConfig kconfig("phonondevicesrc", KConfig::NoGlobals);
KConfigGroup globalGroup(&kconfig, "Globals");
int newIndexForZero = 0;
foreach (const QString &group, kconfig.groupList()) {
KConfigGroup configGroup(&kconfig, group);
int index = configGroup.readEntry("index", -1);
if (index == 0) {
newIndexForZero = globalGroup.readEntry("nextIndex", 0);
configGroup.writeEntry("index", newIndexForZero);
globalGroup.writeEntry("nextIndex", newIndexForZero + 1);
break;
}
}
qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>");
QSettings qconfig(QLatin1String("kde.org"), QLatin1String("libphonon"));
QSettingsGroup outputGroup(&qconfig, QLatin1String("AudioOutputDevice"));
for (int i = -1; i < 10; ++i) {
const QString oldKey = QLatin1String("Category") + QString::number(i);
const QString newKey = QLatin1String("Category_") + QString::number(i);
if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {
QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());
QMutableListIterator<int> index(deviceIndexes);
while (index.hasNext()) {
index.next();
if (index.value() < 10000 && index.value() >= 0) {
if (index.value() == 0) {
Q_ASSERT(newIndexForZero);
index.setValue(-newIndexForZero);
} else {
index.setValue(-index.value());
}
}
}
outputGroup.setValue(newKey, deviceIndexes);
outputGroup.removeEntry(oldKey);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>/* dbRecordEditor.cc KPilot
**
** Copyright (C) 2003 by Dan Pilone
** Written 2003 by Reinhold Kainhofer
**
**/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <kmessagebox.h>
#include "pilotRecord.h"
#include "dbRecordEditor.h"
//#include "dbRecordEditor_base.h"
#ifdef USE_KHEXEDIT
#include <khexedit/byteseditinterface.h>
#include <khexedit/hexcolumninterface.h>
#include <khexedit/textcolumninterface.h>
using namespace KHE;
#endif
DBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)
: KDialogBase(parent, "RecordEditor",false,i18n("Edit Record..."),
Ok|Cancel), rec(r), nr(n)
{
// fWidget=new DBRecordEditorBase(this);
fWidget=new QWidget(this);
setMainWidget(fWidget);
initWidgets();
fillWidgets();
}
DBRecordEditor::~DBRecordEditor()
{
}
void DBRecordEditor::slotOk()
{
FUNCTIONSETUP;
if (KMessageBox::questionYesNo(this, i18n("Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\n\nReally assign these new flags?"), i18n("Changing record"))==KMessageBox::Yes)
{
int att=rec->getAttrib();
#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;
setFlag(fDirty, dlpRecAttrDirty);
setFlag(fDeleted, dlpRecAttrDeleted);
setFlag(fBusy, dlpRecAttrBusy);
setFlag(fSecret, dlpRecAttrSecret);
setFlag(fArchived, dlpRecAttrArchived);
rec->setAttrib(att);
#undef setFlag
#ifdef USE_KHEXEDIT
if ( fRecordDataIf->isModified() )
{
#ifdef DEBUG
DEBUGKPILOT << "record data changed, new Length of record: " <<
fRecordDataIf->dataSize() << endl;
#endif
// take over data
fRecordDataIf->setAutoDelete( false );
rec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );
}
#endif
KDialogBase::slotOk();
}
}
void DBRecordEditor::slotCancel()
{
KDialogBase::slotCancel();
}
void DBRecordEditor::languageChange()
{
setCaption( tr2i18n( "Form1" ) );
fRecordIndexLabel->setText( tr2i18n( "Record index:" ) );
fRecordIDLabel->setText( tr2i18n( "Record ID:" ) );
fRecordIndex->setText( tr2i18n( "1" ) );
fRecordID->setText( tr2i18n( "1" ) );
fFlagsGroup->setTitle( tr2i18n( "Flags" ) );
fDirty->setText( tr2i18n( "&Dirty" ) );
fDeleted->setText( tr2i18n( "De&leted" ) );
fBusy->setText( tr2i18n( "&Busy" ) );
fSecret->setText( tr2i18n( "&Secret" ) );
fArchived->setText( tr2i18n( "&Archived" ) );
}
void DBRecordEditor::initWidgets()
{
// FUNCTIONSETUP
DBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, "DBRecordEditorBaseLayout");
fRecordIndexLabel = new QLabel( fWidget, "fRecordIndexLabel" );
DBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );
fRecordIDLabel = new QLabel( fWidget, "fRecordIDLabel" );
DBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );
fRecordIndex = new QLineEdit( fWidget, "fRecordIndex" );
fRecordIndex->setReadOnly( TRUE );
DBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );
fRecordID = new QLineEdit( fWidget, "fRecordID" );
fRecordID->setReadOnly( TRUE );
DBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );
fFlagsGroup = new QButtonGroup( fWidget, "fFlagsGroup" );
fFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,
(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );
fFlagsGroup->setColumnLayout(0, Qt::Vertical );
fFlagsGroup->layout()->setSpacing( 6 );
fFlagsGroup->layout()->setMargin( 11 );
fFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );
fFlagsGroupLayout->setAlignment( Qt::AlignTop );
fDirty = new QCheckBox( fFlagsGroup, "fDirty" );
fFlagsGroupLayout->addWidget( fDirty, 0, 0 );
fDeleted = new QCheckBox( fFlagsGroup, "fDeleted" );
fFlagsGroupLayout->addWidget( fDeleted, 1, 0 );
fBusy = new QCheckBox( fFlagsGroup, "fBusy" );
fFlagsGroupLayout->addWidget( fBusy, 0, 1 );
fSecret = new QCheckBox( fFlagsGroup, "fSecret" );
fFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );
fArchived = new QCheckBox( fFlagsGroup, "fArchived" );
fFlagsGroupLayout->addWidget( fArchived, 0, 2 );
DBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );
#ifdef USE_KHEXEDIT
fRecordData = KHE::createBytesEditWidget( fWidget, "fRecordData" );
if( fRecordData )
{
// fetch the editor interface
fRecordDataIf = KHE::bytesEditInterface( fRecordData );
Q_ASSERT( fRecordDataIf ); // This should not fail!
KHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );
if( HexColumn )
{
HexColumn->setNoOfBytesPerLine( 16 );
HexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );
// HexColumn->setCoding( HexColumnInterface::HexadecimalCoding );
// HexColumn->setByteSpacingWidth( 2 );
HexColumn->setNoOfGroupedBytes( 4 );
HexColumn->setGroupSpacingWidth( 8 );
}
KHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );
if( TextColumn )
{
TextColumn->setShowUnprintable( false );
// TextColumn->setSubstituteChar( '*' );
}
}
else
{
QLabel*tmpW = new QLabel( i18n("To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils)."), fWidget );
tmpW->setBackgroundMode( Qt::PaletteMid );
tmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);
tmpW->setFrameShape( QFrame::Panel );
tmpW->setFrameShadow( QFrame::Sunken );
fRecordData = tmpW;
fRecordDataIf = 0;
}
DBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );
#endif
languageChange();
resize( QSize(600, 561).expandedTo(minimumSizeHint()) );
}
void DBRecordEditor::fillWidgets()
{
// FUNCTIONSETUP
fRecordIndex->setText(QString::number(nr));
fRecordID->setText(QString::number(rec->getID()));
int att=rec->getAttrib();
fDirty->setChecked(att & dlpRecAttrDirty);
fDeleted->setChecked(att & dlpRecAttrDeleted);
fBusy->setChecked(att & dlpRecAttrBusy);
fSecret->setChecked(att & dlpRecAttrSecret);
fArchived->setChecked(att & dlpRecAttrArchived);
#ifdef USE_KHEXEDIT
if( fRecordDataIf )
{
int len = rec->getLen();
char* buffer = new char[len];
memcpy( buffer, rec->getData(), len );
fRecordDataIf->setData( buffer, len );
fRecordDataIf->setMaxDataSize( 4096 );
fRecordDataIf->setReadOnly( false );
// Here we set auto delete to true. Only if we
// really take over the data, set it to false.
fRecordDataIf->setAutoDelete( true );
}
#endif
}
#include "dbRecordEditor.moc"
<commit_msg>We want to allow to extend the buffer above the current size, do we? ;) One bug less to report for this temporary solution...<commit_after>/* dbRecordEditor.cc KPilot
**
** Copyright (C) 2003 by Dan Pilone
** Written 2003 by Reinhold Kainhofer
**
**/
/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/
/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/
#include "options.h"
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <kmessagebox.h>
#include "pilotRecord.h"
#include "dbRecordEditor.h"
//#include "dbRecordEditor_base.h"
#ifdef USE_KHEXEDIT
#include <khexedit/byteseditinterface.h>
#include <khexedit/hexcolumninterface.h>
#include <khexedit/textcolumninterface.h>
using namespace KHE;
#endif
DBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)
: KDialogBase(parent, "RecordEditor",false,i18n("Edit Record..."),
Ok|Cancel), rec(r), nr(n)
{
// fWidget=new DBRecordEditorBase(this);
fWidget=new QWidget(this);
setMainWidget(fWidget);
initWidgets();
fillWidgets();
}
DBRecordEditor::~DBRecordEditor()
{
}
void DBRecordEditor::slotOk()
{
FUNCTIONSETUP;
if (KMessageBox::questionYesNo(this, i18n("Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\n\nReally assign these new flags?"), i18n("Changing record"))==KMessageBox::Yes)
{
int att=rec->getAttrib();
#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;
setFlag(fDirty, dlpRecAttrDirty);
setFlag(fDeleted, dlpRecAttrDeleted);
setFlag(fBusy, dlpRecAttrBusy);
setFlag(fSecret, dlpRecAttrSecret);
setFlag(fArchived, dlpRecAttrArchived);
rec->setAttrib(att);
#undef setFlag
#ifdef USE_KHEXEDIT
if ( fRecordDataIf->isModified() )
{
#ifdef DEBUG
DEBUGKPILOT << "record data changed, new Length of record: " <<
fRecordDataIf->dataSize() << endl;
#endif
// take over data
fRecordDataIf->setAutoDelete( false );
rec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );
}
#endif
KDialogBase::slotOk();
}
}
void DBRecordEditor::slotCancel()
{
KDialogBase::slotCancel();
}
void DBRecordEditor::languageChange()
{
setCaption( tr2i18n( "Form1" ) );
fRecordIndexLabel->setText( tr2i18n( "Record index:" ) );
fRecordIDLabel->setText( tr2i18n( "Record ID:" ) );
fRecordIndex->setText( tr2i18n( "1" ) );
fRecordID->setText( tr2i18n( "1" ) );
fFlagsGroup->setTitle( tr2i18n( "Flags" ) );
fDirty->setText( tr2i18n( "&Dirty" ) );
fDeleted->setText( tr2i18n( "De&leted" ) );
fBusy->setText( tr2i18n( "&Busy" ) );
fSecret->setText( tr2i18n( "&Secret" ) );
fArchived->setText( tr2i18n( "&Archived" ) );
}
void DBRecordEditor::initWidgets()
{
// FUNCTIONSETUP
DBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, "DBRecordEditorBaseLayout");
fRecordIndexLabel = new QLabel( fWidget, "fRecordIndexLabel" );
DBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );
fRecordIDLabel = new QLabel( fWidget, "fRecordIDLabel" );
DBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );
fRecordIndex = new QLineEdit( fWidget, "fRecordIndex" );
fRecordIndex->setReadOnly( TRUE );
DBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );
fRecordID = new QLineEdit( fWidget, "fRecordID" );
fRecordID->setReadOnly( TRUE );
DBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );
fFlagsGroup = new QButtonGroup( fWidget, "fFlagsGroup" );
fFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,
(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );
fFlagsGroup->setColumnLayout(0, Qt::Vertical );
fFlagsGroup->layout()->setSpacing( 6 );
fFlagsGroup->layout()->setMargin( 11 );
fFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );
fFlagsGroupLayout->setAlignment( Qt::AlignTop );
fDirty = new QCheckBox( fFlagsGroup, "fDirty" );
fFlagsGroupLayout->addWidget( fDirty, 0, 0 );
fDeleted = new QCheckBox( fFlagsGroup, "fDeleted" );
fFlagsGroupLayout->addWidget( fDeleted, 1, 0 );
fBusy = new QCheckBox( fFlagsGroup, "fBusy" );
fFlagsGroupLayout->addWidget( fBusy, 0, 1 );
fSecret = new QCheckBox( fFlagsGroup, "fSecret" );
fFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );
fArchived = new QCheckBox( fFlagsGroup, "fArchived" );
fFlagsGroupLayout->addWidget( fArchived, 0, 2 );
DBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );
#ifdef USE_KHEXEDIT
fRecordData = KHE::createBytesEditWidget( fWidget, "fRecordData" );
if( fRecordData )
{
// fetch the editor interface
fRecordDataIf = KHE::bytesEditInterface( fRecordData );
Q_ASSERT( fRecordDataIf ); // This should not fail!
KHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );
if( HexColumn )
{
HexColumn->setNoOfBytesPerLine( 16 );
HexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );
// HexColumn->setCoding( HexColumnInterface::HexadecimalCoding );
// HexColumn->setByteSpacingWidth( 2 );
HexColumn->setNoOfGroupedBytes( 4 );
HexColumn->setGroupSpacingWidth( 8 );
}
KHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );
if( TextColumn )
{
TextColumn->setShowUnprintable( false );
// TextColumn->setSubstituteChar( '*' );
}
}
else
{
QLabel*tmpW = new QLabel( i18n("To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils)."), fWidget );
tmpW->setBackgroundMode( Qt::PaletteMid );
tmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);
tmpW->setFrameShape( QFrame::Panel );
tmpW->setFrameShadow( QFrame::Sunken );
fRecordData = tmpW;
fRecordDataIf = 0;
}
DBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );
#endif
languageChange();
resize( QSize(600, 561).expandedTo(minimumSizeHint()) );
}
void DBRecordEditor::fillWidgets()
{
// FUNCTIONSETUP
fRecordIndex->setText(QString::number(nr));
fRecordID->setText(QString::number(rec->getID()));
int att=rec->getAttrib();
fDirty->setChecked(att & dlpRecAttrDirty);
fDeleted->setChecked(att & dlpRecAttrDeleted);
fBusy->setChecked(att & dlpRecAttrBusy);
fSecret->setChecked(att & dlpRecAttrSecret);
fArchived->setChecked(att & dlpRecAttrArchived);
#ifdef USE_KHEXEDIT
if( fRecordDataIf )
{
int len = rec->getLen();
char* buffer = new char[len];
memcpy( buffer, rec->getData(), len );
fRecordDataIf->setData( buffer, len, -1, false );
fRecordDataIf->setMaxDataSize( 4096 );
fRecordDataIf->setReadOnly( false );
// Here we set auto delete to true. Only if we
// really take over the data, set it to false.
fRecordDataIf->setAutoDelete( true );
}
#endif
}
#include "dbRecordEditor.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 <Dreemchest.h>
#include "../Examples.h"
DC_USE_DREEMCHEST
using namespace Platform;
using namespace Renderer;
static String s_vertexShader =
"cbuffer Projection projection : 0; \n"
"cbuffer Camera camera : 1; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = projection.transform \n"
" * camera.rotation \n"
" * gl_Vertex; \n"
" v_texCoord = gl_Vertex.xyz; \n"
"} \n"
;
static String s_fragmentShader =
"uniform samplerCube Texture0; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_FragColor = textureCube(Texture0, v_texCoord); \n"
"} \n"
;
// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
StateBlock8 m_renderStates;
virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
{
Logger::setStandardLogger();
if (!initialize(800, 600))
{
application->quit(-1);
}
// Create a cube vertex buffer and bind it to a render state block
{
InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);
VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));
m_renderStates.bindVertexBuffer(vertexBuffer);
m_renderStates.bindInputLayout(inputLayout);
}
// Load a cubemap texture and bind it to a sampler #0
{
const String envName = "Sierra_Madre_B";
const String files[] =
{
"Assets/Textures/Environments/" + envName + "/posx.tga"
, "Assets/Textures/Environments/" + envName + "/negx.tga"
, "Assets/Textures/Environments/" + envName + "/posy.tga"
, "Assets/Textures/Environments/" + envName + "/negy.tga"
, "Assets/Textures/Environments/" + envName + "/posz.tga"
, "Assets/Textures/Environments/" + envName + "/negz.tga"
};
Examples::Surface pixels;
Examples::Image faces[6];
for (s32 i = 0; i < 6; i++)
{
faces[i] = Examples::tgaFromFile(files[i]);
pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
}
Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
m_renderStates.bindTexture(env, 0);
}
// Create a program that consists from a vertex and fragment shaders.
Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
m_renderStates.bindProgram(program);
}
// This method is declared inside the Examples::ViewerApplicationDelegate.
virtual void handleRenderFrame(const RenderFrame& frame, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
{
commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
}
};
dcDeclareApplication(new Cubemaps)
<commit_msg>Fixed: cube maps example compilation issue<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 <Dreemchest.h>
#include "../Examples.h"
DC_USE_DREEMCHEST
using namespace Platform;
using namespace Renderer;
static String s_vertexShader =
"cbuffer Projection projection : 0; \n"
"cbuffer Camera camera : 1; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_Position = projection.transform \n"
" * camera.rotation \n"
" * gl_Vertex; \n"
" v_texCoord = gl_Vertex.xyz; \n"
"} \n"
;
static String s_fragmentShader =
"uniform samplerCube Texture0; \n"
"varying vec3 v_texCoord; \n"
"void main() \n"
"{ \n"
" gl_FragColor = textureCube(Texture0, v_texCoord); \n"
"} \n"
;
// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
StateBlock8 m_renderStates;
virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
{
Logger::setStandardLogger();
if (!initialize(800, 600))
{
application->quit(-1);
}
// Create a cube vertex buffer and bind it to a render state block
{
InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);
VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));
m_renderStates.bindVertexBuffer(vertexBuffer);
m_renderStates.bindInputLayout(inputLayout);
}
// Load a cubemap texture and bind it to a sampler #0
{
const String envName = "Sierra_Madre_B";
const String files[] =
{
"Assets/Textures/Environments/" + envName + "/posx.tga"
, "Assets/Textures/Environments/" + envName + "/negx.tga"
, "Assets/Textures/Environments/" + envName + "/posy.tga"
, "Assets/Textures/Environments/" + envName + "/negy.tga"
, "Assets/Textures/Environments/" + envName + "/posz.tga"
, "Assets/Textures/Environments/" + envName + "/negz.tga"
};
Examples::Surface pixels;
Examples::Image faces[6];
for (s32 i = 0; i < 6; i++)
{
faces[i] = Examples::tgaFromFile(files[i]);
pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
}
Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
m_renderStates.bindTexture(env, 0);
}
// Create a program that consists from a vertex and fragment shaders.
Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
m_renderStates.bindProgram(program);
}
// This method is declared inside the Examples::ViewerApplicationDelegate.
virtual void handleRenderFrame(RenderFrame& frame, StateStack& stateStack, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
{
commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
}
};
dcDeclareApplication(new Cubemaps)
<|endoftext|>
|
<commit_before>/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "recommendationmanager.h"
#include "recommendationmanageradaptor.h"
#include "recommendation.h"
#include "recommendationaction.h"
#include "locationmanager.h"
#include "kext.h"
#include <kworkspace/kactivityinfo.h>
#include <kworkspace/kactivityconsumer.h>
#include <KRandom>
#include <KRun>
#include <KDebug>
#include <Nepomuk/Query/Query>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/ComparisonTerm>
#include <Nepomuk/Query/LiteralTerm>
#include <Nepomuk/Query/AndTerm>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/Result>
#include <Nepomuk/Resource>
#include <Soprano/Vocabulary/NAO>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMetaType>
#include <QtLocation/QLandmark>
using namespace Soprano::Vocabulary;
using namespace Nepomuk::Vocabulary;
QTM_USE_NAMESPACE
//Q_DECLARE_METATYPE(Contour::Recommendation*)
// TODO: act on several changes:
// * later: triggers from the dms
class Contour::RecommendationManager::Private
{
public:
KActivityConsumer* m_activityConsumer;
LocationManager* m_locationManager;
QList<Recommendation> m_recommendations;
QHash<QString, RecommendationAction> m_actionHash;
QHash<QString, Recommendation> m_RecommendationForAction;
Nepomuk::Query::QueryServiceClient m_queryClient;
RecommendationManager* q;
void updateRecommendations();
void _k_locationChanged(const QList<QLandmark>&);
void _k_currentActivityChanged(const QString&);
void _k_newResults(const QList<Nepomuk::Query::Result>&);
void _k_queryFinished();
};
void Contour::RecommendationManager::Private::updateRecommendations()
{
// remove old recommendations
m_recommendations.clear();
m_actionHash.clear();
m_RecommendationForAction.clear();
// get resources that have been touched in the current activity (the dumb way for now)
const QString query
= QString::fromLatin1("select distinct ?resource, ?uri, ?cache,"
"("
"("
"?lastScore * bif:exp(-"
"bif:datediff('day', ?lastUpdate, \"2011-06-30T13:45:01.996Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"
")"
")"
"as ?score) where {"
"?cache kext:targettedResource ?resource ."
"?cache a kext:ResourceScoreCache ."
"?cache nao:lastModified ?lastUpdate ."
"?cache kext:cachedScore ?lastScore ."
"?cache kext:usedActivity %1 ."
"OPTIONAL { ?resource nie:url ?uri . } ."
"}"
"ORDER BY DESC (?score)"
"LIMIT 10")
.arg(Soprano::Node::resourceToN3(Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()) /*Soprano::Node::literalToN3(Soprano::LiteralValue(m_activityConsumer->currentActivity()))*/);
m_queryClient.sparqlQuery(query);
// IDEA: for files use usage events
// for everything else use changes in data via graph metadata
}
void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)
{
updateRecommendations();
}
void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)
{
updateRecommendations();
}
void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)
{
foreach(const Nepomuk::Query::Result& result, results) {
Recommendation r;
r.resourceUri = KUrl(result.resource().resourceUri()).url();
kWarning() << "Got a new result:" << result.excerpt() << result.score();
// for now we create the one dummy action: open the resource
QString id;
do {
id = KRandom::randomString(5);
} while(m_actionHash.contains(id));
RecommendationAction action;
action.id = id;
action.text = i18n("Open '%1'", result.resource().genericLabel());
m_actionHash[id] = action;
m_RecommendationForAction[id] = r;
r.actions << action;
m_recommendations << r;
}
}
void Contour::RecommendationManager::Private::_k_queryFinished()
{
emit q->recommendationsChanged();
}
Contour::RecommendationManager::RecommendationManager(QObject *parent)
: QObject(parent),
d(new Private())
{
d->q = this;
connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),
this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));
d->m_activityConsumer = new KActivityConsumer(this);
connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),
this, SLOT(_k_currentActivityChanged(QString)));
d->m_locationManager = new LocationManager(this);
connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),
this, SLOT(_k_locationChanged(QList<QLandmark>)));
d->updateRecommendations();
// export via DBus
qDBusRegisterMetaType<Contour::Recommendation>();
qDBusRegisterMetaType<QList<Contour::Recommendation> >();
qDBusRegisterMetaType<Contour::RecommendationAction>();
(void)new RecommendationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this);
}
Contour::RecommendationManager::~RecommendationManager()
{
delete d;
}
QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const
{
return d->m_recommendations;
}
void Contour::RecommendationManager::executeAction(const QString &actionId)
{
if(d->m_actionHash.contains(actionId)) {
RecommendationAction action = d->m_actionHash.value(actionId);
// FIXME: this is the hacky execution of the action, make it correct
Recommendation r = d->m_RecommendationForAction.value(actionId);
(void)new KRun(r.resourceUri, 0);
}
else {
kDebug() << "Invalid action id encountered:" << actionId;
}
}
#include "recommendationmanager.moc"
<commit_msg>Fixed query<commit_after>/*
This file is part of the Nepomuk KDE project.
Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "recommendationmanager.h"
#include "recommendationmanageradaptor.h"
#include "recommendation.h"
#include "recommendationaction.h"
#include "locationmanager.h"
#include "kext.h"
#include <kworkspace/kactivityinfo.h>
#include <kworkspace/kactivityconsumer.h>
#include <KRandom>
#include <KRun>
#include <KDebug>
#include <Nepomuk/Query/Query>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/ComparisonTerm>
#include <Nepomuk/Query/LiteralTerm>
#include <Nepomuk/Query/AndTerm>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/Result>
#include <Nepomuk/Resource>
#include <Soprano/Vocabulary/NAO>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMetaType>
#include <QtLocation/QLandmark>
using namespace Soprano::Vocabulary;
using namespace Nepomuk::Vocabulary;
QTM_USE_NAMESPACE
//Q_DECLARE_METATYPE(Contour::Recommendation*)
// TODO: act on several changes:
// * later: triggers from the dms
class Contour::RecommendationManager::Private
{
public:
KActivityConsumer* m_activityConsumer;
LocationManager* m_locationManager;
QList<Recommendation> m_recommendations;
QHash<QString, RecommendationAction> m_actionHash;
QHash<QString, Recommendation> m_RecommendationForAction;
Nepomuk::Query::QueryServiceClient m_queryClient;
RecommendationManager* q;
void updateRecommendations();
void _k_locationChanged(const QList<QLandmark>&);
void _k_currentActivityChanged(const QString&);
void _k_newResults(const QList<Nepomuk::Query::Result>&);
void _k_queryFinished();
};
void Contour::RecommendationManager::Private::updateRecommendations()
{
// remove old recommendations
m_recommendations.clear();
m_actionHash.clear();
m_RecommendationForAction.clear();
// get resources that have been touched in the current activity (the dumb way for now)
const QString query
= QString::fromLatin1(
"select distinct ?resource, "
" ( "
" ( "
" SUM ( "
" ?lastScore * bif:exp( "
" - bif:datediff('day', ?lastUpdate, %1) "
" ) "
" ) "
" ) "
" as ?score "
" ) where { "
" ?cache kext:targettedResource ?resource . "
" ?cache a kext:ResourceScoreCache . "
" ?cache nao:lastModified ?lastUpdate . "
" ?cache kext:cachedScore ?lastScore . "
" ?cache kext:usedActivity %2 . "
" } "
" GROUP BY (?resource) "
" ORDER BY DESC (?score) "
" LIMIT 10 "
).arg(
Soprano::Node::literalToN3(
QDateTime::currentDateTime()
),
Soprano::Node::resourceToN3(
Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()
)
);
kDebug() << query;
m_queryClient.sparqlQuery(query);
// IDEA: for files use usage events
// for everything else use changes in data via graph metadata
}
void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)
{
updateRecommendations();
}
void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)
{
updateRecommendations();
}
void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)
{
foreach(const Nepomuk::Query::Result& result, results) {
Recommendation r;
r.resourceUri = KUrl(result.resource().resourceUri()).url();
kWarning() << "Got a new result:" << r.resourceUri << result.excerpt() << result.score();
// for now we create the one dummy action: open the resource
QString id;
do {
id = KRandom::randomString(5);
} while(m_actionHash.contains(id));
RecommendationAction action;
action.id = id;
action.text = i18n("Open '%1'", result.resource().genericLabel());
m_actionHash[id] = action;
m_RecommendationForAction[id] = r;
r.actions << action;
m_recommendations << r;
}
}
void Contour::RecommendationManager::Private::_k_queryFinished()
{
emit q->recommendationsChanged();
}
Contour::RecommendationManager::RecommendationManager(QObject *parent)
: QObject(parent),
d(new Private())
{
d->q = this;
connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),
this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));
d->m_activityConsumer = new KActivityConsumer(this);
connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),
this, SLOT(_k_currentActivityChanged(QString)));
d->m_locationManager = new LocationManager(this);
connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),
this, SLOT(_k_locationChanged(QList<QLandmark>)));
d->updateRecommendations();
// export via DBus
qDBusRegisterMetaType<Contour::Recommendation>();
qDBusRegisterMetaType<QList<Contour::Recommendation> >();
qDBusRegisterMetaType<Contour::RecommendationAction>();
(void)new RecommendationManagerAdaptor(this);
QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this);
}
Contour::RecommendationManager::~RecommendationManager()
{
delete d;
}
QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const
{
return d->m_recommendations;
}
void Contour::RecommendationManager::executeAction(const QString &actionId)
{
if(d->m_actionHash.contains(actionId)) {
RecommendationAction action = d->m_actionHash.value(actionId);
// FIXME: this is the hacky execution of the action, make it correct
Recommendation r = d->m_RecommendationForAction.value(actionId);
(void)new KRun(r.resourceUri, 0);
}
else {
kDebug() << "Invalid action id encountered:" << actionId;
}
}
#include "recommendationmanager.moc"
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionEquation.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMorphologicalDialationFilter.h"
#include "itkBinaryMorphologicalErosionFilter.h"
#include "itkBinaryMorphologicalFilterBase.h"
#include "itkBinomialBlurImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkCosImageFilter.h"
#include "itkCurvature2DAnisotropicDiffusionEquation.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkDerivativeImageFilter.h"
#include "itkDifferenceOfGaussiansGradientImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkFileIOToImageFilter.h"
#include "itkFirstDerivativeRecursiveGaussianImageFilter.h"
#include "itkGradient2DAnisotropicDiffusionEquation.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "itkGradientNDAnisotropicDiffusionEquation.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.h"
#include "itkGrayscaleErodeImageFilter.h"
#include "itkGrayscaleFunctionDilateImageFilter.h"
#include "itkGrayscaleFunctionErodeImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageToMeshFilter.h"
#include "itkImageToParametricSpaceFilter.h"
#include "itkImageWriter.h"
#include "itkImportImageFilter.h"
#include "itkJoinImageFilter.h"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMirrorPadImageFilter.h"
#include "itkMorphologyImageFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.h"
#include "itkNeighborhoodOperatorImageFilter.h"
#include "itkNonThreadedShrinkImageFilter.h"
#include "itkPadImageFilter.h"
#include "itkPlaheImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkRawImageWriter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkRecursiveSeparableImageFilter.h"
#include "itkReflectiveImageRegionIterator.h"
#include "itkResampleImageFilter.h"
#include "itkScalarAnisotropicDiffusionEquation.h"
#include "itkSecondDerivativeRecursiveGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkSinImageFilter.h"
#include "itkSpatialFunctionImageEvaluatorFilter.h"
#include "itkSqrtImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.h"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkTransformMeshFilter.h"
#include "itkTwoOutputExampleImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkVTKImageExport.h"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageReader.h"
#include "itkVTKImageWriter.h"
#include "itkVectorAnisotropicDiffusionEquation.h"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvature2DAnisotropicDiffusionEquation.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkVectorExpandImageFilter.h"
#include "itkVectorGradient2DAnisotropicDiffusionEquation.h"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionEquation.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkWrapPadImageFilter.h"
#include "itkWriter.h"
int main ( int argc, char* argv )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionEquation.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMorphologicalDialationFilter.h"
#include "itkBinaryMorphologicalErosionFilter.h"
#include "itkBinaryMorphologicalFilterBase.h"
#include "itkBinomialBlurImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkCosImageFilter.h"
#include "itkCurvature2DAnisotropicDiffusionEquation.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkDerivativeImageFilter.h"
#include "itkDifferenceOfGaussiansGradientImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkFileIOToImageFilter.h"
#include "itkFirstDerivativeRecursiveGaussianImageFilter.h"
#include "itkGradient2DAnisotropicDiffusionEquation.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "itkGradientNDAnisotropicDiffusionEquation.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.h"
#include "itkGrayscaleErodeImageFilter.h"
#include "itkGrayscaleFunctionDilateImageFilter.h"
#include "itkGrayscaleFunctionErodeImageFilter.h"
#include "itkImageToMeshFilter.h"
#include "itkImageToParametricSpaceFilter.h"
#include "itkImageWriter.h"
#include "itkImportImageFilter.h"
#include "itkJoinImageFilter.h"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMirrorPadImageFilter.h"
#include "itkMorphologyImageFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.h"
#include "itkNeighborhoodOperatorImageFilter.h"
#include "itkNonThreadedShrinkImageFilter.h"
#include "itkPadImageFilter.h"
#include "itkPlaheImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkRawImageWriter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkRecursiveSeparableImageFilter.h"
#include "itkReflectiveImageRegionIterator.h"
#include "itkResampleImageFilter.h"
#include "itkScalarAnisotropicDiffusionEquation.h"
#include "itkSecondDerivativeRecursiveGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkSinImageFilter.h"
#include "itkSpatialFunctionImageEvaluatorFilter.h"
#include "itkSqrtImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.h"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkTransformMeshFilter.h"
#include "itkTwoOutputExampleImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkVTKImageExport.h"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageReader.h"
#include "itkVTKImageWriter.h"
#include "itkVectorAnisotropicDiffusionEquation.h"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvature2DAnisotropicDiffusionEquation.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkVectorExpandImageFilter.h"
#include "itkVectorGradient2DAnisotropicDiffusionEquation.h"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionEquation.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkWrapPadImageFilter.h"
#include "itkWriter.h"
int main ( int argc, char* argv )
{
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
// NAUTITIA
//
// jys 24-JUL-2002
//
// Tokenizer is the main program of Tokenizer stuff.
#include "Tokenizer.h"
#include "Automaton.h"
#include "State.h"
// #include "linguisticProcessing/core/Tokenizer/CharChart.h"
#include "common/misc/Exceptions.h"
#include "common/Data/strwstrtools.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h"
#include "linguisticProcessing/core/LinguisticProcessors/LimaStringText.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h"
#include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h"
#include "common/MediaticData/mediaticData.h"
#include "common/time/timeUtilsController.h"
#include <string>
using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::Misc;
namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{
static SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);
class TokenizerPrivate
{
public:
TokenizerPrivate();
virtual ~TokenizerPrivate();
Automaton _automaton;
CharChart* _charChart;
MediaId _language;
};
TokenizerPrivate::TokenizerPrivate() : _automaton()
{}
TokenizerPrivate::~TokenizerPrivate()
{
}
Tokenizer::Tokenizer() : m_d(new TokenizerPrivate())
{}
Tokenizer::~Tokenizer()
{
delete m_d;
}
const CharChart* Tokenizer::charChart() const {return m_d->_charChart;}
CharChart* Tokenizer::charChart() {return m_d->_charChart;}
void Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}
void Tokenizer::init(
Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,
Manager* manager)
{
TOKENIZERLOGINIT;
LDEBUG << "Tokenizer::init";
m_d->_language=manager->getInitializationParameters().media;
try
{
string charchartId=unitConfiguration.getParamsValueAtKey("charChart");
AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);
m_d->_charChart=static_cast<CharChart*>(res);
}
catch (NoSuchParam& )
{
LERROR << "no param 'charChart' in Tokenizer group configuration (language="
<< (int) m_d->_language << ")";
throw InvalidConfiguration();
}
try
{
string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();
string fileName=resourcesPath +"/"+unitConfiguration.getParamsValueAtKey("automatonFile");
m_d->_automaton.setCharChart(m_d->_charChart);
m_d->_automaton.loadFromFile(fileName);
}
catch (NoSuchParam& )
{
LERROR << "no param 'automatonFile' in Tokenizer group configuration (language="
<< (int) m_d->_language << ")";
throw InvalidConfiguration();
}
// when input XML file is syntactically wrong
catch (XmlSyntaxException exc)
{
std::ostringstream mess;
mess << "XmlSyntaxException at line "<<exc._lineNumber<<" cause: ";
switch (exc._why)
{
case XmlSyntaxException::SYNTAX_EXC : mess << "SYNTAX_EXC"; break;
case XmlSyntaxException::NO_DATA_EXC : mess << "NO_DATA_EXC"; break;
case XmlSyntaxException::DOUBLE_EXC : mess << "DOUBLE_EXC"; break;
case XmlSyntaxException::FWD_CLASS_EXC : mess << "FWD_CLASS_EXC"; break;
case XmlSyntaxException::MULT_CLASS_EXC : mess << "MULT_CLASS_EXC"; break;
case XmlSyntaxException::EOF_EXC : mess << "EOF_EXC"; break;
case XmlSyntaxException::NO_CODE_EXC : mess << "NO_CODE_EXC"; break;
case XmlSyntaxException::BAD_CODE_EXC : mess << "BAD_CODE_EXC"; break;
case XmlSyntaxException::NO_CLASS_EXC : mess << "NO_CLASS_EXC"; break;
case XmlSyntaxException::UNK_CLASS_EXC : mess << "UNK_CLASS_EXC"; break;
case XmlSyntaxException::INT_ERROR_EXC : mess << "INT_ERROR_EXC"; break;
case XmlSyntaxException::INV_CLASS_EXC : mess << "INV_CLASS_EXC"; break;
default: mess << "??";
}
LERROR << mess.str();
throw InvalidConfiguration();
}
catch (std::exception &exc)
{
// @todo remove all causes of InfiniteLoopException
LERROR << exc.what();
throw InvalidConfiguration();
}
}
LimaStatusCode Tokenizer::process(
AnalysisContent& analysis) const
{
TimeUtilsController flatTokenizerProcessTime("FlatTokenizer");
TOKENIZERLOGINIT;
LINFO << "start tokenizer process";
LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData("Text"));
AnalysisGraph* anagraph(0);
anagraph=new AnalysisGraph("AnalysisGraph",m_d->_language,true,true);
analysis.setData("AnalysisGraph",anagraph);
LinguisticGraph* graph=anagraph->getGraph();
// Gets transformed file into characters class string
Text* text=new Text(m_d->_language, m_d->_charChart);
text->setText(*originalText);
text->setGraph(anagraph->firstVertex(),graph);
LINFO << "Running automaton on '" << *originalText << "'";
const State* newState = m_d->_automaton.run(*text);
while (newState)
{
LTRACE << "Running automaton";
newState = m_d->_automaton.run(*text, newState);
}
if (text->position() < text->size()-1)
{
LERROR << "Tokenized up to " << text->position()
<< " for a text of size " << text->size() ;
}
text->finalizeAndUnsetGraph();
remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));
delete text;
return SUCCESS_ID;
}
} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
<commit_msg>Simplify a debug output<commit_after>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA 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.
LIMA 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 LIMA. If not, see <http://www.gnu.org/licenses/>
*/
// NAUTITIA
//
// jys 24-JUL-2002
//
// Tokenizer is the main program of Tokenizer stuff.
#include "Tokenizer.h"
#include "Automaton.h"
#include "State.h"
// #include "linguisticProcessing/core/Tokenizer/CharChart.h"
#include "common/misc/Exceptions.h"
#include "common/Data/strwstrtools.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h"
#include "linguisticProcessing/core/LinguisticProcessors/LimaStringText.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h"
#include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h"
#include "common/MediaticData/mediaticData.h"
#include "common/time/timeUtilsController.h"
#include <string>
using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::Misc;
namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{
static SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);
class TokenizerPrivate
{
public:
TokenizerPrivate();
virtual ~TokenizerPrivate();
Automaton _automaton;
CharChart* _charChart;
MediaId _language;
};
TokenizerPrivate::TokenizerPrivate() : _automaton()
{}
TokenizerPrivate::~TokenizerPrivate()
{
}
Tokenizer::Tokenizer() : m_d(new TokenizerPrivate())
{}
Tokenizer::~Tokenizer()
{
delete m_d;
}
const CharChart* Tokenizer::charChart() const {return m_d->_charChart;}
CharChart* Tokenizer::charChart() {return m_d->_charChart;}
void Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}
void Tokenizer::init(
Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,
Manager* manager)
{
TOKENIZERLOGINIT;
LDEBUG << "Tokenizer::init";
m_d->_language=manager->getInitializationParameters().media;
try
{
string charchartId=unitConfiguration.getParamsValueAtKey("charChart");
AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);
m_d->_charChart=static_cast<CharChart*>(res);
}
catch (NoSuchParam& )
{
LERROR << "no param 'charChart' in Tokenizer group configuration (language="
<< (int) m_d->_language << ")";
throw InvalidConfiguration();
}
try
{
string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();
string fileName=resourcesPath +"/"+unitConfiguration.getParamsValueAtKey("automatonFile");
m_d->_automaton.setCharChart(m_d->_charChart);
m_d->_automaton.loadFromFile(fileName);
}
catch (NoSuchParam& )
{
LERROR << "no param 'automatonFile' in Tokenizer group configuration (language="
<< (int) m_d->_language << ")";
throw InvalidConfiguration();
}
// when input XML file is syntactically wrong
catch (XmlSyntaxException exc)
{
std::ostringstream mess;
mess << "XmlSyntaxException at line "<<exc._lineNumber<<" cause: ";
switch (exc._why)
{
case XmlSyntaxException::SYNTAX_EXC : mess << "SYNTAX_EXC"; break;
case XmlSyntaxException::NO_DATA_EXC : mess << "NO_DATA_EXC"; break;
case XmlSyntaxException::DOUBLE_EXC : mess << "DOUBLE_EXC"; break;
case XmlSyntaxException::FWD_CLASS_EXC : mess << "FWD_CLASS_EXC"; break;
case XmlSyntaxException::MULT_CLASS_EXC : mess << "MULT_CLASS_EXC"; break;
case XmlSyntaxException::EOF_EXC : mess << "EOF_EXC"; break;
case XmlSyntaxException::NO_CODE_EXC : mess << "NO_CODE_EXC"; break;
case XmlSyntaxException::BAD_CODE_EXC : mess << "BAD_CODE_EXC"; break;
case XmlSyntaxException::NO_CLASS_EXC : mess << "NO_CLASS_EXC"; break;
case XmlSyntaxException::UNK_CLASS_EXC : mess << "UNK_CLASS_EXC"; break;
case XmlSyntaxException::INT_ERROR_EXC : mess << "INT_ERROR_EXC"; break;
case XmlSyntaxException::INV_CLASS_EXC : mess << "INV_CLASS_EXC"; break;
default: mess << "??";
}
LERROR << mess.str();
throw InvalidConfiguration();
}
catch (std::exception &exc)
{
// @todo remove all causes of InfiniteLoopException
LERROR << exc.what();
throw InvalidConfiguration();
}
}
LimaStatusCode Tokenizer::process(
AnalysisContent& analysis) const
{
TimeUtilsController flatTokenizerProcessTime("FlatTokenizer");
TOKENIZERLOGINIT;
LINFO << "start tokenizer process";
LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData("Text"));
AnalysisGraph* anagraph(0);
anagraph=new AnalysisGraph("AnalysisGraph",m_d->_language,true,true);
analysis.setData("AnalysisGraph",anagraph);
LinguisticGraph* graph=anagraph->getGraph();
// Gets transformed file into characters class string
Text* text=new Text(m_d->_language, m_d->_charChart);
text->setText(*originalText);
text->setGraph(anagraph->firstVertex(),graph);
LINFO << "Running automaton on" << *originalText;
const State* newState = m_d->_automaton.run(*text);
while (newState)
{
LTRACE << "Running automaton";
newState = m_d->_automaton.run(*text, newState);
}
if (text->position() < text->size()-1)
{
LERROR << "Tokenized up to " << text->position()
<< " for a text of size " << text->size() ;
}
text->finalizeAndUnsetGraph();
remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));
delete text;
return SUCCESS_ID;
}
} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
<|endoftext|>
|
<commit_before>#ifndef HASHEROBJ_PY
#define HASHEROBJ_PY
#include "hasher_obj.hpp"
// Simpler HasherObject to be wrapped with SWIG
class HasherObjectPy {
public:
HasherObjectPy() {
hobj = new HasherObject();
};
~HasherObjectPy() {
delete hobj;
};
int read_update_files() {
return hobj->read_update_files();
};
int load_hashcodes() {
return hobj->load_hashcodes();
};
int load_itq_model() {
return hobj->load_itq_model();
};
void set_query_feats_from_disk(std::string filename) {
hobj->set_query_feats_from_disk(filename);
};
void find_knn() {
hobj->find_knn();
};
void set_paths() {
hobj->set_paths();
};
void set_topk(int _top_k) {
hobj->set_topk(_top_k);
};
void set_ratio(float _ratio) {
hobj->set_ratio(_ratio);
};
void set_bit_num(int _bit_num) {
hobj->set_bit_num(_bit_num);
};
void set_norm(int _norm) {
hobj->set_norm(_norm);
};
void set_feature_dim(int _feature_dim) {
hobj->set_feature_dim(_feature_dim);
};
void set_base_modelpath(std::string _base_modelpath){
hobj->set_base_modelpath(_base_modelpath);
};
std::string get_base_modelpath(){
return hobj->get_base_modelpath();
};
void set_base_updatepath(std::string _base_updatepath) {
hobj->set_base_updatepath(_base_updatepath);
};
std::string get_base_updatepath() {
return hobj->get_base_updatepath();
};
void set_outputfile(std::string _outname){
hobj->set_outputfile(_outname);
};
private:
HasherObject* hobj;
};
#endif
<commit_msg>auto set paths and fill data nums<commit_after>#ifndef HASHEROBJ_PY
#define HASHEROBJ_PY
#include "hasher_obj.hpp"
// Simpler HasherObject to be wrapped with SWIG
class HasherObjectPy {
public:
HasherObjectPy() {
hobj = new HasherObject();
};
~HasherObjectPy() {
delete hobj;
};
int read_update_files() {
return hobj->read_update_files();
};
int load_hashcodes() {
hobj->fill_data_nums_accum();
return hobj->load_hashcodes();
};
int load_itq_model() {
return hobj->load_itq_model();
};
void set_query_feats_from_disk(std::string filename) {
hobj->set_query_feats_from_disk(filename);
};
void find_knn() {
hobj->find_knn();
};
void set_paths() {
hobj->set_paths();
};
void set_topk(int _top_k) {
hobj->set_topk(_top_k);
};
void set_ratio(float _ratio) {
hobj->set_ratio(_ratio);
};
void set_bit_num(int _bit_num) {
hobj->set_bit_num(_bit_num);
};
void set_norm(int _norm) {
hobj->set_norm(_norm);
};
void set_feature_dim(int _feature_dim) {
hobj->set_feature_dim(_feature_dim);
};
void set_base_modelpath(std::string _base_modelpath){
hobj->set_base_modelpath(_base_modelpath);
hobj->set_paths();
};
std::string get_base_modelpath(){
return hobj->get_base_modelpath();
};
void set_base_updatepath(std::string _base_updatepath) {
hobj->set_base_updatepath(_base_updatepath);
hobj->set_paths();
};
std::string get_base_updatepath() {
return hobj->get_base_updatepath();
};
void set_outputfile(std::string _outname){
hobj->set_outputfile(_outname);
};
private:
HasherObject* hobj;
};
#endif
<|endoftext|>
|
<commit_before>#include <tiramisu/tiramisu.h>
#include "configuration.h"
using namespace tiramisu;
int main(int argc, char **argv)
{
// Double tiling with Register and Shared memory
// Fused A_reg and non-square tiling
tiramisu::init("matmul");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Declare loop iterators
var i("i", 0, M), j("j", 0, N), k("k", 0, K);
var i0("i0", 0, M / R_BLOCK_I), i1("i1", 0, R_BLOCK_I), j0("j0", 0, N / R_BLOCK_J), j1("j1", 0, R_BLOCK_J), k0("k0", 0, K / BLOCK), k1("k1", 0, BLOCK);
var k0_skiplast("k0", 0, K / BLOCK - 1);
var i00("i00"), i01("i01"), j00("j00"), j01("j01");
// Declare cpu buffers.
buffer b_A("b_A", {M, K}, DATA_PTYPE, a_input);
buffer b_B("b_B", {K, N}, DATA_PTYPE, a_input);
buffer b_C("b_C", {M, N}, DATA_PTYPE, a_output);
buffer b_Consts("b_Consts", {2}, DATA_PTYPE, a_input);
// Declare gpu buffers.
buffer b_A_glb("b_A_glb", {M, K}, DATA_PTYPE, a_temporary);
buffer b_B_glb("b_B_glb", {K, N}, DATA_PTYPE, a_temporary);
buffer b_C_glb("b_C_glb", {M, N}, DATA_PTYPE, a_temporary);
// "+ 1" to reduce shared memory bank conflicts
buffer b_A_shr("b_A_shr", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);
buffer b_B_shr("b_B_shr", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);
buffer b_A_reg("b_A_reg", {1}, DATA_PTYPE, a_temporary);
buffer b_B_reg("b_B_reg", {R_BLOCK_J}, DATA_PTYPE, a_temporary);
buffer b_acc("b_acc", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);
b_A_glb.tag_gpu_global();
b_B_glb.tag_gpu_global();
b_C_glb.tag_gpu_global();
b_A_shr.tag_gpu_shared();
b_B_shr.tag_gpu_shared();
b_A_reg.tag_gpu_register();
b_B_reg.tag_gpu_local();
b_acc.tag_gpu_local();
// Declare input wrappers
input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);
input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);
input c_A({i, k}, DATA_PTYPE);
input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);
input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);
input c_B({k, j}, DATA_PTYPE);
input c_Consts({i}, DATA_PTYPE);
constant c_alpha("alpha", c_Consts(0));
constant c_beta("beta", c_Consts(1));
// Declare computations
computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));
computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));
computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));
computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));
computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));
computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));
computation c_acc_init({i, j}, (float) 0);
computation c_acc({i, j, k}, DATA_PTYPE);
c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));
computation c_C({i, j}, DATA_PTYPE);
c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);
// Declare declarations
computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));
computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));
computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));
computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));
computation c_acc_dec({i0, j0}, allocate(b_acc));
// Declare synchronizer computations
computation c_sync1({i0, j0}, tiramisu::sync());
computation c_sync2({i0, j0, k0}, tiramisu::sync());
// Declare host-gpu transfer computations.
computation copy_A_to_device({}, memcpy(b_A, b_A_glb));
computation copy_B_to_device({}, memcpy(b_B, b_B_glb));
computation copy_C_to_device({}, memcpy(b_C, b_C_glb));
computation copy_C_to_host({}, memcpy(b_C_glb, b_C));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Scheduling commands
c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_acc.interchange(j1, k);
c_acc.interchange(i1, k);
c_acc.split(k, BLOCK, k0, k1);
c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
copy_A_to_device.then(copy_B_to_device, computation::root)
.then(copy_C_to_device, computation::root)
.then(c_A_shr_dec, computation::root)
.then(c_B_shr_dec, j01)
.then(c_A_reg_dec, j01)
.then(c_B_reg_dec, j01)
.then(c_acc_dec, j01)
.then(c_acc_init, j01)
.then(c_A_glb_to_shr_pre, j01)
.then(c_B_glb_to_shr_pre, j01)
.then(c_sync1, j01)
.then(c_A_glb_to_shr, j01)
.then(c_B_glb_to_shr, k0)
.then(c_B_shr_to_reg, k0)
.then(c_A_shr_to_reg, k1)
.then(c_acc, i1)
.then(c_sync2, k0)
.then(c_C, j01)
.then(copy_C_to_host, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
c_A_glb.store_in(&b_A_glb, {i0 * R_BLOCK_I + i1, k0 * BLOCK + j0 % BLOCK});
// Note the transpose:
c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});
c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});
c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});
c_A_shr_to_reg.store_in(&b_A_reg, {0});
// Note that we use a transposed mapping to assure memory coalescing
// This requires R_BLOCK_J to be equal to BLOCK
c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});
c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});
c_B_shr_to_reg.store_in(&b_B_reg, {j1});
c_A.store_in(&b_A_reg, {i % R_BLOCK_I});
c_B.store_in(&b_B_reg, {j % R_BLOCK_J});
c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
c_C.store_in(&b_C_glb);
c_Consts.store_in(&b_Consts, {i});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Generate object files. Last argument triggers cuda compilation.
tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, "fct.o", true);
return 0;
}
<commit_msg>GPU GEMM coalescing<commit_after>#include <tiramisu/tiramisu.h>
#include "configuration.h"
using namespace tiramisu;
int main(int argc, char **argv)
{
// Double tiling with Register and Shared memory
// Fused A_reg and non-square tiling
tiramisu::init("matmul");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
// Declare loop iterators
var i("i", 0, M), j("j", 0, N), k("k", 0, K);
var i0("i0", 0, M / R_BLOCK_I), i1("i1", 0, R_BLOCK_I), j0("j0", 0, N / R_BLOCK_J), j1("j1", 0, R_BLOCK_J), k0("k0", 0, K / BLOCK), k1("k1", 0, BLOCK);
var k0_skiplast("k0", 0, K / BLOCK - 1);
var i00("i00"), i01("i01"), j00("j00"), j01("j01");
// Declare cpu buffers.
buffer b_A("b_A", {M, K}, DATA_PTYPE, a_input);
buffer b_B("b_B", {K, N}, DATA_PTYPE, a_input);
buffer b_C("b_C", {M, N}, DATA_PTYPE, a_output);
buffer b_Consts("b_Consts", {2}, DATA_PTYPE, a_input);
// Declare gpu buffers.
buffer b_A_glb("b_A_glb", {M, K}, DATA_PTYPE, a_temporary);
buffer b_B_glb("b_B_glb", {K, N}, DATA_PTYPE, a_temporary);
buffer b_C_glb("b_C_glb", {M, N}, DATA_PTYPE, a_temporary);
// "+ 1" to reduce shared memory bank conflicts
buffer b_A_shr("b_A_shr", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);
buffer b_B_shr("b_B_shr", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);
buffer b_A_reg("b_A_reg", {1}, DATA_PTYPE, a_temporary);
buffer b_B_reg("b_B_reg", {R_BLOCK_J}, DATA_PTYPE, a_temporary);
buffer b_acc("b_acc", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);
b_A_glb.tag_gpu_global();
b_B_glb.tag_gpu_global();
b_C_glb.tag_gpu_global();
b_A_shr.tag_gpu_shared();
b_B_shr.tag_gpu_shared();
b_A_reg.tag_gpu_register();
b_B_reg.tag_gpu_local();
b_acc.tag_gpu_local();
// Declare input wrappers
input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);
input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);
input c_A({i, k}, DATA_PTYPE);
input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);
input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);
input c_B({k, j}, DATA_PTYPE);
input c_Consts({i}, DATA_PTYPE);
constant c_alpha("alpha", c_Consts(0));
constant c_beta("beta", c_Consts(1));
// Declare computations
computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));
computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));
computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));
computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));
computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));
computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));
computation c_acc_init({i, j}, (float) 0);
computation c_acc({i, j, k}, DATA_PTYPE);
c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));
computation c_C({i, j}, DATA_PTYPE);
c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);
// Declare declarations
computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));
computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));
computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));
computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));
computation c_acc_dec({i0, j0}, allocate(b_acc));
// Declare synchronizer computations
computation c_sync1({i0, j0}, tiramisu::sync());
computation c_sync2({i0, j0, k0}, tiramisu::sync());
// Declare host-gpu transfer computations.
computation copy_A_to_device({}, memcpy(b_A, b_A_glb));
computation copy_B_to_device({}, memcpy(b_B, b_B_glb));
computation copy_C_to_device({}, memcpy(b_C, b_C_glb));
computation copy_C_to_host({}, memcpy(b_C_glb, b_C));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
// Scheduling commands
c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_acc.interchange(j1, k);
c_acc.interchange(i1, k);
c_acc.split(k, BLOCK, k0, k1);
c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
copy_A_to_device.then(copy_B_to_device, computation::root)
.then(copy_C_to_device, computation::root)
.then(c_A_shr_dec, computation::root)
.then(c_B_shr_dec, j01)
.then(c_A_reg_dec, j01)
.then(c_B_reg_dec, j01)
.then(c_acc_dec, j01)
.then(c_acc_init, j01)
.then(c_A_glb_to_shr_pre, j01)
.then(c_B_glb_to_shr_pre, j01)
.then(c_sync1, j01)
.then(c_A_glb_to_shr, j01)
.then(c_B_glb_to_shr, k0)
.then(c_B_shr_to_reg, k0)
.then(c_A_shr_to_reg, k1)
.then(c_acc, i1)
.then(c_sync2, k0)
.then(c_C, j01)
.then(copy_C_to_host, computation::root);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
c_A_glb.store_in(&b_A_glb, {(i0 - i0 % BLOCK + j0 % BLOCK) * R_BLOCK_I + i1, k0 * BLOCK + i0 % BLOCK});
// Note the transpose:
c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});
c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});
c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});
c_A_shr_to_reg.store_in(&b_A_reg, {0});
// Note that we use a transposed mapping to assure memory coalescing
// This requires R_BLOCK_J to be equal to BLOCK
c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});
c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});
c_B_shr_to_reg.store_in(&b_B_reg, {j1});
c_A.store_in(&b_A_reg, {i % R_BLOCK_I});
c_B.store_in(&b_B_reg, {j % R_BLOCK_J});
c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
c_C.store_in(&b_C_glb);
c_Consts.store_in(&b_Consts, {i});
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
// Generate object files. Last argument triggers cuda compilation.
tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, "fct.o", true);
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
namespace RhIO
{
Shell::Shell(std::string server_)
: server(server_), client(NULL), clientSub(NULL), stream(NULL)
{
}
void Shell::terminal_set_ioconfig() {
struct termios custom;
int fd=fileno(stdin);
tcgetattr(fd, &termsave);
custom=termsave;
custom.c_lflag &= ~(ICANON|ECHO);
tcsetattr(fd,TCSANOW,&custom);
// fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
}
void Shell::displayPrompt()
{
Terminal::setColor("yellow", true);
std::cout << "RhIO";
Terminal::clear();
std::cout << ":";
Terminal::setColor("blue", true);
std::cout << getPath();
Terminal::clear();
std::cout << "# " << std::flush;
}
void Shell::run()
{
terminal_set_ioconfig();
std::string reqServer = "tcp://"+server+":"+ServerRepPort;
std::string subServer = "tcp://"+server+":"+ServerPubPort;
terminate = false;
Terminal::setColor("white", true);
std::cout << "Rhoban I/O shell, welcome!" << std::endl;
std::cout << "Connecting to " << server << std::endl;
client = new ClientReq(reqServer);
clientSub = new ClientSub(subServer);
stream = new Stream(this);
std::cout << "Downloading the tree..." << std::endl;
tree = new Node(client, "");
Terminal::clear();
// Reading lines from stdin
while (!terminate ) {
displayPrompt();
std::string line;
// std::getline(std::cin, line);
line=getLine();
parse(line);
}
tcsetattr(fileno(stdin),TCSANOW,&termsave);
std::cout << std::endl << std::flush;
}
std::string Shell::getLine()
{
char c;
std::string line("");
bool done=false;
bool esc_mode=false;
std::deque<std::string>::iterator hist_it=shell_history.end();
int cursorpos=0;
std::string lastcmd("");
while(!done)
{
if ((c = getchar())>0)
{
switch(c)
{
case 0x0a: //enter
putchar(c);
done=true;
lastcmd="";
if(shell_history.size()>0)
lastcmd=shell_history.back();
if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
{
shell_history.push_back(line);
if(shell_history.size()>MAX_HISTORY)
shell_history.pop_front();
hist_it=shell_history.begin();
}
return line;
break;//useless
case 0x01: //Ctrl-a goto begin of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
cursorpos=0;
if(line.size()>0)
Terminal::cursorNLeft(line.size());
break;
case 0x05: //Ctrl-e goto end of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(cursorpos<line.size() )
{
// Terminal::cursorNLeft(cursorpos);
// Terminal::cursorNRight(line.size());
cursorpos=line.size();
}
break;
case 0xc: //Ctrl-l clear screen
Terminal::clearScreen();
Terminal::clearLine();
Terminal::initCursor();
displayPrompt();
line="";
cursorpos=0;
break;
case 0x1b: //begin break mode (arrows)
esc_mode=true;
break;
case 0x5b: //just after 0x1b
break;
case 0x41: //up
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.begin())
{
line=*--hist_it;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
esc_mode=false;
}
break;
case 0x42: //down
if(esc_mode)
{
if(shell_history.size()>0 && hist_it!= shell_history.end())
{
line=*hist_it++;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
else if( hist_it== shell_history.end())
{
Terminal::clearLine();
displayPrompt();
line="";
cursorpos=0;
}
esc_mode=false;
}
break;
case 0x43: //right
if(esc_mode)
{
if(cursorpos<line.size())
{
Terminal::cursorRight();
cursorpos++;
}
esc_mode=false;
}
break;
case 0x44: //left
if(esc_mode)
{
if(cursorpos>0)
{
Terminal::cursorLeft();
cursorpos--;
}
esc_mode=false;
}
break;
case 0x7f: //backspace
if(line.size()>0)
{
line.pop_back();
Terminal::clearLine();
displayPrompt();
cursorpos--;
std::cout<<line;
}
break;
default:
if(line.size()>0)
{
std::string tmp("");
tmp+=c;
line.insert(cursorpos,tmp);
}
else{
line+=c;
}
cursorpos++;
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(line.size()-cursorpos>0)
Terminal::cursorNLeft(line.size()-cursorpos);
break;
}
}
}
line="";
return line;
}
void Shell::parse(std::string line)
{
// Try to interpret command as a set
for (int i=0; i<line.size(); i++) {
if (line[i] == '=') {
std::string lvalue = line.substr(0, i);
std::string rvalue = line.substr(i+1);
trim(lvalue);
trim(rvalue);
set(lvalue, rvalue);
return;
}
}
// Try to split line into parts and execute it
std::list<std::string> parts;
std::string part;
for (int i=0; i<line.size(); i++) {
if (std::isspace(line[i])) {
if (part != "") {
parts.push_back(part);
part = "";
}
} else {
part += line[i];
}
}
if (part != "") {
parts.push_back(part);
}
if (parts.size()) {
auto command = parts.front();
parts.pop_front();
process(command, parts);
}
}
void Shell::process(std::string command, std::list<std::string> args)
{
// First, try to quit/exit
if (command == "quit" || command == "exit") {
terminate = true;
} else {
// Checking for the command in the list
if (commands.count(command)) {
std::vector<std::string> argsV;
for (auto part : args) {
argsV.push_back(part);
}
commands[command]->process(argsV);
} else {
auto nodeValue = getNodeValue(command);
auto value = nodeValue.value;
if (value) {
Node::get(this, nodeValue);
std::cout << command << "=" << Node::toString(value) << std::endl;
} else {
Terminal::setColor("red", true);
std::cout << "Unknown command: " << command << std::endl;
Terminal::clear();
}
}
}
}
void Shell::set(std::string lvalue, std::string rvalue)
{
auto node = getCurrentNode();
auto nodeValue = getNodeValue(lvalue);
auto value = nodeValue.value;
if (value) {
Node::setFromString(this, nodeValue, rvalue);
} else {
Terminal::setColor("red", true);
std::cout << "Unknown parameter: " << lvalue << std::endl;
Terminal::clear();
}
}
void Shell::registerCommand(Command *command)
{
command->setShell(this);
commands[command->getName()] = command;
}
std::map<std::string, Command*> Shell::getCommands()
{
return commands;
}
ClientReq *Shell::getClient()
{
return client;
}
ClientSub *Shell::getClientSub()
{
return clientSub;
}
void Shell::enterPath(std::string path_)
{
path.push_back(path_);
}
void Shell::upPath()
{
if (path.size()) {
path.pop_back();
}
}
bool Shell::goToPath(std::string spath)
{
if (auto node = getNode(spath)) {
auto parts = pathToParts(node->getPath());
path.clear();
for (auto part : parts) {
path.push_back(part);
}
return true;
} else {
return false;
}
}
std::string Shell::getPath()
{
std::string p = "";
for (auto part : path) {
if (p != "") {
p += "/";
}
p += part;
}
return p;
}
std::vector<std::string> Shell::pathToParts(std::string spath)
{
auto parts = split(spath, '/');
std::vector<std::string> path;
for (auto part : parts) {
if (part != "") {
path.push_back(part);
}
}
return path;
}
Node *Shell::getNode(std::string spath)
{
if (spath.size()==0 || spath[0]!='/') {
auto myPath = getPath();
if (myPath != "") {
myPath += "/";
}
spath = myPath + spath;
}
auto path = pathToParts(spath);
Node *node = tree;
for (auto part : path) {
node = node->getChild(part);
if (node == NULL) {
return NULL;
}
}
return node;
}
NodeValue Shell::getNodeValue(std::string path)
{
auto parts = pathToParts(path);
if (parts.size() == 0) {
return NodeValue(NULL, NULL);
}
// Child name
auto name = parts[parts.size()-1];
parts.pop_back();
// Creating value path
std::string prefix = "";
for (auto part : parts) {
if (prefix != "") prefix += "/";
prefix += part;
}
if (path[0] == '/') {
prefix = "/" + prefix;
}
// Getting node
auto node = getNode(prefix);
if (node == NULL) {
return NodeValue(NULL, NULL);
}
return node->getNodeValue(name);
}
Stream *Shell::getStream()
{
return stream;
}
ValueBase *Shell::getValue(std::string path)
{
return getNodeValue(path).value;
}
Node *Shell::getCurrentNode()
{
return getNode();
}
}
<commit_msg>fix maj<commit_after>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
namespace RhIO
{
Shell::Shell(std::string server_)
: server(server_), client(NULL), clientSub(NULL), stream(NULL)
{
}
void Shell::terminal_set_ioconfig() {
struct termios custom;
int fd=fileno(stdin);
tcgetattr(fd, &termsave);
custom=termsave;
custom.c_lflag &= ~(ICANON|ECHO);
tcsetattr(fd,TCSANOW,&custom);
// fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
}
void Shell::displayPrompt()
{
Terminal::setColor("yellow", true);
std::cout << "RhIO";
Terminal::clear();
std::cout << ":";
Terminal::setColor("blue", true);
std::cout << getPath();
Terminal::clear();
std::cout << "# " << std::flush;
}
void Shell::run()
{
terminal_set_ioconfig();
std::string reqServer = "tcp://"+server+":"+ServerRepPort;
std::string subServer = "tcp://"+server+":"+ServerPubPort;
terminate = false;
Terminal::setColor("white", true);
std::cout << "Rhoban I/O shell, welcome!" << std::endl;
std::cout << "Connecting to " << server << std::endl;
client = new ClientReq(reqServer);
clientSub = new ClientSub(subServer);
stream = new Stream(this);
std::cout << "Downloading the tree..." << std::endl;
tree = new Node(client, "");
Terminal::clear();
// Reading lines from stdin
while (!terminate ) {
displayPrompt();
std::string line;
// std::getline(std::cin, line);
line=getLine();
parse(line);
}
tcsetattr(fileno(stdin),TCSANOW,&termsave);
std::cout << std::endl << std::flush;
}
std::string Shell::getLine()
{
char c;
std::string line("");
bool done=false;
bool esc_mode=false;
std::deque<std::string>::iterator hist_it=shell_history.end();
int cursorpos=0;
std::string lastcmd("");
while(!done)
{
if ((c = getchar())>0)
{
switch(c)
{
case 0x0a: //enter
putchar(c);
done=true;
lastcmd="";
if(shell_history.size()>0)
lastcmd=shell_history.back();
if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
{
shell_history.push_back(line);
if(shell_history.size()>MAX_HISTORY)
shell_history.pop_front();
hist_it=shell_history.begin();
}
return line;
break;//useless
case 0x01: //Ctrl-a goto begin of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
cursorpos=0;
if(line.size()>0)
Terminal::cursorNLeft(line.size());
break;
case 0x05: //Ctrl-e goto end of line
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(cursorpos<line.size() )
{
// Terminal::cursorNLeft(cursorpos);
// Terminal::cursorNRight(line.size());
cursorpos=line.size();
}
break;
case 0xc: //Ctrl-l clear screen
Terminal::clearScreen();
Terminal::clearLine();
Terminal::initCursor();
displayPrompt();
line="";
cursorpos=0;
break;
case 0x1b: //begin break mode (arrows)
esc_mode=true;
break;
case 0x5b: //just after 0x1b
break;
case 0x7f: //backspace
if(line.size()>0)
{
line.pop_back();
Terminal::clearLine();
displayPrompt();
cursorpos--;
std::cout<<line;
}
break;
case 0x09: //TAB
break;
// if not esc_mode -> fall to default
case 0x41: //up
if(esc_mode && c==0x41)
{
if(shell_history.size()>0 && hist_it!= shell_history.begin())
{
line=*--hist_it;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
esc_mode=false;
break;
}
case 0x42: //down
if(esc_mode && c==0x42)
{
if(shell_history.size()>0 && hist_it!= shell_history.end())
{
line=*hist_it++;
cursorpos=line.size();
Terminal::clearLine();
displayPrompt();
std::cout<<line;
}
else if( hist_it== shell_history.end())
{
Terminal::clearLine();
displayPrompt();
line="";
cursorpos=0;
}
esc_mode=false;
break;
}
// break;
case 0x43: //right
if(esc_mode && c==0x43)
{
if(cursorpos<line.size())
{
Terminal::cursorRight();
cursorpos++;
}
esc_mode=false;
break;
}
// break;
case 0x44: //left
if(esc_mode && c==0x44)
{
if(cursorpos>0)
{
Terminal::cursorLeft();
cursorpos--;
}
esc_mode=false;
break;
}
// break;
default:
if(line.size()>0)
{
std::string tmp("");
tmp+=c;
line.insert(cursorpos,tmp);
}
else{
line+=c;
}
cursorpos++;
Terminal::clearLine();
displayPrompt();
std::cout<<line;
if(line.size()-cursorpos>0)
Terminal::cursorNLeft(line.size()-cursorpos);
break;
}
}
}
line="";
return line;
}
void Shell::parse(std::string line)
{
// Try to interpret command as a set
for (int i=0; i<line.size(); i++) {
if (line[i] == '=') {
std::string lvalue = line.substr(0, i);
std::string rvalue = line.substr(i+1);
trim(lvalue);
trim(rvalue);
set(lvalue, rvalue);
return;
}
}
// Try to split line into parts and execute it
std::list<std::string> parts;
std::string part;
for (int i=0; i<line.size(); i++) {
if (std::isspace(line[i])) {
if (part != "") {
parts.push_back(part);
part = "";
}
} else {
part += line[i];
}
}
if (part != "") {
parts.push_back(part);
}
if (parts.size()) {
auto command = parts.front();
parts.pop_front();
process(command, parts);
}
}
void Shell::process(std::string command, std::list<std::string> args)
{
// First, try to quit/exit
if (command == "quit" || command == "exit") {
terminate = true;
} else {
// Checking for the command in the list
if (commands.count(command)) {
std::vector<std::string> argsV;
for (auto part : args) {
argsV.push_back(part);
}
commands[command]->process(argsV);
} else {
auto nodeValue = getNodeValue(command);
auto value = nodeValue.value;
if (value) {
Node::get(this, nodeValue);
std::cout << command << "=" << Node::toString(value) << std::endl;
} else {
Terminal::setColor("red", true);
std::cout << "Unknown command: " << command << std::endl;
Terminal::clear();
}
}
}
}
void Shell::set(std::string lvalue, std::string rvalue)
{
auto node = getCurrentNode();
auto nodeValue = getNodeValue(lvalue);
auto value = nodeValue.value;
if (value) {
Node::setFromString(this, nodeValue, rvalue);
} else {
Terminal::setColor("red", true);
std::cout << "Unknown parameter: " << lvalue << std::endl;
Terminal::clear();
}
}
void Shell::registerCommand(Command *command)
{
command->setShell(this);
commands[command->getName()] = command;
}
std::map<std::string, Command*> Shell::getCommands()
{
return commands;
}
ClientReq *Shell::getClient()
{
return client;
}
ClientSub *Shell::getClientSub()
{
return clientSub;
}
void Shell::enterPath(std::string path_)
{
path.push_back(path_);
}
void Shell::upPath()
{
if (path.size()) {
path.pop_back();
}
}
bool Shell::goToPath(std::string spath)
{
if (auto node = getNode(spath)) {
auto parts = pathToParts(node->getPath());
path.clear();
for (auto part : parts) {
path.push_back(part);
}
return true;
} else {
return false;
}
}
std::string Shell::getPath()
{
std::string p = "";
for (auto part : path) {
if (p != "") {
p += "/";
}
p += part;
}
return p;
}
std::vector<std::string> Shell::pathToParts(std::string spath)
{
auto parts = split(spath, '/');
std::vector<std::string> path;
for (auto part : parts) {
if (part != "") {
path.push_back(part);
}
}
return path;
}
Node *Shell::getNode(std::string spath)
{
if (spath.size()==0 || spath[0]!='/') {
auto myPath = getPath();
if (myPath != "") {
myPath += "/";
}
spath = myPath + spath;
}
auto path = pathToParts(spath);
Node *node = tree;
for (auto part : path) {
node = node->getChild(part);
if (node == NULL) {
return NULL;
}
}
return node;
}
NodeValue Shell::getNodeValue(std::string path)
{
auto parts = pathToParts(path);
if (parts.size() == 0) {
return NodeValue(NULL, NULL);
}
// Child name
auto name = parts[parts.size()-1];
parts.pop_back();
// Creating value path
std::string prefix = "";
for (auto part : parts) {
if (prefix != "") prefix += "/";
prefix += part;
}
if (path[0] == '/') {
prefix = "/" + prefix;
}
// Getting node
auto node = getNode(prefix);
if (node == NULL) {
return NodeValue(NULL, NULL);
}
return node->getNodeValue(name);
}
Stream *Shell::getStream()
{
return stream;
}
ValueBase *Shell::getValue(std::string path)
{
return getNodeValue(path).value;
}
Node *Shell::getCurrentNode()
{
return getNode();
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
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 "radialdam_user.h"
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46.h>
static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
user_options_t* user = (user_options_t*) package;
/* [user] User options */
sc_options_add_int (opt, 0, "example", &user->example, 0, "[user] 0 - nomap; 1 - disk [0]");
sc_options_add_double (opt, 0, "g", &user->g, 1.0, "[user] g [1.0]");
sc_options_add_double (opt, 0, "x0", &user->x0, 0.0, "[user] x0 [0.0]");
sc_options_add_double (opt, 0, "y0", &user->y0, 0.0, "[user] y0 [0.0]");
sc_options_add_double (opt, 0, "r0", &user->r0, 0.5, "[user] r0 [0.5]");
sc_options_add_double (opt, 0, "hin", &user->hin, 2.0, "[user] hin [2.0]");
sc_options_add_double (opt, 0, "hout", &user->hout, 1.0, "[user] hout [1.0]");
sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "[user] alpha (for 5-patch map) [0.4]");
sc_options_add_int (opt, 0, "claw-version", &user->claw_version, 5,
"Clawpack_version (4 or 5) [5]");
user->is_registered = 1;
return NULL;
}
static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
user_options_t* user = (user_options_t*) package;
if (user->example < 0 || user->example > 1) {
fclaw_global_essentialf ("Option --user:example must be 0 or 1\n");
return FCLAW_EXIT_QUIET;
}
if (user->example == 1 && user->claw_version == 4)
{
fclaw_global_essentialf("Example 1 (disk) can only be run with claw-version=5\n");
return FCLAW_EXIT_QUIET;
}
return FCLAW_NOEXIT;
}
static const fclaw_app_options_vtable_t options_vtable_user =
{
options_register_user,
NULL,
options_check_user,
NULL
};
static
void register_user_options (fclaw_app_t * app,
const char *configfile,
user_options_t* user)
{
FCLAW_ASSERT (app != NULL);
fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
user);
}
user_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)
{
fclaw_app_t* app;
app = fclaw2d_domain_get_app(domain);
const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);
return (user_options_t*) user;
}
static
void run_program(fclaw_app_t* app)
{
sc_MPI_Comm mpicomm;
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
amr_options_t *gparms;
user_options_t *user;
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
gparms = fclaw_forestclaw_get_options(app);
user = (user_options_t*) fclaw_app_get_user(app);
double rotate[2];
rotate[0] = 0;
rotate[1] = 0;
switch (user->example)
{
case 0:
/* Use [ax,bx]x[ay,by] */
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_nomap();
break;
case 1:
conn = p4est_connectivity_new_disk();
cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,
rotate,user->alpha);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);
/* ---------------------------------------------------------- */
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
fclaw2d_domain_data_new(domain);
fclaw2d_domain_set_app(domain,app);
radialdam_link_solvers(domain);
fclaw2d_initialize(&domain);
fclaw2d_run(&domain);
fclaw2d_finalize(&domain);
fclaw2d_map_destroy(cont);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t suser, *user = &suser;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, user);
/* Register packages */
fclaw_forestclaw_register(app,"fclaw_options.ini");
fc2d_clawpack46_register(app,"fclaw_options.ini");
fc2d_clawpack5_register(app,"fclaw_options.ini");
register_user_options(app,"fclaw_options.ini",user);
/* Read configuration file(s) */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
fclaw2d_clawpatch_link_app(app);
if (!retval & !vexit)
{
run_program(app);
}
fclaw_forestclaw_destroy(app);
fclaw_app_destroy (app);
return 0;
}
<commit_msg>(amrclaw/2d/shallow/radialdam) Minor updates<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
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 "radialdam_user.h"
static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
user_options_t* user = (user_options_t*) package;
/* [user] User options */
sc_options_add_int (opt, 0, "example", &user->example, 0, "[user] 0 - nomap; 1 - disk [0]");
sc_options_add_double (opt, 0, "g", &user->g, 1.0, "[user] g [1.0]");
sc_options_add_double (opt, 0, "x0", &user->x0, 0.0, "[user] x0 [0.0]");
sc_options_add_double (opt, 0, "y0", &user->y0, 0.0, "[user] y0 [0.0]");
sc_options_add_double (opt, 0, "r0", &user->r0, 0.5, "[user] r0 [0.5]");
sc_options_add_double (opt, 0, "hin", &user->hin, 2.0, "[user] hin [2.0]");
sc_options_add_double (opt, 0, "hout", &user->hout, 1.0, "[user] hout [1.0]");
sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "[user] alpha (for 5-patch map) [0.4]");
sc_options_add_int (opt, 0, "claw-version", &user->claw_version, 5,
"Clawpack_version (4 or 5) [5]");
user->is_registered = 1;
return NULL;
}
static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
user_options_t* user = (user_options_t*) package;
if (user->example < 0 || user->example > 1) {
fclaw_global_essentialf ("Option --user:example must be 0 or 1\n");
return FCLAW_EXIT_QUIET;
}
if (user->example == 1 && user->claw_version == 4)
{
fclaw_global_essentialf("Example 1 (disk) can only be run with claw-version=5\n");
return FCLAW_EXIT_QUIET;
}
return FCLAW_NOEXIT;
}
static const fclaw_app_options_vtable_t options_vtable_user =
{
options_register_user,
NULL,
options_check_user,
NULL
};
static
void register_user_options (fclaw_app_t * app,
const char *configfile,
user_options_t* user)
{
FCLAW_ASSERT (app != NULL);
fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
user);
}
user_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)
{
fclaw_app_t* app;
app = fclaw2d_domain_get_app(domain);
const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);
return (user_options_t*) user;
}
static
void run_program(fclaw_app_t* app)
{
sc_MPI_Comm mpicomm;
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
amr_options_t *gparms;
user_options_t *user;
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
gparms = fclaw_forestclaw_get_options(app);
user = (user_options_t*) fclaw_app_get_user(app);
double rotate[2];
rotate[0] = 0;
rotate[1] = 0;
switch (user->example)
{
case 0:
/* Use [ax,bx]x[ay,by] */
conn = p4est_connectivity_new_unitsquare();
cont = fclaw2d_map_new_nomap();
break;
case 1:
conn = p4est_connectivity_new_disk();
cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,
rotate,user->alpha);
break;
default:
SC_ABORT_NOT_REACHED ();
}
domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);
/* ---------------------------------------------------------- */
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
fclaw2d_domain_data_new(domain);
fclaw2d_domain_set_app(domain,app);
radialdam_link_solvers(domain);
fclaw2d_initialize(&domain);
fclaw2d_run(&domain);
fclaw2d_finalize(&domain);
fclaw2d_map_destroy(cont);
}
int
main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
user_options_t suser, *user = &suser;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, user);
/* Register packages */
fclaw_forestclaw_register(app,"fclaw_options.ini");
fc2d_clawpack46_register(app,"fclaw_options.ini");
fc2d_clawpack5_register(app,"fclaw_options.ini");
register_user_options(app,"fclaw_options.ini",user);
/* Read configuration file(s) */
options = fclaw_app_get_options (app);
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
fclaw2d_clawpatch_link_app(app);
if (!retval & !vexit)
{
run_program(app);
}
fclaw_forestclaw_destroy(app);
fclaw_app_destroy (app);
return 0;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013, 2014 JCube001
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 <math.h>
#include "quaternion.h"
Quaternion::Quaternion() :
scalar(1.0f),
x(0.0f),
y(0.0f),
z(0.0f)
{
}
Quaternion::Quaternion(const Quaternion &q) :
scalar(q.scalar),
x(q.x),
y(q.y),
z(q.z)
{
}
Quaternion::Quaternion(float scalar, float x, float y, float z) :
scalar(scalar),
x(x),
y(y),
z(z)
{
}
Quaternion Quaternion::conjugate() const
{
return Quaternion(scalar, -x, -y, -z);
}
void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)
{
ax = x;
ay = y;
az = z;
angle = 2.0f * acos(scalar);
}
void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)
{
roll = atan2(2.0f * ((scalar * x) + (y * z)), 1.0f - (2.0f * ((x * x) + (y * y))));
pitch = asin(2.0f * ((scalar * y) - (z * x)));
yaw = atan2(2.0f * ((scalar * z) + (x * y)), 1.0f - (2.0f * ((y * y) + (z * z))));
}
float Quaternion::dot(const Quaternion &q) const
{
return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);
}
Quaternion Quaternion::inverse() const
{
const float n = norm();
if (n == 0.0f)
{
return Quaternion();
}
return conjugate() / (n * n);
}
float Quaternion::norm() const
{
return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));
}
void Quaternion::normalize()
{
*this /= norm();
}
Quaternion Quaternion::normalized() const
{
return *this / norm();
}
Quaternion &Quaternion::operator=(const Quaternion &q)
{
scalar = q.scalar;
x = q.x;
y = q.y;
z = q.z;
return *this;
}
Quaternion &Quaternion::operator+=(const Quaternion &q)
{
scalar += q.scalar;
x += q.x;
y += q.y;
z += q.z;
return *this;
}
Quaternion &Quaternion::operator-=(const Quaternion &q)
{
scalar -= q.scalar;
x -= q.x;
y -= q.y;
z -= q.z;
return *this;
}
Quaternion &Quaternion::operator*=(float factor)
{
scalar *= factor;
x *= factor;
y *= factor;
z *= factor;
return *this;
}
Quaternion &Quaternion::operator*=(const Quaternion &q)
{
scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);
x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);
y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);
z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);
}
Quaternion &Quaternion::operator/=(float divisor)
{
scalar /= divisor;
x /= divisor;
y /= divisor;
z /= divisor;
return *this;
}
<commit_msg>Added functions for conversions<commit_after>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013, 2014 JCube001
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 <math.h>
#include "quaternion.h"
Quaternion::Quaternion() :
scalar(1.0f),
x(0.0f),
y(0.0f),
z(0.0f)
{
}
Quaternion::Quaternion(const Quaternion &q) :
scalar(q.scalar),
x(q.x),
y(q.y),
z(q.z)
{
}
Quaternion::Quaternion(float scalar, float x, float y, float z) :
scalar(scalar),
x(x),
y(y),
z(z)
{
}
Quaternion Quaternion::conjugate() const
{
return Quaternion(scalar, -x, -y, -z);
}
void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)
{
ax = x;
ay = y;
az = z;
angle = 2.0f * acos(scalar);
}
void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)
{
roll = atan2((y * z) + (scalar * x), 0.5f - ((x * x) + (y * y)));
pitch = asin(-2.0f * ((x * z) + (scalar * y)));
yaw = atan2((x * y) + (scalar * z), 0.5f - ((y * y) + (z * z)));
}
float Quaternion::dot(const Quaternion &q) const
{
return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);
}
Quaternion Quaternion::inverse() const
{
const float n = norm();
if (n == 0.0f)
{
return Quaternion();
}
return conjugate() / (n * n);
}
float Quaternion::norm() const
{
return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));
}
void Quaternion::normalize()
{
*this /= norm();
}
Quaternion Quaternion::normalized() const
{
return *this / norm();
}
Quaternion &Quaternion::operator=(const Quaternion &q)
{
scalar = q.scalar;
x = q.x;
y = q.y;
z = q.z;
return *this;
}
Quaternion &Quaternion::operator+=(const Quaternion &q)
{
scalar += q.scalar;
x += q.x;
y += q.y;
z += q.z;
return *this;
}
Quaternion &Quaternion::operator-=(const Quaternion &q)
{
scalar -= q.scalar;
x -= q.x;
y -= q.y;
z -= q.z;
return *this;
}
Quaternion &Quaternion::operator*=(float factor)
{
scalar *= factor;
x *= factor;
y *= factor;
z *= factor;
return *this;
}
Quaternion &Quaternion::operator*=(const Quaternion &q)
{
scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);
x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);
y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);
z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);
}
Quaternion &Quaternion::operator/=(float divisor)
{
scalar /= divisor;
x /= divisor;
y /= divisor;
z /= divisor;
return *this;
}
<|endoftext|>
|
<commit_before>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>
#include <map>
#include <Network/Network.hpp>
#include <Network/PacketReceiver.hpp>
#include <Network/Sender.hpp>
#include <RadioTx.hpp>
#include <RadioRx.hpp>
#include <Utils.hpp>
#include "Radio.hpp"
using namespace std;
Team team = UnknownTeam;
bool useOpp;
Packet::RadioTx txPacket;
Packet::RadioTx oppTxPacket;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-n i] [-2010] <-y|-b>\n", prog);
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-n: use base station i (0 is the first base station detected by libusb)\n");
fprintf(stderr, "\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\n");
fprintf(stderr, "\t--debug_tx: print transmitted packets\n");
fprintf(stderr, "\t--debug_rx: print received packets\n");
exit(1);
}
void packetHandler(const Packet::RadioTx* packet)
{
txPacket = *packet;
}
void oppPacketHandler(const Packet::RadioTx* packet)
{
oppTxPacket = *packet;
}
int main(int argc, char* argv[])
{
bool debug_tx = false;
bool debug_rx = false;
int n = 0;
for (int i = 0; i < argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "-y") == 0)
{
team = Yellow;
}
else if (strcmp(var, "-b") == 0)
{
team = Blue;
}
else if (strcmp(var, "--debug_tx") == 0)
{
debug_tx = true;
}
else if (strcmp(var, "--debug_rx") == 0)
{
debug_rx = true;
}
else if (strcmp(var, "-n") == 0)
{
if (i == (argc - 1))
{
fprintf(stderr, "-n must be followed by the base station number\n");
usage(argv[0]);
}
}
else if (strcmp(var, "-o") == 0)
{
useOpp = true;
}
}
if (n)
{
fprintf(stderr, "WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\n");
}
Radio *radio = 0;
if (team == UnknownTeam)
{
fprintf(stderr, "Error: No team specified\n");
usage(argv[0]);
}
Network::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
//sender for opponent robots
Network::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
uint8_t reverse_packet[Reverse_Size + 2];
Network::PacketReceiver receiverSelf;
Network::PacketReceiver receiverOpp;
receiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);
if (useOpp)
{
receiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);
}
uint8_t forward_packet[Forward_Size];
int sequence = 0;
uint64_t lastTime = Utils::timestamp();
while (true)
{
bool printed = false;
//clear the incoming packet for the first team only
txPacket = Packet::RadioTx();
//block for self
receiverSelf.receive(true);
//don't block on receiving the opponent
receiverOpp.receive(false);
// Make sure we have a radio
bool first = true;
if (!radio)
{
while (!radio)
{
try
{
radio = new Radio(n);
} catch (exception &ex)
{
if (first)
{
fprintf(stderr, "%s\n", ex.what());
fprintf(stderr, "Waiting for the base station to be connected...\n");
first = false;
}
sleep(1);
}
}
// Drop this forward packet because it's probably really old
continue;
}
//FIXME - Switch between teams for reverse channel
int reverse_board_id = txPacket.reverse_board_id;
// Build a forward packet
forward_packet[0] = (sequence << 4) | reverse_board_id;
forward_packet[1] = 0x0f;
forward_packet[2] = 0x00;
int offset = 3;
int kick_id = -1;
int self_bots = 0;
uint8_t kick_strength = 0;
for (int robot_id = 0; robot_id < 5; ++robot_id)
{
const Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
self_bots++;
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
if (useOpp)
{
offset = 3 + self_bots * 5;
for (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)
{
const Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
}
// ID of kicking robot and kick strength
if (kick_id >= 0)
{
forward_packet[1] = kick_id;
forward_packet[2] = kick_strength;
}
if (debug_tx)
{
uint64_t t1 = Utils::timestamp();
uint64_t dt = t1 - lastTime;
lastTime = t1;
printf("%3ld.%03ldms ", dt / 1000, dt % 1000);
for (unsigned int i = 0; i < Forward_Size; ++i)
{
printf("%02x ", forward_packet[i]);
}
printed = true;
}
bool read_ok = false;
uint64_t rx_time = 0;
try
{
// Send the forward packet
radio->write_packet(forward_packet, Forward_Size);
// Read a forward packet if one is available
read_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);
rx_time = Utils::timestamp();
} catch (exception &ex)
{
fprintf(stderr, "%s\n", ex.what());
delete radio;
radio = 0;
}
sequence = (sequence + 1) & 15;
// Check for a reverse packet
if (read_ok)
{
if (debug_rx)
{
if (debug_tx)
{
printf(" ");
}
printf("rev");
for (unsigned int i = 0; i < Reverse_Size; ++i)
{
printf(" %02x", reverse_packet[i]);
}
printed = true;
}
Packet::RadioRx rxPacket;
int board_id = reverse_packet[0] & 0x0f;
rxPacket.timestamp = rx_time;
rxPacket.board_id = board_id;
rxPacket.rssi = (int8_t)reverse_packet[1] / 2.0;
rxPacket.battery = reverse_packet[3] * 3.3 / 256.0 * 5.0;
rxPacket.ball = reverse_packet[5] & (1 << 5);
rxPacket.charged = reverse_packet[4] & 1;
for (int i = 0; i < 5; ++i)
{
rxPacket.motorFault[i] = reverse_packet[5] & (1 << i);
}
for (int i = 0; i < 4; ++i)
{
rxPacket.encoders[i] = reverse_packet[6 + i];
rxPacket.encoders[i] |= ((reverse_packet[10] >> (i * 2)) & 3) << 8;
}
sender.send(rxPacket);
}
if (printed)
{
printf("\n");
}
}
return 0;
}
<commit_msg>Improved status output for base station reconnection<commit_after>// kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;
// vim:ai ts=4 et
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <assert.h>
#include <map>
#include <Network/Network.hpp>
#include <Network/PacketReceiver.hpp>
#include <Network/Sender.hpp>
#include <RadioTx.hpp>
#include <RadioRx.hpp>
#include <Utils.hpp>
#include "Radio.hpp"
using namespace std;
Team team = UnknownTeam;
bool useOpp;
Packet::RadioTx txPacket;
Packet::RadioTx oppTxPacket;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-n i] [-2010] <-y|-b>\n", prog);
fprintf(stderr, "\t-y: run as the yellow team\n");
fprintf(stderr, "\t-b: run as the blue team\n");
fprintf(stderr, "\t-n: use base station i (0 is the first base station detected by libusb)\n");
fprintf(stderr, "\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\n");
fprintf(stderr, "\t--debug_tx: print transmitted packets\n");
fprintf(stderr, "\t--debug_rx: print received packets\n");
exit(1);
}
void packetHandler(const Packet::RadioTx* packet)
{
txPacket = *packet;
}
void oppPacketHandler(const Packet::RadioTx* packet)
{
oppTxPacket = *packet;
}
int main(int argc, char* argv[])
{
bool debug_tx = false;
bool debug_rx = false;
int n = 0;
for (int i = 0; i < argc; ++i)
{
const char* var = argv[i];
if (strcmp(var, "-y") == 0)
{
team = Yellow;
}
else if (strcmp(var, "-b") == 0)
{
team = Blue;
}
else if (strcmp(var, "--debug_tx") == 0)
{
debug_tx = true;
}
else if (strcmp(var, "--debug_rx") == 0)
{
debug_rx = true;
}
else if (strcmp(var, "-n") == 0)
{
if (i == (argc - 1))
{
fprintf(stderr, "-n must be followed by the base station number\n");
usage(argv[0]);
}
}
else if (strcmp(var, "-o") == 0)
{
useOpp = true;
}
}
if (n)
{
fprintf(stderr, "WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\n");
}
Radio *radio = 0;
if (team == UnknownTeam)
{
fprintf(stderr, "Error: No team specified\n");
usage(argv[0]);
}
Network::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
//sender for opponent robots
Network::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));
uint8_t reverse_packet[Reverse_Size + 2];
Network::PacketReceiver receiverSelf;
Network::PacketReceiver receiverOpp;
receiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);
if (useOpp)
{
receiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);
}
uint8_t forward_packet[Forward_Size];
int sequence = 0;
uint64_t lastTime = Utils::timestamp();
while (true)
{
bool printed = false;
//clear the incoming packet for the first team only
txPacket = Packet::RadioTx();
//block for self
receiverSelf.receive(true);
//don't block on receiving the opponent
receiverOpp.receive(false);
// Make sure we have a radio
bool first = true;
if (!radio)
{
while (!radio)
{
try
{
radio = new Radio(n);
} catch (exception &ex)
{
if (first)
{
fprintf(stderr, "%s\n", ex.what());
fprintf(stderr, "Waiting for the base station to be connected...\n");
first = false;
}
sleep(1);
}
}
fprintf(stderr, "\nRadio connected\n");
// Drop this forward packet because it's probably really old
continue;
}
//FIXME - Switch between teams for reverse channel
int reverse_board_id = txPacket.reverse_board_id;
// Build a forward packet
forward_packet[0] = (sequence << 4) | reverse_board_id;
forward_packet[1] = 0x0f;
forward_packet[2] = 0x00;
int offset = 3;
int kick_id = -1;
int self_bots = 0;
uint8_t kick_strength = 0;
for (int robot_id = 0; robot_id < 5; ++robot_id)
{
const Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
self_bots++;
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
if (useOpp)
{
offset = 3 + self_bots * 5;
for (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)
{
const Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];
int board_id = robot.board_id;
int8_t m0, m1, m2, m3;
uint8_t kick, roller;
if (robot.valid)
{
m1 = -robot.motors[0];
m2 = -robot.motors[1];
m3 = -robot.motors[2];
m0 = -robot.motors[3];
kick = robot.kick;
if (robot.roller > 0)
{
roller = robot.roller * 2;
} else {
roller = 0;
}
} else {
board_id = 15;
m0 = m1 = m2 = m3 = 0;
kick = 0;
roller = 0;
}
if (kick)
{
kick_id = board_id;
kick_strength = kick;
}
forward_packet[offset++] = m0;
forward_packet[offset++] = m1;
forward_packet[offset++] = m2;
forward_packet[offset++] = m3;
forward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);
}
}
// ID of kicking robot and kick strength
if (kick_id >= 0)
{
forward_packet[1] = kick_id;
forward_packet[2] = kick_strength;
}
if (debug_tx)
{
uint64_t t1 = Utils::timestamp();
uint64_t dt = t1 - lastTime;
lastTime = t1;
printf("%3ld.%03ldms ", dt / 1000, dt % 1000);
for (unsigned int i = 0; i < Forward_Size; ++i)
{
printf("%02x ", forward_packet[i]);
}
printed = true;
}
bool read_ok = false;
uint64_t rx_time = 0;
try
{
// Send the forward packet
radio->write_packet(forward_packet, Forward_Size);
// Read a forward packet if one is available
read_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);
rx_time = Utils::timestamp();
} catch (exception &ex)
{
fprintf(stderr, "%s\n", ex.what());
delete radio;
radio = 0;
}
sequence = (sequence + 1) & 15;
// Check for a reverse packet
if (read_ok)
{
if (debug_rx)
{
if (debug_tx)
{
printf(" ");
}
printf("rev");
for (unsigned int i = 0; i < Reverse_Size; ++i)
{
printf(" %02x", reverse_packet[i]);
}
printed = true;
}
Packet::RadioRx rxPacket;
int board_id = reverse_packet[0] & 0x0f;
rxPacket.timestamp = rx_time;
rxPacket.board_id = board_id;
rxPacket.rssi = (int8_t)reverse_packet[1] / 2.0;
rxPacket.battery = reverse_packet[3] * 3.3 / 256.0 * 5.0;
rxPacket.ball = reverse_packet[5] & (1 << 5);
rxPacket.charged = reverse_packet[4] & 1;
for (int i = 0; i < 5; ++i)
{
rxPacket.motorFault[i] = reverse_packet[5] & (1 << i);
}
for (int i = 0; i < 4; ++i)
{
rxPacket.encoders[i] = reverse_packet[6 + i];
rxPacket.encoders[i] |= ((reverse_packet[10] >> (i * 2)) & 3) << 8;
}
sender.send(rxPacket);
}
if (printed)
{
printf("\n");
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autofill/autofill_popup_view.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/autofill/test_autofill_external_delegate.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "content/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::AtLeast;
using testing::_;
namespace {
class MockAutofillExternalDelegate : public TestAutofillExternalDelegate {
public:
MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {}
~MockAutofillExternalDelegate() {}
virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index)
OVERRIDE {}
};
class TestAutofillPopupView : public AutofillPopupView {
public:
explicit TestAutofillPopupView(
content::WebContents* web_contents,
AutofillExternalDelegate* autofill_external_delegate)
: AutofillPopupView(web_contents, autofill_external_delegate) {}
virtual ~TestAutofillPopupView() {}
MOCK_METHOD0(Hide, void());
MOCK_METHOD1(InvalidateRow, void(size_t));
void SetSelectedLine(size_t selected_line) {
AutofillPopupView::SetSelectedLine(selected_line);
}
protected:
virtual void ShowInternal() OVERRIDE {}
virtual void HideInternal() OVERRIDE {}
};
} // namespace
class AutofillPopupViewBrowserTest : public InProcessBrowserTest {
public:
AutofillPopupViewBrowserTest() {}
virtual ~AutofillPopupViewBrowserTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
web_contents_ = browser()->GetSelectedWebContents();
ASSERT_TRUE(web_contents_ != NULL);
autofill_popup_view_.reset(new TestAutofillPopupView(
web_contents_,
&autofill_external_delegate_));
}
protected:
content::WebContents* web_contents_;
scoped_ptr<TestAutofillPopupView> autofill_popup_view_;
MockAutofillExternalDelegate autofill_external_delegate_;
};
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
SwitchTabAndHideAutofillPopup) {
EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_WEB_CONTENTS_HIDDEN,
content::Source<content::WebContents>(web_contents_));
browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),
content::PAGE_TRANSITION_START_PAGE);
observer.Wait();
// The mock verifies that the call was made.
}
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
FLAKY_TestPageNavigationHidingAutofillPopup) {
EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<content::NavigationController>(
&(web_contents_->GetController())));
browser()->OpenURL(content::OpenURLParams(
GURL(chrome::kAboutBlankURL), content::Referrer(),
CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
browser()->OpenURL(content::OpenURLParams(
GURL(chrome::kChromeUIAboutURL), content::Referrer(),
CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
observer.Wait();
// The mock verifies that the call was made.
}
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
SetSelectedAutofillLineAndCallInvalidate) {
std::vector<string16> autofill_values;
autofill_values.push_back(string16());
std::vector<int> autofill_ids;
autofill_ids.push_back(0);
autofill_popup_view_->Show(
autofill_values, autofill_values, autofill_values, autofill_ids, 0);
// Make sure that when a new line is selected, it is invalidated so it can
// be updated to show it is selected.
int selected_line = 0;
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));
autofill_popup_view_->SetSelectedLine(selected_line);
// Ensure that the row isn't invalidated if it didn't change.
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0);
autofill_popup_view_->SetSelectedLine(selected_line);
// Change back to no selection.
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));
autofill_popup_view_->SetSelectedLine(-1);
}
<commit_msg>No Longer Mark AutofillPopupViewBrowserTest.TestPageNavigationHidingAutofillPopup as Flaky<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autofill/autofill_popup_view.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/autofill/test_autofill_external_delegate.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "content/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::AtLeast;
using testing::_;
namespace {
class MockAutofillExternalDelegate : public TestAutofillExternalDelegate {
public:
MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {}
~MockAutofillExternalDelegate() {}
virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index)
OVERRIDE {}
};
class TestAutofillPopupView : public AutofillPopupView {
public:
explicit TestAutofillPopupView(
content::WebContents* web_contents,
AutofillExternalDelegate* autofill_external_delegate)
: AutofillPopupView(web_contents, autofill_external_delegate) {}
virtual ~TestAutofillPopupView() {}
MOCK_METHOD0(Hide, void());
MOCK_METHOD1(InvalidateRow, void(size_t));
void SetSelectedLine(size_t selected_line) {
AutofillPopupView::SetSelectedLine(selected_line);
}
protected:
virtual void ShowInternal() OVERRIDE {}
virtual void HideInternal() OVERRIDE {}
};
} // namespace
class AutofillPopupViewBrowserTest : public InProcessBrowserTest {
public:
AutofillPopupViewBrowserTest() {}
virtual ~AutofillPopupViewBrowserTest() {}
virtual void SetUpOnMainThread() OVERRIDE {
web_contents_ = browser()->GetSelectedWebContents();
ASSERT_TRUE(web_contents_ != NULL);
autofill_popup_view_.reset(new TestAutofillPopupView(
web_contents_,
&autofill_external_delegate_));
}
protected:
content::WebContents* web_contents_;
scoped_ptr<TestAutofillPopupView> autofill_popup_view_;
MockAutofillExternalDelegate autofill_external_delegate_;
};
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
SwitchTabAndHideAutofillPopup) {
EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_WEB_CONTENTS_HIDDEN,
content::Source<content::WebContents>(web_contents_));
browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),
content::PAGE_TRANSITION_START_PAGE);
observer.Wait();
// The mock verifies that the call was made.
}
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
TestPageNavigationHidingAutofillPopup) {
EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));
ui_test_utils::WindowedNotificationObserver observer(
content::NOTIFICATION_NAV_ENTRY_COMMITTED,
content::Source<content::NavigationController>(
&(web_contents_->GetController())));
browser()->OpenURL(content::OpenURLParams(
GURL(chrome::kAboutBlankURL), content::Referrer(),
CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
browser()->OpenURL(content::OpenURLParams(
GURL(chrome::kChromeUIAboutURL), content::Referrer(),
CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
observer.Wait();
// The mock verifies that the call was made.
}
IN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,
SetSelectedAutofillLineAndCallInvalidate) {
std::vector<string16> autofill_values;
autofill_values.push_back(string16());
std::vector<int> autofill_ids;
autofill_ids.push_back(0);
autofill_popup_view_->Show(
autofill_values, autofill_values, autofill_values, autofill_ids, 0);
// Make sure that when a new line is selected, it is invalidated so it can
// be updated to show it is selected.
int selected_line = 0;
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));
autofill_popup_view_->SetSelectedLine(selected_line);
// Ensure that the row isn't invalidated if it didn't change.
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0);
autofill_popup_view_->SetSelectedLine(selected_line);
// Change back to no selection.
EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));
autofill_popup_view_->SetSelectedLine(-1);
}
<|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 "chrome/browser/renderer_host/test/test_render_view_host.h"
#include "chrome/browser/browser_url_handler.h"
#include "chrome/browser/renderer_host/test/test_backing_store.h"
#include "chrome/browser/tab_contents/test_tab_contents.h"
#include "chrome/common/dom_storage_common.h"
#include "chrome/common/render_messages.h"
#include "gfx/rect.h"
using webkit_glue::PasswordForm;
TestRenderViewHost::TestRenderViewHost(SiteInstance* instance,
RenderViewHostDelegate* delegate,
int routing_id)
: RenderViewHost(instance, delegate, routing_id,
kInvalidSessionStorageNamespaceId),
render_view_created_(false),
delete_counter_(NULL) {
set_view(new TestRenderWidgetHostView(this));
}
TestRenderViewHost::~TestRenderViewHost() {
if (delete_counter_)
++*delete_counter_;
// Since this isn't a traditional view, we have to delete it.
delete view();
}
bool TestRenderViewHost::CreateRenderView(
URLRequestContextGetter* request_context) {
DCHECK(!render_view_created_);
render_view_created_ = true;
process()->ViewCreated();
return true;
}
bool TestRenderViewHost::IsRenderViewLive() const {
return render_view_created_;
}
void TestRenderViewHost::TestOnMessageReceived(const IPC::Message& msg) {
OnMessageReceived(msg);
}
void TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {
ViewHostMsg_FrameNavigate_Params params;
params.page_id = page_id;
params.url = url;
params.referrer = GURL();
params.transition = PageTransition::LINK;
params.redirects = std::vector<GURL>();
params.should_update_history = true;
params.searchable_form_url = GURL();
params.searchable_form_encoding = std::string();
params.password_form = PasswordForm();
params.security_info = std::string();
params.gesture = NavigationGestureUser;
params.contents_mime_type = std::string();
params.is_post = false;
params.is_content_filtered = false;
params.http_status_code = 0;
ViewHostMsg_FrameNavigate msg(1, params);
OnMsgNavigate(msg);
}
TestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)
: rwh_(rwh),
is_showing_(false) {
}
BackingStore* TestRenderWidgetHostView::AllocBackingStore(
const gfx::Size& size) {
return new TestBackingStore(rwh_, size);
}
VideoLayer* TestRenderWidgetHostView::AllocVideoLayer(
const gfx::Size& size) {
NOTIMPLEMENTED();
return NULL;
}
#if defined(OS_MACOSX)
gfx::Rect TestRenderWidgetHostView::GetWindowRect() {
return gfx::Rect();
}
gfx::Rect TestRenderWidgetHostView::GetRootWindowRect() {
return gfx::Rect();
}
void TestRenderWidgetHostView::SetActive(bool active) {
// <viettrungluu@gmail.com>: Do I need to do anything here?
}
gfx::PluginWindowHandle
TestRenderWidgetHostView::AllocateFakePluginWindowHandle() {
return NULL;
}
void TestRenderWidgetHostView::DestroyFakePluginWindowHandle(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 io_surface_identifier) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
TransportDIB::Handle transport_dib) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::DrawAcceleratedSurfaceInstances(
CGLContextObj context) {
}
#endif
void RenderViewHostTestHarness::NavigateAndCommit(const GURL& url) {
controller().LoadURL(url, GURL(), 0);
GURL loaded_url(url);
bool reverse_on_redirect = false;
BrowserURLHandler::RewriteURLIfNecessary(
&loaded_url, profile(), &reverse_on_redirect);
rvh()->SendNavigate(process()->max_page_id() + 1, loaded_url);
}
void RenderViewHostTestHarness::Reload() {
NavigationEntry* entry = controller().GetLastCommittedEntry();
DCHECK(entry);
controller().Reload(false);
rvh()->SendNavigate(entry->page_id(), entry->url());
}
void RenderViewHostTestHarness::SetUp() {
// See comment above profile_ decl for why we check for NULL here.
if (!profile_.get())
profile_.reset(new TestingProfile());
// This will be deleted when the TabContents goes away.
SiteInstance* instance = SiteInstance::CreateSiteInstance(profile_.get());
contents_.reset(new TestTabContents(profile_.get(), instance));
user_data_manager_.reset(UserDataManager::Create());
}
void RenderViewHostTestHarness::TearDown() {
contents_.reset();
// Make sure that we flush any messages related to TabContents destruction
// before we destroy the profile.
MessageLoop::current()->RunAllPending();
}
<commit_msg>Destroy testing profile on UI thread.<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 "chrome/browser/renderer_host/test/test_render_view_host.h"
#include "chrome/browser/browser_url_handler.h"
#include "chrome/browser/renderer_host/test/test_backing_store.h"
#include "chrome/browser/tab_contents/test_tab_contents.h"
#include "chrome/common/dom_storage_common.h"
#include "chrome/common/render_messages.h"
#include "gfx/rect.h"
using webkit_glue::PasswordForm;
TestRenderViewHost::TestRenderViewHost(SiteInstance* instance,
RenderViewHostDelegate* delegate,
int routing_id)
: RenderViewHost(instance, delegate, routing_id,
kInvalidSessionStorageNamespaceId),
render_view_created_(false),
delete_counter_(NULL) {
set_view(new TestRenderWidgetHostView(this));
}
TestRenderViewHost::~TestRenderViewHost() {
if (delete_counter_)
++*delete_counter_;
// Since this isn't a traditional view, we have to delete it.
delete view();
}
bool TestRenderViewHost::CreateRenderView(
URLRequestContextGetter* request_context) {
DCHECK(!render_view_created_);
render_view_created_ = true;
process()->ViewCreated();
return true;
}
bool TestRenderViewHost::IsRenderViewLive() const {
return render_view_created_;
}
void TestRenderViewHost::TestOnMessageReceived(const IPC::Message& msg) {
OnMessageReceived(msg);
}
void TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {
ViewHostMsg_FrameNavigate_Params params;
params.page_id = page_id;
params.url = url;
params.referrer = GURL();
params.transition = PageTransition::LINK;
params.redirects = std::vector<GURL>();
params.should_update_history = true;
params.searchable_form_url = GURL();
params.searchable_form_encoding = std::string();
params.password_form = PasswordForm();
params.security_info = std::string();
params.gesture = NavigationGestureUser;
params.contents_mime_type = std::string();
params.is_post = false;
params.is_content_filtered = false;
params.http_status_code = 0;
ViewHostMsg_FrameNavigate msg(1, params);
OnMsgNavigate(msg);
}
TestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)
: rwh_(rwh),
is_showing_(false) {
}
BackingStore* TestRenderWidgetHostView::AllocBackingStore(
const gfx::Size& size) {
return new TestBackingStore(rwh_, size);
}
VideoLayer* TestRenderWidgetHostView::AllocVideoLayer(
const gfx::Size& size) {
NOTIMPLEMENTED();
return NULL;
}
#if defined(OS_MACOSX)
gfx::Rect TestRenderWidgetHostView::GetWindowRect() {
return gfx::Rect();
}
gfx::Rect TestRenderWidgetHostView::GetRootWindowRect() {
return gfx::Rect();
}
void TestRenderWidgetHostView::SetActive(bool active) {
// <viettrungluu@gmail.com>: Do I need to do anything here?
}
gfx::PluginWindowHandle
TestRenderWidgetHostView::AllocateFakePluginWindowHandle() {
return NULL;
}
void TestRenderWidgetHostView::DestroyFakePluginWindowHandle(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 io_surface_identifier) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
TransportDIB::Handle transport_dib) {
}
void TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(
gfx::PluginWindowHandle window) {
}
void TestRenderWidgetHostView::DrawAcceleratedSurfaceInstances(
CGLContextObj context) {
}
#endif
void RenderViewHostTestHarness::NavigateAndCommit(const GURL& url) {
controller().LoadURL(url, GURL(), 0);
GURL loaded_url(url);
bool reverse_on_redirect = false;
BrowserURLHandler::RewriteURLIfNecessary(
&loaded_url, profile(), &reverse_on_redirect);
rvh()->SendNavigate(process()->max_page_id() + 1, loaded_url);
}
void RenderViewHostTestHarness::Reload() {
NavigationEntry* entry = controller().GetLastCommittedEntry();
DCHECK(entry);
controller().Reload(false);
rvh()->SendNavigate(entry->page_id(), entry->url());
}
void RenderViewHostTestHarness::SetUp() {
// See comment above profile_ decl for why we check for NULL here.
if (!profile_.get())
profile_.reset(new TestingProfile());
// This will be deleted when the TabContents goes away.
SiteInstance* instance = SiteInstance::CreateSiteInstance(profile_.get());
contents_.reset(new TestTabContents(profile_.get(), instance));
user_data_manager_.reset(UserDataManager::Create());
}
void RenderViewHostTestHarness::TearDown() {
contents_.reset();
// Make sure that we flush any messages related to TabContents destruction
// before we destroy the profile.
MessageLoop::current()->RunAllPending();
// Release the profile on the UI thread.
message_loop_.DeleteSoon(FROM_HERE, profile_.release());
message_loop_.RunAllPending();
}
<|endoftext|>
|
<commit_before>#include "application.hpp"
#include "widget.hpp"
#include "paint_event.hpp"
#include <SDL2/SDL.h>
#include <stdexcept>
#include <algorithm>
Application *Application::instance_ = nullptr;
Application::Application(int &argc, char **argv)
{
if (instance_ != nullptr)
throw std::runtime_error("The program can have only one instance of Application");
instance_ = this;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError()));
}
Application::~Application()
{
SDL_Quit();
instance_ = nullptr;
}
int Application::exec()
{
bool done = false;
while (!done)
{
SDL_Event e;
while (SDL_PollEvent(&e))
{
switch (e.type)
{
case SDL_WINDOWEVENT:
{
Widget *w = widgetByWindowId(e.window.windowID);
switch (e.window.event)
{
case SDL_WINDOWEVENT_SHOWN:
{
PaintEvent event;
w->paintEvent(event);
}
break;
}
break;
}
case SDL_QUIT:
done = true;
break;
}
}
}
return 0;
}
Application *Application::instance()
{
return instance_;
}
void Application::addWidget(Widget *w)
{
widgetList_.push_back(w);
}
void Application::removeWidget(Widget *w)
{
widgetList_.erase(std::remove(begin(widgetList_), end(widgetList_), w), end(widgetList_));
}
Widget *Application::widgetByWindowId(Uint32 id)
{
for (const auto w: widgetList_)
if (id == w->windowId())
return w;
return nullptr;
}
<commit_msg>Fix 100% CPU usage<commit_after>#include "application.hpp"
#include "widget.hpp"
#include "paint_event.hpp"
#include <SDL2/SDL.h>
#include <stdexcept>
#include <algorithm>
#include <iostream>
Application *Application::instance_ = nullptr;
Application::Application(int &argc, char **argv)
{
if (instance_ != nullptr)
throw std::runtime_error("The program can have only one instance of Application");
instance_ = this;
if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
throw std::runtime_error("SDL_Init Error: " + std::string(SDL_GetError()));
}
Application::~Application()
{
SDL_Quit();
instance_ = nullptr;
}
int Application::exec()
{
bool done = false;
while (!done)
{
SDL_Event e;
if (SDL_WaitEvent(&e))
{
switch (e.type)
{
case SDL_WINDOWEVENT:
{
Widget *w = widgetByWindowId(e.window.windowID);
switch (e.window.event)
{
case SDL_WINDOWEVENT_SHOWN:
{
PaintEvent event;
w->paintEvent(event);
}
break;
}
break;
}
case SDL_QUIT:
done = true;
break;
}
}
}
return 0;
}
Application *Application::instance()
{
return instance_;
}
void Application::addWidget(Widget *w)
{
widgetList_.push_back(w);
}
void Application::removeWidget(Widget *w)
{
widgetList_.erase(std::remove(begin(widgetList_), end(widgetList_), w), end(widgetList_));
}
Widget *Application::widgetByWindowId(Uint32 id)
{
for (const auto w: widgetList_)
if (id == w->windowId())
return w;
return nullptr;
}
<|endoftext|>
|
<commit_before>/*
* main.cpp
* Program: kalarm
* Copyright © 2001-2007 by David Jarvie <software@astrojar.org.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <stdlib.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>
#include "kalarmapp.h"
#define PROGRAM_NAME "kalarm"
static KCmdLineOptions options[] =
{
{ "a", 0, 0 },
{ "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 },
{ "A", 0, 0 },
{ "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 },
{ "auto-close", I18N_NOOP("Auto-close alarm window after --late-cancel period"), 0 },
{ "bcc", I18N_NOOP("Blind copy email to self"), 0 },
{ "b", 0, 0 },
{ "beep", I18N_NOOP("Beep when message is displayed"), 0 },
{ "colour", 0, 0 },
{ "c", 0, 0 },
{ "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 },
{ "colourfg", 0, 0 },
{ "C", 0, 0 },
{ "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 },
{ "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 },
{ "d", 0, 0 },
{ "disable", I18N_NOOP("Disable the alarm"), 0 },
{ "e", 0, 0 },
{ "!exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 },
{ "edit <eventID>", I18N_NOOP("Display the alarm edit dialog to edit the specified alarm"), 0 },
{ "n", 0, 0 },
{ "edit-new", I18N_NOOP("Display the alarm edit dialog to edit a new alarm"), 0 },
{ "edit-new-preset <templateName>", I18N_NOOP("Display the alarm edit dialog, preset with a template"), 0 },
{ "f", 0, 0 },
{ "file <url>", I18N_NOOP("File to display"), 0 },
{ "F", 0, 0 },
{ "from-id <ID>", I18N_NOOP("KMail identity to use as sender of email"), 0 },
{ "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 },
{ "i", 0, 0 },
{ "interval <period>", I18N_NOOP("Interval between alarm repetitions"), 0 },
{ "k", 0, 0 },
{ "korganizer", I18N_NOOP("Show alarm as an event in KOrganizer"), 0 },
{ "l", 0, 0 },
{ "late-cancel <period>", I18N_NOOP("Cancel alarm if more than 'period' late when triggered"), "1" },
{ "L", 0, 0 },
{ "login", I18N_NOOP("Repeat alarm at every login"), 0 },
{ "m", 0, 0 },
{ "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 },
{ "p", 0, 0 },
{ "play <url>", I18N_NOOP("Audio file to play once"), 0 },
{ "P", 0, 0 },
{ "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 },
{ "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 },
{ "R", 0, 0 },
{ "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 },
{ "reminder-once <period>", I18N_NOOP("Display reminder once, before first alarm recurrence"), 0 },
{ "r", 0, 0 },
{ "repeat <count>", I18N_NOOP("Number of times to repeat alarm (including initial occasion)"), 0 },
{ "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 },
{ "s", 0, 0 },
{ "speak", I18N_NOOP("Speak the message when it is displayed"), 0 },
{ "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 },
{ "S", 0, 0 },
{ "subject", I18N_NOOP("Email subject line"), 0 },
{ "t", 0, 0 },
{ "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"), 0 },
{ "tray", I18N_NOOP("Display system tray icon"), 0 },
{ "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 },
{ "u", 0, 0 },
{ "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"), 0 },
{ "V", 0, 0 },
{ "volume <percent>", I18N_NOOP("Volume to play audio file"), 0 },
{ "+[message]", I18N_NOOP("Message text to display"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION,
I18N_NOOP("Personal alarm message, command and email scheduler for KDE"),
KAboutData::License_GPL,
"Copyright 2001-2007, David Jarvie", 0, "http://www.astrojar.org.uk/linux/kalarm.html");
aboutData.addAuthor("David Jarvie", 0, "software@astrojar.org.uk");
aboutData.setOrganizationDomain("kde.org");
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!KAlarmApp::start())
{
// An instance of the application is already running
exit(0);
}
// This is the first time through
kDebug(5950) << "main(): initialising\n";
KAlarmApp* app = KAlarmApp::getInstance();
app->restoreSession();
return app->exec();
}
<commit_msg>Amend KAlarm URL.<commit_after>/*
* main.cpp
* Program: kalarm
* Copyright © 2001-2007 by David Jarvie <software@astrojar.org.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h"
#include <stdlib.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include <kdebug.h>
#include "kalarmapp.h"
#define PROGRAM_NAME "kalarm"
static KCmdLineOptions options[] =
{
{ "a", 0, 0 },
{ "ack-confirm", I18N_NOOP("Prompt for confirmation when alarm is acknowledged"), 0 },
{ "A", 0, 0 },
{ "attach <url>", I18N_NOOP("Attach file to email (repeat as needed)"), 0 },
{ "auto-close", I18N_NOOP("Auto-close alarm window after --late-cancel period"), 0 },
{ "bcc", I18N_NOOP("Blind copy email to self"), 0 },
{ "b", 0, 0 },
{ "beep", I18N_NOOP("Beep when message is displayed"), 0 },
{ "colour", 0, 0 },
{ "c", 0, 0 },
{ "color <color>", I18N_NOOP("Message background color (name or hex 0xRRGGBB)"), 0 },
{ "colourfg", 0, 0 },
{ "C", 0, 0 },
{ "colorfg <color>", I18N_NOOP("Message foreground color (name or hex 0xRRGGBB)"), 0 },
{ "cancelEvent <eventID>", I18N_NOOP("Cancel alarm with the specified event ID"), 0 },
{ "d", 0, 0 },
{ "disable", I18N_NOOP("Disable the alarm"), 0 },
{ "e", 0, 0 },
{ "!exec <commandline>", I18N_NOOP("Execute a shell command line"), 0 },
{ "edit <eventID>", I18N_NOOP("Display the alarm edit dialog to edit the specified alarm"), 0 },
{ "n", 0, 0 },
{ "edit-new", I18N_NOOP("Display the alarm edit dialog to edit a new alarm"), 0 },
{ "edit-new-preset <templateName>", I18N_NOOP("Display the alarm edit dialog, preset with a template"), 0 },
{ "f", 0, 0 },
{ "file <url>", I18N_NOOP("File to display"), 0 },
{ "F", 0, 0 },
{ "from-id <ID>", I18N_NOOP("KMail identity to use as sender of email"), 0 },
{ "handleEvent <eventID>", I18N_NOOP("Trigger or cancel alarm with the specified event ID"), 0 },
{ "i", 0, 0 },
{ "interval <period>", I18N_NOOP("Interval between alarm repetitions"), 0 },
{ "k", 0, 0 },
{ "korganizer", I18N_NOOP("Show alarm as an event in KOrganizer"), 0 },
{ "l", 0, 0 },
{ "late-cancel <period>", I18N_NOOP("Cancel alarm if more than 'period' late when triggered"), "1" },
{ "L", 0, 0 },
{ "login", I18N_NOOP("Repeat alarm at every login"), 0 },
{ "m", 0, 0 },
{ "mail <address>", I18N_NOOP("Send an email to the given address (repeat as needed)"), 0 },
{ "p", 0, 0 },
{ "play <url>", I18N_NOOP("Audio file to play once"), 0 },
{ "P", 0, 0 },
{ "play-repeat <url>", I18N_NOOP("Audio file to play repeatedly"), 0 },
{ "recurrence <spec>", I18N_NOOP("Specify alarm recurrence using iCalendar syntax"), 0 },
{ "R", 0, 0 },
{ "reminder <period>", I18N_NOOP("Display reminder in advance of alarm"), 0 },
{ "reminder-once <period>", I18N_NOOP("Display reminder once, before first alarm recurrence"), 0 },
{ "r", 0, 0 },
{ "repeat <count>", I18N_NOOP("Number of times to repeat alarm (including initial occasion)"), 0 },
{ "reset", I18N_NOOP("Reset the alarm scheduling daemon"), 0 },
{ "s", 0, 0 },
{ "speak", I18N_NOOP("Speak the message when it is displayed"), 0 },
{ "stop", I18N_NOOP("Stop the alarm scheduling daemon"), 0 },
{ "S", 0, 0 },
{ "subject", I18N_NOOP("Email subject line"), 0 },
{ "t", 0, 0 },
{ "time <time>", I18N_NOOP("Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"), 0 },
{ "tray", I18N_NOOP("Display system tray icon"), 0 },
{ "triggerEvent <eventID>", I18N_NOOP("Trigger alarm with the specified event ID"), 0 },
{ "u", 0, 0 },
{ "until <time>", I18N_NOOP("Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]"), 0 },
{ "V", 0, 0 },
{ "volume <percent>", I18N_NOOP("Volume to play audio file"), 0 },
{ "+[message]", I18N_NOOP("Message text to display"), 0 },
KCmdLineLastOption
};
int main(int argc, char *argv[])
{
KAboutData aboutData(PROGRAM_NAME, I18N_NOOP("KAlarm"), KALARM_VERSION,
I18N_NOOP("Personal alarm message, command and email scheduler for KDE"),
KAboutData::License_GPL,
"Copyright 2001-2007, David Jarvie", 0, "http://www.astrojar.org.uk/kalarm");
aboutData.addAuthor("David Jarvie", 0, "software@astrojar.org.uk");
aboutData.setOrganizationDomain("kde.org");
KCmdLineArgs::init(argc, argv, &aboutData);
KCmdLineArgs::addCmdLineOptions(options);
KUniqueApplication::addCmdLineOptions();
if (!KAlarmApp::start())
{
// An instance of the application is already running
exit(0);
}
// This is the first time through
kDebug(5950) << "main(): initialising\n";
KAlarmApp* app = KAlarmApp::getInstance();
app->restoreSession();
return app->exec();
}
<|endoftext|>
|
<commit_before>/*
$Id$
KNotes - Notes for the KDE Project
Copyright (C) 1997 Bernd Johannes Wuebben
wuebben@math.cornell.edu
wuebben@kde.org
This class is a modified version of a class found in:
qtremind - an X windows appoint reminder program.
Copyright (C) 1997 Tom Daley
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <qbitmap.h>
#include <qtimer.h>
#include <spin.h>
#include "up.xbm"
#include "down.xbm"
QtedSetInt::QtedSetInt(int min, int max, int start_value, int format,
QWidget *parent, const char *name) :
QWidget(parent, name), _min(min), _max(max),
_format(format), _up_timer_p(NULL), _dn_timer_p(NULL) {
if (_max <_min) // make sure numbers make sense
_max = _min;
QString str;
str.sprintf("%d", _min); // find the max number string length
_length = str.length();
str.sprintf("%d", _max);
if ((int)str.length() > _length)
_length = str.length();
_upButton_p = new QPushButton(this);
QBitmap up_bm(up_arrow_width, up_arrow_height, up_arrow_bits, TRUE);
_upButton_p->setPixmap(up_bm);
_upButton_p->setAutoResize(TRUE);
_dnButton_p = new QPushButton(this);
QBitmap dn_bm(dn_arrow_width, dn_arrow_height, dn_arrow_bits, TRUE);
_dnButton_p->setPixmap(dn_bm);
_dnButton_p->setAutoResize(TRUE);
_label_p = new QLabel("Foo", this);
_label_p->setAlignment(AlignCenter);
_label_p->setLineWidth(2);
_label_p->setFrameStyle(QFrame::Panel | QFrame::Sunken);
_label_p->setBackgroundColor(white);
value(start_value);
setSize();
connect(_upButton_p, SIGNAL(pressed()), this, SLOT(upPressed()));
connect(_upButton_p, SIGNAL(released()), this, SLOT(upReleased()));
connect(_dnButton_p, SIGNAL(pressed()), this, SLOT(dnPressed()));
connect(_dnButton_p, SIGNAL(released()), this, SLOT(dnReleased()));
}
//*****************************************************************************
void QtedSetInt::
setSize(void) {
int num_wid;// mid_wid;
int bt_sz = 13;
int w, mid_w, label_h;
label_h = fontMetrics().lineSpacing () + 2 * _label_p->frameWidth();
num_wid = fontMetrics().maxWidth() * _length;
num_wid += 2 * _label_p->frameWidth();
if (num_wid > bt_sz * 2)
w = num_wid;
else
w = bt_sz * 2;
mid_w = w / 2;
_label_p->setGeometry(0, 0, w, label_h);
_upButton_p->setGeometry(mid_w - bt_sz, label_h +2, bt_sz, bt_sz);
_dnButton_p->setGeometry(mid_w, label_h +2, bt_sz, bt_sz);
setFixedSize(w, label_h + bt_sz +2);
}
//*****************************************************************************
void QtedSetInt::
setText(void) {
QString str;
switch (_format) {
case RightJustified:
str.sprintf("%*d", _length, _value);
break;
case Centered:
str.sprintf("%d", _value);
break;
case ZeroFilled:
str.sprintf("%0*d", _length, _value);
break;
}
_label_p->setText(str);
}
//*****************************************************************************
void QtedSetInt::
value(int the_value) {
if (the_value < _min)
_value = _min;
else if (the_value > _max)
_value = _max;
else
_value = the_value;
setText();
}
//*****************************************************************************
void QtedSetInt::
upPressed() {
incValue();
if (_up_timer_p == NULL) {
_up_timer_p= new QTimer(this);
connect(_up_timer_p, SIGNAL(timeout()), this, SLOT(upRepeat()));
}
if (_value == _max)
_up_timer_p->stop();
else
_up_timer_p->changeInterval((int)(0.25 * 1000));
}
//*****************************************************************************
void QtedSetInt::
upReleased() {
_up_timer_p->stop();
}
//*****************************************************************************
void QtedSetInt::
upRepeat() {
incValue();
if (_value == _max)
_up_timer_p->stop();
else
_up_timer_p->changeInterval((int)(0.033 * 1000));
}
//*****************************************************************************
void QtedSetInt::
dnPressed() {
decValue();
if (_dn_timer_p == NULL) {
_dn_timer_p= new QTimer(this);
connect(_dn_timer_p, SIGNAL(timeout()), this, SLOT(dnRepeat()));
}
if (_value == _min)
_dn_timer_p->stop();
else
_dn_timer_p->changeInterval((int)(0.25 * 1000));
}
//*****************************************************************************
void QtedSetInt::
dnReleased() {
_dn_timer_p->stop();
}
//*****************************************************************************
void QtedSetInt::
dnRepeat() {
decValue();
if (_value == _min)
_dn_timer_p->stop();
else
_dn_timer_p->changeInterval((int)(0.033 * 1000));
}
//*****************************************************************************
void QtedSetInt::
incValue(void) {
if (_value < _max) {
_value++;
setText();
}
}
//*****************************************************************************
void QtedSetInt::
decValue(void) {
if (_value > _min) {
_value--;
setText();
}
}
//*****************************************************************************
#include "spin.moc"
<commit_msg>Bernd: colorscheme related changes<commit_after>/*
$Id$
KNotes - Notes for the KDE Project
Copyright (C) 1997 Bernd Johannes Wuebben
wuebben@math.cornell.edu
wuebben@kde.org
This class is a modified version of a class found in:
qtremind - an X windows appoint reminder program.
Copyright (C) 1997 Tom Daley
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <qbitmap.h>
#include <qtimer.h>
#include <spin.h>
#include "up.xbm"
#include "down.xbm"
QtedSetInt::QtedSetInt(int min, int max, int start_value, int format,
QWidget *parent, const char *name) :
QWidget(parent, name), _min(min), _max(max),
_format(format), _up_timer_p(NULL), _dn_timer_p(NULL) {
if (_max <_min) // make sure numbers make sense
_max = _min;
QString str;
str.sprintf("%d", _min); // find the max number string length
_length = str.length();
str.sprintf("%d", _max);
if ((int)str.length() > _length)
_length = str.length();
_upButton_p = new QPushButton(this);
QBitmap up_bm(up_arrow_width, up_arrow_height, up_arrow_bits, TRUE);
_upButton_p->setPixmap(up_bm);
_upButton_p->setAutoResize(TRUE);
_dnButton_p = new QPushButton(this);
QBitmap dn_bm(dn_arrow_width, dn_arrow_height, dn_arrow_bits, TRUE);
_dnButton_p->setPixmap(dn_bm);
_dnButton_p->setAutoResize(TRUE);
_label_p = new QLabel("Foo", this);
_label_p->setAlignment(AlignCenter);
_label_p->setLineWidth(2);
_label_p->setFrameStyle(QFrame::Panel | QFrame::Sunken);
// _label_p->setBackgroundColor(white);
value(start_value);
setSize();
connect(_upButton_p, SIGNAL(pressed()), this, SLOT(upPressed()));
connect(_upButton_p, SIGNAL(released()), this, SLOT(upReleased()));
connect(_dnButton_p, SIGNAL(pressed()), this, SLOT(dnPressed()));
connect(_dnButton_p, SIGNAL(released()), this, SLOT(dnReleased()));
}
//*****************************************************************************
void QtedSetInt::
setSize(void) {
int num_wid;// mid_wid;
int bt_sz = 13;
int w, mid_w, label_h;
label_h = fontMetrics().lineSpacing () + 2 * _label_p->frameWidth();
num_wid = fontMetrics().maxWidth() * _length;
num_wid += 2 * _label_p->frameWidth();
if (num_wid > bt_sz * 2)
w = num_wid;
else
w = bt_sz * 2;
mid_w = w / 2;
_label_p->setGeometry(0, 0, w, label_h);
_upButton_p->setGeometry(mid_w - bt_sz, label_h +2, bt_sz, bt_sz);
_dnButton_p->setGeometry(mid_w, label_h +2, bt_sz, bt_sz);
setFixedSize(w, label_h + bt_sz +2);
}
//*****************************************************************************
void QtedSetInt::
setText(void) {
QString str;
switch (_format) {
case RightJustified:
str.sprintf("%*d", _length, _value);
break;
case Centered:
str.sprintf("%d", _value);
break;
case ZeroFilled:
str.sprintf("%0*d", _length, _value);
break;
}
_label_p->setText(str);
}
//*****************************************************************************
void QtedSetInt::
value(int the_value) {
if (the_value < _min)
_value = _min;
else if (the_value > _max)
_value = _max;
else
_value = the_value;
setText();
}
//*****************************************************************************
void QtedSetInt::
upPressed() {
incValue();
if (_up_timer_p == NULL) {
_up_timer_p= new QTimer(this);
connect(_up_timer_p, SIGNAL(timeout()), this, SLOT(upRepeat()));
}
if (_value == _max)
_up_timer_p->stop();
else
_up_timer_p->changeInterval((int)(0.25 * 1000));
}
//*****************************************************************************
void QtedSetInt::
upReleased() {
_up_timer_p->stop();
}
//*****************************************************************************
void QtedSetInt::
upRepeat() {
incValue();
if (_value == _max)
_up_timer_p->stop();
else
_up_timer_p->changeInterval((int)(0.033 * 1000));
}
//*****************************************************************************
void QtedSetInt::
dnPressed() {
decValue();
if (_dn_timer_p == NULL) {
_dn_timer_p= new QTimer(this);
connect(_dn_timer_p, SIGNAL(timeout()), this, SLOT(dnRepeat()));
}
if (_value == _min)
_dn_timer_p->stop();
else
_dn_timer_p->changeInterval((int)(0.25 * 1000));
}
//*****************************************************************************
void QtedSetInt::
dnReleased() {
_dn_timer_p->stop();
}
//*****************************************************************************
void QtedSetInt::
dnRepeat() {
decValue();
if (_value == _min)
_dn_timer_p->stop();
else
_dn_timer_p->changeInterval((int)(0.033 * 1000));
}
//*****************************************************************************
void QtedSetInt::
incValue(void) {
if (_value < _max) {
_value++;
setText();
}
}
//*****************************************************************************
void QtedSetInt::
decValue(void) {
if (_value > _min) {
_value--;
setText();
}
}
//*****************************************************************************
#include "spin.moc"
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/nest/p10_htm_adu_ctrl.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/// ----------------------------------------------------------------------------
/// @file p10_htm_adu_ctrl.C
///
/// @brief Provides ADU control functions that help with HTM collection actions.
///
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Nicholas Landi <nlandi@ibm.com>
/// *HWP FW Owner : Ilya Smirnov <ismirno@us.ibm.com>
/// *HWP Consumed by : HB
///----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p10_htm_adu_ctrl.H>
#include <fapi2_mem_access.H>
#include <p10_putmemproc.H>
#include <fapi2_subroutine_executor.H>
///
/// See doxygen in p10_htm_adu_ctrl.H
///
fapi2::ReturnCode aduNHTMControl(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_addr)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
uint32_t l_mem_flags = fapi2::SBE_MEM_ACCESS_FLAGS_SWITCH_MODE
| fapi2::SBE_MEM_ACCESS_FLAGS_TARGET_PROC;
uint32_t l_bytes = 2; // Want a TSIZE of 2 for these htm ctrl commands
uint8_t l_data[2] = {0, 0}; // give a pointer to real data to prevent any undefined behavior
FAPI_DBG("Debug data: Target: mem_flags: 0x%08llx, addr: 0x%016llx", l_mem_flags, i_addr);
FAPI_DBG("Attempting to put pMisc command");
FAPI_CALL_SUBROUTINE(l_rc,
p10_putmemproc,
i_target,
i_addr,
l_bytes,
l_data,
l_mem_flags);
fapi_try_exit:
FAPI_DBG("Exiting");
return l_rc;
}
<commit_msg>Update to change invokation of putmemproc for HTM<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/nest/p10_htm_adu_ctrl.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
/// ----------------------------------------------------------------------------
/// @file p10_htm_adu_ctrl.C
///
/// @brief Provides ADU control functions that help with HTM collection actions.
///
///----------------------------------------------------------------------------
/// *HWP HWP Owner : Nicholas Landi <nlandi@ibm.com>
/// *HWP FW Owner : Ilya Smirnov <ismirno@us.ibm.com>
/// *HWP Consumed by : HB
///----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p10_htm_adu_ctrl.H>
#include <fapi2_mem_access.H>
#include <p10_putmemproc.H>
///
/// See doxygen in p10_htm_adu_ctrl.H
///
fapi2::ReturnCode aduNHTMControl(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
const uint64_t i_addr)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
uint32_t l_mem_flags = fapi2::SBE_MEM_ACCESS_FLAGS_SWITCH_MODE
| fapi2::SBE_MEM_ACCESS_FLAGS_TARGET_PROC;
uint32_t l_bytes = 2; // Want a TSIZE of 2 for these htm ctrl commands
uint8_t l_data[2] = {0, 0}; // give a pointer to real data to prevent any undefined behavior
FAPI_DBG("Debug data: Target: mem_flags: 0x%08llx, addr: 0x%016llx", l_mem_flags, i_addr);
FAPI_DBG("Attempting to put pMisc command");
FAPI_EXEC_HWP(l_rc,
p10_putmemproc,
i_target,
i_addr,
l_bytes,
l_data,
l_mem_flags);
FAPI_DBG("Exiting");
return l_rc;
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_skewadjust.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_skewadjust.C
///
/// @brief update clock mesh deskew
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 1
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_skewadjust.H"
fapi2::ReturnCode p9_mem_skewadjust(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
return fapi2::FAPI2_RC_SUCCESS;
}
<commit_msg>Update hardware procedure metadata<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_skewadjust.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_mem_skewadjust.C
///
/// @brief update clock mesh deskew
//------------------------------------------------------------------------------
// *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
//## auto_generated
#include "p9_mem_skewadjust.H"
fapi2::ReturnCode p9_mem_skewadjust(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "document_runnable.h"
#include <vespa/vespalib/util/exceptions.h>
namespace document {
Runnable::Runnable()
: _stateLock(),
_state(NOT_RUNNING)
{
// if (pool) start(*pool);
}
Runnable::~Runnable() {
vespalib::MonitorGuard monitorGuard(_stateLock);
assert(_state == NOT_RUNNING);
}
bool Runnable::start(FastOS_ThreadPool& pool)
{
vespalib::MonitorGuard monitor(_stateLock);
while (_state == STOPPING) monitor.wait();
if (_state != NOT_RUNNING) return false;
_state = STARTING;
if (pool.NewThread(this) == nullptr) {
throw vespalib::IllegalStateException("Faled starting a new thread", VESPA_STRLOC);
}
return true;
}
bool Runnable::stop()
{
vespalib::MonitorGuard monitor(_stateLock);
if (_state == STOPPING || _state == NOT_RUNNING) return false;
GetThread()->SetBreakFlag();
_state = STOPPING;
return onStop();
}
bool Runnable::onStop()
{
return true;
}
bool Runnable::join() const
{
vespalib::MonitorGuard monitor(_stateLock);
assert ((_state != STARTING) && (_state != RUNNING));
while (_state != NOT_RUNNING) monitor.wait();
return true;
}
void Runnable::Run(FastOS_ThreadInterface*, void*)
{
{
vespalib::MonitorGuard monitor(_stateLock);
// Dont set state if its alreadyt at stopping. (And let run() be
// called even though about to stop for consistency)
if (_state == STARTING) {
_state = RUNNING;
}
}
// By not catching exceptions, they should abort whole application.
// We should thus not need to have a catch all to set state to not
// running.
run();
{
vespalib::MonitorGuard monitor(_stateLock);
_state = NOT_RUNNING;
monitor.broadcast();
}
}
}
<commit_msg>Remove leftover code.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "document_runnable.h"
#include <vespa/vespalib/util/exceptions.h>
namespace document {
Runnable::Runnable()
: _stateLock(),
_state(NOT_RUNNING)
{
}
Runnable::~Runnable() {
vespalib::MonitorGuard monitorGuard(_stateLock);
assert(_state == NOT_RUNNING);
}
bool Runnable::start(FastOS_ThreadPool& pool)
{
vespalib::MonitorGuard monitor(_stateLock);
while (_state == STOPPING) monitor.wait();
if (_state != NOT_RUNNING) return false;
_state = STARTING;
if (pool.NewThread(this) == nullptr) {
throw vespalib::IllegalStateException("Faled starting a new thread", VESPA_STRLOC);
}
return true;
}
bool Runnable::stop()
{
vespalib::MonitorGuard monitor(_stateLock);
if (_state == STOPPING || _state == NOT_RUNNING) return false;
GetThread()->SetBreakFlag();
_state = STOPPING;
return onStop();
}
bool Runnable::onStop()
{
return true;
}
bool Runnable::join() const
{
vespalib::MonitorGuard monitor(_stateLock);
assert ((_state != STARTING) && (_state != RUNNING));
while (_state != NOT_RUNNING) monitor.wait();
return true;
}
void Runnable::Run(FastOS_ThreadInterface*, void*)
{
{
vespalib::MonitorGuard monitor(_stateLock);
// Dont set state if its alreadyt at stopping. (And let run() be
// called even though about to stop for consistency)
if (_state == STARTING) {
_state = RUNNING;
}
}
// By not catching exceptions, they should abort whole application.
// We should thus not need to have a catch all to set state to not
// running.
run();
{
vespalib::MonitorGuard monitor(_stateLock);
_state = NOT_RUNNING;
monitor.broadcast();
}
}
}
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2018 IncludeOS AS, Oslo, Norway
//
// 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 UTIL_ALLOC_PMR
#define UTIL_ALLOC_PMR
#if __has_include(<experimental/memory_resource>)
#include <experimental/memory_resource>
#include <experimental/vector>
namespace std {
namespace pmr = std::experimental::pmr;
}
#else
#include <memory_resource>
#include <vector> // For pmr::vector
#endif
#include <delegate>
#include <malloc.h>
namespace os::mem::detail {
class Pmr_pool;
using Pool_ptr = std::shared_ptr<Pmr_pool>;
}
namespace os::mem {
class Pmr_resource;
class Pmr_pool {
public:
static constexpr size_t default_max_resources = 64;
using Resource = Pmr_resource;
using Resource_ptr = std::unique_ptr<Pmr_resource, delegate<void(Resource*)>>;
inline Pmr_pool(size_t capacity,
size_t cap_suballoc = 0,
size_t max_rescount = default_max_resources);
inline Resource_ptr get_resource();
inline void return_resource(Resource* res);
inline std::size_t resource_capacity();
inline std::size_t resource_count();
inline std::size_t total_capacity();
inline void set_resource_capacity(std::size_t);
inline void set_total_capacity(std::size_t);
inline std::size_t allocated();
inline std::size_t allocatable();
inline std::size_t alloc_count();
inline std::size_t dealloc_count();
inline bool full();
inline bool empty();
private:
detail::Pool_ptr impl;
};
class Pmr_resource : public std::pmr::memory_resource {
public:
using Pool_ptr = detail::Pool_ptr;
inline Pmr_resource(Pool_ptr p);
inline Pool_ptr pool();
inline void* do_allocate(std::size_t size, std::size_t align) override;
inline void do_deallocate (void* ptr, size_t, size_t) override;
inline bool do_is_equal(const std::pmr::memory_resource&) const noexcept override;
inline std::size_t capacity();
inline std::size_t allocatable();
inline std::size_t allocated();
inline std::size_t alloc_count();
inline std::size_t dealloc_count();
inline bool full();
inline bool empty();
private:
Pool_ptr pool_;
std::size_t used = 0;
std::size_t allocs = 0;
std::size_t deallocs = 0;
};
struct Default_pmr : public std::pmr::memory_resource {
void* do_allocate(std::size_t size, std::size_t align) override {
return memalign(align, size);
}
void do_deallocate (void* ptr, size_t, size_t) override {
std::free(ptr);
}
bool do_is_equal (const std::pmr::memory_resource& other) const noexcept override {
if (const auto* underlying = dynamic_cast<const Default_pmr*>(&other))
return true;
return false;
}
};
}
#include <util/detail/alloc_pmr.hpp>
#endif
<commit_msg>util: Make it possible to default construct pmr alloc<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2018 IncludeOS AS, Oslo, Norway
//
// 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 UTIL_ALLOC_PMR
#define UTIL_ALLOC_PMR
#if __has_include(<experimental/memory_resource>)
#include <experimental/memory_resource>
#include <experimental/vector>
namespace std {
namespace pmr = std::experimental::pmr;
}
#else
#include <memory_resource>
#include <vector> // For pmr::vector
#endif
#include <delegate>
#include <malloc.h>
namespace os::mem::detail {
class Pmr_pool;
using Pool_ptr = std::shared_ptr<Pmr_pool>;
}
namespace os::mem {
class Pmr_resource;
class Pmr_pool {
public:
static constexpr size_t default_max_resources = 64;
using Resource = Pmr_resource;
using Resource_ptr = std::unique_ptr<Pmr_resource, delegate<void(Resource*)>>;
inline Pmr_pool(size_t capacity,
size_t cap_suballoc = 0,
size_t max_rescount = default_max_resources);
inline Pmr_pool() = default;
inline Resource_ptr get_resource();
inline void return_resource(Resource* res);
inline std::size_t resource_capacity();
inline std::size_t resource_count();
inline std::size_t total_capacity();
inline void set_resource_capacity(std::size_t);
inline void set_total_capacity(std::size_t);
inline std::size_t allocated();
inline std::size_t allocatable();
inline std::size_t alloc_count();
inline std::size_t dealloc_count();
inline bool full();
inline bool empty();
private:
detail::Pool_ptr impl;
};
class Pmr_resource : public std::pmr::memory_resource {
public:
using Pool_ptr = detail::Pool_ptr;
inline Pmr_resource(Pool_ptr p);
inline Pool_ptr pool();
inline void* do_allocate(std::size_t size, std::size_t align) override;
inline void do_deallocate (void* ptr, size_t, size_t) override;
inline bool do_is_equal(const std::pmr::memory_resource&) const noexcept override;
inline std::size_t capacity();
inline std::size_t allocatable();
inline std::size_t allocated();
inline std::size_t alloc_count();
inline std::size_t dealloc_count();
inline bool full();
inline bool empty();
private:
Pool_ptr pool_;
std::size_t used = 0;
std::size_t allocs = 0;
std::size_t deallocs = 0;
};
struct Default_pmr : public std::pmr::memory_resource {
void* do_allocate(std::size_t size, std::size_t align) override {
return memalign(align, size);
}
void do_deallocate (void* ptr, size_t, size_t) override {
std::free(ptr);
}
bool do_is_equal (const std::pmr::memory_resource& other) const noexcept override {
if (const auto* underlying = dynamic_cast<const Default_pmr*>(&other))
return true;
return false;
}
};
}
#include <util/detail/alloc_pmr.hpp>
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 libmv authors.
//
// 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 "libmv/multiview/reconstruction_image_order_selection.h"
#include "libmv/multiview/robust_homography.h"
namespace libmv {
void SelectEfficientImageOrder(
const Matches &matches,
std::list<vector<Matches::ImageID> >*connected_graph_list) {
typedef std::pair<Matches::ImageID, Matches::ImageID> ImagesTypePairs;
typedef vector<ImagesTypePairs > ImagesPairs;
double h, score, max_error_h = 1;
Mat3 H;
// TODO(julien) Find connected graph and do the rest of every graph
{
// Selects the two views that are not too closed but share common tracks
size_t i = 0;
double score_max_1 = 0;
ImagesTypePairs image_pair_max_1;
vector<Mat2X> xs(matches.NumImages());
std::set<Matches::ImageID>::const_iterator image_iter1 =
matches.get_images().begin();
std::set<Matches::ImageID>::const_iterator image_iter2;
image_pair_max_1 = ImagesTypePairs(*matches.get_images().begin(),
*(++matches.get_images().begin()));
vector<Mat> xs2;
// HACK(julien) we force to keep the first image
// TODO(julien) implements a better selection
//for (;image_iter1 != matches.get_images().end(); ++image_iter1) {
{
image_iter2 = image_iter1;
image_iter2++;
for (;image_iter2 != matches.get_images().end(); ++image_iter2) {
TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);
if (xs2[0].cols() >= 4) {
h = HomographyFromCorrespondences4PointRobust(xs2[0], xs2[1],
max_error_h,
&H, NULL, 1e-2);
// the score is homography x number of matches
//TODO(julien) Actually it should be the median of the homography...
score = h * xs2[0].cols();
i++;
VLOG(1) << "Score["<<i<<"] = " << score <<"\n";
if (score > score_max_1) {
score_max_1 = score;
image_pair_max_1 = ImagesTypePairs(*image_iter1, *image_iter2);
VLOG(1) << " max score found !\n";
}
}
}
}
vector<Matches::ImageID> v(matches.NumImages());
if (score_max_1 != 0) {
v[0] = image_pair_max_1.first;
v[1] = image_pair_max_1.second;
i = 2;
} else {
i = 0;
}
// Fill the rest of images (not ordered)
// TODO(julien) maybe we can do better than a non ordered list here?
image_iter1 = matches.get_images().begin();
for (;image_iter1 != matches.get_images().end(); ++image_iter1) {
if (score_max_1 == 0 || (*image_iter1 != v[0] && *image_iter1 != v[1])) {
v[i] = *image_iter1;
++i;
}
}
connected_graph_list->push_back(v);
}
}
} // namespace libmv
<commit_msg>Add a image order selection method based on a max score selection.<commit_after>// Copyright (c) 2010 libmv authors.
//
// 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 <map>
#include "libmv/multiview/reconstruction_image_order_selection.h"
#include "libmv/multiview/robust_homography.h"
namespace libmv {
void FillPairwiseMatchesMatrix(const Matches &matches,
Mat *m) {
m->resize(matches.NumImages(),
matches.NumImages());
m->setZero();
std::set<Matches::ImageID>::const_iterator image_iter1 =
matches.get_images().begin();
std::set<Matches::ImageID>::const_iterator image_iter2;
vector<Mat> xs2;
for (;image_iter1 != matches.get_images().end(); ++image_iter1) {
image_iter2 = image_iter1;
image_iter2++;
for (;image_iter2 != matches.get_images().end(); ++image_iter2) {
TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);
(*m)(*image_iter1, *image_iter2) = xs2[0].cols();
}
}
}
void FillPairwiseMatchesHomographyMatrix(const Matches &matches,
Mat *m) {
m->resize(matches.NumImages(),
matches.NumImages());
m->setZero();
double h, max_error_h = 1;
Mat3 H;
std::set<Matches::ImageID>::const_iterator image_iter1 =
matches.get_images().begin();
std::set<Matches::ImageID>::const_iterator image_iter2;
vector<Mat> xs2;
for (;image_iter1 != matches.get_images().end(); ++image_iter1) {
image_iter2 = image_iter1;
image_iter2++;
for (;image_iter2 != matches.get_images().end(); ++image_iter2) {
TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);
(*m)(*image_iter1, *image_iter2) = xs2[0].cols();
if (xs2[0].cols() >= 4) {
h = HomographyFromCorrespondences4PointRobust(xs2[0], xs2[1],
max_error_h,
&H, NULL, 1e-2);
(*m)(*image_iter1, *image_iter2) *= h;
}
}
}
}
bool AddIndex(int id, vector<uint> *id_ordered) {
for (uint i = 0; i < id_ordered->size() ;++i) {
if ((*id_ordered)[i] == id) {
return false;
}
}
id_ordered->push_back(id);
return true;
}
void RecursivePairwiseHighScoresSearch(Mat &m,
const Vec2i seed,
vector<uint> *id_ordered) {
double val_c, val_r;
Vec2i max_c, max_r;
int nothing;
// Set to zero (to avoid to get the same couple)
m(seed[0], seed[1]) = 0;
// Find the best score for the col
val_c = m.col(seed[1]).maxCoeff(&max_c[0], ¬hing);
max_c[1] = seed[1];
// Find the best score for the row
val_r = m.row(seed[0]).maxCoeff(¬hing, &max_r[1]);
max_r[0] = seed[0];
if (val_c > 0)
m(max_c[0], max_c[1]) = 0;
if (val_r > 0)
m(max_r[0], max_r[1]) = 0;
if (val_c < val_r) {
if (val_r > 0) {
AddIndex(max_r[1], id_ordered);
RecursivePairwiseHighScoresSearch(m, max_r, id_ordered);
}
if (val_c > 0) {
AddIndex(max_c[0], id_ordered);
RecursivePairwiseHighScoresSearch(m, max_c, id_ordered);
}
} else {
if (val_c > 0) {
AddIndex(max_c[0], id_ordered);
RecursivePairwiseHighScoresSearch(m, max_c, id_ordered);
}
if (val_r > 0){
AddIndex(max_r[1], id_ordered);
RecursivePairwiseHighScoresSearch(m, max_r, id_ordered);
}
}
}
void RecoverOrderFromPairwiseHighScores(
const Matches &matches,
Mat &m,
std::list<vector<Matches::ImageID> > *connected_graph_list) {
//connected_graph_list->clear();
std::map<uint, Matches::ImageID> map_img_ids;
std::set<Matches::ImageID>::const_iterator image_iter1 =
matches.get_images().begin();
uint i_img = 0;
for (;image_iter1 != matches.get_images().end(); ++image_iter1, ++i_img) {
map_img_ids[i_img] = *image_iter1;
}
Vec2i max;
double val = 1;
while (val > 0) {
// Find the global best score
val = m.maxCoeff(&max[0], &max[1]);
//From this seed, find the second best score in the same col/row
if (val > 0) {
vector<uint> id_ordered;
id_ordered.push_back(max[0]);
id_ordered.push_back(max[1]);
RecursivePairwiseHighScoresSearch(m, max, &id_ordered);
vector<Matches::ImageID> v_ids(id_ordered.size());
for (i_img = 0; i_img < id_ordered.size(); ++i_img) {
v_ids[i_img] = (map_img_ids[id_ordered[i_img]]);
}
connected_graph_list->push_back(v_ids);
}
}
}
void SelectEfficientImageOrder(
const Matches &matches,
std::list<vector<Matches::ImageID> >*connected_graph_list) {
Mat m;
FillPairwiseMatchesHomographyMatrix(matches, &m);
std::cout << " M = " << m <<"\n";
RecoverOrderFromPairwiseHighScores(matches, m, connected_graph_list);
}
} // namespace libmv<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * 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 author nor the names of other 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 <stdafx.h>
#include "MasterTransport.h"
#include <core/audio/GaplessTransport.h>
#include <core/audio/CrossfadeTransport.h>
#include <core/support/Preferences.h>
#include <core/support/PreferenceKeys.h>
using namespace musik::box::audio;
using namespace musik::core::audio;
using namespace musik::core;
using namespace musik::core::prefs;
using namespace musik::core::sdk;
MasterTransport::MasterTransport()
: prefs(Preferences::ForComponent(components::Playback)) {
this->type = (Type) this->prefs->GetInt(keys::Transport, Gapless);
this->SwitchTo(this->type);
}
MasterTransport::~MasterTransport() {
}
void MasterTransport::SwitchTo(Type type) {
if (!this->transport || this->type != type) {
this->type = type;
this->prefs->SetInt(keys::Transport, (int) this->type);
switch (this->type) {
case Gapless:
this->transport.reset(new GaplessTransport());
break;
case Crossfade:
this->transport.reset(new CrossfadeTransport());
break;
}
this->transport->PlaybackEvent.connect(
this, &MasterTransport::OnPlaybackEvent);
this->transport->StreamEvent.connect(
this, &MasterTransport::OnStreamEvent);
this->transport->TimeChanged.connect(
this, &MasterTransport::OnTimeChanged);
this->transport->VolumeChanged.connect(
this, &MasterTransport::OnVolumeChanged);
}
}
MasterTransport::Type MasterTransport::GetType() {
return this->type;
}
void MasterTransport::PrepareNextTrack(const std::string& trackUrl) {
this->transport->PrepareNextTrack(trackUrl);
}
void MasterTransport::Start(const std::string& trackUrl) {
this->transport->Start(trackUrl);
}
void MasterTransport::Stop() {
this->transport->Stop();
}
bool MasterTransport::Pause() {
return this->transport->Pause();
}
bool MasterTransport::Resume() {
return this->transport->Resume();
}
double MasterTransport::Position() {
return this->transport->Position();
}
void MasterTransport::SetPosition(double seconds) {
this->transport->SetPosition(seconds);
}
double MasterTransport::Volume() {
return this->transport->Volume();
}
void MasterTransport::SetVolume(double volume) {
this->transport->SetVolume(volume);
}
double MasterTransport::GetDuration() {
return this->transport->GetDuration();
}
bool MasterTransport::IsMuted() {
return this->transport->IsMuted();
}
void MasterTransport::SetMuted(bool muted) {
this->transport->SetMuted(muted);
}
void MasterTransport::ReloadOutput() {
this->transport->ReloadOutput();
}
PlaybackState MasterTransport::GetPlaybackState() {
return this->transport->GetPlaybackState();
}
void MasterTransport::OnStreamEvent(int type, std::string url) {
this->StreamEvent(type, url);
}
void MasterTransport::OnPlaybackEvent(int type) {
this->PlaybackEvent(type);
}
void MasterTransport::OnVolumeChanged() {
this->VolumeChanged();
}
void MasterTransport::OnTimeChanged(double time) {
this->TimeChanged(time);
}<commit_msg>A small bugfix to restore volume after switching transports.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube 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:
//
// * 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 author nor the names of other 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 <stdafx.h>
#include "MasterTransport.h"
#include <core/audio/GaplessTransport.h>
#include <core/audio/CrossfadeTransport.h>
#include <core/support/Preferences.h>
#include <core/support/PreferenceKeys.h>
using namespace musik::box::audio;
using namespace musik::core::audio;
using namespace musik::core;
using namespace musik::core::prefs;
using namespace musik::core::sdk;
MasterTransport::MasterTransport()
: prefs(Preferences::ForComponent(components::Playback)) {
this->type = (Type) this->prefs->GetInt(keys::Transport, Gapless);
this->SwitchTo(this->type);
}
MasterTransport::~MasterTransport() {
}
void MasterTransport::SwitchTo(Type type) {
if (!this->transport || this->type != type) {
this->type = type;
this->prefs->SetInt(keys::Transport, (int) this->type);
double volume = this->transport ? this->transport->Volume() : -1;
switch (this->type) {
case Gapless:
this->transport.reset(new GaplessTransport());
break;
case Crossfade:
this->transport.reset(new CrossfadeTransport());
break;
}
if (volume > 0) {
this->transport->SetVolume(volume);
}
this->transport->PlaybackEvent.connect(
this, &MasterTransport::OnPlaybackEvent);
this->transport->StreamEvent.connect(
this, &MasterTransport::OnStreamEvent);
this->transport->TimeChanged.connect(
this, &MasterTransport::OnTimeChanged);
this->transport->VolumeChanged.connect(
this, &MasterTransport::OnVolumeChanged);
}
}
MasterTransport::Type MasterTransport::GetType() {
return this->type;
}
void MasterTransport::PrepareNextTrack(const std::string& trackUrl) {
this->transport->PrepareNextTrack(trackUrl);
}
void MasterTransport::Start(const std::string& trackUrl) {
this->transport->Start(trackUrl);
}
void MasterTransport::Stop() {
this->transport->Stop();
}
bool MasterTransport::Pause() {
return this->transport->Pause();
}
bool MasterTransport::Resume() {
return this->transport->Resume();
}
double MasterTransport::Position() {
return this->transport->Position();
}
void MasterTransport::SetPosition(double seconds) {
this->transport->SetPosition(seconds);
}
double MasterTransport::Volume() {
return this->transport->Volume();
}
void MasterTransport::SetVolume(double volume) {
this->transport->SetVolume(volume);
}
double MasterTransport::GetDuration() {
return this->transport->GetDuration();
}
bool MasterTransport::IsMuted() {
return this->transport->IsMuted();
}
void MasterTransport::SetMuted(bool muted) {
this->transport->SetMuted(muted);
}
void MasterTransport::ReloadOutput() {
this->transport->ReloadOutput();
}
PlaybackState MasterTransport::GetPlaybackState() {
return this->transport->GetPlaybackState();
}
void MasterTransport::OnStreamEvent(int type, std::string url) {
this->StreamEvent(type, url);
}
void MasterTransport::OnPlaybackEvent(int type) {
this->PlaybackEvent(type);
}
void MasterTransport::OnVolumeChanged() {
this->VolumeChanged();
}
void MasterTransport::OnTimeChanged(double time) {
this->TimeChanged(time);
}<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for T0 calibration TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>
ClassImp(AliT0CalibTimeEq)
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
fMeanVertex(0),
fRmsVertex(0)
{
//
}
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
fMeanVertex(0),
fRmsVertex(0)
{
//constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
}
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
fMeanVertex(0),
fRmsVertex(0)
{
// copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
}
//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
return *this;
}
//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
//
// destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
//reset values
memset(fCFDvalue,0,120*sizeof(Float_t));
memset(fTimeEq,1,24*sizeof(Float_t));
}
//________________________________________________________________
void AliT0CalibTimeEq::Print(Option_t*) const
{
// print time values
printf("\n ---- PM Arrays ----\n\n");
printf(" Time delay CFD \n");
for (Int_t i=0; i<24; i++) printf(" CFD %f ",fTimeEq[i]);
printf("\n Mean Vertex %f \n", fMeanVertex);
}
//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
// compute online equalized time
Double_t mean=0, meanver=0;
Double_t rms=0, rmsver=0;
Int_t nent=0;
Bool_t ok=false;
gFile = TFile::Open(filePhys);
if(!gFile) {
AliError("No input PHYS data found ");
}
else
{
ok=true;
Char_t buf1[30];
for (Int_t i=0; i<24; i++)
{
sprintf(buf1,"CFD1-CFD%d",i+1);
TH1F *cfd = (TH1F*) gFile->Get(buf1);
if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
// printf(" i = %d buf1 = %s\n", i, buf1);
if(cfd) {
mean=cfd->GetMean();
rms=cfd->GetRMS();
nent=cfd->GetEntries();
// printf ("%f %f %i \n",mean,rms,nent);
if(nent<50 || rms>10 ) ok=false;
}
SetTimeEq(i,mean);
SetTimeEqRms(i,rms);
if (cfd) delete cfd;
}
TH1F *ver = (TH1F*) gFile->Get("hVertex");
if(!ver) AliWarning("no Vertex histograms collected by PHYS DA for Zvertex");
if(ver) {
meanver = ver->GetMean();
rmsver = ver->GetRMS();
}
SetMeanVertex(meanver);
SetRmsVertex(rmsver);
gFile->Close();
delete gFile;
}
return ok;
}
<commit_msg>more protection for small number of entries<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for T0 calibration TM-AC-AM_6-02-2006
// equalize time shift for each time CFD channel
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliT0CalibTimeEq.h"
#include "AliLog.h"
#include <TFile.h>
#include <TMath.h>
#include <TF1.h>
#include <TSpectrum.h>
#include <TProfile.h>
#include <iostream>
ClassImp(AliT0CalibTimeEq)
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),
fMeanVertex(0),
fRmsVertex(0)
{
//
}
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),
fMeanVertex(0),
fRmsVertex(0)
{
//constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
}
//________________________________________________________________
AliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),
fMeanVertex(0),
fRmsVertex(0)
{
// copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
}
//________________________________________________________________
AliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
return *this;
}
//________________________________________________________________
AliT0CalibTimeEq::~AliT0CalibTimeEq()
{
//
// destrictor
}
//________________________________________________________________
void AliT0CalibTimeEq::Reset()
{
//reset values
memset(fCFDvalue,0,120*sizeof(Float_t));
memset(fTimeEq,1,24*sizeof(Float_t));
}
//________________________________________________________________
void AliT0CalibTimeEq::Print(Option_t*) const
{
// print time values
printf("\n ---- PM Arrays ----\n\n");
printf(" Time delay CFD \n");
for (Int_t i=0; i<24; i++) printf(" CFD %f ",fTimeEq[i]);
printf("\n Mean Vertex %f \n", fMeanVertex);
}
//________________________________________________________________
Bool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)
{
// compute online equalized time
Double_t mean=0, meanver=0;
Double_t rms=0, rmsver=0;
Int_t nent=0;
Bool_t ok=false;
gFile = TFile::Open(filePhys);
if(!gFile) {
AliError("No input PHYS data found ");
}
else
{
ok=true;
Char_t buf1[30];
for (Int_t i=0; i<24; i++)
{
sprintf(buf1,"CFD1-CFD%d",i+1);
TH1F *cfd = (TH1F*) gFile->Get(buf1);
if(!cfd) AliWarning(Form("no histograms collected by PHYS DA for channel %i", i));
// printf(" i = %d buf1 = %s\n", i, buf1);
if(cfd) {
mean=cfd->GetMean();
rms=cfd->GetRMS();
nent=cfd->GetEntries();
// printf ("%f %f %i \n",mean,rms,nent);
if(nent<200 || rms>10 ) ok=false;
}
SetTimeEq(i,mean);
SetTimeEqRms(i,rms);
if (cfd) delete cfd;
}
TH1F *ver = (TH1F*) gFile->Get("hVertex");
if(!ver) AliWarning("no Vertex histograms collected by PHYS DA for Zvertex");
if(ver) {
meanver = ver->GetMean();
rmsver = ver->GetRMS();
}
SetMeanVertex(meanver);
SetRmsVertex(rmsver);
gFile->Close();
delete gFile;
}
return ok;
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#ifndef TELEGRAM_QT_API_UTILS_HPP
#define TELEGRAM_QT_API_UTILS_HPP
#include "telegramqt_global.h"
#include "TelegramNamespace.hpp"
#include "TLTypes.hpp"
#include <QDateTime>
namespace Telegram {
namespace Utils {
TELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLInputPeer &inputPeer, quint32 selfId);
TELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLPeer &peer);
TELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLUser &user);
TELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLChat *chat);
TELEGRAMQT_EXPORT TLPeer toTLPeer(const Telegram::Peer &peer);
TELEGRAMQT_EXPORT Telegram::Peer getMessageDialogPeer(const TLMessage &message, quint32 applicantUserId);
TELEGRAMQT_EXPORT QString mimeTypeByStorageFileType(TLValue type);
TELEGRAMQT_EXPORT TelegramNamespace::MessageType getPublicMessageType(const TLMessageMedia &media);
TELEGRAMQT_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageType type);
TELEGRAMQT_EXPORT TelegramNamespace::MessageAction toPublicMessageAction(TLValue action);
TELEGRAMQT_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageAction action);
TELEGRAMQT_EXPORT quint64 formatTimeStamp(qint64 timeInMs);
TELEGRAMQT_EXPORT quint64 timeStampToMSecsSinceEpoch(quint64 ts);
TELEGRAMQT_EXPORT quint32 getCurrentTime();
} // Utils namespace
} // Telegram namespace
inline quint32 Telegram::Utils::getCurrentTime()
{
#if QT_VERSION > QT_VERSION_CHECK(5, 8, 0)
qint64 timestamp = QDateTime::currentSecsSinceEpoch();
#else
qint64 timestamp = QDateTime::currentMSecsSinceEpoch() / 1000;
#endif
return static_cast<quint32>(timestamp);
}
#endif // TELEGRAM_QT_API_UTILS_HPP
<commit_msg>ApiUtils: Mark functions as internal export<commit_after>/*
Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#ifndef TELEGRAM_QT_API_UTILS_HPP
#define TELEGRAM_QT_API_UTILS_HPP
#include "telegramqt_global.h"
#include "TelegramNamespace.hpp"
#include "TLTypes.hpp"
#include <QDateTime>
namespace Telegram {
namespace Utils {
TELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLInputPeer &inputPeer, quint32 selfId);
TELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLPeer &peer);
TELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLUser &user);
TELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLChat *chat);
TELEGRAMQT_INTERNAL_EXPORT TLPeer toTLPeer(const Telegram::Peer &peer);
TELEGRAMQT_INTERNAL_EXPORT Telegram::Peer getMessageDialogPeer(const TLMessage &message, quint32 applicantUserId);
TELEGRAMQT_INTERNAL_EXPORT QString mimeTypeByStorageFileType(TLValue type);
TELEGRAMQT_INTERNAL_EXPORT TelegramNamespace::MessageType getPublicMessageType(const TLMessageMedia &media);
TELEGRAMQT_INTERNAL_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageType type);
TELEGRAMQT_INTERNAL_EXPORT TelegramNamespace::MessageAction toPublicMessageAction(TLValue action);
TELEGRAMQT_INTERNAL_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageAction action);
TELEGRAMQT_EXPORT quint64 formatTimeStamp(qint64 timeInMs);
TELEGRAMQT_EXPORT quint64 timeStampToMSecsSinceEpoch(quint64 ts);
TELEGRAMQT_EXPORT quint32 getCurrentTime();
} // Utils namespace
} // Telegram namespace
inline quint32 Telegram::Utils::getCurrentTime()
{
#if QT_VERSION > QT_VERSION_CHECK(5, 8, 0)
qint64 timestamp = QDateTime::currentSecsSinceEpoch();
#else
qint64 timestamp = QDateTime::currentMSecsSinceEpoch() / 1000;
#endif
return static_cast<quint32>(timestamp);
}
#endif // TELEGRAM_QT_API_UTILS_HPP
<|endoftext|>
|
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) Microsoft Corporation
*
* 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.
*
*/
/**
Test JIT code emission.
*/
#include "stdafx.h"
#include "catch.hpp"
#include "testing_util.h"
#include <Python.h>
#include <frameobject.h>
#include <pyjit.h>
class EmissionTest {
private:
PyCodeObject *m_code;
PyJittedCode *m_jittedcode;
PyObject *run() {
auto sysModule = PyImport_ImportModule("sys");
auto globals = PyDict_New();
auto builtins = PyThreadState_GET()->interp->builtins;
PyDict_SetItemString(globals, "__builtins__", builtins);
PyDict_SetItemString(globals, "sys", sysModule);
/* XXX Why?
PyRun_String("finalized = False\nclass RefCountCheck:\n def __del__(self):\n print('finalizing')\n global finalized\n finalized = True\n def __add__(self, other):\n return self", Py_file_input, globals, globals);
if (PyErr_Occurred()) {
PyErr_Print();
return "";
}*/
// Don't DECREF as frames are recycled.
auto frame = PyFrame_New(PyThreadState_Get(), m_code, globals, PyDict_New());
auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);
Py_DECREF(globals);
Py_DECREF(sysModule);
return res;
}
public:
EmissionTest(const char *code) {
m_code = CompileCode(code);
if (m_code == nullptr) {
FAIL("failed to compile code");
}
m_jittedcode = JitCompile(m_code);
if (m_jittedcode == nullptr) {
FAIL("failed to JIT code");
}
}
~EmissionTest() {
Py_XDECREF(m_code);
Py_XDECREF(m_jittedcode);
}
const char* returns() {
auto res = run();
REQUIRE(res != nullptr);
REQUIRE(!PyErr_Occurred());
auto repr = PyUnicode_AsUTF8(PyObject_Repr(res));
Py_DECREF(res);
auto tstate = PyThreadState_GET();
REQUIRE(tstate->exc_value == nullptr);
REQUIRE(tstate->exc_traceback == nullptr);
if (tstate->exc_type != nullptr) {
REQUIRE(tstate->exc_type == Py_None);
}
return repr;
}
PyObject* raises() {
auto res = run();
REQUIRE(res == nullptr);
return PyErr_Occurred();
}
};
TEST_CASE("General list unpacking", "[list][BUILD_LIST_UNPACK][emission]") {
SECTION("common case") {
auto t = EmissionTest("def f(): return [1, *[2], 3]");
REQUIRE(t.returns() == "[1, 2, 3]");
}
SECTION("unpacking a non-iterable") {
auto t = EmissionTest("def f(): return [1, *2, 3]");
REQUIRE(t.raises() == PyExc_TypeError);
}
}<commit_msg>Use std::string for macro support in Catch for comparisons<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) Microsoft Corporation
*
* 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.
*
*/
/**
Test JIT code emission.
*/
#include "stdafx.h"
#include "catch.hpp"
#include "testing_util.h"
#include <Python.h>
#include <frameobject.h>
#include <pyjit.h>
class EmissionTest {
private:
PyCodeObject *m_code;
PyJittedCode *m_jittedcode;
PyObject *run() {
auto sysModule = PyImport_ImportModule("sys");
auto globals = PyDict_New();
auto builtins = PyThreadState_GET()->interp->builtins;
PyDict_SetItemString(globals, "__builtins__", builtins);
PyDict_SetItemString(globals, "sys", sysModule);
/* XXX Why?
PyRun_String("finalized = False\nclass RefCountCheck:\n def __del__(self):\n print('finalizing')\n global finalized\n finalized = True\n def __add__(self, other):\n return self", Py_file_input, globals, globals);
if (PyErr_Occurred()) {
PyErr_Print();
return "";
}*/
// Don't DECREF as frames are recycled.
auto frame = PyFrame_New(PyThreadState_Get(), m_code, globals, PyDict_New());
auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);
Py_DECREF(globals);
Py_DECREF(sysModule);
return res;
}
public:
EmissionTest(const char *code) {
m_code = CompileCode(code);
if (m_code == nullptr) {
FAIL("failed to compile code");
}
m_jittedcode = JitCompile(m_code);
if (m_jittedcode == nullptr) {
FAIL("failed to JIT code");
}
}
~EmissionTest() {
Py_XDECREF(m_code);
Py_XDECREF(m_jittedcode);
}
std::string& returns() {
auto res = run();
REQUIRE(res != nullptr);
REQUIRE(!PyErr_Occurred());
auto repr = PyUnicode_AsUTF8(PyObject_Repr(res));
Py_DECREF(res);
auto tstate = PyThreadState_GET();
REQUIRE(tstate->exc_value == nullptr);
REQUIRE(tstate->exc_traceback == nullptr);
if (tstate->exc_type != nullptr) {
REQUIRE(tstate->exc_type == Py_None);
}
return std::string(repr);
}
PyObject* raises() {
auto res = run();
REQUIRE(res == nullptr);
return PyErr_Occurred();
}
};
TEST_CASE("General list unpacking", "[list][BUILD_LIST_UNPACK][emission]") {
SECTION("common case") {
auto t = EmissionTest("def f(): return [1, *[2], 3]");
REQUIRE(t.returns() == "[1, 2, 3]");
}
SECTION("unpacking a non-iterable") {
auto t = EmissionTest("def f(): return [1, *2, 3]");
REQUIRE(t.raises() == PyExc_TypeError);
}
}<|endoftext|>
|
<commit_before>#include "TiLDA_MKe.h"
#include "Arduino.h"
TiLDA_MKe::TiLDA_MKe() :
glcd(LCD_CS, LCD_A0, LCD_RESET)
{
// GLCD setup
pinMode(LCD_POWER, OUTPUT);
digitalWrite(LCD_POWER, LOW);
/*
* I think the EMF board def. puts this on a PWM pin
* but keeping it on digital makes it easier to toggle
*/
pinMode(LCD_BACKLIGHT, OUTPUT);
// Configure buttons
buttons.addButton(BUTTON_LIGHT);
buttons.addButton(BUTTON_SCREEN_RIGHT);
buttons.addButton(BUTTON_SCREEN_LEFT);
buttons.addButton(BUTTON_A);
buttons.addButton(BUTTON_B);
buttons.addButton(BUTTON_UP);
buttons.addButton(BUTTON_RIGHT);
buttons.addButton(BUTTON_DOWN);
buttons.addButton(BUTTON_LEFT);
buttons.addButton(BUTTON_CENTER);
// LED setup
uint8_t inital_state = 0;
setLED(1, inital_state, inital_state, inital_state);
setLED(2, inital_state, inital_state, inital_state);
// Battery monitor setup
pinMode(MCP_STAT, INPUT_PULLUP);
pinMode(VBATT_MON, INPUT);
}
/**
* Sets the state of the backlight.
*
* @param state State to set backlight to (1 or 0)
*/
void TiLDA_MKe::setBacklight(uint8_t state)
{
digitalWrite(LCD_BACKLIGHT, state);
}
/**
* Gets the state of the backlight.
*
* @returns Backlight state
*/
uint8_t TiLDA_MKe::backlight()
{
return digitalRead(LCD_BACKLIGHT);
}
/**
* Flips the state of the backlight then returns the new state.
*
* @returns New backlight state
*/
uint8_t TiLDA_MKe::toggleBacklight()
{
digitalWrite(LCD_BACKLIGHT, !backlight());
return digitalRead(LCD_BACKLIGHT);
}
/**
* Sets the colour and brightness of the RGB LEDs.
*
* @param led LED to set (1 or 2)
* @param r Red intensity
* @param g Green intensity
* @param b Blue intensity
*/
void TiLDA_MKe::setLED(uint8_t led, uint8_t r, uint8_t g, uint8_t b)
{
switch(led)
{
case 1:
analogWrite(LED1_RED, r);
analogWrite(LED1_GREEN, g);
analogWrite(LED1_BLUE, b);
break;
case 2:
analogWrite(LED2_RED, r);
analogWrite(LED2_GREEN, g);
analogWrite(LED2_BLUE, b);
break;
default:
return;
}
}
/**
* Gets an approximation of the battery percentage.
*
* Note that the value is only accurate when not charging.
*
* @return Approx battery percentage
*/
uint8_t TiLDA_MKe::getBatteryPercentage()
{
return (analogRead(VBATT_MON) - PMIC_BATTERY_FLAT) * PMIC_BATTERY_PERCENT_RATIO;
}
/**
* Gets the battery voltage.
*
* @return Battery voltage
*/
float TiLDA_MKe::getBatteryVoltage()
{
return (analogRead(VBATT_MON) * (3.3 / 512));
}
/**
* Tests if the batter is being charged.
*
* @return True if charging, false otherwise
*/
bool TiLDA_MKe::isCharging()
{
return !digitalRead(MCP_STAT);
}
<commit_msg>Small change in toggleBacklight<commit_after>#include "TiLDA_MKe.h"
#include "Arduino.h"
TiLDA_MKe::TiLDA_MKe() :
glcd(LCD_CS, LCD_A0, LCD_RESET)
{
// GLCD setup
pinMode(LCD_POWER, OUTPUT);
digitalWrite(LCD_POWER, LOW);
/*
* I think the EMF board def. puts this on a PWM pin
* but keeping it on digital makes it easier to toggle
*/
pinMode(LCD_BACKLIGHT, OUTPUT);
// Configure buttons
buttons.addButton(BUTTON_LIGHT);
buttons.addButton(BUTTON_SCREEN_RIGHT);
buttons.addButton(BUTTON_SCREEN_LEFT);
buttons.addButton(BUTTON_A);
buttons.addButton(BUTTON_B);
buttons.addButton(BUTTON_UP);
buttons.addButton(BUTTON_RIGHT);
buttons.addButton(BUTTON_DOWN);
buttons.addButton(BUTTON_LEFT);
buttons.addButton(BUTTON_CENTER);
// LED setup
uint8_t inital_state = 0;
setLED(1, inital_state, inital_state, inital_state);
setLED(2, inital_state, inital_state, inital_state);
// Battery monitor setup
pinMode(MCP_STAT, INPUT_PULLUP);
pinMode(VBATT_MON, INPUT);
}
/**
* Sets the state of the backlight.
*
* @param state State to set backlight to (1 or 0)
*/
void TiLDA_MKe::setBacklight(uint8_t state)
{
digitalWrite(LCD_BACKLIGHT, state);
}
/**
* Gets the state of the backlight.
*
* @returns Backlight state
*/
uint8_t TiLDA_MKe::backlight()
{
return digitalRead(LCD_BACKLIGHT);
}
/**
* Flips the state of the backlight then returns the new state.
*
* @returns New backlight state
*/
uint8_t TiLDA_MKe::toggleBacklight()
{
digitalWrite(LCD_BACKLIGHT, !backlight());
return backlight();
}
/**
* Sets the colour and brightness of the RGB LEDs.
*
* @param led LED to set (1 or 2)
* @param r Red intensity
* @param g Green intensity
* @param b Blue intensity
*/
void TiLDA_MKe::setLED(uint8_t led, uint8_t r, uint8_t g, uint8_t b)
{
switch(led)
{
case 1:
analogWrite(LED1_RED, r);
analogWrite(LED1_GREEN, g);
analogWrite(LED1_BLUE, b);
break;
case 2:
analogWrite(LED2_RED, r);
analogWrite(LED2_GREEN, g);
analogWrite(LED2_BLUE, b);
break;
default:
return;
}
}
/**
* Gets an approximation of the battery percentage.
*
* Note that the value is only accurate when not charging.
*
* @return Approx battery percentage
*/
uint8_t TiLDA_MKe::getBatteryPercentage()
{
return (analogRead(VBATT_MON) - PMIC_BATTERY_FLAT) * PMIC_BATTERY_PERCENT_RATIO;
}
/**
* Gets the battery voltage.
*
* @return Battery voltage
*/
float TiLDA_MKe::getBatteryVoltage()
{
return (analogRead(VBATT_MON) * (3.3 / 512));
}
/**
* Tests if the batter is being charged.
*
* @return True if charging, false otherwise
*/
bool TiLDA_MKe::isCharging()
{
return !digitalRead(MCP_STAT);
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "imported_search_context.h"
#include "imported_attribute_vector.h"
#include <vespa/searchlib/common/bitvectoriterator.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include "attributeiterators.hpp"
using search::datastore::EntryRef;
using search::queryeval::EmptySearch;
using search::queryeval::SearchIterator;
using search::attribute::ReferenceAttribute;
using search::AttributeVector;
using ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;
using ReverseMapping = ReferenceAttribute::ReverseMapping;
using SearchContext = AttributeVector::SearchContext;
namespace search::attribute {
ImportedSearchContext::ImportedSearchContext(
std::unique_ptr<QueryTermSimple> term,
const SearchContextParams& params,
const ImportedAttributeVector& imported_attribute)
: _imported_attribute(imported_attribute),
_reference_attribute(*_imported_attribute.getReferenceAttribute()),
_target_attribute(*_imported_attribute.getTargetAttribute()),
_target_search_context(_target_attribute.getSearch(std::move(term), params)),
_referencedLids(_reference_attribute.getReferencedLids()),
_referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),
_merger(_reference_attribute.getCommittedDocIdLimit()),
_fetchPostingsDone(false)
{
}
ImportedSearchContext::~ImportedSearchContext() {
}
unsigned int ImportedSearchContext::approximateHits() const {
return _reference_attribute.getNumDocs();
}
std::unique_ptr<queryeval::SearchIterator>
ImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {
if (_merger.hasArray()) {
if (_merger.emptyArray()) {
return SearchIterator::UP(new EmptySearch());
} else {
using Posting = btree::BTreeKeyData<uint32_t, int32_t>;
using DocIt = DocIdIterator<Posting>;
DocIt postings;
auto array = _merger.getArray();
postings.set(&array[0], &array[array.size()]);
return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);
}
} else if (_merger.hasBitVector()) {
return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);
}
if (!strict) {
return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);
} else {
return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);
}
}
namespace {
struct WeightedRef {
EntryRef revMapIdx;
int32_t weight;
WeightedRef(EntryRef revMapIdx_, int32_t weight_)
: revMapIdx(revMapIdx_),
weight(weight_)
{
}
};
struct TargetWeightedResult {
std::vector<WeightedRef> weightedRefs;
size_t sizeSum;
TargetWeightedResult()
: weightedRefs(),
sizeSum(0)
{}
static TargetWeightedResult
getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit) __attribute__((noinline));
};
class ReverseMappingBitVector
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
public:
ReverseMappingBitVector(const ReverseMapping &reverseMapping, EntryRef revMapIdx)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx)
{}
~ReverseMappingBitVector() { }
template <typename Func>
void foreach_key(Func func) const {
_reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });
}
};
struct TargetResult {
static void
getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit,
PostingListMerger<int32_t> & merger) __attribute__((noinline));
};
TargetWeightedResult
TargetWeightedResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit)
{
TargetWeightedResult targetResult;
fef::TermFieldMatchData matchData;
auto targetItr = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
uint32_t lid = 1;
targetItr->initRange(1, docIdLimit);
while (lid < docIdLimit) {
if (targetItr->seek(lid)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (revMapIdx.valid()) {
uint32_t size = reverseMapping.frozenSize(revMapIdx);
targetResult.sizeSum += size;
targetItr->unpack(lid);
int32_t weight = matchData.getWeight();
targetResult.weightedRefs.emplace_back(revMapIdx, weight);
}
++lid;
} else {
++lid;
uint32_t nextLid = targetItr->getDocId();
if (nextLid > lid) {
lid = nextLid;
}
}
}
return targetResult;
}
void
TargetResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit,
PostingListMerger<int32_t> & merger)
{
fef::TermFieldMatchData matchData;
auto it = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
it->initRange(1, docIdLimit);
for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (__builtin_expect(revMapIdx.valid(), true)) {
merger.addToBitVector(ReverseMappingBitVector(reverseMapping, revMapIdx));
}
}
}
class ReverseMappingPostingList
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
int32_t _weight;
public:
ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx),
_weight(weight)
{}
~ReverseMappingPostingList() { }
template <typename Func>
void foreach(Func func) const {
int32_t weight = _weight;
_reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });
}
};
}
void ImportedSearchContext::makeMergedPostings(bool isFilter)
{
uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();
std::atomic_thread_fence(std::memory_order_acquire);
const auto &reverseMapping = _reference_attribute.getReverseMapping();
if (isFilter) {
_merger.allocBitVector();
TargetResult::getResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context, committedTargetDocIdLimit, _merger);
} else {
TargetWeightedResult targetResult(TargetWeightedResult::getResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context,
committedTargetDocIdLimit));
_merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);
for (const auto &weightedRef : targetResult.weightedRefs) {
_merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));
}
}
_merger.merge();
}
void ImportedSearchContext::fetchPostings(bool strict) {
assert(!_fetchPostingsDone);
_fetchPostingsDone = true;
_target_search_context->fetchPostings(strict);
if (strict || _target_attribute.getConfig().fastSearch()) {
makeMergedPostings(_target_attribute.getConfig().getIsFilter());
}
}
bool ImportedSearchContext::valid() const {
return _target_search_context->valid();
}
Int64Range ImportedSearchContext::getAsIntegerTerm() const {
return _target_search_context->getAsIntegerTerm();
}
const QueryTermBase& ImportedSearchContext::queryTerm() const {
return _target_search_context->queryTerm();
}
const vespalib::string& ImportedSearchContext::attributeName() const {
return _imported_attribute.getName();
}
}
<commit_msg>Simplify the loop.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "imported_search_context.h"
#include "imported_attribute_vector.h"
#include <vespa/searchlib/common/bitvectoriterator.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include "attributeiterators.hpp"
using search::datastore::EntryRef;
using search::queryeval::EmptySearch;
using search::queryeval::SearchIterator;
using search::attribute::ReferenceAttribute;
using search::AttributeVector;
using ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;
using ReverseMapping = ReferenceAttribute::ReverseMapping;
using SearchContext = AttributeVector::SearchContext;
namespace search::attribute {
ImportedSearchContext::ImportedSearchContext(
std::unique_ptr<QueryTermSimple> term,
const SearchContextParams& params,
const ImportedAttributeVector& imported_attribute)
: _imported_attribute(imported_attribute),
_reference_attribute(*_imported_attribute.getReferenceAttribute()),
_target_attribute(*_imported_attribute.getTargetAttribute()),
_target_search_context(_target_attribute.getSearch(std::move(term), params)),
_referencedLids(_reference_attribute.getReferencedLids()),
_referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),
_merger(_reference_attribute.getCommittedDocIdLimit()),
_fetchPostingsDone(false)
{
}
ImportedSearchContext::~ImportedSearchContext() {
}
unsigned int ImportedSearchContext::approximateHits() const {
return _reference_attribute.getNumDocs();
}
std::unique_ptr<queryeval::SearchIterator>
ImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {
if (_merger.hasArray()) {
if (_merger.emptyArray()) {
return SearchIterator::UP(new EmptySearch());
} else {
using Posting = btree::BTreeKeyData<uint32_t, int32_t>;
using DocIt = DocIdIterator<Posting>;
DocIt postings;
auto array = _merger.getArray();
postings.set(&array[0], &array[array.size()]);
return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);
}
} else if (_merger.hasBitVector()) {
return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);
}
if (!strict) {
return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);
} else {
return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);
}
}
namespace {
struct WeightedRef {
EntryRef revMapIdx;
int32_t weight;
WeightedRef(EntryRef revMapIdx_, int32_t weight_)
: revMapIdx(revMapIdx_),
weight(weight_)
{
}
};
struct TargetWeightedResult {
std::vector<WeightedRef> weightedRefs;
size_t sizeSum;
TargetWeightedResult()
: weightedRefs(),
sizeSum(0)
{}
static TargetWeightedResult
getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit) __attribute__((noinline));
};
class ReverseMappingBitVector
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
public:
ReverseMappingBitVector(const ReverseMapping &reverseMapping, EntryRef revMapIdx)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx)
{}
~ReverseMappingBitVector() { }
template <typename Func>
void foreach_key(Func func) const {
_reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });
}
};
struct TargetResult {
static void
getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit,
PostingListMerger<int32_t> & merger) __attribute__((noinline));
};
TargetWeightedResult
TargetWeightedResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit)
{
TargetWeightedResult targetResult;
fef::TermFieldMatchData matchData;
auto it = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
it->initRange(1, docIdLimit);
for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (__builtin_expect(revMapIdx.valid(), true)) {
uint32_t size = reverseMapping.frozenSize(revMapIdx);
targetResult.sizeSum += size;
it->doUnpack(lid);
int32_t weight = matchData.getWeight();
targetResult.weightedRefs.emplace_back(revMapIdx, weight);
}
}
return targetResult;
}
void
TargetResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,
SearchContext &target_search_context, uint32_t committedDocIdLimit,
PostingListMerger<int32_t> & merger)
{
fef::TermFieldMatchData matchData;
auto it = target_search_context.createIterator(&matchData, true);
uint32_t docIdLimit = reverseMappingRefs.size();
if (docIdLimit > committedDocIdLimit) {
docIdLimit = committedDocIdLimit;
}
it->initRange(1, docIdLimit);
for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {
EntryRef revMapIdx = reverseMappingRefs[lid];
if (__builtin_expect(revMapIdx.valid(), true)) {
merger.addToBitVector(ReverseMappingBitVector(reverseMapping, revMapIdx));
}
}
}
class ReverseMappingPostingList
{
const ReverseMapping &_reverseMapping;
EntryRef _revMapIdx;
int32_t _weight;
public:
ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)
: _reverseMapping(reverseMapping),
_revMapIdx(revMapIdx),
_weight(weight)
{}
~ReverseMappingPostingList() { }
template <typename Func>
void foreach(Func func) const {
int32_t weight = _weight;
_reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });
}
};
}
void ImportedSearchContext::makeMergedPostings(bool isFilter)
{
uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();
std::atomic_thread_fence(std::memory_order_acquire);
const auto &reverseMapping = _reference_attribute.getReverseMapping();
if (isFilter) {
_merger.allocBitVector();
TargetResult::getResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context, committedTargetDocIdLimit, _merger);
} else {
TargetWeightedResult targetResult(TargetWeightedResult::getResult(_reference_attribute.getReverseMappingRefs(),
_reference_attribute.getReverseMapping(),
*_target_search_context,
committedTargetDocIdLimit));
_merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);
for (const auto &weightedRef : targetResult.weightedRefs) {
_merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));
}
}
_merger.merge();
}
void ImportedSearchContext::fetchPostings(bool strict) {
assert(!_fetchPostingsDone);
_fetchPostingsDone = true;
_target_search_context->fetchPostings(strict);
if (strict || _target_attribute.getConfig().fastSearch()) {
makeMergedPostings(_target_attribute.getConfig().getIsFilter());
}
}
bool ImportedSearchContext::valid() const {
return _target_search_context->valid();
}
Int64Range ImportedSearchContext::getAsIntegerTerm() const {
return _target_search_context->getAsIntegerTerm();
}
const QueryTermBase& ImportedSearchContext::queryTerm() const {
return _target_search_context->queryTerm();
}
const vespalib::string& ImportedSearchContext::attributeName() const {
return _imported_attribute.getName();
}
}
<|endoftext|>
|
<commit_before>#include "config.h"
#include "vm.hpp"
#include "state.hpp"
#include "memory.hpp"
#include "memory/collector.hpp"
#include "memory/immix.hpp"
#include "memory/third_region.hpp"
#include "memory/tracer.hpp"
#include "logger.hpp"
namespace rubinius {
namespace memory {
void MemoryTracer::trace_heap(STATE) {
heap_->collect_start(state);
heap_->collect_references(state, [this](STATE, Object** obj){
trace_object(state, obj);
});
for(auto i = state->collector()->memory_handles().begin();
i != state->collector()->memory_handles().end();
++i)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
MemoryHandle* handle = header->extended_header()->get_handle();
if(handle->accesses() > 0 || handle->cycles() < 3) {
if(header->object_p()) {
Object* obj = reinterpret_cast<Object*>(header);
trace_object(state, &obj);
// TODO: MemoryHeader set new address
} else if(header->data_p()) {
// DataHeader* data = reinterpret_cast<DataHeader*>(header);
// TODO: process data (not C-API Data) instances
}
} else if(handle->rdata_p()) {
// TODO: GC investigate why we are retaining these
Object* obj = reinterpret_cast<Object*>(header);
trace_object(state, &obj);
// TODO: MemoryHeader set new address
}
handle->cycle();
handle->unset_accesses();
}
trace_mark_stack(state);
state->memory()->collector()->trace_finalizers(state, this);
trace_mark_stack(state);
for(auto i = state->collector()->references().begin();
i != state->collector()->references().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(header->referenced() == 0) {
i = state->collector()->references().erase(i);
} else {
++i;
}
}
for(auto i = state->collector()->memory_handles().begin();
i != state->collector()->memory_handles().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(!header->marked_p(state->memory()->mark())) {
MemoryHeader* h = *i;
delete h->extended_header()->get_handle();
i = state->collector()->memory_handles().erase(i);
} else {
++i;
}
}
for(auto i = state->collector()->weakrefs().begin();
i != state->collector()->weakrefs().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(!header->marked_p(state->memory()->mark())) {
i = state->collector()->weakrefs().erase(i);
} else {
Object* obj = reinterpret_cast<Object*>(header);
TypeInfo* ti = state->memory()->type_info[obj->type_id()];
ti->update_weakref(state, obj);
++i;
}
}
heap_->collect_finish(state);
logger::info("memory tracer: max recursion: %ld, max mark stack size: %ld",
max_recursion_, max_mark_stack_size_);
}
void MemoryTracer::trace_mark_stack(STATE) {
while(!mark_stack_.empty()) {
Object* obj = mark_stack_.get();
trace_object(state, &obj);
}
}
void MemoryTracer::mark_object_region(STATE, Object** obj) {
Object* object = *obj;
switch(object->region()) {
case eThreadRegion:
// TODO: GC
break;
case eFirstRegion: {
Object* copy = state->memory()->main_heap()->first_region()->mark_address_of_object(
state, nullptr, object, state->memory()->main_heap()->first_region()->allocator());
if(copy != object) *obj = copy;
break;
}
case eSecondRegion:
// TODO: GC
break;
case eThirdRegion:
// Do nothing
break;
}
}
void MemoryTracer::trace_object(STATE, Object** obj, size_t recursion_count) {
Object* object = *obj;
if(!object || !object->reference_p()) return;
if(object->marked_p(state->memory()->mark())) {
if(object->scanned_p()) return;
} else {
mark_object_region(state, obj);
object->set_marked(state->memory()->mark());
object->unsynchronized_unset_scanned();
}
if(state->vm()->stack_limit_p(&object)) {
mark_stack_.add(0, object);
if(mark_stack_.size() > max_mark_stack_size_) {
max_mark_stack_size_ = mark_stack_.size();
}
return;
}
object->unsynchronized_set_scanned();
recursion_count++;
if(recursion_count > max_recursion_) {
max_recursion_ = recursion_count;
}
trace_object(state, object->p_klass(), recursion_count);
trace_object(state, object->p_ivars(), recursion_count);
TypeInfo* ti = state->memory()->type_info[object->type_id()];
ti->mark(state, object, [&](STATE, Object** obj){
trace_object(state, obj, recursion_count);
});
}
}
}
<commit_msg>Use unsynchronized set during GC.<commit_after>#include "config.h"
#include "vm.hpp"
#include "state.hpp"
#include "memory.hpp"
#include "memory/collector.hpp"
#include "memory/immix.hpp"
#include "memory/third_region.hpp"
#include "memory/tracer.hpp"
#include "logger.hpp"
namespace rubinius {
namespace memory {
void MemoryTracer::trace_heap(STATE) {
heap_->collect_start(state);
heap_->collect_references(state, [this](STATE, Object** obj){
trace_object(state, obj);
});
for(auto i = state->collector()->memory_handles().begin();
i != state->collector()->memory_handles().end();
++i)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
MemoryHandle* handle = header->extended_header()->get_handle();
if(handle->accesses() > 0 || handle->cycles() < 3) {
if(header->object_p()) {
Object* obj = reinterpret_cast<Object*>(header);
trace_object(state, &obj);
// TODO: MemoryHeader set new address
} else if(header->data_p()) {
// DataHeader* data = reinterpret_cast<DataHeader*>(header);
// TODO: process data (not C-API Data) instances
}
} else if(handle->rdata_p()) {
// TODO: GC investigate why we are retaining these
Object* obj = reinterpret_cast<Object*>(header);
trace_object(state, &obj);
// TODO: MemoryHeader set new address
}
handle->cycle();
handle->unset_accesses();
}
trace_mark_stack(state);
state->memory()->collector()->trace_finalizers(state, this);
trace_mark_stack(state);
for(auto i = state->collector()->references().begin();
i != state->collector()->references().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(header->referenced() == 0) {
i = state->collector()->references().erase(i);
} else {
++i;
}
}
for(auto i = state->collector()->memory_handles().begin();
i != state->collector()->memory_handles().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(!header->marked_p(state->memory()->mark())) {
MemoryHeader* h = *i;
delete h->extended_header()->get_handle();
i = state->collector()->memory_handles().erase(i);
} else {
++i;
}
}
for(auto i = state->collector()->weakrefs().begin();
i != state->collector()->weakrefs().end();)
{
MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);
if(!header->marked_p(state->memory()->mark())) {
i = state->collector()->weakrefs().erase(i);
} else {
Object* obj = reinterpret_cast<Object*>(header);
TypeInfo* ti = state->memory()->type_info[obj->type_id()];
ti->update_weakref(state, obj);
++i;
}
}
heap_->collect_finish(state);
logger::info("memory tracer: max recursion: %ld, max mark stack size: %ld",
max_recursion_, max_mark_stack_size_);
}
void MemoryTracer::trace_mark_stack(STATE) {
while(!mark_stack_.empty()) {
Object* obj = mark_stack_.get();
trace_object(state, &obj);
}
}
void MemoryTracer::mark_object_region(STATE, Object** obj) {
Object* object = *obj;
switch(object->region()) {
case eThreadRegion:
// TODO: GC
break;
case eFirstRegion: {
Object* copy = state->memory()->main_heap()->first_region()->mark_address_of_object(
state, nullptr, object, state->memory()->main_heap()->first_region()->allocator());
if(copy != object) *obj = copy;
break;
}
case eSecondRegion:
// TODO: GC
break;
case eThirdRegion:
// Do nothing
break;
}
}
void MemoryTracer::trace_object(STATE, Object** obj, size_t recursion_count) {
Object* object = *obj;
if(!object || !object->reference_p()) return;
if(object->marked_p(state->memory()->mark())) {
if(object->scanned_p()) return;
} else {
mark_object_region(state, obj);
object->unsynchronized_set_marked(state->memory()->mark());
object->unsynchronized_unset_scanned();
}
if(state->vm()->stack_limit_p(&object)) {
mark_stack_.add(0, object);
if(mark_stack_.size() > max_mark_stack_size_) {
max_mark_stack_size_ = mark_stack_.size();
}
return;
}
object->unsynchronized_set_scanned();
recursion_count++;
if(recursion_count > max_recursion_) {
max_recursion_ = recursion_count;
}
trace_object(state, object->p_klass(), recursion_count);
trace_object(state, object->p_ivars(), recursion_count);
TypeInfo* ti = state->memory()->type_info[object->type_id()];
ti->mark(state, object, [&](STATE, Object** obj){
trace_object(state, obj, recursion_count);
});
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cctype>
#include "compiler/expression/ftnode.h"
#include "util/stl_util.h"
#include "ft_stop_words_set.h"
#include "ft_token_matcher.h"
#include "ft_util.h"
#include "ft_wildcard.h"
using namespace std;
using namespace zorba::locale;
namespace zorba {
///////////////////////////////////////////////////////////////////////////////
inline bool get_diacritics_insensitive( ftmatch_options const &options ) {
if ( ftdiacritics_option const *const d = options.get_diacritics_option() )
return d->get_mode() == ft_diacritics_mode::insensitive;
return false;
}
inline bool get_stemming( ftmatch_options const &options ) {
if ( ftstem_option const *const s = options.get_stem_option() )
return s->get_mode() == ft_stem_mode::with;
return false;
}
inline ft_stop_words_set const* get_stop_words( ftmatch_options const &options,
iso639_1::type lang ) {
if ( ftstop_word_option const *const sw = options.get_stop_word_option() )
return ft_stop_words_set::construct( *sw, lang );
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
ft_token_matcher::ft_token_matcher( ftmatch_options const &options ) :
case_option_( options.get_case_option() ),
diacritics_insensitive_( get_diacritics_insensitive( options ) ),
lang_( get_lang_from( &options ) ),
stemming_( get_stemming( options ) ),
stop_words_( get_stop_words( options, lang_ ) ),
wildcards_( get_wildcards_from( &options ) )
{
}
ft_token_matcher::~ft_token_matcher() {
delete stop_words_;
}
///////////////////////////////////////////////////////////////////////////////
bool ft_token_matcher::match( FTToken const &dt, FTToken const &qt ) const {
int dt_selector = FTToken::original;
int qt_selector = FTToken::original;
if ( stop_words_ ) {
//
// Perform stop-word comparison early so as not to waste time doing the
// stuff below for stop-words.
//
// Perform stop-word comparison case-insensitively. Note, however, that
// the XQuery Full Text spec currently isn't clear on whether this should
// be done case-insensitively. See W3C Bug 9858.
//
if ( stop_words_->contains( qt.value( FTToken::lower ) ) )
return true;
}
if ( case_option_ ) {
switch ( case_option_->get_mode() ) {
case ft_case_mode::insensitive:
dt_selector |= FTToken::lower;
qt_selector |= FTToken::lower;
break;
case ft_case_mode::sensitive:
// do nothing
break;
case ft_case_mode::lower:
qt_selector |= FTToken::lower;
break;
case ft_case_mode::upper:
qt_selector |= FTToken::upper;
break;
}
}
if ( stemming_ ) {
dt_selector |= FTToken::stem;
qt_selector |= FTToken::stem;
}
if ( diacritics_insensitive_ ) {
dt_selector |= FTToken::ascii;
qt_selector |= FTToken::ascii;
}
if ( wildcards_ ) {
return dt.value( dt_selector ) == qt.wildcard( qt_selector );
}
return dt.value( dt_selector, lang_ ) == qt.value( qt_selector, lang_ );
}
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Comment clarification.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cctype>
#include "compiler/expression/ftnode.h"
#include "util/stl_util.h"
#include "ft_stop_words_set.h"
#include "ft_token_matcher.h"
#include "ft_util.h"
#include "ft_wildcard.h"
using namespace std;
using namespace zorba::locale;
namespace zorba {
///////////////////////////////////////////////////////////////////////////////
inline bool get_diacritics_insensitive( ftmatch_options const &options ) {
if ( ftdiacritics_option const *const d = options.get_diacritics_option() )
return d->get_mode() == ft_diacritics_mode::insensitive;
return false;
}
inline bool get_stemming( ftmatch_options const &options ) {
if ( ftstem_option const *const s = options.get_stem_option() )
return s->get_mode() == ft_stem_mode::with;
return false;
}
inline ft_stop_words_set const* get_stop_words( ftmatch_options const &options,
iso639_1::type lang ) {
if ( ftstop_word_option const *const sw = options.get_stop_word_option() )
return ft_stop_words_set::construct( *sw, lang );
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
ft_token_matcher::ft_token_matcher( ftmatch_options const &options ) :
case_option_( options.get_case_option() ),
diacritics_insensitive_( get_diacritics_insensitive( options ) ),
lang_( get_lang_from( &options ) ),
stemming_( get_stemming( options ) ),
stop_words_( get_stop_words( options, lang_ ) ),
wildcards_( get_wildcards_from( &options ) )
{
}
ft_token_matcher::~ft_token_matcher() {
delete stop_words_;
}
///////////////////////////////////////////////////////////////////////////////
bool ft_token_matcher::match( FTToken const &dt, FTToken const &qt ) const {
int dt_selector = FTToken::original;
int qt_selector = FTToken::original;
if ( stop_words_ ) {
//
// Perform stop-word comparison early so as not to waste time doing the
// stuff below for stop-words.
//
// Perform stop-word comparison case-insensitively. Note, however, that
// the XQuery Full Text spec currently isn't clear on whether this should
// be done case-insensitively.
//
// See also: http://www.w3.org/Bugs/Public/show_bug.cgi?id=9858
//
if ( stop_words_->contains( qt.value( FTToken::lower ) ) )
return true;
}
if ( case_option_ ) {
switch ( case_option_->get_mode() ) {
case ft_case_mode::insensitive:
dt_selector |= FTToken::lower;
qt_selector |= FTToken::lower;
break;
case ft_case_mode::sensitive:
// do nothing
break;
case ft_case_mode::lower:
qt_selector |= FTToken::lower;
break;
case ft_case_mode::upper:
qt_selector |= FTToken::upper;
break;
}
}
if ( stemming_ ) {
dt_selector |= FTToken::stem;
qt_selector |= FTToken::stem;
}
if ( diacritics_insensitive_ ) {
dt_selector |= FTToken::ascii;
qt_selector |= FTToken::ascii;
}
if ( wildcards_ ) {
return dt.value( dt_selector ) == qt.wildcard( qt_selector );
}
return dt.value( dt_selector, lang_ ) == qt.value( qt_selector, lang_ );
}
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <numa.h>
#include "raw_data_array.h"
namespace fm
{
namespace detail
{
namespace
{
class deleter
{
size_t size;
public:
deleter(size_t size) {
this->size = size;
}
void operator()(char *addr) {
numa_free(addr, size);
}
};
}
raw_data_array::raw_data_array(size_t num_bytes, int node_id)
{
this->num_bytes = num_bytes;
void *addr = numa_alloc_onnode(num_bytes, node_id);
data = std::shared_ptr<char>((char *) addr, deleter(num_bytes));
start = data.get();
num_used_bytes = num_bytes;
}
}
}
<commit_msg>[Matrix]: fix a bug in raw_data_array.<commit_after>/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng (zhengda1936@gmail.com)
*
* This file is part of FlashMatrix.
*
* 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 <numa.h>
#include "raw_data_array.h"
namespace fm
{
namespace detail
{
namespace
{
class deleter
{
size_t size;
public:
deleter(size_t size) {
this->size = size;
}
void operator()(char *addr) {
numa_free(addr, size);
}
};
}
raw_data_array::raw_data_array(size_t num_bytes, int node_id)
{
this->node_id = node_id;
this->num_bytes = num_bytes;
void *addr = numa_alloc_onnode(num_bytes, node_id);
data = std::shared_ptr<char>((char *) addr, deleter(num_bytes));
start = data.get();
num_used_bytes = num_bytes;
}
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/shared/exp_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file explorer_check_for_ready.H
/// @brief explorer_check_for_ready HWP declaration
///
// *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: CI
#ifndef EXP_CONSTS_H
#define EXP_CONSTS_H
namespace mss
{
namespace exp
{
constexpr uint32_t OCMB_ADDR_SHIFT = 3;
///
/// @brief explorer ffdc codes
///
enum ffdc_codes
{
EXP_I2C_GET_FIELD = 0x0000,
EXP_I2C_SET_FIELD = 0x0001,
READ_HOST_FW_RESPONSE_STRUCT = 0x0003,
READ_SENSOR_CACHE_STRUCT = 0x0004,
};
namespace i2c
{
/// @brief List of explorer I2C commands
///
enum cmd_id : uint8_t
{
FW_BOOT_CONFIG = 0x01,
FW_STATUS = 0x02,
FW_REG_ADDR_LATCH = 0x03,
FW_REG_READ = 0x04,
FW_REG_WRITE = 0x05,
FW_DOWNLOAD = 0x06,
FW_CONT_REG_READ = 0x07,
FW_CONT_REG_WRITE = 0x08,
};
///
/// @brief common explorer sizes
///
enum sizes
{
// 32-bit commands
FW_BOOT_CONFIG_BYTE_LEN = 4,
FW_STATUS_BYTE_LEN = 4,
FW_WRITE_REG_DATA_SIZE = 0x08,
FW_REG_ADDR_LATCH_SIZE = 0x04,
FW_I2C_SCOM_READ_SIZE = 0x05,
// Largest R/W length for bytes of data
MIN_DATA_BYTES_LEN = 1,
MAX_DATA_BYTES_LEN = 32,
};
///
/// @brief General I2C status codes
/// @note Shared I2C status codes for EXP_FW_REG_READ, EXP_FW_REG_WRITE,
/// EXP_FW_CONT_REG_READ, and EXP_FW_CONT_REG_WRITE
///
enum status_codes
{
SUCCESS = 0x00,
ADDRESS_OUT_OF_RANGE = 0x01,
ADDRESS_PROHIBITED = 0x02,
};
///
/// @brief status codes for FW_BOOT_CONFIG
///
enum fw_boot_cfg_status
{
FW_BOOT_CFG_SUCCESS = status_codes::SUCCESS,
// Loopback fail
FW_BOOT_CFG_LB_FAIL = 0x01,
// Transport layer fail
FW_BOOT_CFG_UNSUPPORTED_TL = 0x02,
// DL (data link) layer fail
FW_BOOT_CFG_UNSUPPORTED_DL = 0x03,
// SERDES (serializer/deserializer) FREQ fail
FW_BOOT_CFG_UNSUPPORTED_SERDES_FREQ = 0x04,
};
///
/// @brief I2C boot stage options
/// @note certain cmds work in certain boot stages
///
enum boot_stages
{
BOOT_ROM_STAGE = 0x01,
FW_UPGRADE_MODE = 0x02,
RUNTIME_FW = 0x03,
};
///
/// @brief Useful constants for i2c scom functionality
///
/// @note FIRST_BYTE_MASK = allows us to mask off first by of
/// an address to check if its an IBM SCOM
/// LAST_THREE_BYTES_MASK = used as part of formula to translate
/// a given address to an IBM scom address
/// OCBM_UNCACHED_OFFSET = Also used as part of formula for translating
/// a given address to the correct IBM or microchip form
/// IBM_SCOM_OFFSET_LHS and IBM_SCOM_OFFSET_RHS are used in formula
/// for calculating IBM scom address for left and right side of addr
/// IBM_SCOM_INDICATOR is the indicator bit in the first byte of an
/// address that tells us if it is a IBM scom or not
///
enum i2c_scom_consts : uint32_t
{
FIRST_BYTE_MASK = 0xFF000000,
LAST_THREE_BYTES_MASK = 0x00FFFFFF,
OCMB_UNCACHED_OFFSET = 0xA0000000,
IBM_SCOM_OFFSET_LHS = 0x08000000,
IBM_SCOM_OFFSET_RHS = 0x08000004,
IBM_SCOM_INDICATOR = IBM_SCOM_OFFSET_LHS,
};
///
/// @brief Simple enum allows code to pick between left and right
///
/// This is used when deciding if we are writing/reading from left
/// side of IBM address or right side. This is needed because IBM
/// scoms are 64 bits while the OCMB only has 32 bit regs.
enum addrSide
{
LHS = 0x00,
RHS = 0x01
};
}// i2c
}// exp
}// mss
#endif
<commit_msg>Add exp_draminit and fix data_structs constants<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/shared/exp_consts.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file explorer_check_for_ready.H
/// @brief explorer_check_for_ready HWP declaration
///
// *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: CI
#ifndef EXP_CONSTS_H
#define EXP_CONSTS_H
namespace mss
{
namespace exp
{
constexpr uint32_t OCMB_ADDR_SHIFT = 3;
///
/// @brief explorer ffdc codes
///
enum ffdc_codes
{
EXP_I2C_GET_FIELD = 0x0000,
EXP_I2C_SET_FIELD = 0x0001,
READ_HOST_FW_RESPONSE_STRUCT = 0x0003,
READ_SENSOR_CACHE_STRUCT = 0x0004,
};
namespace i2c
{
/// @brief List of explorer I2C commands
///
enum cmd_id : uint8_t
{
FW_BOOT_CONFIG = 0x01,
FW_STATUS = 0x02,
FW_REG_ADDR_LATCH = 0x03,
FW_REG_READ = 0x04,
FW_REG_WRITE = 0x05,
FW_DOWNLOAD = 0x06,
FW_CONT_REG_READ = 0x07,
FW_CONT_REG_WRITE = 0x08,
};
///
/// @brief common explorer sizes
///
enum sizes
{
// 32-bit commands
FW_BOOT_CONFIG_BYTE_LEN = 4,
FW_STATUS_BYTE_LEN = 4,
FW_WRITE_REG_DATA_SIZE = 0x08,
FW_REG_ADDR_LATCH_SIZE = 0x04,
FW_I2C_SCOM_READ_SIZE = 0x05,
// Largest R/W length for bytes of data
MIN_DATA_BYTES_LEN = 1,
MAX_DATA_BYTES_LEN = 32,
};
///
/// @brief General I2C status codes
/// @note Shared I2C status codes for EXP_FW_REG_READ, EXP_FW_REG_WRITE,
/// EXP_FW_CONT_REG_READ, and EXP_FW_CONT_REG_WRITE
///
enum status_codes
{
SUCCESS = 0x00,
ADDRESS_OUT_OF_RANGE = 0x01,
ADDRESS_PROHIBITED = 0x02,
};
///
/// @brief status codes for FW_BOOT_CONFIG
///
enum fw_boot_cfg_status
{
FW_BOOT_CFG_SUCCESS = status_codes::SUCCESS,
// Loopback fail
FW_BOOT_CFG_LB_FAIL = 0x01,
// Transport layer fail
FW_BOOT_CFG_UNSUPPORTED_TL = 0x02,
// DL (data link) layer fail
FW_BOOT_CFG_UNSUPPORTED_DL = 0x03,
// SERDES (serializer/deserializer) FREQ fail
FW_BOOT_CFG_UNSUPPORTED_SERDES_FREQ = 0x04,
};
///
/// @brief I2C boot stage options
/// @note certain cmds work in certain boot stages
///
enum boot_stages
{
BOOT_ROM_STAGE = 0x01,
FW_UPGRADE_MODE = 0x02,
RUNTIME_FW = 0x03,
};
///
/// @brief Useful constants for i2c scom functionality
///
/// @note FIRST_BYTE_MASK = allows us to mask off first by of
/// an address to check if its an IBM SCOM
/// LAST_THREE_BYTES_MASK = used as part of formula to translate
/// a given address to an IBM scom address
/// OCBM_UNCACHED_OFFSET = Also used as part of formula for translating
/// a given address to the correct IBM or microchip form
/// IBM_SCOM_OFFSET_LHS and IBM_SCOM_OFFSET_RHS are used in formula
/// for calculating IBM scom address for left and right side of addr
/// IBM_SCOM_INDICATOR is the indicator bit in the first byte of an
/// address that tells us if it is a IBM scom or not
///
enum i2c_scom_consts : uint32_t
{
FIRST_BYTE_MASK = 0xFF000000,
LAST_THREE_BYTES_MASK = 0x00FFFFFF,
OCMB_UNCACHED_OFFSET = 0xA0000000,
IBM_SCOM_OFFSET_LHS = 0x08000000,
IBM_SCOM_OFFSET_RHS = 0x08000004,
IBM_SCOM_INDICATOR = IBM_SCOM_OFFSET_LHS,
};
///
/// @brief Simple enum allows code to pick between left and right
///
/// This is used when deciding if we are writing/reading from left
/// side of IBM address or right side. This is needed because IBM
/// scoms are 64 bits while the OCMB only has 32 bit regs.
enum addrSide
{
LHS = 0x00,
RHS = 0x01
};
}// i2c
namespace omi
{
///
/// @brief HOST-FW Commands and Responses
///
enum cmd_and_response_id
{
FW_DDR_INTERFACE_INIT = 0x01,
FW_TEMP_SENSOR_INIT = 0x02,
FW_ERR_LOGGING_INTERFACE_INIT = 0x03,
FW_GO_COMMAND = 0x04,
FW_ADAPTER_PROPERTIES_GET = 0x05,
FW_STATUS_GET = 0x06,
FW_TEMPERATURE_GET = 0x07,
FW_ERROR_LOG_GET = 0x08,
FW_SPD_DATA_SET = 0x09,
FW_BINARY_UPGRADE = 0x0A,
FW_FLASH_LOADER_VERSION_INFO = 0x0B,
};
///
/// @brief Response argument parameters
///
enum response_arg
{
SUCCESS = 0,
ERROR_CODE = 1,
};
}// omi
}// exp
}// mss
#endif
<|endoftext|>
|
<commit_before>class BlockArray {
// double complex data[zblock=0..NB-1][yblock=0..NB-1]
// [arr=0..1][zresidual=0..P-1][yresidual=0..P-1][x=0..PPD-1]
unsigned long long size;
Complx *arr; // But this array may never be allocated!
public:
int ppd, numblock, block;
long long unsigned int narray; // Make uint64 to avoid overflow in later calculations
char TMPDIR[1024];
int ramdisk;
BlockArray(int _ppd, int _numblock, int _narray, char *_dir, int ramdisk) {
ppd = _ppd;
numblock = _numblock;
block = ppd/numblock;
narray = _narray;
strcpy(TMPDIR,_dir);
arr = NULL;
assert(ppd%2==0); // PPD must be even, due to incomplete Nyquist code
assert(numblock%2==0); // Number of blocks must be even
assert(ppd==numblock*block); // We'd like the blocks to divide evenly
size = 1llu*ppd*ppd*ppd*narray;
#ifndef DISK
arr = new Complx[size];
#elif defined DIRECTIO
fileoffset = 0;
diskbuffer = 1024*512; // Magic number pulled from io_dio.cpp
ramdisk = 0;
#endif
}
~BlockArray() {
delete []arr;
}
// Complx *point(int a, int z, int y, int x) {
// // Return a pointer to this part of the buffer
// int zblock = z/block;
// int yblock = y/block;
// return arr+x+ppd*(y-block*yblock+block*(z-block*zblock+block*(a+narray*(yblock+numblock*zblock))));
// }
#ifdef DISK
#ifdef DIRECTIO
// These routines are for DIRECTIO
private:
char filename[200];
off_t fileoffset;
int diskbuffer;
public:
void bopen(int yblock, int zblock, const char *mode) {
// DirectIO actually opens and closes the files on demand, so we don't need to open the file here
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
sprintf(filename,"%s/zeldovich.%1d.%1d",TMPDIR,yblock,zblock);
FILE * outfile = fopen(filename,"a");
assert(outfile != NULL);
fclose(outfile);
fileoffset = 0; // We're opening a new file, so reset the file offset
return;
}
void bclose() { return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
WriteDirect WD(ramdisk, diskbuffer);
int sizebytes = num*sizeof(Complx);
WD.BlockingAppend(filename, (char*)buffer, sizebytes);
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
ReadDirect RD(ramdisk, diskbuffer);
size_t sizebytes = num*sizeof(Complx);
RD.BlockingRead( filename, (char*)buffer, sizebytes, fileoffset);
fileoffset += sizebytes;
}
#else
// These routines are for reading blocks on and off disk
private:
FILE *fp;
public:
void bopen(int yblock, int zblock, const char *mode) {
// Set up for reading or writing this block
char filename[200];
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
sprintf(filename,"%s/zeldovich.%1d.%1d",TMPDIR,yblock,zblock);
fp = fopen(filename,mode);
if(fp ==NULL) printf("bad filename: %s",filename);
assert(fp!=NULL);
return;
}
void bclose() { fclose(fp); return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
fwrite(buffer,sizeof(Complx),num,fp);
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
fread(buffer,sizeof(Complx),num,fp);
}
#endif
#else
// These routines are for reading in and out of a big array in memory
private:
Complx *IOptr;
public:
void bopen(int yblock, int zblock, const char *mode) {
// Set up for reading or writing this block
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
IOptr = arr+(zblock*numblock+yblock)*(block*block*ppd*narray);
return;
}
void bclose() { IOptr = NULL; return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
memcpy(IOptr,buffer,sizeof(Complx)*num); IOptr+=num;
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
memcpy(buffer,IOptr,sizeof(Complx)*num); IOptr+=num;
}
#endif
};<commit_msg>Clean up tmp files<commit_after>class BlockArray {
// double complex data[zblock=0..NB-1][yblock=0..NB-1]
// [arr=0..1][zresidual=0..P-1][yresidual=0..P-1][x=0..PPD-1]
unsigned long long size;
Complx *arr; // But this array may never be allocated!
public:
int ppd, numblock, block;
long long unsigned int narray; // Make uint64 to avoid overflow in later calculations
char TMPDIR[1024];
int ramdisk;
BlockArray(int _ppd, int _numblock, int _narray, char *_dir, int ramdisk) {
ppd = _ppd;
numblock = _numblock;
block = ppd/numblock;
narray = _narray;
strcpy(TMPDIR,_dir);
arr = NULL;
assert(ppd%2==0); // PPD must be even, due to incomplete Nyquist code
assert(numblock%2==0); // Number of blocks must be even
assert(ppd==numblock*block); // We'd like the blocks to divide evenly
size = 1llu*ppd*ppd*ppd*narray;
#ifndef DISK
arr = new Complx[size];
#elif defined DIRECTIO
fileoffset = 0;
diskbuffer = 1024*512; // Magic number pulled from io_dio.cpp
ramdisk = 0;
#endif
}
~BlockArray() {
#ifdef DISK
// Clean up the "zeldovich.*.*" files
for(int yblock = 0; yblock < numblock; yblock++){
for(int zblock = 0; zblock < numblock; zblock++){
sprintf(filename,"%s/zeldovich.%1d.%1d",TMPDIR,yblock,zblock);
remove(filename);
}
}
#else
delete []arr;
#endif
}
// Complx *point(int a, int z, int y, int x) {
// // Return a pointer to this part of the buffer
// int zblock = z/block;
// int yblock = y/block;
// return arr+x+ppd*(y-block*yblock+block*(z-block*zblock+block*(a+narray*(yblock+numblock*zblock))));
// }
#ifdef DISK
#ifdef DIRECTIO
// These routines are for DIRECTIO
private:
char filename[1024];
off_t fileoffset;
int diskbuffer;
public:
void bopen(int yblock, int zblock, const char *mode) {
// DirectIO actually opens and closes the files on demand, so we don't need to open the file here
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
sprintf(filename,"%s/zeldovich.%1d.%1d",TMPDIR,yblock,zblock);
FILE * outfile = fopen(filename,"a");
assert(outfile != NULL);
fclose(outfile);
fileoffset = 0; // We're opening a new file, so reset the file offset
return;
}
void bclose() { return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
WriteDirect WD(ramdisk, diskbuffer);
int sizebytes = num*sizeof(Complx);
WD.BlockingAppend(filename, (char*)buffer, sizebytes);
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
ReadDirect RD(ramdisk, diskbuffer);
size_t sizebytes = num*sizeof(Complx);
RD.BlockingRead( filename, (char*)buffer, sizebytes, fileoffset);
fileoffset += sizebytes;
}
#else
// These routines are for reading blocks on and off disk
private:
FILE *fp;
char filename[1024];
public:
void bopen(int yblock, int zblock, const char *mode) {
// Set up for reading or writing this block
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
sprintf(filename,"%s/zeldovich.%1d.%1d",TMPDIR,yblock,zblock);
fp = fopen(filename,mode);
if(fp == NULL) printf("bad filename: %s",filename);
assert(fp!=NULL);
return;
}
void bclose() { fclose(fp); return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
fwrite(buffer,sizeof(Complx),num,fp);
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
fread(buffer,sizeof(Complx),num,fp);
}
#endif
#else
// These routines are for reading in and out of a big array in memory
private:
Complx *IOptr;
public:
void bopen(int yblock, int zblock, const char *mode) {
// Set up for reading or writing this block
assert(yblock>=0&&yblock<numblock);
assert(zblock>=0&&zblock<numblock);
IOptr = arr+(zblock*numblock+yblock)*(block*block*ppd*narray);
return;
}
void bclose() { IOptr = NULL; return; }
void bwrite(Complx *buffer,int num) {
// Write num Complx numbers to the buffer, increment the pointer
memcpy(IOptr,buffer,sizeof(Complx)*num); IOptr+=num;
}
void bread(Complx *buffer,int num) {
// Read num Complx numbers into the buffer, increment the pointer
memcpy(buffer,IOptr,sizeof(Complx)*num); IOptr+=num;
}
#endif
};<|endoftext|>
|
<commit_before>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量
typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
struct SqStack
{
SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL
SElemType *top; // 栈顶指针
int stacksize; // 当前已分配的存储空间,以元素为单位
Status InitStack()
{
// 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE
// 请补全代码
base=malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
if(base=NULL)return ERROR;
top=base+1;
stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SElemType e)
{
// 在栈S中插入元素e为新的栈顶元素
// 请补全代码
if(top-base>=stacksize){
base=remalloc(base,(stacksize+STACKINCREMENT)*sizeof(Element));
if(base==NULL){
return ERROR;
}
}else{
*top=e;
top++;
}
return OK;
}
Status Pop(SElemType &e)
{
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(--top);
return OK;
}
Status GetTop(SElemType &e)
{
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(top-1);
return OK;
}
int StackLength()
{
// 返回栈S的元素个数
// 请补全代码
return top-base-1;
}
Status StackTraverse(SqStack S)
{
// 从栈顶到栈底依次输出栈中的每个元素
SElemType *p = (SElemType *)malloc(sizeof(SElemType));
p = *top; //请填空
if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
else
{
printf("The Stack is: ");
p--;
while(p-base>1) //请填空
{
printf("%d ", *p);
p--; //请填空
}
}
printf("\n");
return OK;
}
}; // 顺序栈
int main()
{
int a;
SqStack S;
SElemType x, e;
if(S.InitStack()) // 判断顺序表是否创建成功,请填空
{
printf("A Stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d", &x);
if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空
else printf("The Element %d is Successfully Pushed!\n", x);
break;
case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空
else printf("The Element %d is Successfully Poped!\n", e);
break;
case 3: if(S.top(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空
else printf("The Top Element is %d!\n", e);
break;
case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
break;
case 5: S.StackTraverse() //请填空
break;
case 0: return 1;
}
}
}<commit_msg>update uoj8583<commit_after>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量
typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
struct SqStack
{
SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL
SElemType *top; // 栈顶指针
int stacksize; // 当前已分配的存储空间,以元素为单位
Status InitStack()
{
// 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE
// 请补全代码
base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
if(base=NULL)return ERROR;
top=base+1;
stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SElemType e)
{
// 在栈S中插入元素e为新的栈顶元素
// 请补全代码
if(top-base>=stacksize){
base=realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElement));
if(base==NULL){
return ERROR;
}
}else{
*top=e;
top++;
}
return OK;
}
Status Pop(SElemType &e)
{
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(--top);
return OK;
}
Status GetTop(SElemType &e)
{
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(top-1);
return OK;
}
int StackLength()
{
// 返回栈S的元素个数
// 请补全代码
return top-base-1;
}
Status StackTraverse(SqStack S)
{
// 从栈顶到栈底依次输出栈中的每个元素
SElemType *p = (SElemType *)malloc(sizeof(SElemType));
p = *top; //请填空
if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
else
{
printf("The Stack is: ");
p--;
while(p-base>1) //请填空
{
printf("%d ", *p);
p--; //请填空
}
}
printf("\n");
return OK;
}
}; // 顺序栈
int main()
{
int a;
SqStack S;
SElemType x, e;
if(S.InitStack()) // 判断顺序表是否创建成功,请填空
{
printf("A Stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d", &x);
if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空
else printf("The Element %d is Successfully Pushed!\n", x);
break;
case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空
else printf("The Element %d is Successfully Poped!\n", e);
break;
case 3: if(S.top(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空
else printf("The Top Element is %d!\n", e);
break;
case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
break;
case 5: S.StackTraverse() //请填空
break;
case 0: return 1;
}
}
}<|endoftext|>
|
<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "wfa/panelmatch/client/privatemembership/decrypt_query_results.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common_cpp/macros/macros.h"
#include "google/protobuf/repeated_field.h"
#include "private_membership/rlwe/batch/cpp/client/client.h"
#include "private_membership/rlwe/batch/proto/client.pb.h"
#include "private_membership/rlwe/batch/proto/shared.pb.h"
#include "wfa/panelmatch/client/exchangetasks/join_key.pb.h"
#include "wfa/panelmatch/client/privatemembership/event_data_decryptor.h"
#include "wfa/panelmatch/client/privatemembership/query.pb.h"
#include "wfa/panelmatch/common/compression/compressor.h"
#include "wfa/panelmatch/common/compression/make_compressor.h"
namespace wfa::panelmatch::client::privatemembership {
namespace {
using ClientEncryptedQueryResult =
::private_membership::batch::EncryptedQueryResult;
using ClientDecryptedQueryResult =
::private_membership::batch::DecryptedQueryResult;
using ClientDecryptQueriesRequest =
::private_membership::batch::DecryptQueriesRequest;
using ClientDecryptQueriesResponse =
::private_membership::batch::DecryptQueriesResponse;
using ::private_membership::batch::DecryptQueries;
absl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(
const DecryptQueryResultsRequest& request) {
ClientDecryptQueriesRequest client_decrypt_queries_request;
client_decrypt_queries_request.mutable_parameters()->ParseFromString(
request.serialized_parameters());
client_decrypt_queries_request.mutable_private_key()->ParseFromString(
request.serialized_private_key());
client_decrypt_queries_request.mutable_public_key()->ParseFromString(
request.serialized_public_key());
for (const EncryptedQueryResult& encrypted_query_result :
request.encrypted_query_results()) {
client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(
encrypted_query_result.serialized_encrypted_query_result());
}
return DecryptQueries(client_decrypt_queries_request);
}
absl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(
const ClientDecryptedQueryResult& client_decrypted_query_result,
const std::string& lookup_key, const std::string& hkdf_pepper) {
DecryptEventDataRequest decrypt_event_data_request;
decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);
decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);
EncryptedEventData encrypted_event_data;
encrypted_event_data.ParseFromString(client_decrypted_query_result.result());
decrypt_event_data_request.mutable_encrypted_event_data_set()
->mutable_query_id()
->set_id(client_decrypted_query_result.query_metadata().query_id());
*decrypt_event_data_request.mutable_encrypted_event_data_set()
->mutable_encrypted_event_data()
->mutable_ciphertexts() =
*std::move(encrypted_event_data.mutable_ciphertexts());
return DecryptEventData(decrypt_event_data_request);
}
absl::StatusOr<DecryptQueryResultsResponse> RemoveAes(
const DecryptQueryResultsRequest& request,
const ClientDecryptQueriesResponse& client_decrypt_queries_response) {
DecryptQueryResultsResponse result;
for (const ClientDecryptedQueryResult& client_decrypted_query_result :
client_decrypt_queries_response.result()) {
ASSIGN_OR_RETURN(
*result.add_event_data_sets(),
RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,
request.decrypted_join_key().key(),
request.hkdf_pepper()));
}
return result;
}
absl::Status Decompress(const CompressionParameters& compression_parameters,
DecryptQueryResultsResponse& response) {
ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,
MakeCompressor(compression_parameters));
for (auto& data_set : *response.mutable_event_data_sets()) {
for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {
ASSIGN_OR_RETURN(*plaintext.mutable_payload(),
compressor->Decompress(plaintext.payload()));
}
}
return absl::OkStatus();
}
} // namespace
absl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(
const DecryptQueryResultsRequest& request) {
// Step 1: Decrypt the encrypted query response
ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,
RemoveRlwe(request));
// If this is for a padding query, don't attempt to remove AES or decompress.
// TODO(efoxepstein@): padding queries should be signalled explicitly.
// Rather than detecting them based on the JKI, we should just have a boolean
// flag in `request`.
absl::string_view join_key_identifier = request.decrypted_join_key().key();
if (join_key_identifier.empty() ||
join_key_identifier.substr(0, 14) == "padding-query:") {
DecryptQueryResultsResponse result;
for (const ClientDecryptedQueryResult& client_decrypted_query_result :
client_decrypt_queries_response.result()) {
DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();
decrypted_data_set->mutable_query_id()->set_id(
client_decrypted_query_result.query_metadata().query_id());
decrypted_data_set->add_decrypted_event_data()->set_payload(
client_decrypted_query_result.result());
}
return result;
}
// Step 2: Decrypt the encrypted event data
ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,
RemoveAes(request, client_decrypt_queries_response));
// Step 3: Decompress the decrypted event data
RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));
return result;
}
} // namespace wfa::panelmatch::client::privatemembership
<commit_msg>Remove unnecessary check in private membership decryption (#333)<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "wfa/panelmatch/client/privatemembership/decrypt_query_results.h"
#include <memory>
#include <string>
#include <utility>
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common_cpp/macros/macros.h"
#include "google/protobuf/repeated_field.h"
#include "private_membership/rlwe/batch/cpp/client/client.h"
#include "private_membership/rlwe/batch/proto/client.pb.h"
#include "private_membership/rlwe/batch/proto/shared.pb.h"
#include "wfa/panelmatch/client/exchangetasks/join_key.pb.h"
#include "wfa/panelmatch/client/privatemembership/event_data_decryptor.h"
#include "wfa/panelmatch/client/privatemembership/query.pb.h"
#include "wfa/panelmatch/common/compression/compressor.h"
#include "wfa/panelmatch/common/compression/make_compressor.h"
namespace wfa::panelmatch::client::privatemembership {
namespace {
using ClientEncryptedQueryResult =
::private_membership::batch::EncryptedQueryResult;
using ClientDecryptedQueryResult =
::private_membership::batch::DecryptedQueryResult;
using ClientDecryptQueriesRequest =
::private_membership::batch::DecryptQueriesRequest;
using ClientDecryptQueriesResponse =
::private_membership::batch::DecryptQueriesResponse;
using ::private_membership::batch::DecryptQueries;
absl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(
const DecryptQueryResultsRequest& request) {
ClientDecryptQueriesRequest client_decrypt_queries_request;
client_decrypt_queries_request.mutable_parameters()->ParseFromString(
request.serialized_parameters());
client_decrypt_queries_request.mutable_private_key()->ParseFromString(
request.serialized_private_key());
client_decrypt_queries_request.mutable_public_key()->ParseFromString(
request.serialized_public_key());
for (const EncryptedQueryResult& encrypted_query_result :
request.encrypted_query_results()) {
client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(
encrypted_query_result.serialized_encrypted_query_result());
}
return DecryptQueries(client_decrypt_queries_request);
}
absl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(
const ClientDecryptedQueryResult& client_decrypted_query_result,
const std::string& lookup_key, const std::string& hkdf_pepper) {
DecryptEventDataRequest decrypt_event_data_request;
decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);
decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);
EncryptedEventData encrypted_event_data;
encrypted_event_data.ParseFromString(client_decrypted_query_result.result());
decrypt_event_data_request.mutable_encrypted_event_data_set()
->mutable_query_id()
->set_id(client_decrypted_query_result.query_metadata().query_id());
*decrypt_event_data_request.mutable_encrypted_event_data_set()
->mutable_encrypted_event_data()
->mutable_ciphertexts() =
*std::move(encrypted_event_data.mutable_ciphertexts());
return DecryptEventData(decrypt_event_data_request);
}
absl::StatusOr<DecryptQueryResultsResponse> RemoveAes(
const DecryptQueryResultsRequest& request,
const ClientDecryptQueriesResponse& client_decrypt_queries_response) {
DecryptQueryResultsResponse result;
for (const ClientDecryptedQueryResult& client_decrypted_query_result :
client_decrypt_queries_response.result()) {
ASSIGN_OR_RETURN(
*result.add_event_data_sets(),
RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,
request.decrypted_join_key().key(),
request.hkdf_pepper()));
}
return result;
}
absl::Status Decompress(const CompressionParameters& compression_parameters,
DecryptQueryResultsResponse& response) {
ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,
MakeCompressor(compression_parameters));
for (auto& data_set : *response.mutable_event_data_sets()) {
for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {
ASSIGN_OR_RETURN(*plaintext.mutable_payload(),
compressor->Decompress(plaintext.payload()));
}
}
return absl::OkStatus();
}
} // namespace
absl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(
const DecryptQueryResultsRequest& request) {
// Step 1: Decrypt the encrypted query response
ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,
RemoveRlwe(request));
// If this is for a padding query, don't attempt to remove AES or decompress.
absl::string_view join_key = request.decrypted_join_key().key();
if (join_key.empty()) {
DecryptQueryResultsResponse result;
for (const ClientDecryptedQueryResult& client_decrypted_query_result :
client_decrypt_queries_response.result()) {
DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();
decrypted_data_set->mutable_query_id()->set_id(
client_decrypted_query_result.query_metadata().query_id());
decrypted_data_set->add_decrypted_event_data()->set_payload(
client_decrypted_query_result.result());
}
return result;
}
// Step 2: Decrypt the encrypted event data
ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,
RemoveAes(request, client_decrypt_queries_response));
// Step 3: Decompress the decrypted event data
RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));
return result;
}
} // namespace wfa::panelmatch::client::privatemembership
<|endoftext|>
|
<commit_before>
#include <cassert>
#include <iostream>
#include <scm/gl_core/buffer_objects.h>
#include <scm/gl_core/render_device.h>
namespace scm {
namespace gl {
template <class host_block_type>
uniform_block<host_block_type>::uniform_block()
{
}
template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)
: _host_block(new host_block_type())
{
_device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
}
template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
: _host_block(new host_block_type(in_block)),
{
_device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
commit_block(in_device->main_context());
}
template <class host_block_type>
uniform_block<host_block_type>::~uniform_block()
{
reset();
}
template <class host_block_type>
void
uniform_block<host_block_type>::reset()
{
_device_block.reset();
_host_block.reset();
}
template <class host_block_type>
void
uniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)
{
assert(_device_block);
assert(_host_block);
_current_context = in_context;
}
template <class host_block_type>
void
uniform_block<host_block_type>::end_manipulation()
{
assert(_device_block);
assert(_host_block);
commit_block(_current_context);
_current_context.reset();
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type&
uniform_block<host_block_type>::operator*() const
{
return (*_host_block);
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::operator->() const
{
return (_host_block.get());
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::get_block() const
{
return (_host_block.get());
}
template <class host_block_type>
const buffer_ptr&
uniform_block<host_block_type>::block_buffer() const
{
return (_device_block);
}
template <class host_block_type>
void
uniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)
{
using namespace scm::gl;
assert(_device_block);
assert(_host_block);
block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));
if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {
std::cerr << "uniform_block<>::commit_block(): error copying host block to gpu memory." << std::endl;
}
in_context->unmap_buffer(_device_block);
}
template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device)
{
return (uniform_block<host_block_type>(in_device));
}
template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
{
return (uniform_block<host_block_type>(in_device, in_block));
}
} // namespace gl
} // namespace scm
<commit_msg>linux fix uniform_buffer_adaptor<commit_after>
#include <cassert>
#include <iostream>
#include <scm/gl_core/buffer_objects.h>
#include <scm/gl_core/render_device.h>
namespace scm {
namespace gl {
template <class host_block_type>
uniform_block<host_block_type>::uniform_block()
{
}
template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)
: _host_block(new host_block_type())
{
_device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
}
template <class host_block_type>
uniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
: _host_block(new host_block_type(in_block))
{
_device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));
commit_block(in_device->main_context());
}
template <class host_block_type>
uniform_block<host_block_type>::~uniform_block()
{
reset();
}
template <class host_block_type>
void
uniform_block<host_block_type>::reset()
{
_device_block.reset();
_host_block.reset();
}
template <class host_block_type>
void
uniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)
{
assert(_device_block);
assert(_host_block);
_current_context = in_context;
}
template <class host_block_type>
void
uniform_block<host_block_type>::end_manipulation()
{
assert(_device_block);
assert(_host_block);
commit_block(_current_context);
_current_context.reset();
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type&
uniform_block<host_block_type>::operator*() const
{
return (*_host_block);
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::operator->() const
{
return (_host_block.get());
}
template <class host_block_type>
typename uniform_block<host_block_type>::block_type*
uniform_block<host_block_type>::get_block() const
{
return (_host_block.get());
}
template <class host_block_type>
const buffer_ptr&
uniform_block<host_block_type>::block_buffer() const
{
return (_device_block);
}
template <class host_block_type>
void
uniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)
{
using namespace scm::gl;
assert(_device_block);
assert(_host_block);
block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));
if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {
std::cerr << "uniform_block<>::commit_block(): error copying host block to gpu memory." << std::endl;
}
in_context->unmap_buffer(_device_block);
}
template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device)
{
return (uniform_block<host_block_type>(in_device));
}
template <class host_block_type>
uniform_block<host_block_type>
make_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)
{
return (uniform_block<host_block_type>(in_device, in_block));
}
} // namespace gl
} // namespace scm
<|endoftext|>
|
<commit_before>#include <QSound>
#include "MoNv.h"
enum CAUSE{
CANG_YAN_FA_DIAN=3001,
TIAN_HUO_DUAN_KONG=3002,
MO_NV_ZHI_NU=3003,
MO_NV_ZHI_NU_ATTACK=30031,
TI_SHEN_WAN_OU=3004,
YONG_SHENG_YIN_SHI_JI=3005,
TONG_KU_LIAN_JIE=3006,
TONG_KU_LIAN_JIE_CARD=30061,
MO_NENG_FAN_ZHUAN=3007
};
MoNv::MoNv()
{
makeConnection();
setMyRole(this);
Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
buttonArea->addButton(cangYanFaDian);
connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));
tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
buttonArea->addButton(tianHuoDuanKong);
connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));
tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
buttonArea->addButton(tongKuLianJie);
connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}
int MoNv::checkFire()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> handcards = dataInterface->getHandCards();
int fire = 0;
for(int i=0; i<handcards.size();i++)
{
if(handcards[i]->getElement() == QStringLiteral("fire"))
fire ++;
if(myself->getTap() && handcards[i]->getType() == "attack" &&
(handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
fire ++;
}
return fire;
}
void MoNv::enbleFire()
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
}
handArea->enableElement(QStringLiteral("fire"));
}
void MoNv::enbleFireAttack(QString element)
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
if(element == "water")
handArea->enableElement(element);
if(element == "fire")
{
handArea->enableElement("fire");
handArea->enableElement("thunder");
handArea->enableElement("earth");
handArea->enableElement("wind");
}
}
else
{
handArea->enableElement(element);
}
}
void MoNv::attacked(QString element,int hitRate)
{
state=2;
playerArea->setQuota(1);
handArea->setQuota(1);
decisionArea->enable(1);
if(hitRate==0)
{
this->enbleFireAttack(element);
handArea->enableElement("darkness");
}
handArea->disableMagic();
handArea->enableElement("light");
gui->alert();
QSound::play("sound/Warning.wav");
}
void MoNv::normal()
{
Role::normal();
Player* myself=dataInterface->getMyself();
int fire = checkFire();
if(fire > 0)
buttonArea->enable(3);
if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
buttonArea->enable(4);
if(myself->getEnergy()>0)
buttonArea->enable(5);
unactionalCheck();
}
void MoNv::CangYanFaDian()
{
state = CANG_YAN_FA_DIAN;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TianHuoDuanKong()
{
state = TIAN_HUO_DUAN_KONG;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(2);
playerArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TongKuLianJie()
{
state = TONG_KU_LIAN_JIE;
handArea->reset();
playerArea->reset();
tipArea->reset();
playerArea->enableAll();
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::cardAnalyse()
{
Role::cardAnalyse();
switch (state)
{
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
playerArea->enableAll();
break;
case TI_SHEN_WAN_OU:
playerArea->enableMate();
break;
case MO_NENG_FAN_ZHUAN:
playerArea->enableEnemy();
break;
}
}
void MoNv::MoNvZhiNu()
{
state = MO_NV_ZHI_NU;
gui->reset();
tipArea->setMsg(QStringLiteral("发动【魔女之怒】,并选择要摸取的手牌数量"));
for(int i =0; i < 3 ; i ++)
tipArea->addBoxItem(QString::number(i));
tipArea->showBox();
decisionArea->enable(0);
decisionArea->enable(1);
}
void MoNv::TiShenWanOu()
{
state=TI_SHEN_WAN_OU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
handArea->setQuota(1);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::MoNengFanZhuan()
{
state=MO_NENG_FAN_ZHUAN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
handArea->setQuota(2,9);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::askForSkill(network::Command* cmd)
{
switch (cmd->respond_id()) {
case MO_NV_ZHI_NU:
MoNvZhiNu();
break;
case TI_SHEN_WAN_OU:
TiShenWanOu();
break;
case MO_NENG_FAN_ZHUAN:
MoNengFanZhuan();
break;
default:
Role::askForSkill(cmd);
break;
}
}
void MoNv::onOkClicked()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case 1:
if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
(selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
state = MO_NV_ZHI_NU_ATTACK;
action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_card_ids(selectedCards[0]->getID());
usedAttack=true;
usedMagic=usedSpecial=false;
gui->reset();
emit sendCommand(network::MSG_ACTION, action);
}
break;
case TI_SHEN_WAN_OU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(TI_SHEN_WAN_OU);
respond->add_card_ids(selectedCards[0]->getID());
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NENG_FAN_ZHUAN);
respond->add_dst_ids(selectedPlayers[0]->getID());
for(int i =0; i < selectedCards.size();i++)
respond->add_card_ids(selectedCards[i]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NV_ZHI_NU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NV_ZHI_NU);
respond->add_args(1);// 1表示选择发动
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
start =true;
gui->reset();
break;
case CANG_YAN_FA_DIAN:
action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TIAN_HUO_DUAN_KONG:
action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_card_ids(selectedCards[1]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TONG_KU_LIAN_JIE:
action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
action->set_src_id(myID);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_args(1);
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
Role::onOkClicked();
}
void MoNv::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case MO_NV_ZHI_NU:
case TI_SHEN_WAN_OU:
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(state);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
case TONG_KU_LIAN_JIE:
normal();
break;
}
}
<commit_msg>魔女 痛苦链接<commit_after>#include <QSound>
#include "MoNv.h"
enum CAUSE{
CANG_YAN_FA_DIAN=3001,
TIAN_HUO_DUAN_KONG=3002,
MO_NV_ZHI_NU=3003,
MO_NV_ZHI_NU_ATTACK=30031,
TI_SHEN_WAN_OU=3004,
YONG_SHENG_YIN_SHI_JI=3005,
TONG_KU_LIAN_JIE=3006,
TONG_KU_LIAN_JIE_CARD=30061,
MO_NENG_FAN_ZHUAN=3007
};
MoNv::MoNv()
{
makeConnection();
setMyRole(this);
Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
buttonArea->addButton(cangYanFaDian);
connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));
tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
buttonArea->addButton(tianHuoDuanKong);
connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));
tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
buttonArea->addButton(tongKuLianJie);
connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}
int MoNv::checkFire()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> handcards = dataInterface->getHandCards();
int fire = 0;
for(int i=0; i<handcards.size();i++)
{
if(handcards[i]->getElement() == QStringLiteral("fire"))
fire ++;
if(myself->getTap() && handcards[i]->getType() == "attack" &&
(handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
fire ++;
}
return fire;
}
void MoNv::enbleFire()
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
}
handArea->enableElement(QStringLiteral("fire"));
}
void MoNv::enbleFireAttack(QString element)
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
if(element == "water")
handArea->enableElement(element);
if(element == "fire")
{
handArea->enableElement("fire");
handArea->enableElement("thunder");
handArea->enableElement("earth");
handArea->enableElement("wind");
}
}
else
{
handArea->enableElement(element);
}
}
void MoNv::attacked(QString element,int hitRate)
{
state=2;
playerArea->setQuota(1);
handArea->setQuota(1);
decisionArea->enable(1);
if(hitRate==0)
{
this->enbleFireAttack(element);
handArea->enableElement("darkness");
}
handArea->disableMagic();
handArea->enableElement("light");
gui->alert();
QSound::play("sound/Warning.wav");
}
void MoNv::normal()
{
Role::normal();
Player* myself=dataInterface->getMyself();
int fire = checkFire();
if(fire > 0)
buttonArea->enable(3);
if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
buttonArea->enable(4);
if(myself->getEnergy()>0)
buttonArea->enable(5);
unactionalCheck();
}
void MoNv::CangYanFaDian()
{
state = CANG_YAN_FA_DIAN;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TianHuoDuanKong()
{
state = TIAN_HUO_DUAN_KONG;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(2);
playerArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TongKuLianJie()
{
state = TONG_KU_LIAN_JIE;
handArea->reset();
playerArea->reset();
tipArea->reset();
playerArea->enableEnemy();
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::cardAnalyse()
{
Role::cardAnalyse();
switch (state)
{
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
playerArea->enableAll();
break;
case TI_SHEN_WAN_OU:
playerArea->enableMate();
break;
case MO_NENG_FAN_ZHUAN:
playerArea->enableEnemy();
break;
}
}
void MoNv::MoNvZhiNu()
{
state = MO_NV_ZHI_NU;
gui->reset();
tipArea->setMsg(QStringLiteral("发动【魔女之怒】,并选择要摸取的手牌数量"));
for(int i =0; i < 3 ; i ++)
tipArea->addBoxItem(QString::number(i));
tipArea->showBox();
decisionArea->enable(0);
decisionArea->enable(1);
}
void MoNv::TiShenWanOu()
{
state=TI_SHEN_WAN_OU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
handArea->setQuota(1);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::MoNengFanZhuan()
{
state=MO_NENG_FAN_ZHUAN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
handArea->setQuota(2,9);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::askForSkill(network::Command* cmd)
{
switch (cmd->respond_id()) {
case MO_NV_ZHI_NU:
MoNvZhiNu();
break;
case TI_SHEN_WAN_OU:
TiShenWanOu();
break;
case MO_NENG_FAN_ZHUAN:
MoNengFanZhuan();
break;
default:
Role::askForSkill(cmd);
break;
}
}
void MoNv::onOkClicked()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case 1:
if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
(selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
state = MO_NV_ZHI_NU_ATTACK;
action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_card_ids(selectedCards[0]->getID());
usedAttack=true;
usedMagic=usedSpecial=false;
gui->reset();
emit sendCommand(network::MSG_ACTION, action);
}
break;
case TI_SHEN_WAN_OU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(TI_SHEN_WAN_OU);
respond->add_card_ids(selectedCards[0]->getID());
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NENG_FAN_ZHUAN);
respond->add_dst_ids(selectedPlayers[0]->getID());
for(int i =0; i < selectedCards.size();i++)
respond->add_card_ids(selectedCards[i]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NV_ZHI_NU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NV_ZHI_NU);
respond->add_args(1);// 1表示选择发动
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
start =true;
gui->reset();
break;
case CANG_YAN_FA_DIAN:
action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TIAN_HUO_DUAN_KONG:
action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_card_ids(selectedCards[1]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TONG_KU_LIAN_JIE:
action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
action->set_src_id(myID);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_args(1);
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
Role::onOkClicked();
}
void MoNv::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case MO_NV_ZHI_NU:
case TI_SHEN_WAN_OU:
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(state);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
case TONG_KU_LIAN_JIE:
normal();
break;
}
}
<|endoftext|>
|
<commit_before>#include "ModernGL-Constants.hpp"
#include "ModernGL-Types.hpp"
#define STR_VERSION(ver) # ver
void RegisterConstants(PyObject * module) {
PyModule_AddObject(module, "ENABLE_NOTHING", CreateEnableFlagType(ENABLE_NOTHING));
PyModule_AddObject(module, "ENABLE_BLEND", CreateEnableFlagType(ENABLE_BLEND));
PyModule_AddObject(module, "ENABLE_CULL_FACE", CreateEnableFlagType(ENABLE_CULL_FACE));
PyModule_AddObject(module, "ENABLE_DEPTH_TEST", CreateEnableFlagType(ENABLE_DEPTH_TEST));
PyModule_AddObject(module, "ENABLE_MULTISAMPLE", CreateEnableFlagType(ENABLE_MULTISAMPLE));
PyModule_AddObject(module, "ENABLE_ALL", CreateEnableFlagType(ENABLE_ALL));
PyModule_AddStringConstant(module, "VERSION", STR_VERSION(MODERN_GL_VERSION));
PyModule_AddStringConstant(module, "__AUTHOR_NAME__", "Szabolcs Dombi");
PyModule_AddStringConstant(module, "__AUTHOR_EMAIL__", "cprogrammer1994@gmail.com");
PyModule_AddObject(module, "screen", CreateFramebufferType(0, 0, 0));
}
#undef STR_VERSION
<commit_msg>better uppercase screen<commit_after>#include "ModernGL-Constants.hpp"
#include "ModernGL-Types.hpp"
#define STR_VERSION(ver) # ver
void RegisterConstants(PyObject * module) {
PyModule_AddObject(module, "ENABLE_NOTHING", CreateEnableFlagType(ENABLE_NOTHING));
PyModule_AddObject(module, "ENABLE_BLEND", CreateEnableFlagType(ENABLE_BLEND));
PyModule_AddObject(module, "ENABLE_CULL_FACE", CreateEnableFlagType(ENABLE_CULL_FACE));
PyModule_AddObject(module, "ENABLE_DEPTH_TEST", CreateEnableFlagType(ENABLE_DEPTH_TEST));
PyModule_AddObject(module, "ENABLE_MULTISAMPLE", CreateEnableFlagType(ENABLE_MULTISAMPLE));
PyModule_AddObject(module, "ENABLE_ALL", CreateEnableFlagType(ENABLE_ALL));
PyModule_AddObject(module, "SCREEN", CreateFramebufferType(0, 0, 0));
PyModule_AddStringConstant(module, "VERSION", STR_VERSION(MODERN_GL_VERSION));
PyModule_AddStringConstant(module, "__AUTHOR_NAME__", "Szabolcs Dombi");
PyModule_AddStringConstant(module, "__AUTHOR_EMAIL__", "cprogrammer1994@gmail.com");
}
#undef STR_VERSION
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "EventDispatcher.h"
class ObserverMock : public EventObserver
{
public:
virtual void notify(const Event& event, int timeOutInSeconds)
{
mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds);
}
virtual void notifyRegistration(EventObserver* newObserver)
{
mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver);
}
};
class EventComparator : public MockNamedValueComparator
{
public:
virtual bool isEqual(const void* object1, const void* object2)
{
return ((Event*)object1)->type == ((Event*)object2)->type;
}
virtual SimpleString valueToString(const void* object)
{
return StringFrom(((Event*)object)->type);
}
};
TEST_GROUP(EventDispatcher)
{
Event event;
EventDispatcher* dispatcher;
ObserverMock observer;
ObserverMock observer2;
EventComparator eventComparator;
void setup()
{
dispatcher = new EventDispatcher;
mock().installComparator("Event", eventComparator);
}
void teardown()
{
delete dispatcher;
mock().removeAllComparatorsAndCopiers();
}
};
TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)
{
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)
{
mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
event.type = IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)
{
event.type = LESS_IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)
{
mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2);
event.type = IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);
dispatcher->dispatchEvent(event, 10);
}
<commit_msg>remove warning, cast from 'const void *' to 'Event *' drops const qualifier.<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* 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 <organization> 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 EARLIER MENTIONED AUTHORS ``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.
*/
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "EventDispatcher.h"
class ObserverMock : public EventObserver
{
public:
virtual void notify(const Event& event, int timeOutInSeconds)
{
mock().actualCall("notify").onObject(this).withParameterOfType("Event", "event", (void*) &event).withParameter("timeOutInSeconds", timeOutInSeconds);
}
virtual void notifyRegistration(EventObserver* newObserver)
{
mock().actualCall("notifyRegistration").onObject(this).withParameter("newObserver", newObserver);
}
};
class EventComparator : public MockNamedValueComparator
{
public:
virtual bool isEqual(const void* object1, const void* object2)
{
return ((const Event*)object1)->type == ((const Event*)object2)->type;
}
virtual SimpleString valueToString(const void* object)
{
return StringFrom(((const Event*)object)->type);
}
};
TEST_GROUP(EventDispatcher)
{
Event event;
EventDispatcher* dispatcher;
ObserverMock observer;
ObserverMock observer2;
EventComparator eventComparator;
void setup()
{
dispatcher = new EventDispatcher;
mock().installComparator("Event", eventComparator);
}
void teardown()
{
delete dispatcher;
mock().removeAllComparatorsAndCopiers();
}
};
TEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)
{
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)
{
mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
event.type = IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)
{
event.type = LESS_IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->dispatchEvent(event, 10);
}
TEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)
{
mock().expectOneCall("notify").onObject(&observer).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
mock().expectOneCall("notify").onObject(&observer2).withParameterOfType("Event", "event", &event).withParameter("timeOutInSeconds", 10);
mock().expectOneCall("notifyRegistration").onObject(&observer).withParameter("newObserver", &observer2);
event.type = IMPORTANT_EVENT;
dispatcher->registerObserver(IMPORTANT_EVENT, &observer);
dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);
dispatcher->dispatchEvent(event, 10);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2015 Mark Charlebois. 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 simulator.cpp
* A device simulator
*/
#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>
#include "simulator.h"
using namespace simulator;
static px4_task_t g_sim_task = -1;
Simulator *Simulator::_instance = NULL;
Simulator *Simulator::getInstance()
{
return _instance;
}
bool Simulator::getMPUReport(uint8_t *buf, int len)
{
return _mpu.copyData(buf, len);
}
bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
return _accel.copyData(buf, len);
}
bool Simulator::getMagReport(uint8_t *buf, int len)
{
return _mag.copyData(buf, len);
}
bool Simulator::getBaroSample(uint8_t *buf, int len)
{
return _baro.copyData(buf, len);
}
bool Simulator::getGPSSample(uint8_t *buf, int len)
{
return _gps.copyData(buf, len);
}
bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
return _airspeed.copyData(buf, len);
}
void Simulator::write_MPU_data(void *buf)
{
_mpu.writeData(buf);
}
void Simulator::write_accel_data(void *buf)
{
_accel.writeData(buf);
}
void Simulator::write_mag_data(void *buf)
{
_mag.writeData(buf);
}
void Simulator::write_baro_data(void *buf)
{
_baro.writeData(buf);
}
void Simulator::write_gps_data(void *buf)
{
_gps.writeData(buf);
}
void Simulator::write_airspeed_data(void *buf)
{
_airspeed.writeData(buf);
}
int Simulator::start(int argc, char *argv[])
{
int ret = 0;
_instance = new Simulator();
if (_instance) {
drv_led_start();
if (argv[2][1] == 's') {
_instance->initializeSensorData();
#ifndef __PX4_QURT
// Update sensor data
_instance->pollForMAVLinkMessages(false);
#endif
} else if (argv[2][1] == 'p') {
// Update sensor data
_instance->pollForMAVLinkMessages(true);
} else {
_instance->initializeSensorData();
_instance->_initialized = true;
}
} else {
PX4_WARN("Simulator creation failed");
ret = 1;
}
return ret;
}
static void usage()
{
PX4_WARN("Usage: simulator {start -[spt] |stop}");
PX4_WARN("Simulate raw sensors: simulator start -s");
PX4_WARN("Publish sensors combined: simulator start -p");
PX4_WARN("Dummy unit test data: simulator start -t");
}
__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS
extern "C" {
int simulator_main(int argc, char *argv[])
{
int ret = 0;
if (argc == 3 && strcmp(argv[1], "start") == 0) {
if (strcmp(argv[2], "-s") == 0 ||
strcmp(argv[2], "-p") == 0 ||
strcmp(argv[2], "-t") == 0) {
if (g_sim_task >= 0) {
warnx("Simulator already started");
return 0;
}
g_sim_task = px4_task_spawn_cmd("Simulator",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
1500,
Simulator::start,
argv);
// now wait for the command to complete
while (true) {
if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
break;
} else {
usleep(100000);
}
}
} else {
usage();
ret = -EINVAL;
}
} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
if (g_sim_task < 0) {
PX4_WARN("Simulator not running");
} else {
px4_task_delete(g_sim_task);
g_sim_task = -1;
}
} else {
usage();
ret = -EINVAL;
}
return ret;
}
}
<commit_msg>Simulator: All app names are lowercase!<commit_after>/****************************************************************************
*
* Copyright (c) 2015 Mark Charlebois. 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 simulator.cpp
* A device simulator
*/
#include <px4_log.h>
#include <px4_tasks.h>
#include <px4_time.h>
#include <pthread.h>
#include <poll.h>
#include <systemlib/err.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <drivers/drv_led.h>
#include "simulator.h"
using namespace simulator;
static px4_task_t g_sim_task = -1;
Simulator *Simulator::_instance = NULL;
Simulator *Simulator::getInstance()
{
return _instance;
}
bool Simulator::getMPUReport(uint8_t *buf, int len)
{
return _mpu.copyData(buf, len);
}
bool Simulator::getRawAccelReport(uint8_t *buf, int len)
{
return _accel.copyData(buf, len);
}
bool Simulator::getMagReport(uint8_t *buf, int len)
{
return _mag.copyData(buf, len);
}
bool Simulator::getBaroSample(uint8_t *buf, int len)
{
return _baro.copyData(buf, len);
}
bool Simulator::getGPSSample(uint8_t *buf, int len)
{
return _gps.copyData(buf, len);
}
bool Simulator::getAirspeedSample(uint8_t *buf, int len)
{
return _airspeed.copyData(buf, len);
}
void Simulator::write_MPU_data(void *buf)
{
_mpu.writeData(buf);
}
void Simulator::write_accel_data(void *buf)
{
_accel.writeData(buf);
}
void Simulator::write_mag_data(void *buf)
{
_mag.writeData(buf);
}
void Simulator::write_baro_data(void *buf)
{
_baro.writeData(buf);
}
void Simulator::write_gps_data(void *buf)
{
_gps.writeData(buf);
}
void Simulator::write_airspeed_data(void *buf)
{
_airspeed.writeData(buf);
}
int Simulator::start(int argc, char *argv[])
{
int ret = 0;
_instance = new Simulator();
if (_instance) {
drv_led_start();
if (argv[2][1] == 's') {
_instance->initializeSensorData();
#ifndef __PX4_QURT
// Update sensor data
_instance->pollForMAVLinkMessages(false);
#endif
} else if (argv[2][1] == 'p') {
// Update sensor data
_instance->pollForMAVLinkMessages(true);
} else {
_instance->initializeSensorData();
_instance->_initialized = true;
}
} else {
PX4_WARN("Simulator creation failed");
ret = 1;
}
return ret;
}
static void usage()
{
PX4_WARN("Usage: simulator {start -[spt] |stop}");
PX4_WARN("Simulate raw sensors: simulator start -s");
PX4_WARN("Publish sensors combined: simulator start -p");
PX4_WARN("Dummy unit test data: simulator start -t");
}
__BEGIN_DECLS
extern int simulator_main(int argc, char *argv[]);
__END_DECLS
extern "C" {
int simulator_main(int argc, char *argv[])
{
int ret = 0;
if (argc == 3 && strcmp(argv[1], "start") == 0) {
if (strcmp(argv[2], "-s") == 0 ||
strcmp(argv[2], "-p") == 0 ||
strcmp(argv[2], "-t") == 0) {
if (g_sim_task >= 0) {
warnx("Simulator already started");
return 0;
}
g_sim_task = px4_task_spawn_cmd("simulator",
SCHED_DEFAULT,
SCHED_PRIORITY_MAX - 5,
1500,
Simulator::start,
argv);
// now wait for the command to complete
while (true) {
if (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {
break;
} else {
usleep(100000);
}
}
} else {
usage();
ret = -EINVAL;
}
} else if (argc == 2 && strcmp(argv[1], "stop") == 0) {
if (g_sim_task < 0) {
PX4_WARN("Simulator not running");
} else {
px4_task_delete(g_sim_task);
g_sim_task = -1;
}
} else {
usage();
ret = -EINVAL;
}
return ret;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2021 The CFU-Playground Authors
* Copyright 2019 The TensorFlow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h"
#include <cstdio>
#include "gateware_constants.h"
#include "hps_cfu.h"
#include "tensorflow/lite/kernels/internal/common.h"
#if GATEWARE_GEN == 2
namespace tflite {
namespace reference_integer_ops {
namespace {
// Loads four post process parameters into the CFU
void LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,
const int32_t* output_shift,
const int32_t* output_multiplier) {
for (int i = channel_start; i < channel_start + 4; i++) {
cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);
// Note : shift is stored as a negative number in tflite model
cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);
cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);
}
}
// Loads filter parameters, correctly split between the two
// stores
void LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,
const uint32_t* data_base) {
const int num_filter_words_per_output =
filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
const uint32_t* filter_data =
data_base + channel_start * num_filter_words_per_output;
size_t addr_base = 0;
for (int i = channel_start; i < channel_start + 4; i += 2) {
for (int store = 0; store < 2; store++) {
uint32_t addr = addr_base;
for (int j = 0; j < num_filter_words_per_output; j++) {
uint32_t data = *filter_data++;
cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);
addr++;
}
}
addr_base += num_filter_words_per_output;
}
}
// Collects a single ouput value and optionally places it into memory
inline void CollectValue(uint32_t*& p, int advance, bool write) {
uint32_t val = cfu_get(REG_OUTPUT_WORD);
if (write) {
*p = val;
p += advance;
}
}
// Collects output from the accelerator into the output area
// Collects one word per output pixel
void CollectOutput(int channel, uint32_t* output, const int height,
const int width, const int depth) {
const int num_pixels = height * width;
const int num_words_per_pixel = depth / 4;
uint32_t* p = output + channel / 4;
for (int pixel = 0; pixel < num_pixels; pixel += 4) {
CollectValue(p, num_words_per_pixel, true);
CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);
CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);
CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);
}
}
}; // namespace
bool CanAccelerateConv4x4(const ConvParams& params,
const RuntimeShape& input_shape,
const RuntimeShape& filter_shape,
const RuntimeShape& output_shape,
const int32_t* bias_data) {
// No padding allowed
if (params.padding_type != PaddingType::kValid) return false;
// Must have bias_data and single batch
if (!bias_data) return false;
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
if (batches != 1) return false;
// Input and output depths must be a multiple of 16
// NB: We could probably relax output depth to be a multiple of 4
const int input_depth = input_shape.Dims(3);
const int output_depth = output_shape.Dims(3);
// if (input_depth % 16 != 0) return false;
// if (output_depth % 16 != 0) return false;
// Currently, only works where input and output depths are exactly 16
if (input_depth != 16) return false;
if (output_depth != 16) return false;
// Must be 4x4
const int filter_height = filter_shape.Dims(1);
const int filter_width = filter_shape.Dims(2);
if (filter_height != 4 || filter_width != 4) return false;
// Must fit in filter word storag e
const int num_filter_words = input_depth * output_depth * 4 * 4 / 4;
if (num_filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE)
return false;
// Dilation must be 1
if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)
return false;
// Stride must be 1
const int stride_width = params.stride_width;
const int stride_height = params.stride_height;
if (stride_height != 1 || stride_width != 1) return false;
return true;
}
// Accelerated Conv2D
void ConvPerChannel4x4(const ConvParams& params,
const int32_t* output_multiplier,
const int32_t* output_shift,
const RuntimeShape& input_shape,
const int8_t* input_data,
const RuntimeShape& filter_shape,
const int8_t* filter_data,
const RuntimeShape& bias_shape, const int32_t* bias_data,
const RuntimeShape& output_shape, int8_t* output_data) {
// Calculates in trances of four channels (one output word)
const int channels_per_tranche = 4;
// Get parameters.
const int32_t input_offset = params.input_offset; // r = s(q - Z)
// TODO: handle stride
// const int stride_width = params.stride_width;
// const int stride_height = params.stride_height;
// TODO: handle padding
// const int pad_width = params.padding_values.width;
// const int pad_height = params.padding_values.height;
const int32_t output_offset = params.output_offset;
// Set min and max value of the output.
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Consistency checks
TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
// Get dimensions of the tensors.
const int input_width = input_shape.Dims(2);
const int output_height = output_shape.Dims(1);
const int output_width = output_shape.Dims(2);
const int num_output_values_per_tranche =
output_width * output_height * channels_per_tranche;
// Filter words required to calculate each tranche
const int filter_words_per_channel =
filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
const int filter_words_per_tranche =
filter_words_per_channel * channels_per_tranche;
// Base address is bank address (4 words per bank) within 256K arena
uint32_t input_base_addr =
(reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16;
for (int channel = 0; channel < output_depth;
channel += channels_per_tranche) {
// Reset to ensure important state is initialized
cfu_set(REG_ACCELERATOR_RESET, 0);
// Configure simple values
cfu_set(REG_INPUT_OFFSET, input_offset);
cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche / 2);
cfu_set(REG_OUTPUT_OFFSET, output_offset);
cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);
cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);
cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);
cfu_set(REG_NUM_PIXELS_X, output_width);
cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16);
cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width);
cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);
cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);
cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);
LoadFourPostProcessParameters(channel, bias_data, output_shift,
output_multiplier);
LoadFourFilterData(channel, filter_shape,
reinterpret_cast<const uint32_t*>(filter_data));
// Start Accelerator
cfu_set(REG_ACCELERATOR_START, 0);
// Collect data
CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),
output_height, output_width, output_depth);
}
}
} // namespace reference_integer_ops
} // namespace tflite
#endif // GATEWARE_GEN
<commit_msg>gen2/conv_accel_gen_2: Allow larger Conv2D ops<commit_after>/*
* Copyright 2021 The CFU-Playground Authors
* Copyright 2019 The TensorFlow Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tensorflow/lite/kernels/internal/reference/integer_ops/conv_accel_gen_2.h"
#include <cstdio>
#include "gateware_constants.h"
#include "hps_cfu.h"
#include "tensorflow/lite/kernels/internal/common.h"
#if GATEWARE_GEN == 2
namespace tflite {
namespace reference_integer_ops {
namespace {
// Loads four post process parameters into the CFU
void LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,
const int32_t* output_shift,
const int32_t* output_multiplier) {
for (int i = channel_start; i < channel_start + 4; i++) {
cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);
// Note : shift is stored as a negative number in tflite model
cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);
cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);
}
}
// Loads filter parameters, correctly split between the two
// stores
void LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,
const uint32_t* data_base) {
const int num_filter_words_per_output =
filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
const uint32_t* filter_data =
data_base + channel_start * num_filter_words_per_output;
size_t addr_base = 0;
for (int i = channel_start; i < channel_start + 4; i += 2) {
for (int store = 0; store < 2; store++) {
uint32_t addr = addr_base;
for (int j = 0; j < num_filter_words_per_output; j++) {
uint32_t data = *filter_data++;
cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);
addr++;
}
}
addr_base += num_filter_words_per_output;
}
}
// Collects a single ouput value and optionally places it into memory
inline void CollectValue(uint32_t*& p, int advance, bool write) {
uint32_t val = cfu_get(REG_OUTPUT_WORD);
if (write) {
*p = val;
p += advance;
}
}
// Collects output from the accelerator into the output area
// Collects one word per output pixel
void CollectOutput(int channel, uint32_t* output, const int height,
const int width, const int depth) {
const int num_pixels = height * width;
const int num_words_per_pixel = depth / 4;
uint32_t* p = output + channel / 4;
for (int pixel = 0; pixel < num_pixels; pixel += 4) {
CollectValue(p, num_words_per_pixel, true);
CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);
CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);
CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);
}
}
}; // namespace
bool CanAccelerateConv4x4(const ConvParams& params,
const RuntimeShape& input_shape,
const RuntimeShape& filter_shape,
const RuntimeShape& output_shape,
const int32_t* bias_data) {
// No padding allowed
if (params.padding_type != PaddingType::kValid) return false;
// Must have bias_data and single batch
if (!bias_data) return false;
const int batches = MatchingDim(input_shape, 0, output_shape, 0);
if (batches != 1) return false;
// Input and output depths must be a multiples of 16 and 4
const int input_depth = input_shape.Dims(3);
const int output_depth = output_shape.Dims(3);
if (input_depth % 16 != 0) return false;
if (output_depth % 4 != 0) return false;
// Must be 4x4
const int filter_height = filter_shape.Dims(1);
const int filter_width = filter_shape.Dims(2);
if (filter_height != 4 || filter_width != 4) return false;
// Must fit in filter word storage
const int filter_values_per_output =
input_depth * filter_height * filter_width;
// Calculate 4 output values per tranche
const int filter_values = 4 * filter_values_per_output;
// 4 values per word
const int filter_words = filter_values / 4;
if (filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE) return false;
// Dilation must be 1
if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)
return false;
// Stride must be 1
const int stride_width = params.stride_width;
const int stride_height = params.stride_height;
if (stride_height != 1 || stride_width != 1) return false;
return true;
}
// Accelerated Conv2D
void ConvPerChannel4x4(const ConvParams& params,
const int32_t* output_multiplier,
const int32_t* output_shift,
const RuntimeShape& input_shape,
const int8_t* input_data,
const RuntimeShape& filter_shape,
const int8_t* filter_data,
const RuntimeShape& bias_shape, const int32_t* bias_data,
const RuntimeShape& output_shape, int8_t* output_data) {
// Calculates in tranches of four channels (one output word)
const int channels_per_tranche = 4;
// Get parameters.
const int32_t input_offset = params.input_offset; // r = s(q - Z)
// TODO: handle stride
// const int stride_width = params.stride_width;
// const int stride_height = params.stride_height;
// TODO: handle padding
// const int pad_width = params.padding_values.width;
// const int pad_height = params.padding_values.height;
const int32_t output_offset = params.output_offset;
// Set min and max value of the output.
const int32_t output_activation_min = params.quantized_activation_min;
const int32_t output_activation_max = params.quantized_activation_max;
// Consistency checks
TFLITE_DCHECK_LE(output_activation_min, output_activation_max);
TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);
TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);
const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);
const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);
TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);
// Get dimensions of the tensors.
const int input_width = input_shape.Dims(2);
const int output_height = output_shape.Dims(1);
const int output_width = output_shape.Dims(2);
// Round up output values to next multiple of 16
const int num_output_values_per_tranche =
(output_width * output_height * channels_per_tranche + 15) / 16 * 16;
// Filter words required to calculate each tranche
const int filter_words_per_channel =
filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) / 4;
const int filter_words_per_tranche =
filter_words_per_channel * channels_per_tranche;
// Base address is bank address (4 words per bank) within 256K arena
uint32_t input_base_addr =
(reinterpret_cast<uint32_t>(input_data) & 0x3ffff) / 16;
for (int channel = 0; channel < output_depth;
channel += channels_per_tranche) {
// Reset to ensure important state is initialized
cfu_set(REG_ACCELERATOR_RESET, 0);
// Configure simple values
cfu_set(REG_INPUT_OFFSET, input_offset);
cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche / 2);
cfu_set(REG_OUTPUT_OFFSET, output_offset);
cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);
cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);
cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);
cfu_set(REG_NUM_PIXELS_X, output_width);
cfu_set(REG_PIXEL_ADVANCE_X, input_depth / 16);
cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth / 16) * input_width);
cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);
cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);
cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);
LoadFourPostProcessParameters(channel, bias_data, output_shift,
output_multiplier);
LoadFourFilterData(channel, filter_shape,
reinterpret_cast<const uint32_t*>(filter_data));
// Start Accelerator
cfu_set(REG_ACCELERATOR_START, 0);
// Collect data
CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),
output_height, output_width, output_depth);
}
}
} // namespace reference_integer_ops
} // namespace tflite
#endif // GATEWARE_GEN
<|endoftext|>
|
<commit_before>
#include "rootdir.h"
RootDir::RootDir():m_dirs(0){
m_dirs = new Dir[32];
}
RootDir::~RootDir(){
delete []m_dirs;
}
<commit_msg>again getting rid of that hardcoded number<commit_after>
#include "rootdir.h"
#define DIR_ENTRIES 32
RootDir::RootDir():m_dirs(0){
m_dirs = new Dir[DIR_ENTRIES];
}
RootDir::~RootDir(){
delete []m_dirs;
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <vector>
#include "iterators.hpp"
#include "logging.hpp"
#include "GlobalContext.hpp"
#include "mtac/remove_empty_functions.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Quadruple.hpp"
using namespace eddic;
bool mtac::remove_empty_functions::operator()(mtac::Program& program){
std::vector<std::string> removed_functions;
bool changes = false;
auto it = iterate(program.functions);
while(it.has_next()){
auto& function = *it;
if(function.is_main()){
++it;
continue;
}
unsigned int statements = function.size_no_nop();
if(statements == 0){
program.context->stats().inc_counter("empty_function_removed");
LOG<Debug>("Optimizer") << "Remove empty function " << function.get_name() << log::endl;
changes = true;
removed_functions.push_back(function.get_name());
it.erase();
} else {
++it;
}
}
if(!removed_functions.empty()){
for(auto& function : program.functions){
for(auto& block : function){
auto fit = block->statements.begin();
while(fit != block->statements.end()){
auto& quadruple = *fit;
if(quadruple.op == mtac::Operator::CALL){
auto function_name = quadruple.function().mangled_name();
if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){
//Update the call graph
--program.call_graph.edge(function.definition(), quadruple.function())->count;
int parameters = quadruple.function().parameters().size();
if(parameters > 0){
//The parameters are in the previous block
if(fit == block->statements.begin()){
auto previous = block->prev;
auto fend = previous->statements.end();
--fend;
while(parameters > 0){
fend = previous->statements.erase(fend);
--fend;
--parameters;
}
fit = block->statements.erase(fit);
}
//The parameters are in the same block
else {
while(parameters >= 0){
fit = block->statements.erase(fit);
--fit;
--parameters;
}
}
} else {
fit = block->statements.erase(fit);
}
continue;
}
}
++fit;
}
}
}
}
return changes;
}
<commit_msg>STL Refactor<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <vector>
#include "iterators.hpp"
#include "logging.hpp"
#include "GlobalContext.hpp"
#include "mtac/remove_empty_functions.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Quadruple.hpp"
using namespace eddic;
bool mtac::remove_empty_functions::operator()(mtac::Program& program){
std::vector<std::string> removed_functions;
program.functions.erase(std::remove_if(program.functions.begin(), program.functions.end(),
[&program,&removed_functions](auto& function){
if(!function.is_main() && function.size_no_nop() == 0){
program.context->stats().inc_counter("empty_function_removed");
LOG<Debug>("Optimizer") << "Remove empty function " << function.get_name() << log::endl;
removed_functions.push_back(function.get_name());
return true;
}
return false;
}), program.functions.end());
if(!removed_functions.empty()){
for(auto& function : program.functions){
for(auto& block : function){
auto fit = block->statements.begin();
while(fit != block->statements.end()){
auto& quadruple = *fit;
if(quadruple.op == mtac::Operator::CALL){
auto function_name = quadruple.function().mangled_name();
if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){
//Update the call graph
--program.call_graph.edge(function.definition(), quadruple.function())->count;
int parameters = quadruple.function().parameters().size();
if(parameters > 0){
//The parameters are in the previous block
if(fit == block->statements.begin()){
auto previous = block->prev;
auto fend = previous->statements.end();
--fend;
while(parameters > 0){
fend = previous->statements.erase(fend);
--fend;
--parameters;
}
fit = block->statements.erase(fit);
}
//The parameters are in the same block
else {
while(parameters >= 0){
fit = block->statements.erase(fit);
--fit;
--parameters;
}
}
} else {
fit = block->statements.erase(fit);
}
continue;
}
}
++fit;
}
}
}
}
return !removed_functions.empty();
}
<|endoftext|>
|
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2014--2015
*/
/*
Alternate POST / setup and loop / main for non-OpenTRV code running on OpenTRV h/w platform.
Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc!
*/
#include "V0p2_Main.h"
#include "V0p2_Generic_Config.h"
#include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers.
// Arduino libraries.
//#include <Wire.h>
#ifdef ALLOW_CC1_SUPPORT
#include <OTProtocolCC.h>
#endif
#include "Control.h"
#include "FHT8V_Wireless_Rad_Valve.h"
#include "Power_Management.h"
#include "RFM22_Radio.h"
#include "Security.h"
#include "Serial_IO.h"
#include "UI_Minimal.h"
// Link in support for alternate Power On Self-Test and main loop if required.
#if defined(ALT_MAIN_LOOP)
// Mask for Port B input change interrupts.
#define MASK_PB_BASIC 0b00000000 // Nothing.
#ifdef PIN_RFM_NIRQ
#if (PIN_RFM_NIRQ < 8) || (PIN_RFM_NIRQ > 15)
#error PIN_RFM_NIRQ expected to be on port B
#endif
#define RFM23B_INT_MASK (1 << (PIN_RFM_NIRQ&7))
#define MASK_PB (MASK_PB_BASIC | RFM23B_INT_MASK)
#else
#define MASK_PB MASK_PB_BASIC
#endif
//// Mask for Port D input change interrupts.
//#define MASK_PD_BASIC 0b00000001 // Just RX.
//#if defined(ENABLE_VOICE_SENSOR)
//#if VOICE_NIRQ > 7
//#error voice interrupt on wrong port
//#endif
//#define VOICE_INT_MASK (1 << (VOICE_NIRQ&7))
//#define MASK_PD (MASK_PD_BASIC | VOICE_INT_MASK)
//#else
//#define MASK_PD MASK_PD_BASIC // Just RX.
//#endif
// Called from startup() after some initial setup has been done.
// Can abort with panic() if need be.
void POSTalt()
{
#if defined(USE_MODULE_RFM22RADIOSIMPLE)
// Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised.
static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true);
RFM23B.preinit(NULL);
// Check that the radio is correctly connected; panic if not...
if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); }
#endif
// Force initialisation into low-power state.
const int heat = TemperatureC16.read();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("temp: ");
DEBUG_SERIAL_PRINT(heat);
DEBUG_SERIAL_PRINTLN();
#endif
// const int light = AmbLight.read();
//#if 0 && defined(DEBUG)
// DEBUG_SERIAL_PRINT_FLASHSTRING("light: ");
// DEBUG_SERIAL_PRINT(light);
// DEBUG_SERIAL_PRINTLN();
//#endif
// Trailing setup for the run
// --------------------------
// Set up async edge interrupts.
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
//PCMSK0 = PB; PCINT 0--7 (LEARN1 and Radio)
//PCMSK1 = PC; PCINT 8--15
//PCMSK2 = PD; PCINT 16--24 (LEARN2 and MODE, RX)
PCICR =
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
1 | // 0x1 enables PB/PCMSK0.
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
2 | // 0x2 enables PC/PCMSK1.
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
4 | // 0x4 enables PD/PCMSK2.
#endif
0;
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
PCMSK0 = MASK_PB;
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
PCMSK1 = MASK_PC;
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
PCMSK2 = MASK_PD;
#endif
}
RFM23B.listen(true);
}
#if defined(ALT_MAIN_LOOP)
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
//// Interrupt count. Marked volatile so safe to read without a lock as is a single byte.
//static volatile uint8_t intCountPB;
// Previous state of port B pins to help detect changes.
static volatile uint8_t prevStatePB;
// Interrupt service routine for PB I/O port transition changes.
ISR(PCINT0_vect)
{
// ++intCountPB;
const uint8_t pins = PINB;
const uint8_t changes = pins ^ prevStatePB;
prevStatePB = pins;
#if defined(RFM23B_INT_MASK)
// RFM23B nIRQ falling edge is of interest.
// Handler routine not required/expected to 'clear' this interrupt.
// TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue/epilogue time and space.
if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))
{ RFM23B.handleInterruptSimple(); }
#endif
}
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PB interrupts required.
// Previous state of port C pins to help detect changes.
static volatile uint8_t prevStatePC;
// Interrupt service routine for PC I/O port transition changes.
ISR(PCINT1_vect)
{
// const uint8_t pins = PINC;
// const uint8_t changes = pins ^ prevStatePC;
// prevStatePC = pins;
//
// ...
}
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
// Previous state of port D pins to help detect changes.
static volatile uint8_t prevStatePD;
// Interrupt service routine for PD I/O port transition changes (including RX).
ISR(PCINT2_vect)
{
// const uint8_t pins = PIND;
// const uint8_t changes = pins ^ prevStatePD;
// prevStatePD = pins;
//
// ....
}
#endif
#endif // ALT_MAIN
// Called from loop().
void loopAlt()
{
// Sleep in low-power mode (waiting for interrupts) until seconds roll.
// NOTE: sleep at the top of the loop to minimise timing jitter/delay from Arduino background activity after loop() returns.
// DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms.
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("*E"); // End-of-cycle sleep.
#endif
#if !defined(MIN_ENERGY_BOOT)
OTV0P2BASE::powerDownSerial(); // Ensure that serial I/O is off.
// Power down most stuff (except radio for hub RX).
minimisePowerWithoutSleep();
#endif
static uint_fast8_t TIME_LSD; // Controller's notion of seconds within major cycle.
uint_fast8_t newTLSD;
while(TIME_LSD == (newTLSD = OTV0P2BASE::getSecondsLT()))
{
// Poll I/O and process message incrementally (in this otherwise idle time)
// before sleep and on wakeup in case some IO needs further processing now,
// eg work was accrued during the previous major slow/outer loop
// or the in a previous orbit of this loop sleep or nap was terminated by an I/O interrupt.
// Come back and have another go if work was done, until the next tick at most.
if(handleQueuedMessages(&Serial, true, &RFM23B)) { continue; }
// If missing h/w interrupts for anything that needs rapid response
// then AVOID the lowest-power long sleep.
#if CONFIG_IMPLIES_MAY_NEED_CONTINUOUS_RX && !defined(PIN_RFM_NIRQ)
#define MUST_POLL_FREQUENTLY true
#else
#define MUST_POLL_FREQUENTLY false
#endif
if(MUST_POLL_FREQUENTLY /** && in hub mode */ )
{
// No h/w interrupt wakeup on receipt of frame,
// so can only sleep for a short time between explicit poll()s,
// though allow wake on interrupt anyway to minimise loop timing jitter.
OTV0P2BASE::nap(WDTO_15MS, true);
}
else
{
// Normal long minimal-power sleep until wake-up interrupt.
// Rely on interrupt to force fall through to I/O poll() below.
OTV0P2BASE::sleepUntilInt();
}
// DEBUG_SERIAL_PRINTLN_FLASHSTRING("w"); // Wakeup.
// idle15AndPoll(); // Attempt to crash the board!
}
TIME_LSD = newTLSD;
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("*S"); // Start-of-cycle wake.
#endif
// START LOOP BODY
// ===============
// DEBUG_SERIAL_PRINTLN_FLASHSTRING("*");
// // Power up serial for the loop body.
// // May just want to turn it on in POSTalt() and leave it on...
// const bool neededWaking = powerUpSerialIfDisabled();
//#if defined(USE_MODULE_FHT8VSIMPLE)
// // Try for double TX for more robust conversation with valve?
// const bool doubleTXForFTH8V = false;
// // FHT8V is highest priority and runs first.
// // ---------- HALF SECOND #0 -----------
// bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); // Time for extra TX before UI.
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@0"); }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE)
// if(useExtraFHT8VTXSlots)
// {
// // Time for extra TX before other actions, but don't bother if minimising power in frost mode.
// // ---------- HALF SECOND #1 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@1"); }
// }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)
// if(useExtraFHT8VTXSlots)
// {
// // ---------- HALF SECOND #2 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@2"); }
// }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)
// if(useExtraFHT8VTXSlots)
// {
// // ---------- HALF SECOND #3 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@3"); }
// }
//#endif
#ifdef HAS_DORM1_VALVE_DRIVE
// Yank valve to random target every minute to try to upset it!
if(0 == TIME_LSD) { ValveDirect.set(OTV0P2BASE::randRNG8() % 101); }
// Simulate human doing the right thing after fitting valve.
if(ValveDirect.isWaitingForValveToBeFitted()) { ValveDirect.signalValveFitted(); }
// Provide regular poll to motor driver.
// May take significant time to run
// so don't call when timing is critical or not much left,
// eg around critical TXes.
ValveDirect.read();
#endif
// // Reading shaft encoder.
// // Measure motor count against (fixed) internal reference.
// power_intermittent_peripherals_enable(true);
// const uint16_t mc = analogueNoiseReducedRead(MOTOR_DRIVE_MC_AIN, INTERNAL);
// void power_intermittent_peripherals_disable();
// DEBUG_SERIAL_PRINT_FLASHSTRING("Count input: ");
// DEBUG_SERIAL_PRINT(mc);
// DEBUG_SERIAL_PRINTLN();
// // Command-Line Interface (CLI) polling.
// // If a reasonable chunk of the minor cycle remains after all other work is done
// // AND the CLI is / should be active OR a status line has just been output
// // then poll/prompt the user for input
// // using a timeout which should safely avoid overrun, ie missing the next basic tick,
// // and which should also allow some energy-saving sleep.
//#if 1 // && defined(SUPPORT_CLI)
// if(true)
// {
// const uint8_t sct = getSubCycleTime();
// const uint8_t listenTime = max(GSCT_MAX/16, CLI_POLL_MIN_SCT);
// if(sct < (GSCT_MAX - 2*listenTime))
// // Don't listen beyond the last 16th of the cycle,
// // or a minimal time if only prodding for interaction with automated front-end,
// // as listening for UART RX uses lots of power.
// { pollCLI(OTV0P2BASE::randRNG8NextBoolean() ? (GSCT_MAX-listenTime) : (sct+CLI_POLL_MIN_SCT), 0 == TIME_LSD); }
// }
//#endif
// // Force any pending output before return / possible UART power-down.
// flushSerialSCTSensitive();
// if(neededWaking) { OTV0P2BASE::powerDownSerial(); }
}
#endif
<commit_msg>TODO-370: stress testing<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2014--2015
*/
/*
Alternate POST / setup and loop / main for non-OpenTRV code running on OpenTRV h/w platform.
Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc!
*/
#include "V0p2_Main.h"
#include "V0p2_Generic_Config.h"
#include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers.
// Arduino libraries.
//#include <Wire.h>
#ifdef ALLOW_CC1_SUPPORT
#include <OTProtocolCC.h>
#endif
#include "Control.h"
#include "FHT8V_Wireless_Rad_Valve.h"
#include "Power_Management.h"
#include "RFM22_Radio.h"
#include "Security.h"
#include "Serial_IO.h"
#include "UI_Minimal.h"
// Link in support for alternate Power On Self-Test and main loop if required.
#if defined(ALT_MAIN_LOOP)
// Mask for Port B input change interrupts.
#define MASK_PB_BASIC 0b00000000 // Nothing.
#ifdef PIN_RFM_NIRQ
#if (PIN_RFM_NIRQ < 8) || (PIN_RFM_NIRQ > 15)
#error PIN_RFM_NIRQ expected to be on port B
#endif
#define RFM23B_INT_MASK (1 << (PIN_RFM_NIRQ&7))
#define MASK_PB (MASK_PB_BASIC | RFM23B_INT_MASK)
#else
#define MASK_PB MASK_PB_BASIC
#endif
//// Mask for Port D input change interrupts.
//#define MASK_PD_BASIC 0b00000001 // Just RX.
//#if defined(ENABLE_VOICE_SENSOR)
//#if VOICE_NIRQ > 7
//#error voice interrupt on wrong port
//#endif
//#define VOICE_INT_MASK (1 << (VOICE_NIRQ&7))
//#define MASK_PD (MASK_PD_BASIC | VOICE_INT_MASK)
//#else
//#define MASK_PD MASK_PD_BASIC // Just RX.
//#endif
// Called from startup() after some initial setup has been done.
// Can abort with panic() if need be.
void POSTalt()
{
#if defined(USE_MODULE_RFM22RADIOSIMPLE)
// Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised.
static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true);
RFM23B.preinit(NULL);
// Check that the radio is correctly connected; panic if not...
if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); }
#endif
// Force initialisation into low-power state.
const int heat = TemperatureC16.read();
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINT_FLASHSTRING("temp: ");
DEBUG_SERIAL_PRINT(heat);
DEBUG_SERIAL_PRINTLN();
#endif
// const int light = AmbLight.read();
//#if 0 && defined(DEBUG)
// DEBUG_SERIAL_PRINT_FLASHSTRING("light: ");
// DEBUG_SERIAL_PRINT(light);
// DEBUG_SERIAL_PRINTLN();
//#endif
// Trailing setup for the run
// --------------------------
// Set up async edge interrupts.
ATOMIC_BLOCK (ATOMIC_RESTORESTATE)
{
//PCMSK0 = PB; PCINT 0--7 (LEARN1 and Radio)
//PCMSK1 = PC; PCINT 8--15
//PCMSK2 = PD; PCINT 16--24 (LEARN2 and MODE, RX)
PCICR =
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
1 | // 0x1 enables PB/PCMSK0.
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
2 | // 0x2 enables PC/PCMSK1.
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
4 | // 0x4 enables PD/PCMSK2.
#endif
0;
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
PCMSK0 = MASK_PB;
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PC interrupts required.
PCMSK1 = MASK_PC;
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
PCMSK2 = MASK_PD;
#endif
}
RFM23B.listen(true);
}
#if defined(ALT_MAIN_LOOP)
#if defined(MASK_PB) && (MASK_PB != 0) // If PB interrupts required.
//// Interrupt count. Marked volatile so safe to read without a lock as is a single byte.
//static volatile uint8_t intCountPB;
// Previous state of port B pins to help detect changes.
static volatile uint8_t prevStatePB;
// Interrupt service routine for PB I/O port transition changes.
ISR(PCINT0_vect)
{
// ++intCountPB;
const uint8_t pins = PINB;
const uint8_t changes = pins ^ prevStatePB;
prevStatePB = pins;
#if defined(RFM23B_INT_MASK)
// RFM23B nIRQ falling edge is of interest.
// Handler routine not required/expected to 'clear' this interrupt.
// TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue/epilogue time and space.
if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))
{ RFM23B.handleInterruptSimple(); }
#endif
}
#endif
#if defined(MASK_PC) && (MASK_PC != 0) // If PB interrupts required.
// Previous state of port C pins to help detect changes.
static volatile uint8_t prevStatePC;
// Interrupt service routine for PC I/O port transition changes.
ISR(PCINT1_vect)
{
// const uint8_t pins = PINC;
// const uint8_t changes = pins ^ prevStatePC;
// prevStatePC = pins;
//
// ...
}
#endif
#if defined(MASK_PD) && (MASK_PD != 0) // If PD interrupts required.
// Previous state of port D pins to help detect changes.
static volatile uint8_t prevStatePD;
// Interrupt service routine for PD I/O port transition changes (including RX).
ISR(PCINT2_vect)
{
// const uint8_t pins = PIND;
// const uint8_t changes = pins ^ prevStatePD;
// prevStatePD = pins;
//
// ....
}
#endif
#endif // ALT_MAIN
// Called from loop().
void loopAlt()
{
// Sleep in low-power mode (waiting for interrupts) until seconds roll.
// NOTE: sleep at the top of the loop to minimise timing jitter/delay from Arduino background activity after loop() returns.
// DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms.
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("*E"); // End-of-cycle sleep.
#endif
#if !defined(MIN_ENERGY_BOOT)
OTV0P2BASE::powerDownSerial(); // Ensure that serial I/O is off.
// Power down most stuff (except radio for hub RX).
minimisePowerWithoutSleep();
#endif
static uint_fast8_t TIME_LSD; // Controller's notion of seconds within major cycle.
uint_fast8_t newTLSD;
while(TIME_LSD == (newTLSD = OTV0P2BASE::getSecondsLT()))
{
// Poll I/O and process message incrementally (in this otherwise idle time)
// before sleep and on wakeup in case some IO needs further processing now,
// eg work was accrued during the previous major slow/outer loop
// or the in a previous orbit of this loop sleep or nap was terminated by an I/O interrupt.
// Come back and have another go if work was done, until the next tick at most.
if(handleQueuedMessages(&Serial, true, &RFM23B)) { continue; }
// If missing h/w interrupts for anything that needs rapid response
// then AVOID the lowest-power long sleep.
#if CONFIG_IMPLIES_MAY_NEED_CONTINUOUS_RX && !defined(PIN_RFM_NIRQ)
#define MUST_POLL_FREQUENTLY true
#else
#define MUST_POLL_FREQUENTLY false
#endif
if(MUST_POLL_FREQUENTLY /** && in hub mode */ )
{
// No h/w interrupt wakeup on receipt of frame,
// so can only sleep for a short time between explicit poll()s,
// though allow wake on interrupt anyway to minimise loop timing jitter.
OTV0P2BASE::nap(WDTO_15MS, true);
}
else
{
// Normal long minimal-power sleep until wake-up interrupt.
// Rely on interrupt to force fall through to I/O poll() below.
OTV0P2BASE::sleepUntilInt();
}
// DEBUG_SERIAL_PRINTLN_FLASHSTRING("w"); // Wakeup.
// idle15AndPoll(); // Attempt to crash the board!
}
TIME_LSD = newTLSD;
#if 0 && defined(DEBUG)
DEBUG_SERIAL_PRINTLN_FLASHSTRING("*S"); // Start-of-cycle wake.
#endif
// START LOOP BODY
// ===============
// DEBUG_SERIAL_PRINTLN_FLASHSTRING("*");
// // Power up serial for the loop body.
// // May just want to turn it on in POSTalt() and leave it on...
// const bool neededWaking = powerUpSerialIfDisabled();
//#if defined(USE_MODULE_FHT8VSIMPLE)
// // Try for double TX for more robust conversation with valve?
// const bool doubleTXForFTH8V = false;
// // FHT8V is highest priority and runs first.
// // ---------- HALF SECOND #0 -----------
// bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); // Time for extra TX before UI.
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@0"); }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE)
// if(useExtraFHT8VTXSlots)
// {
// // Time for extra TX before other actions, but don't bother if minimising power in frost mode.
// // ---------- HALF SECOND #1 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@1"); }
// }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)
// if(useExtraFHT8VTXSlots)
// {
// // ---------- HALF SECOND #2 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@2"); }
// }
//#endif
//#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)
// if(useExtraFHT8VTXSlots)
// {
// // ---------- HALF SECOND #3 -----------
// useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V);
//// if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@3"); }
// }
//#endif
#ifdef HAS_DORM1_VALVE_DRIVE
// Move valve to new target every minute to try to upset it!
// Targets at key thresholds and random.
if(0 == TIME_LSD)
{
switch(OTV0P2BASE::randRNG8() & 1)
{
case 0: ValveDirect.set(DEFAULT_MIN_VALVE_PC_REALLY_OPEN-1); break; // Nominally shut.
case 1: ValveDirect.set(DEFAULT_VALVE_PC_MODERATELY_OPEN); break; // Nominally open.
// Random.
// default: ValveDirect.set(OTV0P2BASE::randRNG8() % 101); break;
}
}
// Simulate human doing the right thing after fitting valve when required.
if(ValveDirect.isWaitingForValveToBeFitted()) { ValveDirect.signalValveFitted(); }
// Provide regular poll to motor driver.
// May take significant time to run
// so don't call when timing is critical or not much left,
// eg around critical TXes.
const uint8_t pc = ValveDirect.read();
DEBUG_SERIAL_PRINT_FLASHSTRING("Pos%: ");
DEBUG_SERIAL_PRINT(pc);
DEBUG_SERIAL_PRINTLN();
#endif
// // Reading shaft encoder.
// // Measure motor count against (fixed) internal reference.
// power_intermittent_peripherals_enable(true);
// const uint16_t mc = analogueNoiseReducedRead(MOTOR_DRIVE_MC_AIN, INTERNAL);
// void power_intermittent_peripherals_disable();
// DEBUG_SERIAL_PRINT_FLASHSTRING("Count input: ");
// DEBUG_SERIAL_PRINT(mc);
// DEBUG_SERIAL_PRINTLN();
// // Command-Line Interface (CLI) polling.
// // If a reasonable chunk of the minor cycle remains after all other work is done
// // AND the CLI is / should be active OR a status line has just been output
// // then poll/prompt the user for input
// // using a timeout which should safely avoid overrun, ie missing the next basic tick,
// // and which should also allow some energy-saving sleep.
//#if 1 // && defined(SUPPORT_CLI)
// if(true)
// {
// const uint8_t sct = getSubCycleTime();
// const uint8_t listenTime = max(GSCT_MAX/16, CLI_POLL_MIN_SCT);
// if(sct < (GSCT_MAX - 2*listenTime))
// // Don't listen beyond the last 16th of the cycle,
// // or a minimal time if only prodding for interaction with automated front-end,
// // as listening for UART RX uses lots of power.
// { pollCLI(OTV0P2BASE::randRNG8NextBoolean() ? (GSCT_MAX-listenTime) : (sct+CLI_POLL_MIN_SCT), 0 == TIME_LSD); }
// }
//#endif
// // Force any pending output before return / possible UART power-down.
// flushSerialSCTSensitive();
// if(neededWaking) { OTV0P2BASE::powerDownSerial(); }
}
#endif
<|endoftext|>
|
<commit_before>// TODO(pbos): Remove this file when it's no longer built in Chromium.
<commit_msg>Remove webrtcvideoengine.cc.<commit_after><|endoftext|>
|
<commit_before>// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/system/public/handlers.h"
#include "net/instaweb/system/public/system_rewrite_options.h"
#include "net/instaweb/util/public/writer.h"
#include "pagespeed/kernel/base/string.h"
namespace net_instaweb {
extern const char* CSS_console_css;
extern const char* JS_console_js;
// Handler which serves PSOL console.
void ConsoleHandler(SystemRewriteOptions* options, Writer* writer,
MessageHandler* handler) {
bool statistics_enabled = options->statistics_enabled();
bool logging_enabled = options->statistics_logging_enabled();
bool log_dir_set = !options->log_dir().empty();
if (statistics_enabled && logging_enabled && log_dir_set) {
// TODO(sligocki): Move static content to a data2cc library.
writer->Write("<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <title>Pagespeed Console</title>\n"
" <style>\n"
" #title {\n"
" font-size: 300%;\n"
" }\n"
" </style>\n"
" <style>", handler);
writer->Write(CSS_console_css, handler);
writer->Write("</style>\n"
" </head>\n"
" <body>\n"
" <div id='top-bar'>\n"
" <span id='title'>Pagespeed Console</span>\n"
" </div>\n"
"\n"
" <div id='suggestions'>\n"
" <p>\n"
" Notable issues:\n"
" </p>\n"
" <div id='pagespeed-graphs-container'></div>\n"
" </div>\n"
" <script src='https://www.google.com/jsapi'></script>\n"
" <script>var pagespeedStatisticsUrl = '", handler);
writer->Write(options->statistics_handler_path(), handler);
writer->Write("'</script>\n"
" <script>", handler);
writer->Write(JS_console_js, handler);
writer->Write("</script>\n"
" </body>\n"
"</html>\n", handler);
} else {
writer->Write("<!DOCTYPE html>\n"
"<p>\n"
" Failed to load Pagespeed Console because:\n"
"</p>\n"
"<ul>\n", handler);
if (!statistics_enabled) {
writer->Write(" <li>ModPagespeedStatistics is not enabled.</li>\n",
handler);
}
if (!logging_enabled) {
writer->Write(" <li>ModPagespeedStatisticsLogging is not enabled."
"</li>\n", handler);
}
if (!log_dir_set) {
writer->Write(" <li>ModPagespeedLogFile is not set.</li>\n", handler);
}
writer->Write("</ul>\n"
"<p>\n"
" In order to use the console you must add the following\n"
" configuration:\n"
"</p>\n"
"<pre>\n"
" ModPagespeedStatistics on\n"
" ModPagespeedStatisticsLogging on\n"
" ModPagespeedLogFile /var/log/pagespeed\n"
"</pre>\n"
"<p>\n"
" See <a href='https://developers.google.com/speed/pagespe"
"ed/module/console'>documentation</a> for more details.\n"
"</p>\n", handler);
}
}
} // namespace net_instaweb
<commit_msg>Update ConsoleHandler to spit out server agnostic configuration information, depending mostly on the documentation link to explain how to correctly configure.<commit_after>// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: sligocki@google.com (Shawn Ligocki)
#include "net/instaweb/system/public/handlers.h"
#include "net/instaweb/system/public/system_rewrite_options.h"
#include "net/instaweb/util/public/writer.h"
#include "pagespeed/kernel/base/string.h"
namespace net_instaweb {
extern const char* CSS_console_css;
extern const char* JS_console_js;
// Handler which serves PSOL console.
void ConsoleHandler(SystemRewriteOptions* options, Writer* writer,
MessageHandler* handler) {
bool statistics_enabled = options->statistics_enabled();
bool logging_enabled = options->statistics_logging_enabled();
bool log_dir_set = !options->log_dir().empty();
if (statistics_enabled && logging_enabled && log_dir_set) {
// TODO(sligocki): Move static content to a data2cc library.
writer->Write("<!DOCTYPE html>\n"
"<html>\n"
" <head>\n"
" <title>PageSpeed Console</title>\n"
" <style>\n"
" #title {\n"
" font-size: 300%;\n"
" }\n"
" </style>\n"
" <style>", handler);
writer->Write(CSS_console_css, handler);
writer->Write("</style>\n"
" </head>\n"
" <body>\n"
" <div id='top-bar'>\n"
" <span id='title'>PageSpeed Console</span>\n"
" </div>\n"
"\n"
" <div id='suggestions'>\n"
" <p>\n"
" Notable issues:\n"
" </p>\n"
" <div id='pagespeed-graphs-container'></div>\n"
" </div>\n"
" <script src='https://www.google.com/jsapi'></script>\n"
" <script>var pagespeedStatisticsUrl = '", handler);
writer->Write(options->statistics_handler_path(), handler);
writer->Write("'</script>\n"
" <script>", handler);
writer->Write(JS_console_js, handler);
writer->Write("</script>\n"
" </body>\n"
"</html>\n", handler);
} else {
writer->Write("<!DOCTYPE html>\n"
"<p>\n"
" Failed to load PageSpeed Console because:\n"
"</p>\n"
"<ul>\n", handler);
if (!statistics_enabled) {
writer->Write(" <li>Statistics is not enabled.</li>\n",
handler);
}
if (!logging_enabled) {
writer->Write(" <li>StatisticsLogging is not enabled."
"</li>\n", handler);
}
if (!log_dir_set) {
writer->Write(" <li>LogDir is not set.</li>\n", handler);
}
writer->Write("</ul>\n"
"<p>\n"
" In order to use the console you must configure these\n"
" options. See the <a href='https://developers.google.com/"
"speed/pagespeed/module/console'>console documentation</a>\n"
" for more details.\n"
"</p>\n", handler);
}
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before><commit_msg>Http Cache: Enable some checks to track a low volume crash.<commit_after><|endoftext|>
|
<commit_before>
# include <Siv3D.hpp> // OpenSiv3D v0.4.3
struct AnimationTexture
{
Array<Texture> textures;
Array<int32> delays;
int32 duration = 0;
explicit operator bool() const noexcept
{
return !textures.isEmpty();
}
Size size() const noexcept
{
if (!textures)
{
return Size(0, 0);
}
return textures.front().size();
}
size_t frames() const noexcept
{
return textures.size();
}
size_t getFrameIndex(int32 timeMillisec) const noexcept
{
return AnimatedGIFReader::MillisecToIndex(timeMillisec, delays, duration);
}
const Texture& getTexture(int32 timeMillisec) const noexcept
{
return textures[getFrameIndex(timeMillisec)];
}
};
void Main()
{
AnimationTexture animation;
{
const AnimatedGIFReader gif(U"example/test.gif");
if (!gif)
{
throw Error(U"Failed to open a gif file");
}
Array<Image> images;
if (gif.read(images, animation.delays, animation.duration))
{
animation.textures = images.map([](const Image& i) { return Texture(i); });
}
else
{
throw Error(U"Failed to load a gif animation");
}
}
Print << U"{}, {} frames ({} ms)"_fmt(animation.size(), animation.frames(), animation.duration);
const Point pos(10, 90);
bool showTiles = false;
while (System::Update())
{
const int32 timeMillisec = static_cast<int32>(Scene::Time() * 1000);
const auto& texture = animation.getTexture(timeMillisec);
SimpleGUI::CheckBox(showTiles, U"Show tiles", Vec2(10, 40));
if (showTiles)
{
Rect(pos, texture.size()).draw();
{
ScopedViewport2D vp(pos, texture.size());
for (auto p : step(texture.size() / 10 + Size(1, 1)))
{
if (IsEven(p.x + p.y))
{
Rect(p * 10, 10).draw(ColorF(0.8));
}
}
}
}
texture.draw(pos);
}
}
<commit_msg>v0.4.3 beta 準備 (mac)<commit_after>
# include <Siv3D.hpp> // OpenSiv3D v0.4.3
void Main()
{
// 背景を水色にする
Scene::SetBackground(ColorF(0.8, 0.9, 1.0));
// 大きさ 60 のフォントを用意
const Font font(60);
// 猫のテクスチャを用意
const Texture cat(Emoji(U"🐈"));
// 猫の座標
Vec2 catPos(640, 450);
while (System::Update())
{
// テキストを画面の中心に描く
font(U"Hello, Siv3D!🐣").drawAt(Scene::Center(), Palette::Black);
// 大きさをアニメーションさせて猫を表示する
cat.resized(100 + Periodic::Sine0_1(1s) * 20).drawAt(catPos);
// マウスカーソルに追従する半透明の赤い円を描く
Circle(Cursor::Pos(), 40).draw(ColorF(1, 0, 0, 0.5));
// [A] キーが押されたら
if (KeyA.down())
{
// Hello とデバッグ表示する
Print << U"Hello!";
}
// ボタンが押されたら
if (SimpleGUI::Button(U"Move the cat", Vec2(600, 20)))
{
// 猫の座標を画面内のランダムな位置に移動する
catPos = RandomVec2(Scene::Rect());
}
}
}
//
// = アドバイス =
// macOS 10.15 Catalina で、アプリケーションを起動するたびに
// ファイルアクセス許可のダイアログが表示される場合、プロジェクトのフォルダを
// User/アプリケーション に移動させることで通常は表示されなくなります。
// 特別なファイルシステム関数の使用や、Web カメラ、マイク使用時のダイアログは消せません。
//
// = お役立ちリンク =
//
// OpenSiv3D リファレンス
// https://siv3d.github.io/ja-jp/
//
// チュートリアル
// https://siv3d.github.io/ja-jp/tutorial/basic/
//
// よくある間違い
// https://siv3d.github.io/ja-jp/articles/mistakes/
//
// サポートについて
// https://siv3d.github.io/ja-jp/support/support/
//
// Siv3D Slack (ユーザコミュニティ) への参加
// https://siv3d.github.io/ja-jp/community/community/
//
// 新機能の提案やバグの報告
// https://github.com/Siv3D/OpenSiv3D/issues
//
<|endoftext|>
|
<commit_before>#ifndef CLFFT_HPP_
#define CLFFT_HPP_
#include "helper.h"
#include "fft_abstract.hpp"
#include "fixture_test_suite.hpp"
#include "clfft_helper.hpp"
#include <clFFT.h>
namespace gearshifft
{
namespace ClFFT
{
namespace traits
{
template< typename T_Precision >
struct Types;
template<>
struct Types<float>
{
using ComplexType = cl_float2;
using RealType = cl_float;
};
template<>
struct Types<double>
{
using ComplexType = cl_double2;
using RealType = cl_double;
};
template< typename TPrecision=float >
struct FFTPrecision: std::integral_constant< clfftPrecision, CLFFT_SINGLE >{};
template<>
struct FFTPrecision<double>: std::integral_constant< clfftPrecision, CLFFT_DOUBLE >{};
template< bool IsComplex=true >
struct FFTLayout {
static constexpr clfftLayout value = CLFFT_COMPLEX_INTERLEAVED;
static constexpr clfftLayout value_transformed = CLFFT_COMPLEX_INTERLEAVED;
};
template<>
struct FFTLayout<false> {
static constexpr clfftLayout value = CLFFT_REAL;
static constexpr clfftLayout value_transformed = CLFFT_HERMITIAN_INTERLEAVED;
};
template< bool T_isInplace=true >
struct FFTInplace: std::integral_constant< clfftResultLocation, CLFFT_INPLACE >{};
template<>
struct FFTInplace<false>: std::integral_constant< clfftResultLocation, CLFFT_OUTOFPLACE >{};
} // traits
struct Context {
cl_platform_id platform = 0;
cl_device_id device = 0;
cl_context ctx = 0;
void create() {
std::cout<<"Create OpenCL and clFFT context ..."<<std::endl;
cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };
cl_int err = CL_SUCCESS;
findClDevice(CL_DEVICE_TYPE_GPU, &platform, &device);
props[1] = (cl_context_properties)platform;
ctx = clCreateContext( props, 1, &device, nullptr, nullptr, &err );
CHECK_CL(err);
clfftSetupData fftSetup;
CHECK_CL(clfftInitSetupData(&fftSetup));
CHECK_CL(clfftSetup(&fftSetup));
}
void destroy() {
if(ctx) {
std::cout << "Destroying clFFT and OpenCL Context ..." << std::endl;
CHECK_CL( clfftTeardown( ) );
CHECK_CL(clReleaseContext( ctx ));
ctx = 0;
}
}
~Context()
{
destroy();
}
} context;
/**
* Plan Creator depending on FFT transform type.
*/
template<clfftDim FFTDim, size_t Ndim>
constexpr void makePlan(clfftPlanHandle& plan, const std::array<unsigned,Ndim>& e){
size_t clLengths[3] = {e[0], Ndim==2?e[1]:1, Ndim==3?e[2]:1};
CHECK_CL(clfftCreateDefaultPlan(&plan, context.ctx, FFTDim, clLengths));
}
/**
* ClFFT plan and execution class.
*
* This class handles:
* - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.
*/
template<typename TFFT, // see fft_abstract.hpp (FFT_Inplace_Real, ...)
typename TPrecision, // double, float
size_t NDim // 1..3
>
struct ClFFTImpl
{
using ComplexType = typename traits::Types<TPrecision>::ComplexType;
using RealType = typename traits::Types<TPrecision>::RealType;
using Extent = std::array<unsigned,NDim>;
static constexpr auto IsInplace = TFFT::IsInplace;
static constexpr auto IsComplex = TFFT::IsComplex;
static constexpr auto Padding = IsInplace && IsComplex==false;
static constexpr clfftDim FFTDim = NDim==1 ? CLFFT_1D : NDim==2 ? CLFFT_2D : CLFFT_3D;
using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;
size_t n_;
size_t n_padded_;
Extent extents_;
cl_command_queue queue_ = 0;
clfftPlanHandle plan_ = 0;
cl_mem data_ = 0;
cl_mem data_transform_ = 0; // intermediate buffer
size_t data_size_ = 0;
size_t data_transform_size_ = 0;
size_t w;
size_t h;
size_t pitch;
size_t region[3];
size_t offset[3] = {0, 0, 0};
size_t strides[3] = {1};
size_t transform_strides[3] = {1};
size_t dist;
size_t transform_dist;
ClFFTImpl(const Extent& cextents)
: extents_(cextents)
{
cl_int err;
if(context.ctx==0)
context.create();
queue_ = clCreateCommandQueue( context.ctx, context.device, 0, &err );
CHECK_CL(err);
n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<unsigned>());
if(Padding){
n_padded_ = n_ / extents_[0] * (extents_[0]/2 + 1);
w = extents_[0] * sizeof(RealType);
h = n_ * sizeof(RealType) / w;
pitch = (extents_[0]/2+1) * sizeof(ComplexType);
region[0] = w; // in bytes
region[1] = h; // in counts (OpenCL1.1 is wrong here saying in bytes)
region[2] = 1; // in counts (same)
strides[1] = 2*(extents_[0]/2+1);
strides[2] = 2 * n_padded_ / extents_[NDim-1];
transform_strides[1] = extents_[0]/2+1;
transform_strides[2] = n_padded_ / extents_[NDim-1];
dist = 2 * n_padded_;
transform_dist = n_padded_;
}
data_size_ = ( Padding ? 2*n_padded_*sizeof(RealType) : n_ * sizeof(RealOrComplexType) );
data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);
}
/**
* Returns allocated memory on device for FFT
*/
size_t getAllocSize() {
return data_size_ + data_transform_size_;
}
/**
* Returns estimated allocated memory on device for FFT plan
*/
size_t getPlanSize() {
size_t size1 = 0;
size_t size2 = 0;
init_forward();
CHECK_CL(clfftGetTmpBufSize( plan_, &size1 ));
init_backward();
CHECK_CL(clfftGetTmpBufSize( plan_, &size2 ));
CHECK_CL(clfftDestroyPlan( &plan_ ));
return std::max(size1,size2);
}
// --- next methods are benchmarked ---
void malloc() {
cl_int err;
data_ = clCreateBuffer( context.ctx,
CL_MEM_READ_WRITE,
data_size_,
nullptr, // host pointer @todo
&err );
//std::cout << " data " << data_size_ << std::endl;
if(IsInplace==false){
data_transform_ = clCreateBuffer( context.ctx,
CL_MEM_READ_WRITE,
data_transform_size_,
nullptr, // host pointer
&err );
//std::cout << " transform " <<data_transform_size_ << std::endl;
}
}
// create FFT plan handle
void init_forward() {
makePlan<FFTDim>(plan_, extents_);
CHECK_CL(clfftSetPlanPrecision(plan_, traits::FFTPrecision<TPrecision>::value));
CHECK_CL(clfftSetLayout(plan_,
traits::FFTLayout<IsComplex>::value,
traits::FFTLayout<IsComplex>::value_transformed));
CHECK_CL(clfftSetResultLocation(plan_, traits::FFTInplace<IsInplace>::value));
if(Padding){
CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, strides));
CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, transform_strides));
CHECK_CL(clfftSetPlanDistance(plan_, dist, transform_dist));
}
CHECK_CL(clfftBakePlan(plan_,
1, // number of queues
&queue_,
nullptr, // callback
nullptr)); // user data
}
// recreates plan if needed
void init_backward() {
if(IsComplex==false){
CHECK_CL(clfftSetLayout(plan_,
traits::FFTLayout<IsComplex>::value_transformed,
traits::FFTLayout<IsComplex>::value));
if(Padding){
CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, strides));
CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, transform_strides));
CHECK_CL(clfftSetPlanDistance(plan_, transform_dist, dist));
}
CHECK_CL(clfftBakePlan(plan_,
1, // number of queues
&queue_,
0, // callback
0)); // user data
}
}
void execute_forward() {
CHECK_CL(clfftEnqueueTransform(plan_,
CLFFT_FORWARD,
1, // numQueuesAndEvents
&queue_,
0, // numWaitEvents
0, // waitEvents
0, // outEvents
&data_, // input
IsInplace ? &data_ : &data_transform_, // output
0)); // tmpBuffer
CHECK_CL(clFinish(queue_));
}
void execute_backward() {
CHECK_CL(clfftEnqueueTransform(plan_,
CLFFT_BACKWARD,
1, // numQueuesAndEvents
&queue_,
0, // numWaitEvents
nullptr, // waitEvents
nullptr, // outEvents
IsInplace ? &data_ : &data_transform_, // input
IsInplace ? &data_ : &data_, // output
nullptr)); // tmpBuffer
CHECK_CL(clFinish(queue_));
}
template<typename THostData>
void upload(THostData* input) {
if(Padding && NDim>1)
{
//printf("pitch=%zu w=%zu h=%zu\n", pitch, w, h);
CHECK_CL(clEnqueueWriteBufferRect( queue_,
data_,
CL_TRUE, // blocking_write
offset, // buffer origin
offset, // host origin
region,
pitch, // buffer row pitch
0, // buffer slice pitch
0, // host row pitch
0, // host slice pitch
input,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}else{
CHECK_CL(clEnqueueWriteBuffer( queue_,
data_,
CL_TRUE, // blocking_write
0, // offset
Padding ? n_*sizeof(RealType) : data_size_,
input,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}
}
template<typename THostData>
void download(THostData* output) {
if(Padding && NDim>1)
{
CHECK_CL(clEnqueueReadBufferRect( queue_,
data_,
CL_TRUE, // blocking_write
offset, // buffer origin
offset, // host origin
region,
pitch, // buffer row pitch
0, // buffer slice pitch
0, // host row pitch
0, // host slice pitch
output,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}else{
CHECK_CL(clEnqueueReadBuffer( queue_,
data_,
CL_TRUE, // blocking_write
0, // offset
Padding ? n_*sizeof(RealType) : data_size_,
output,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}
}
void destroy() {
CHECK_CL( clFinish(queue_) );
CHECK_CL( clReleaseMemObject( data_ ) );
if(IsInplace==false)
CHECK_CL( clReleaseMemObject( data_transform_ ) );
CHECK_CL(clfftDestroyPlan( &plan_ ));
CHECK_CL( clReleaseCommandQueue( queue_ ) );
data_ = 0;
data_transform_ = 0;
plan_ = 0;
queue_ = 0;
}
};
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, ClFFTImpl, helper::TimerCPU> Inplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, ClFFTImpl, helper::TimerCPU> Outplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, ClFFTImpl, helper::TimerCPU> Inplace_Complex;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, ClFFTImpl, helper::TimerCPU> Outplace_Complex;
} // namespace ClFFT
} // gearshifft
// -- Execute Benchmarks --
RUN_BENCHMARKS_NORMALIZED_FFT(ClFFT,
gearshifft::ClFFT::Inplace_Real,
gearshifft::ClFFT::Outplace_Real,
gearshifft::ClFFT::Inplace_Complex,
gearshifft::ClFFT::Outplace_Complex
)
#endif /* CLFFT_HPP_ */
<commit_msg>minor code change.<commit_after>#ifndef CLFFT_HPP_
#define CLFFT_HPP_
#include "helper.h"
#include "fft_abstract.hpp"
#include "fixture_test_suite.hpp"
#include "clfft_helper.hpp"
#include <clFFT.h>
namespace gearshifft
{
namespace ClFFT
{
namespace traits
{
template< typename T_Precision >
struct Types;
template<>
struct Types<float>
{
using ComplexType = cl_float2;
using RealType = cl_float;
};
template<>
struct Types<double>
{
using ComplexType = cl_double2;
using RealType = cl_double;
};
template< typename TPrecision=float >
struct FFTPrecision: std::integral_constant< clfftPrecision, CLFFT_SINGLE >{};
template<>
struct FFTPrecision<double>: std::integral_constant< clfftPrecision, CLFFT_DOUBLE >{};
template< bool IsComplex=true >
struct FFTLayout {
static constexpr clfftLayout value = CLFFT_COMPLEX_INTERLEAVED;
static constexpr clfftLayout value_transformed = CLFFT_COMPLEX_INTERLEAVED;
};
template<>
struct FFTLayout<false> {
static constexpr clfftLayout value = CLFFT_REAL;
static constexpr clfftLayout value_transformed = CLFFT_HERMITIAN_INTERLEAVED;
};
template< bool T_isInplace=true >
struct FFTInplace: std::integral_constant< clfftResultLocation, CLFFT_INPLACE >{};
template<>
struct FFTInplace<false>: std::integral_constant< clfftResultLocation, CLFFT_OUTOFPLACE >{};
} // traits
struct Context {
cl_platform_id platform = 0;
cl_device_id device = 0;
cl_context ctx = 0;
void create() {
std::cout<<"Create OpenCL and clFFT context ..."<<std::endl;
cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };
cl_int err = CL_SUCCESS;
findClDevice(CL_DEVICE_TYPE_GPU, &platform, &device);
props[1] = (cl_context_properties)platform;
ctx = clCreateContext( props, 1, &device, nullptr, nullptr, &err );
CHECK_CL(err);
clfftSetupData fftSetup;
CHECK_CL(clfftInitSetupData(&fftSetup));
CHECK_CL(clfftSetup(&fftSetup));
}
void destroy() {
if(ctx) {
std::cout << "Destroying clFFT and OpenCL Context ..." << std::endl;
CHECK_CL( clfftTeardown( ) );
CHECK_CL(clReleaseContext( ctx ));
ctx = 0;
}
}
~Context()
{
destroy();
}
} context;
/**
* Plan Creator depending on FFT transform type.
*/
template<clfftDim FFTDim, size_t Ndim>
constexpr void makePlan(clfftPlanHandle& plan, const std::array<unsigned,Ndim>& e){
size_t clLengths[3] = {e[0], Ndim==2?e[1]:1, Ndim==3?e[2]:1};
CHECK_CL(clfftCreateDefaultPlan(&plan, context.ctx, FFTDim, clLengths));
}
/**
* ClFFT plan and execution class.
*
* This class handles:
* - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.
*/
template<typename TFFT, // see fft_abstract.hpp (FFT_Inplace_Real, ...)
typename TPrecision, // double, float
size_t NDim // 1..3
>
struct ClFFTImpl
{
using ComplexType = typename traits::Types<TPrecision>::ComplexType;
using RealType = typename traits::Types<TPrecision>::RealType;
using Extent = std::array<unsigned,NDim>;
static constexpr auto IsInplace = TFFT::IsInplace;
static constexpr auto IsComplex = TFFT::IsComplex;
static constexpr auto Padding = IsInplace && IsComplex==false;
static constexpr clfftDim FFTDim = NDim==1 ? CLFFT_1D : NDim==2 ? CLFFT_2D : CLFFT_3D;
using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;
size_t n_;
size_t n_padded_;
Extent extents_;
cl_command_queue queue_ = 0;
clfftPlanHandle plan_ = 0;
cl_mem data_ = 0;
cl_mem data_transform_ = 0; // intermediate buffer
size_t data_size_ = 0;
size_t data_transform_size_ = 0;
size_t w;
size_t h;
size_t pitch;
size_t region[3];
size_t offset[3] = {0, 0, 0};
size_t strides[3] = {1};
size_t transform_strides[3] = {1};
size_t dist;
size_t transform_dist;
ClFFTImpl(const Extent& cextents)
: extents_(cextents)
{
cl_int err;
if(context.ctx==0)
context.create();
queue_ = clCreateCommandQueue( context.ctx, context.device, 0, &err );
CHECK_CL(err);
n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<unsigned>());
if(Padding){
n_padded_ = n_ / extents_[0] * (extents_[0]/2 + 1);
w = extents_[0] * sizeof(RealType);
h = n_ / extents_[0];
pitch = (extents_[0]/2+1) * sizeof(ComplexType);
region[0] = w; // in bytes
region[1] = h; // in counts (OpenCL1.1 is wrong here saying in bytes)
region[2] = 1; // in counts (same)
strides[1] = 2*(extents_[0]/2+1);
strides[2] = 2 * n_padded_ / extents_[NDim-1];
transform_strides[1] = extents_[0]/2+1;
transform_strides[2] = n_padded_ / extents_[NDim-1];
dist = 2 * n_padded_;
transform_dist = n_padded_;
}
data_size_ = ( Padding ? 2*n_padded_*sizeof(RealType) : n_ * sizeof(RealOrComplexType) );
data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);
}
/**
* Returns allocated memory on device for FFT
*/
size_t getAllocSize() {
return data_size_ + data_transform_size_;
}
/**
* Returns estimated allocated memory on device for FFT plan
*/
size_t getPlanSize() {
size_t size1 = 0;
size_t size2 = 0;
init_forward();
CHECK_CL(clfftGetTmpBufSize( plan_, &size1 ));
init_backward();
CHECK_CL(clfftGetTmpBufSize( plan_, &size2 ));
CHECK_CL(clfftDestroyPlan( &plan_ ));
return std::max(size1,size2);
}
// --- next methods are benchmarked ---
void malloc() {
cl_int err;
data_ = clCreateBuffer( context.ctx,
CL_MEM_READ_WRITE,
data_size_,
nullptr, // host pointer @todo
&err );
//std::cout << " data " << data_size_ << std::endl;
if(IsInplace==false){
data_transform_ = clCreateBuffer( context.ctx,
CL_MEM_READ_WRITE,
data_transform_size_,
nullptr, // host pointer
&err );
//std::cout << " transform " <<data_transform_size_ << std::endl;
}
}
// create FFT plan handle
void init_forward() {
makePlan<FFTDim>(plan_, extents_);
CHECK_CL(clfftSetPlanPrecision(plan_, traits::FFTPrecision<TPrecision>::value));
CHECK_CL(clfftSetLayout(plan_,
traits::FFTLayout<IsComplex>::value,
traits::FFTLayout<IsComplex>::value_transformed));
CHECK_CL(clfftSetResultLocation(plan_, traits::FFTInplace<IsInplace>::value));
if(Padding){
CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, strides));
CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, transform_strides));
CHECK_CL(clfftSetPlanDistance(plan_, dist, transform_dist));
}
CHECK_CL(clfftBakePlan(plan_,
1, // number of queues
&queue_,
nullptr, // callback
nullptr)); // user data
}
// recreates plan if needed
void init_backward() {
if(IsComplex==false){
CHECK_CL(clfftSetLayout(plan_,
traits::FFTLayout<IsComplex>::value_transformed,
traits::FFTLayout<IsComplex>::value));
if(Padding){
CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, strides));
CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, transform_strides));
CHECK_CL(clfftSetPlanDistance(plan_, transform_dist, dist));
}
CHECK_CL(clfftBakePlan(plan_,
1, // number of queues
&queue_,
0, // callback
0)); // user data
}
}
void execute_forward() {
CHECK_CL(clfftEnqueueTransform(plan_,
CLFFT_FORWARD,
1, // numQueuesAndEvents
&queue_,
0, // numWaitEvents
0, // waitEvents
0, // outEvents
&data_, // input
IsInplace ? &data_ : &data_transform_, // output
0)); // tmpBuffer
CHECK_CL(clFinish(queue_));
}
void execute_backward() {
CHECK_CL(clfftEnqueueTransform(plan_,
CLFFT_BACKWARD,
1, // numQueuesAndEvents
&queue_,
0, // numWaitEvents
nullptr, // waitEvents
nullptr, // outEvents
IsInplace ? &data_ : &data_transform_, // input
IsInplace ? &data_ : &data_, // output
nullptr)); // tmpBuffer
CHECK_CL(clFinish(queue_));
}
template<typename THostData>
void upload(THostData* input) {
if(Padding && NDim>1)
{
//printf("pitch=%zu w=%zu h=%zu\n", pitch, w, h);
CHECK_CL(clEnqueueWriteBufferRect( queue_,
data_,
CL_TRUE, // blocking_write
offset, // buffer origin
offset, // host origin
region,
pitch, // buffer row pitch
0, // buffer slice pitch
0, // host row pitch
0, // host slice pitch
input,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}else{
CHECK_CL(clEnqueueWriteBuffer( queue_,
data_,
CL_TRUE, // blocking_write
0, // offset
Padding ? n_*sizeof(RealType) : data_size_,
input,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}
}
template<typename THostData>
void download(THostData* output) {
if(Padding && NDim>1)
{
CHECK_CL(clEnqueueReadBufferRect( queue_,
data_,
CL_TRUE, // blocking_write
offset, // buffer origin
offset, // host origin
region,
pitch, // buffer row pitch
0, // buffer slice pitch
0, // host row pitch
0, // host slice pitch
output,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}else{
CHECK_CL(clEnqueueReadBuffer( queue_,
data_,
CL_TRUE, // blocking_write
0, // offset
Padding ? n_*sizeof(RealType) : data_size_,
output,
0, // num_events_in_wait_list
nullptr, // event_wait_list
nullptr )); // event
}
}
void destroy() {
CHECK_CL( clFinish(queue_) );
CHECK_CL( clReleaseMemObject( data_ ) );
if(IsInplace==false)
CHECK_CL( clReleaseMemObject( data_transform_ ) );
CHECK_CL(clfftDestroyPlan( &plan_ ));
CHECK_CL( clReleaseCommandQueue( queue_ ) );
data_ = 0;
data_transform_ = 0;
plan_ = 0;
queue_ = 0;
}
};
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, ClFFTImpl, helper::TimerCPU> Inplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, ClFFTImpl, helper::TimerCPU> Outplace_Real;
typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, ClFFTImpl, helper::TimerCPU> Inplace_Complex;
typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, ClFFTImpl, helper::TimerCPU> Outplace_Complex;
} // namespace ClFFT
} // gearshifft
// -- Execute Benchmarks --
RUN_BENCHMARKS_NORMALIZED_FFT(ClFFT,
gearshifft::ClFFT::Inplace_Real,
gearshifft::ClFFT::Outplace_Real,
gearshifft::ClFFT::Inplace_Complex,
gearshifft::ClFFT::Outplace_Complex
)
#endif /* CLFFT_HPP_ */
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The Native Client 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 <errno.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>
#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability_sockets.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/trusted/debug_stub/platform.h"
#include "native_client/src/trusted/debug_stub/transport.h"
#include "native_client/src/trusted/debug_stub/util.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
using gdb_rsp::stringvec;
using gdb_rsp::StringSplit;
namespace port {
typedef int socklen_t;
class Transport : public ITransport {
public:
Transport()
: buf_(new char[kBufSize]),
pos_(0),
size_(0) {
handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#if NACL_WINDOWS
CreateSocketEvent();
#endif
}
explicit Transport(NaClSocketHandle s)
: buf_(new char[kBufSize]),
pos_(0),
size_(0),
handle_(s) {
#if NACL_WINDOWS
CreateSocketEvent();
#endif
}
~Transport() {
if (handle_ != NACL_INVALID_SOCKET) NaClCloseSocket(handle_);
#if NACL_WINDOWS
if (!WSACloseEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::~Transport: Failed to close socket event\n");
}
#endif
}
#if NACL_WINDOWS
void CreateSocketEvent() {
socket_event_ = WSACreateEvent();
if (socket_event_ == WSA_INVALID_EVENT) {
NaClLog(LOG_FATAL,
"Transport::CreateSocketEvent: Failed to create socket event\n");
}
if (WSAEventSelect(handle_, socket_event_, FD_READ) == SOCKET_ERROR) {
NaClLog(LOG_FATAL,
"Transport::CreateSocketEvent: Failed to bind event to socket\n");
}
}
#endif
// Read from this transport, return true on success.
virtual bool Read(void *ptr, int32_t len);
// Write to this transport, return true on success.
virtual bool Write(const void *ptr, int32_t len);
// Return true if there is data to read.
virtual bool IsDataAvailable() {
if (pos_ < size_) {
return true;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(handle_, &fds);
// We want a "non-blocking" check
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
// Check if this file handle can select on read
int cnt = select(static_cast<int>(handle_) + 1, &fds, 0, 0, &timeout);
// If we are ready, or if there is an error. We return true
// on error, to let the next IO request fail.
if (cnt != 0) return true;
return false;
}
virtual void WaitForDebugStubEvent(struct NaClApp *nap,
bool ignore_input_from_gdb);
// On windows, the header that defines this has other definition
// colitions, so we define it outselves just in case
#ifndef SD_BOTH
#define SD_BOTH 2
#endif
virtual void Disconnect() {
// Shutdown the conneciton in both diections. This should
// always succeed, and nothing we can do if this fails.
(void) ::shutdown(handle_, SD_BOTH);
}
protected:
// Copy buffered data to *dst up to len bytes and update dst and len.
void CopyFromBuffer(char **dst, int32_t *len);
// Read available data from the socket. Return false on EOF or error.
bool ReadSomeData();
static const int kBufSize = 4096;
nacl::scoped_array<char> buf_;
int32_t pos_;
int32_t size_;
NaClSocketHandle handle_;
#if NACL_WINDOWS
HANDLE socket_event_;
#endif
};
void Transport::CopyFromBuffer(char **dst, int32_t *len) {
int32_t copy_bytes = std::min(*len, size_ - pos_);
memcpy(*dst, buf_.get() + pos_, copy_bytes);
pos_ += copy_bytes;
*len -= copy_bytes;
*dst += copy_bytes;
}
bool Transport::ReadSomeData() {
while (true) {
int result = ::recv(handle_, buf_.get() + size_, kBufSize - size_, 0);
if (result > 0) {
size_ += result;
return true;
}
if (result == 0)
return false;
#if NACL_WINDOWS
// WSAEventSelect sets socket to non-blocking mode. This is essential
// for socket event notification to work, there is no workaround.
// See remarks section at the page
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms741576(v=vs.85).aspx
if (NaClSocketGetLastError() == WSAEWOULDBLOCK) {
if (WaitForSingleObject(socket_event_, INFINITE) == WAIT_FAILED) {
NaClLog(LOG_FATAL,
"Transport::ReadSomeData: Failed to wait on socket event\n");
}
if (!ResetEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::ReadSomeData: Failed to reset socket event\n");
}
continue;
}
#endif
if (NaClSocketGetLastError() != EINTR)
return false;
}
}
bool Transport::Read(void *ptr, int32_t len) {
char *dst = static_cast<char *>(ptr);
if (pos_ < size_) {
CopyFromBuffer(&dst, &len);
}
while (len > 0) {
pos_ = 0;
size_ = 0;
if (!ReadSomeData()) {
return false;
}
CopyFromBuffer(&dst, &len);
}
return true;
}
bool Transport::Write(const void *ptr, int32_t len) {
const char *src = static_cast<const char *>(ptr);
while (len > 0) {
int result = ::send(handle_, src, len, 0);
if (result > 0) {
src += result;
len -= result;
continue;
}
if (result == 0) {
return false;
}
if (NaClSocketGetLastError() != EINTR) {
return false;
}
}
return true;
}
void Transport::WaitForDebugStubEvent(struct NaClApp *nap,
bool ignore_input_from_gdb) {
bool wait = true;
// If we are told to ignore messages from gdb, we will exit from this
// function only if new data is sent by gdb.
if ((pos_ < size_ && !ignore_input_from_gdb) ||
nap->faulted_thread_count > 0) {
// Clear faulted thread events to save debug stub loop iterations.
wait = false;
}
#if NACL_WINDOWS
HANDLE handles[2];
handles[0] = nap->faulted_thread_event;
handles[1] = socket_event_;
int count = size_ < kBufSize ? 2 : 1;
int result = WaitForMultipleObjects(count, handles, FALSE,
wait ? INFINITE : 0);
if (result == WAIT_OBJECT_0 + 1) {
if (!ResetEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: "
"Failed to reset socket event\n");
}
return;
}
if (result == WAIT_TIMEOUT || result == WAIT_OBJECT_0)
return;
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Wait for events failed\n");
#else
fd_set fds;
FD_ZERO(&fds);
FD_SET(nap->faulted_thread_fd_read, &fds);
int max_fd = nap->faulted_thread_fd_read;
if (size_ < kBufSize) {
FD_SET(handle_, &fds);
max_fd = std::max(max_fd, handle_);
}
int ret;
// We don't need sleep-polling on Linux now, so we set either zero or infinite
// timeout.
if (wait) {
ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
} else {
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
ret = select(max_fd + 1, &fds, NULL, NULL, &timeout);
}
if (ret < 0) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Failed to wait for "
"debug stub event\n");
}
if (ret > 0) {
if (FD_ISSET(nap->faulted_thread_fd_read, &fds)) {
char buf[16];
if (read(nap->faulted_thread_fd_read, &buf, sizeof(buf)) < 0) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Failed to read from "
"debug stub event pipe fd\n");
}
}
if (FD_ISSET(handle_, &fds))
ReadSomeData();
}
#endif
}
// Convert string in the form of [addr][:port] where addr is a
// IPv4 address or host name, and port is a 16b tcp/udp port.
// Both portions are optional, and only the portion of the address
// provided is updated. Values are provided in network order.
static bool StringToIPv4(const std::string &instr, uint32_t *addr,
uint16_t *port) {
// Make a copy so the are unchanged unless we succeed
uint32_t outaddr = *addr;
uint16_t outport = *port;
// Substrings of the full ADDR:PORT
std::string addrstr;
std::string portstr;
// We should either have one or two tokens in the form of:
// IP - IP, NUL
// IP: - IP, NUL
// :PORT - NUL, PORT
// IP:PORT - IP, PORT
// Search for the port marker
size_t portoff = instr.find(':');
// If we found a ":" before the end, get both substrings
if ((portoff != std::string::npos) && (portoff + 1 < instr.size())) {
addrstr = instr.substr(0, portoff);
portstr = instr.substr(portoff + 1, std::string::npos);
} else {
// otherwise the entire string is the addr portion.
addrstr = instr;
portstr = "";
}
// If the address portion was provided, update it
if (addrstr.size()) {
// Special case 0.0.0.0 which means any IPv4 interface
if (addrstr == "0.0.0.0") {
outaddr = 0;
} else {
struct hostent *host = gethostbyname(addrstr.data());
// Check that we found an IPv4 host
if ((NULL == host) || (AF_INET != host->h_addrtype)) return false;
// Make sure the IP list isn't empty.
if (0 == host->h_addr_list[0]) return false;
// Use the first address in the array of address pointers.
uint32_t **addrarray = reinterpret_cast<uint32_t**>(host->h_addr_list);
outaddr = *addrarray[0];
}
}
// if the port portion was provided, then update it
if (portstr.size()) {
int val = atoi(portstr.data());
if ((val < 0) || (val > 65535)) return false;
outport = ntohs(static_cast<uint16_t>(val));
}
// We haven't failed, so set the values
*addr = outaddr;
*port = outport;
return true;
}
static bool BuildSockAddr(const char *addr, struct sockaddr_in *sockaddr) {
std::string addrstr = addr;
uint32_t *pip = reinterpret_cast<uint32_t*>(&sockaddr->sin_addr.s_addr);
uint16_t *pport = reinterpret_cast<uint16_t*>(&sockaddr->sin_port);
sockaddr->sin_family = AF_INET;
return StringToIPv4(addrstr, pip, pport);
}
SocketBinding::SocketBinding(NaClSocketHandle socket_handle)
: socket_handle_(socket_handle) {
}
SocketBinding *SocketBinding::Bind(const char *addr) {
NaClSocketHandle socket_handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket_handle == NACL_INVALID_SOCKET) {
NaClLog(LOG_ERROR, "Failed to create socket.\n");
return NULL;
}
struct sockaddr_in saddr;
// Clearing sockaddr_in first appears to be necessary on Mac OS X.
memset(&saddr, 0, sizeof(saddr));
socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(0x7F000001);
saddr.sin_port = htons(4014);
// Override portions address that are provided
if (addr) BuildSockAddr(addr, &saddr);
// This is necessary to ensure that the TCP port is released
// promptly when sel_ldr exits. Without this, the TCP port might
// only be released after a timeout, and later processes can fail
// to bind it.
int reuse_address = 1;
if (setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<char *>(&reuse_address),
sizeof(reuse_address))) {
NaClLog(LOG_WARNING, "Failed to set SO_REUSEADDR option.\n");
}
// Do not delay sending small packets. This significantly speeds up
// remote debugging. Debug stub uses buffering to send outgoing packets so
// they are not split into more TCP packets than necessary.
int nodelay = 1;
if (setsockopt(socket_handle, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char *>(&nodelay),
sizeof(nodelay))) {
NaClLog(LOG_WARNING, "Failed to set TCP_NODELAY option.\n");
}
struct sockaddr *psaddr = reinterpret_cast<struct sockaddr *>(&saddr);
if (bind(socket_handle, psaddr, addrlen)) {
NaClLog(LOG_ERROR, "Failed to bind server.\n");
return NULL;
}
if (listen(socket_handle, 1)) {
NaClLog(LOG_ERROR, "Failed to listen.\n");
return NULL;
}
return new SocketBinding(socket_handle);
}
ITransport *SocketBinding::AcceptConnection() {
NaClSocketHandle socket = ::accept(socket_handle_, NULL, 0);
if (socket != NACL_INVALID_SOCKET)
return new Transport(socket);
return NULL;
}
} // namespace port
<commit_msg>Debug stub: Set NODELAY on NaCl debug TCP socket<commit_after>/*
* Copyright (c) 2012 The Native Client 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 <errno.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <string>
#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability_sockets.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/trusted/debug_stub/platform.h"
#include "native_client/src/trusted/debug_stub/transport.h"
#include "native_client/src/trusted/debug_stub/util.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
using gdb_rsp::stringvec;
using gdb_rsp::StringSplit;
namespace port {
typedef int socklen_t;
class Transport : public ITransport {
public:
Transport()
: buf_(new char[kBufSize]),
pos_(0),
size_(0) {
handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#if NACL_WINDOWS
CreateSocketEvent();
#endif
}
explicit Transport(NaClSocketHandle s)
: buf_(new char[kBufSize]),
pos_(0),
size_(0),
handle_(s) {
#if NACL_WINDOWS
CreateSocketEvent();
#endif
}
~Transport() {
if (handle_ != NACL_INVALID_SOCKET) NaClCloseSocket(handle_);
#if NACL_WINDOWS
if (!WSACloseEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::~Transport: Failed to close socket event\n");
}
#endif
}
#if NACL_WINDOWS
void CreateSocketEvent() {
socket_event_ = WSACreateEvent();
if (socket_event_ == WSA_INVALID_EVENT) {
NaClLog(LOG_FATAL,
"Transport::CreateSocketEvent: Failed to create socket event\n");
}
if (WSAEventSelect(handle_, socket_event_, FD_READ) == SOCKET_ERROR) {
NaClLog(LOG_FATAL,
"Transport::CreateSocketEvent: Failed to bind event to socket\n");
}
}
#endif
// Read from this transport, return true on success.
virtual bool Read(void *ptr, int32_t len);
// Write to this transport, return true on success.
virtual bool Write(const void *ptr, int32_t len);
// Return true if there is data to read.
virtual bool IsDataAvailable() {
if (pos_ < size_) {
return true;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(handle_, &fds);
// We want a "non-blocking" check
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
// Check if this file handle can select on read
int cnt = select(static_cast<int>(handle_) + 1, &fds, 0, 0, &timeout);
// If we are ready, or if there is an error. We return true
// on error, to let the next IO request fail.
if (cnt != 0) return true;
return false;
}
virtual void WaitForDebugStubEvent(struct NaClApp *nap,
bool ignore_input_from_gdb);
// On windows, the header that defines this has other definition
// colitions, so we define it outselves just in case
#ifndef SD_BOTH
#define SD_BOTH 2
#endif
virtual void Disconnect() {
// Shutdown the conneciton in both diections. This should
// always succeed, and nothing we can do if this fails.
(void) ::shutdown(handle_, SD_BOTH);
}
protected:
// Copy buffered data to *dst up to len bytes and update dst and len.
void CopyFromBuffer(char **dst, int32_t *len);
// Read available data from the socket. Return false on EOF or error.
bool ReadSomeData();
static const int kBufSize = 4096;
nacl::scoped_array<char> buf_;
int32_t pos_;
int32_t size_;
NaClSocketHandle handle_;
#if NACL_WINDOWS
HANDLE socket_event_;
#endif
};
void Transport::CopyFromBuffer(char **dst, int32_t *len) {
int32_t copy_bytes = std::min(*len, size_ - pos_);
memcpy(*dst, buf_.get() + pos_, copy_bytes);
pos_ += copy_bytes;
*len -= copy_bytes;
*dst += copy_bytes;
}
bool Transport::ReadSomeData() {
while (true) {
int result = ::recv(handle_, buf_.get() + size_, kBufSize - size_, 0);
if (result > 0) {
size_ += result;
return true;
}
if (result == 0)
return false;
#if NACL_WINDOWS
// WSAEventSelect sets socket to non-blocking mode. This is essential
// for socket event notification to work, there is no workaround.
// See remarks section at the page
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms741576(v=vs.85).aspx
if (NaClSocketGetLastError() == WSAEWOULDBLOCK) {
if (WaitForSingleObject(socket_event_, INFINITE) == WAIT_FAILED) {
NaClLog(LOG_FATAL,
"Transport::ReadSomeData: Failed to wait on socket event\n");
}
if (!ResetEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::ReadSomeData: Failed to reset socket event\n");
}
continue;
}
#endif
if (NaClSocketGetLastError() != EINTR)
return false;
}
}
bool Transport::Read(void *ptr, int32_t len) {
char *dst = static_cast<char *>(ptr);
if (pos_ < size_) {
CopyFromBuffer(&dst, &len);
}
while (len > 0) {
pos_ = 0;
size_ = 0;
if (!ReadSomeData()) {
return false;
}
CopyFromBuffer(&dst, &len);
}
return true;
}
bool Transport::Write(const void *ptr, int32_t len) {
const char *src = static_cast<const char *>(ptr);
while (len > 0) {
int result = ::send(handle_, src, len, 0);
if (result > 0) {
src += result;
len -= result;
continue;
}
if (result == 0) {
return false;
}
if (NaClSocketGetLastError() != EINTR) {
return false;
}
}
return true;
}
void Transport::WaitForDebugStubEvent(struct NaClApp *nap,
bool ignore_input_from_gdb) {
bool wait = true;
// If we are told to ignore messages from gdb, we will exit from this
// function only if new data is sent by gdb.
if ((pos_ < size_ && !ignore_input_from_gdb) ||
nap->faulted_thread_count > 0) {
// Clear faulted thread events to save debug stub loop iterations.
wait = false;
}
#if NACL_WINDOWS
HANDLE handles[2];
handles[0] = nap->faulted_thread_event;
handles[1] = socket_event_;
int count = size_ < kBufSize ? 2 : 1;
int result = WaitForMultipleObjects(count, handles, FALSE,
wait ? INFINITE : 0);
if (result == WAIT_OBJECT_0 + 1) {
if (!ResetEvent(socket_event_)) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: "
"Failed to reset socket event\n");
}
return;
}
if (result == WAIT_TIMEOUT || result == WAIT_OBJECT_0)
return;
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Wait for events failed\n");
#else
fd_set fds;
FD_ZERO(&fds);
FD_SET(nap->faulted_thread_fd_read, &fds);
int max_fd = nap->faulted_thread_fd_read;
if (size_ < kBufSize) {
FD_SET(handle_, &fds);
max_fd = std::max(max_fd, handle_);
}
int ret;
// We don't need sleep-polling on Linux now, so we set either zero or infinite
// timeout.
if (wait) {
ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
} else {
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
ret = select(max_fd + 1, &fds, NULL, NULL, &timeout);
}
if (ret < 0) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Failed to wait for "
"debug stub event\n");
}
if (ret > 0) {
if (FD_ISSET(nap->faulted_thread_fd_read, &fds)) {
char buf[16];
if (read(nap->faulted_thread_fd_read, &buf, sizeof(buf)) < 0) {
NaClLog(LOG_FATAL,
"Transport::WaitForDebugStubEvent: Failed to read from "
"debug stub event pipe fd\n");
}
}
if (FD_ISSET(handle_, &fds))
ReadSomeData();
}
#endif
}
// Convert string in the form of [addr][:port] where addr is a
// IPv4 address or host name, and port is a 16b tcp/udp port.
// Both portions are optional, and only the portion of the address
// provided is updated. Values are provided in network order.
static bool StringToIPv4(const std::string &instr, uint32_t *addr,
uint16_t *port) {
// Make a copy so the are unchanged unless we succeed
uint32_t outaddr = *addr;
uint16_t outport = *port;
// Substrings of the full ADDR:PORT
std::string addrstr;
std::string portstr;
// We should either have one or two tokens in the form of:
// IP - IP, NUL
// IP: - IP, NUL
// :PORT - NUL, PORT
// IP:PORT - IP, PORT
// Search for the port marker
size_t portoff = instr.find(':');
// If we found a ":" before the end, get both substrings
if ((portoff != std::string::npos) && (portoff + 1 < instr.size())) {
addrstr = instr.substr(0, portoff);
portstr = instr.substr(portoff + 1, std::string::npos);
} else {
// otherwise the entire string is the addr portion.
addrstr = instr;
portstr = "";
}
// If the address portion was provided, update it
if (addrstr.size()) {
// Special case 0.0.0.0 which means any IPv4 interface
if (addrstr == "0.0.0.0") {
outaddr = 0;
} else {
struct hostent *host = gethostbyname(addrstr.data());
// Check that we found an IPv4 host
if ((NULL == host) || (AF_INET != host->h_addrtype)) return false;
// Make sure the IP list isn't empty.
if (0 == host->h_addr_list[0]) return false;
// Use the first address in the array of address pointers.
uint32_t **addrarray = reinterpret_cast<uint32_t**>(host->h_addr_list);
outaddr = *addrarray[0];
}
}
// if the port portion was provided, then update it
if (portstr.size()) {
int val = atoi(portstr.data());
if ((val < 0) || (val > 65535)) return false;
outport = ntohs(static_cast<uint16_t>(val));
}
// We haven't failed, so set the values
*addr = outaddr;
*port = outport;
return true;
}
static bool BuildSockAddr(const char *addr, struct sockaddr_in *sockaddr) {
std::string addrstr = addr;
uint32_t *pip = reinterpret_cast<uint32_t*>(&sockaddr->sin_addr.s_addr);
uint16_t *pport = reinterpret_cast<uint16_t*>(&sockaddr->sin_port);
sockaddr->sin_family = AF_INET;
return StringToIPv4(addrstr, pip, pport);
}
SocketBinding::SocketBinding(NaClSocketHandle socket_handle)
: socket_handle_(socket_handle) {
}
SocketBinding *SocketBinding::Bind(const char *addr) {
NaClSocketHandle socket_handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket_handle == NACL_INVALID_SOCKET) {
NaClLog(LOG_ERROR, "Failed to create socket.\n");
return NULL;
}
struct sockaddr_in saddr;
// Clearing sockaddr_in first appears to be necessary on Mac OS X.
memset(&saddr, 0, sizeof(saddr));
socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(0x7F000001);
saddr.sin_port = htons(4014);
// Override portions address that are provided
if (addr) BuildSockAddr(addr, &saddr);
// This is necessary to ensure that the TCP port is released
// promptly when sel_ldr exits. Without this, the TCP port might
// only be released after a timeout, and later processes can fail
// to bind it.
int reuse_address = 1;
if (setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<char *>(&reuse_address),
sizeof(reuse_address))) {
NaClLog(LOG_WARNING, "Failed to set SO_REUSEADDR option.\n");
}
struct sockaddr *psaddr = reinterpret_cast<struct sockaddr *>(&saddr);
if (bind(socket_handle, psaddr, addrlen)) {
NaClLog(LOG_ERROR, "Failed to bind server.\n");
return NULL;
}
if (listen(socket_handle, 1)) {
NaClLog(LOG_ERROR, "Failed to listen.\n");
return NULL;
}
return new SocketBinding(socket_handle);
}
ITransport *SocketBinding::AcceptConnection() {
NaClSocketHandle socket = ::accept(socket_handle_, NULL, 0);
if (socket != NACL_INVALID_SOCKET) {
// Do not delay sending small packets. This significantly speeds up
// remote debugging. Debug stub uses buffering to send outgoing packets so
// they are not split into more TCP packets than necessary.
int nodelay = 1;
if (setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char *>(&nodelay),
sizeof(nodelay))) {
NaClLog(LOG_WARNING, "Failed to set TCP_NODELAY option.\n");
}
return new Transport(socket);
}
return NULL;
}
} // namespace port
<|endoftext|>
|
<commit_before>#ifndef RBX_VM_H
#define RBX_VM_H
#include "missing/time.h"
#include "globals.hpp"
#include "memory/object_mark.hpp"
#include "memory/managed.hpp"
#include "vm_thread_state.hpp"
#include "thread_nexus.hpp"
#include "metrics.hpp"
#include "util/thread.hpp"
#include "memory/variable_buffer.hpp"
#include "memory/root_buffer.hpp"
#include "memory/slab.hpp"
#include "shared_state.hpp"
#include "unwind_info.hpp"
#include "fiber_stack.hpp"
#include "sodium/randombytes.h"
#include <atomic>
#include <vector>
#include <setjmp.h>
#include <stdint.h>
namespace llvm {
class Module;
}
namespace rbxti {
class Env;
}
namespace rubinius {
class Exception;
class LLVMState;
namespace event {
class Loop;
}
namespace memory {
class GarbageCollector;
class WriteBarrier;
}
class Assertion;
class CallSiteInformation;
class Channel;
class CompiledCode;
class ConfigParser;
class Configuration;
class Fiber;
class GlobalCache;
class LookupTable;
class Memory;
class NativeMethodEnvironment;
class Object;
class Park;
class Primitives;
class SharedState;
class String;
class Symbol;
class SymbolTable;
class Tuple;
class TypeError;
class TypeInfo;
class VariableScope;
struct CallFrame;
enum MethodMissingReason {
eNone, ePrivate, eProtected, eSuper, eVCall, eNormal
};
enum ConstantMissingReason {
vFound, vPrivate, vNonExistent
};
/**
* Represents an execution context for running Ruby code.
*
* Each Ruby thread is backed by an instance of this class, as well as an
* instance of the Thread class. Thread manages the (Ruby visible) thread-
* related state, while this class manages the execution machinery for
* running Ruby code.
*/
class VM : public memory::ManagedThread {
friend class State;
private:
UnwindInfoSet unwinds_;
CallFrame* call_frame_;
ThreadNexus* thread_nexus_;
CallSiteInformation* saved_call_site_information_;
FiberStacks fiber_stacks_;
Park* park_;
void* stack_start_;
size_t stack_size_;
size_t stack_cushion_;
void* current_stack_start_;
size_t current_stack_size_;
bool interrupt_with_signal_;
bool interrupt_by_kill_;
bool check_local_interrupts_;
bool thread_step_;
utilities::thread::SpinLock interrupt_lock_;
MethodMissingReason method_missing_reason_;
ConstantMissingReason constant_missing_reason_;
bool zombie_;
bool allocation_tracking_;
bool main_thread_;
std::atomic<ThreadNexus::Phase> thread_phase_;
uint32_t profile_interval_;
uint32_t profile_counter_;
CompiledCode** profile_;
uint64_t profile_sample_count_;
uint64_t profile_report_interval_;
native_int max_profile_entries_;
native_int min_profile_sample_count_;
public:
/* Data members */
SharedState& shared;
memory::TypedRoot<Channel*> waiting_channel_;
memory::TypedRoot<Exception*> interrupted_exception_;
/// The Thread object for this VM state
memory::TypedRoot<Thread*> thread;
/// The current fiber running on this thread
memory::TypedRoot<Fiber*> current_fiber;
/// Root fiber, if any (lazily initialized)
memory::TypedRoot<Fiber*> root_fiber;
/// Object that waits for inflation
memory::TypedRoot<Object*> waiting_object_;
uint64_t start_time_;
NativeMethodEnvironment* native_method_environment;
void (*custom_wakeup_)(void*);
void* custom_wakeup_data_;
VMThreadState thread_state_;
public: /* Inline methods */
UnwindInfoSet& unwinds() {
return unwinds_;
}
uint32_t thread_id() const {
return id_;
}
ThreadNexus::Phase thread_phase() {
return thread_phase_;
}
ThreadNexus* thread_nexus() {
return thread_nexus_;
}
void set_thread_phase(ThreadNexus::Phase thread_phase) {
thread_phase_ = thread_phase;
}
utilities::thread::SpinLock& interrupt_lock() {
return interrupt_lock_;
}
void set_zombie(STATE);
bool zombie_p() {
return zombie_;
}
void set_main_thread() {
main_thread_ = true;
}
bool main_thread_p() {
return main_thread_;
}
VMThreadState* thread_state() {
return &thread_state_;
}
Memory* memory() {
return shared.memory();
}
void set_start_time();
double run_time();
void raise_stack_error(STATE);
void validate_stack_size(STATE, size_t size);
size_t stack_size() {
return current_stack_size_;
}
void restore_stack_bounds() {
current_stack_start_ = stack_start_;
current_stack_size_ = stack_size_;
}
void set_stack_bounds(void* start, size_t size) {
current_stack_start_ = start;
current_stack_size_ = size - stack_cushion_;
}
void set_stack_bounds(size_t size);
bool check_stack(STATE, void* stack_address) {
ssize_t stack_used =
(reinterpret_cast<intptr_t>(current_stack_start_)
- reinterpret_cast<intptr_t>(stack_address));
if(stack_used < 0) stack_used = -stack_used;
if(static_cast<size_t>(stack_used) > current_stack_size_) {
raise_stack_error(state);
return false;
}
return true;
}
bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame);
bool pop_call_frame(STATE, CallFrame* frame) {
call_frame_ = frame;
return !thread_interrupted_p(state);
}
bool thread_interrupted_p(STATE) {
if(check_local_interrupts()) {
return check_thread_raise_or_kill(state);
}
return false;
}
bool check_thread_raise_or_kill(STATE);
// Do NOT de-duplicate
void set_call_frame(CallFrame* frame) {
call_frame_ = frame;
}
CallFrame* call_frame() {
return call_frame_;
}
CallFrame* get_call_frame(ssize_t up=0);
CallFrame* get_ruby_frame(ssize_t up=0);
CallFrame* get_variables_frame(ssize_t up=0);
CallFrame* get_scope_frame(ssize_t up=0);
bool scope_valid_p(VariableScope* scope);
void set_call_site_information(CallSiteInformation* info) {
saved_call_site_information_ = info;
}
CallSiteInformation* saved_call_site_information() {
return saved_call_site_information_;
}
GlobalCache* global_cache() const {
return shared.global_cache;
}
Globals& globals() {
return shared.globals;
}
MethodMissingReason method_missing_reason() const {
return method_missing_reason_;
}
void set_method_missing_reason(MethodMissingReason reason) {
method_missing_reason_ = reason;
}
ConstantMissingReason constant_missing_reason() const {
return constant_missing_reason_;
}
void set_constant_missing_reason(ConstantMissingReason reason) {
constant_missing_reason_ = reason;
}
void after_fork_child(STATE);
bool thread_step() const {
return thread_step_;
}
void clear_thread_step() {
clear_check_local_interrupts();
thread_step_ = false;
}
void set_thread_step() {
set_check_local_interrupts();
thread_step_ = true;
}
bool check_local_interrupts() const {
return check_local_interrupts_;
}
void clear_check_local_interrupts() {
check_local_interrupts_ = false;
}
void set_check_local_interrupts() {
check_local_interrupts_ = true;
}
bool interrupt_by_kill() const {
return interrupt_by_kill_;
}
void clear_interrupt_by_kill() {
interrupt_by_kill_ = false;
}
void set_interrupt_by_kill() {
interrupt_by_kill_ = true;
}
Exception* interrupted_exception() const {
return interrupted_exception_.get();
}
void clear_interrupted_exception() {
interrupted_exception_.set(cNil);
}
bool allocation_tracking() const {
return allocation_tracking_;
}
void enable_allocation_tracking() {
allocation_tracking_ = true;
}
void disable_allocation_tracking() {
allocation_tracking_ = false;
}
FiberStack* allocate_fiber_stack(size_t stack_size) {
return fiber_stacks_.allocate(stack_size);
}
void* fiber_trampoline() {
return fiber_stacks_.trampoline();
}
FiberData* new_fiber_data(size_t stack_size, bool root=false) {
return fiber_stacks_.new_data(stack_size, root);
}
void remove_fiber_data(FiberData* data) {
fiber_stacks_.remove_data(data);
}
memory::VariableRootBuffers& current_root_buffers();
public:
static VM* current();
static void discard(STATE, VM*);
public:
/* Prototypes */
VM(uint32_t id, SharedState& shared, const char* name = NULL);
~VM();
void bootstrap_class(STATE);
void bootstrap_ontology(STATE);
void bootstrap_symbol(STATE);
void collect_maybe(STATE);
native_int max_profile_entries() {
return max_profile_entries_;
}
uint64_t profile_sample_count() {
return profile_sample_count_;
}
CompiledCode** profile() {
return profile_;
}
void update_profile(STATE);
void sort_profile();
#define RBX_PROFILE_MAX_SHIFT 0xf
#define RBX_PROFILE_MAX_INTERVAL 0x1fff
void set_profile_interval() {
profile_interval_ = randombytes_random();
profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT);
profile_interval_ &= RBX_PROFILE_MAX_INTERVAL;
profile_counter_ = 0;
}
void checkpoint(STATE) {
metrics().machine.checkpoints++;
if(thread_nexus_->try_lock(this)) {
metrics().machine.stops++;
collect_maybe(state);
thread_nexus_->unlock();
}
if(profile_counter_++ >= profile_interval_) {
update_profile(state);
set_profile_interval();
}
}
void blocking_suspend(STATE, metrics::metric& counter);
void sleeping_suspend(STATE, metrics::metric& counter);
void blocking_phase() {
thread_nexus_->blocking_phase(this);
}
void managed_phase() {
thread_nexus_->managed_phase(this);
}
void unmanaged_phase() {
thread_nexus_->unmanaged_phase(this);
}
void set_current_thread();
void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern);
void bootstrap_exceptions(STATE);
void initialize_fundamental_constants(STATE);
void initialize_builtin_classes(STATE);
void initialize_platform_data(STATE);
Object* ruby_lib_version();
void set_current_fiber(Fiber* fib);
TypeInfo* find_type(int type);
static void init_ffi(STATE);
void raise_from_errno(const char* reason);
void raise_exception(Exception* exc);
Exception* new_exception(Class* cls, const char* msg);
Object* current_block();
void set_const(const char* name, Object* val);
void set_const(Module* mod, const char* name, Object* val);
Object* path2class(const char* name);
llvm::Module* llvm_module();
void llvm_cleanup();
void print_backtrace();
void wait_on_channel(Channel* channel);
void wait_on_inflated_lock(Object* wait);
void wait_on_custom_function(void (*func)(void*), void* data);
void clear_waiter();
bool wakeup(STATE);
void reset_parked();
void set_sleeping();
void clear_sleeping();
void interrupt_with_signal() {
interrupt_with_signal_ = true;
}
void register_raise(STATE, Exception* exc);
void register_kill(STATE);
void gc_scan(memory::GarbageCollector* gc);
void gc_fiber_clear_mark();
void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true);
void gc_verify(memory::GarbageCollector* gc);
};
}
#endif
<commit_msg>Slightly relax memory ordering for ThreadNexus::Phase.<commit_after>#ifndef RBX_VM_H
#define RBX_VM_H
#include "missing/time.h"
#include "globals.hpp"
#include "memory/object_mark.hpp"
#include "memory/managed.hpp"
#include "vm_thread_state.hpp"
#include "thread_nexus.hpp"
#include "metrics.hpp"
#include "util/thread.hpp"
#include "memory/variable_buffer.hpp"
#include "memory/root_buffer.hpp"
#include "memory/slab.hpp"
#include "shared_state.hpp"
#include "unwind_info.hpp"
#include "fiber_stack.hpp"
#include "sodium/randombytes.h"
#include <atomic>
#include <vector>
#include <setjmp.h>
#include <stdint.h>
namespace llvm {
class Module;
}
namespace rbxti {
class Env;
}
namespace rubinius {
class Exception;
class LLVMState;
namespace event {
class Loop;
}
namespace memory {
class GarbageCollector;
class WriteBarrier;
}
class Assertion;
class CallSiteInformation;
class Channel;
class CompiledCode;
class ConfigParser;
class Configuration;
class Fiber;
class GlobalCache;
class LookupTable;
class Memory;
class NativeMethodEnvironment;
class Object;
class Park;
class Primitives;
class SharedState;
class String;
class Symbol;
class SymbolTable;
class Tuple;
class TypeError;
class TypeInfo;
class VariableScope;
struct CallFrame;
enum MethodMissingReason {
eNone, ePrivate, eProtected, eSuper, eVCall, eNormal
};
enum ConstantMissingReason {
vFound, vPrivate, vNonExistent
};
/**
* Represents an execution context for running Ruby code.
*
* Each Ruby thread is backed by an instance of this class, as well as an
* instance of the Thread class. Thread manages the (Ruby visible) thread-
* related state, while this class manages the execution machinery for
* running Ruby code.
*/
class VM : public memory::ManagedThread {
friend class State;
private:
UnwindInfoSet unwinds_;
CallFrame* call_frame_;
ThreadNexus* thread_nexus_;
CallSiteInformation* saved_call_site_information_;
FiberStacks fiber_stacks_;
Park* park_;
void* stack_start_;
size_t stack_size_;
size_t stack_cushion_;
void* current_stack_start_;
size_t current_stack_size_;
bool interrupt_with_signal_;
bool interrupt_by_kill_;
bool check_local_interrupts_;
bool thread_step_;
utilities::thread::SpinLock interrupt_lock_;
MethodMissingReason method_missing_reason_;
ConstantMissingReason constant_missing_reason_;
bool zombie_;
bool allocation_tracking_;
bool main_thread_;
std::atomic<ThreadNexus::Phase> thread_phase_;
uint32_t profile_interval_;
uint32_t profile_counter_;
CompiledCode** profile_;
uint64_t profile_sample_count_;
uint64_t profile_report_interval_;
native_int max_profile_entries_;
native_int min_profile_sample_count_;
public:
/* Data members */
SharedState& shared;
memory::TypedRoot<Channel*> waiting_channel_;
memory::TypedRoot<Exception*> interrupted_exception_;
/// The Thread object for this VM state
memory::TypedRoot<Thread*> thread;
/// The current fiber running on this thread
memory::TypedRoot<Fiber*> current_fiber;
/// Root fiber, if any (lazily initialized)
memory::TypedRoot<Fiber*> root_fiber;
/// Object that waits for inflation
memory::TypedRoot<Object*> waiting_object_;
uint64_t start_time_;
NativeMethodEnvironment* native_method_environment;
void (*custom_wakeup_)(void*);
void* custom_wakeup_data_;
VMThreadState thread_state_;
public: /* Inline methods */
UnwindInfoSet& unwinds() {
return unwinds_;
}
uint32_t thread_id() const {
return id_;
}
ThreadNexus* thread_nexus() {
return thread_nexus_;
}
ThreadNexus::Phase thread_phase() {
return thread_phase_.load(std::memory_order_acquire);
}
void set_thread_phase(ThreadNexus::Phase thread_phase) {
thread_phase_.store(thread_phase, std::memory_order_release);
}
utilities::thread::SpinLock& interrupt_lock() {
return interrupt_lock_;
}
void set_zombie(STATE);
bool zombie_p() {
return zombie_;
}
void set_main_thread() {
main_thread_ = true;
}
bool main_thread_p() {
return main_thread_;
}
VMThreadState* thread_state() {
return &thread_state_;
}
Memory* memory() {
return shared.memory();
}
void set_start_time();
double run_time();
void raise_stack_error(STATE);
void validate_stack_size(STATE, size_t size);
size_t stack_size() {
return current_stack_size_;
}
void restore_stack_bounds() {
current_stack_start_ = stack_start_;
current_stack_size_ = stack_size_;
}
void set_stack_bounds(void* start, size_t size) {
current_stack_start_ = start;
current_stack_size_ = size - stack_cushion_;
}
void set_stack_bounds(size_t size);
bool check_stack(STATE, void* stack_address) {
ssize_t stack_used =
(reinterpret_cast<intptr_t>(current_stack_start_)
- reinterpret_cast<intptr_t>(stack_address));
if(stack_used < 0) stack_used = -stack_used;
if(static_cast<size_t>(stack_used) > current_stack_size_) {
raise_stack_error(state);
return false;
}
return true;
}
bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame);
bool pop_call_frame(STATE, CallFrame* frame) {
call_frame_ = frame;
return !thread_interrupted_p(state);
}
bool thread_interrupted_p(STATE) {
if(check_local_interrupts()) {
return check_thread_raise_or_kill(state);
}
return false;
}
bool check_thread_raise_or_kill(STATE);
// Do NOT de-duplicate
void set_call_frame(CallFrame* frame) {
call_frame_ = frame;
}
CallFrame* call_frame() {
return call_frame_;
}
CallFrame* get_call_frame(ssize_t up=0);
CallFrame* get_ruby_frame(ssize_t up=0);
CallFrame* get_variables_frame(ssize_t up=0);
CallFrame* get_scope_frame(ssize_t up=0);
bool scope_valid_p(VariableScope* scope);
void set_call_site_information(CallSiteInformation* info) {
saved_call_site_information_ = info;
}
CallSiteInformation* saved_call_site_information() {
return saved_call_site_information_;
}
GlobalCache* global_cache() const {
return shared.global_cache;
}
Globals& globals() {
return shared.globals;
}
MethodMissingReason method_missing_reason() const {
return method_missing_reason_;
}
void set_method_missing_reason(MethodMissingReason reason) {
method_missing_reason_ = reason;
}
ConstantMissingReason constant_missing_reason() const {
return constant_missing_reason_;
}
void set_constant_missing_reason(ConstantMissingReason reason) {
constant_missing_reason_ = reason;
}
void after_fork_child(STATE);
bool thread_step() const {
return thread_step_;
}
void clear_thread_step() {
clear_check_local_interrupts();
thread_step_ = false;
}
void set_thread_step() {
set_check_local_interrupts();
thread_step_ = true;
}
bool check_local_interrupts() const {
return check_local_interrupts_;
}
void clear_check_local_interrupts() {
check_local_interrupts_ = false;
}
void set_check_local_interrupts() {
check_local_interrupts_ = true;
}
bool interrupt_by_kill() const {
return interrupt_by_kill_;
}
void clear_interrupt_by_kill() {
interrupt_by_kill_ = false;
}
void set_interrupt_by_kill() {
interrupt_by_kill_ = true;
}
Exception* interrupted_exception() const {
return interrupted_exception_.get();
}
void clear_interrupted_exception() {
interrupted_exception_.set(cNil);
}
bool allocation_tracking() const {
return allocation_tracking_;
}
void enable_allocation_tracking() {
allocation_tracking_ = true;
}
void disable_allocation_tracking() {
allocation_tracking_ = false;
}
FiberStack* allocate_fiber_stack(size_t stack_size) {
return fiber_stacks_.allocate(stack_size);
}
void* fiber_trampoline() {
return fiber_stacks_.trampoline();
}
FiberData* new_fiber_data(size_t stack_size, bool root=false) {
return fiber_stacks_.new_data(stack_size, root);
}
void remove_fiber_data(FiberData* data) {
fiber_stacks_.remove_data(data);
}
memory::VariableRootBuffers& current_root_buffers();
public:
static VM* current();
static void discard(STATE, VM*);
public:
/* Prototypes */
VM(uint32_t id, SharedState& shared, const char* name = NULL);
~VM();
void bootstrap_class(STATE);
void bootstrap_ontology(STATE);
void bootstrap_symbol(STATE);
void collect_maybe(STATE);
native_int max_profile_entries() {
return max_profile_entries_;
}
uint64_t profile_sample_count() {
return profile_sample_count_;
}
CompiledCode** profile() {
return profile_;
}
void update_profile(STATE);
void sort_profile();
#define RBX_PROFILE_MAX_SHIFT 0xf
#define RBX_PROFILE_MAX_INTERVAL 0x1fff
void set_profile_interval() {
profile_interval_ = randombytes_random();
profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT);
profile_interval_ &= RBX_PROFILE_MAX_INTERVAL;
profile_counter_ = 0;
}
void checkpoint(STATE) {
metrics().machine.checkpoints++;
if(thread_nexus_->try_lock(this)) {
metrics().machine.stops++;
collect_maybe(state);
thread_nexus_->unlock();
}
if(profile_counter_++ >= profile_interval_) {
update_profile(state);
set_profile_interval();
}
}
void blocking_suspend(STATE, metrics::metric& counter);
void sleeping_suspend(STATE, metrics::metric& counter);
void blocking_phase() {
thread_nexus_->blocking_phase(this);
}
void managed_phase() {
thread_nexus_->managed_phase(this);
}
void unmanaged_phase() {
thread_nexus_->unmanaged_phase(this);
}
void set_current_thread();
void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern);
void bootstrap_exceptions(STATE);
void initialize_fundamental_constants(STATE);
void initialize_builtin_classes(STATE);
void initialize_platform_data(STATE);
Object* ruby_lib_version();
void set_current_fiber(Fiber* fib);
TypeInfo* find_type(int type);
static void init_ffi(STATE);
void raise_from_errno(const char* reason);
void raise_exception(Exception* exc);
Exception* new_exception(Class* cls, const char* msg);
Object* current_block();
void set_const(const char* name, Object* val);
void set_const(Module* mod, const char* name, Object* val);
Object* path2class(const char* name);
llvm::Module* llvm_module();
void llvm_cleanup();
void print_backtrace();
void wait_on_channel(Channel* channel);
void wait_on_inflated_lock(Object* wait);
void wait_on_custom_function(void (*func)(void*), void* data);
void clear_waiter();
bool wakeup(STATE);
void reset_parked();
void set_sleeping();
void clear_sleeping();
void interrupt_with_signal() {
interrupt_with_signal_ = true;
}
void register_raise(STATE, Exception* exc);
void register_kill(STATE);
void gc_scan(memory::GarbageCollector* gc);
void gc_fiber_clear_mark();
void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true);
void gc_verify(memory::GarbageCollector* gc);
};
}
#endif
<|endoftext|>
|
<commit_before>#ifndef HEAPS_H
#define HEAPS_H
#include"objects.hpp"
class Generic;
class SharedVar;
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
class Semispace {
private:
void* mem;
void* allocpt;
void* svallocpt; // sharedvar allocation point
size_t prev_alloc;
size_t max;
public:
Semispace(size_t);
~Semispace();
void* alloc(size_t);
void dealloc(void*);
SharedVar* sv_alloc(void);
void sv_dealloc(SharedVar*);
void resize(size_t);
bool can_fit(size_t) const;
size_t size(void) const { return max; };
size_t used(void) const {
return (size_t)(((char*) allocpt) - ((char*) mem))
+ (size_t)((((char*) mem) + max) - ((char*) svallocpt));
};
std::pair<boost::shared_ptr<Semispace>, Generic* >
clone(Generic*) const;
friend class Heap;
};
/*last-in-first-out allocation semispace*/
class LifoSemispace {
private:
void* mem;
void* allocpt;
void* end;
size_t prevalloc;
public:
LifoSemispace(size_t sz);
~LifoSemispace();
void* alloc(size_t sz);
void dealloc(void*); // used only in a constructor-fail delete
void normal_dealloc(Generic*);
bool can_fit(size_t) const;
size_t size(void) const {
return (size_t) (((char*) end) - ((char*) mem));
}
size_t used(void) const {
return (size_t) (((char*) end) - ((char*) allocpt));
}
/*no need to clone LIFO semispaces: they never get passed around*/
friend class Heap;
};
#endif //HEAPS_H
<commit_msg>inc/heaps.hpp: minor comment<commit_after>#ifndef HEAPS_H
#define HEAPS_H
#include"objects.hpp"
class Generic;
class SharedVar;
/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/
class Semispace {
private:
void* mem;
void* allocpt;
void* svallocpt; // sharedvar allocation point
size_t prev_alloc;
size_t max;
public:
Semispace(size_t);
~Semispace();
void* alloc(size_t);
void dealloc(void*);
SharedVar* sv_alloc(void);
void sv_dealloc(SharedVar*);
void resize(size_t);
bool can_fit(size_t) const;
size_t size(void) const { return max; };
size_t used(void) const {
return (size_t)(((char*) allocpt) - ((char*) mem))
+ (size_t)((((char*) mem) + max) - ((char*) svallocpt));
};
std::pair<boost::shared_ptr<Semispace>, Generic* >
clone(Generic*) const;
friend class Heap;
};
/*last-in-first-out allocation semispace*/
class LifoSemispace {
private:
void* mem;
void* allocpt;
void* end;
size_t prevalloc;
public:
LifoSemispace(size_t sz);
~LifoSemispace();
void* alloc(size_t sz);
void dealloc(void*); // used only in a constructor-fail delete
void normal_dealloc(Generic*);
/*no svallocation: no sharedvar's allowed in LifoSemispace*/
bool can_fit(size_t) const;
size_t size(void) const {
return (size_t) (((char*) end) - ((char*) mem));
}
size_t used(void) const {
return (size_t) (((char*) end) - ((char*) allocpt));
}
/*no need to clone LIFO semispaces: they never get passed around*/
friend class Heap;
};
#endif //HEAPS_H
<|endoftext|>
|
<commit_before>#include "persons.h"
#include <iomanip>
//Default Constructor.
//Not actually used.
Persons::Persons()
{
name = " ";
gender = ' ';
birthYear = 1980;
deathYear = 0;
alive = true;
}
//Constructor.
//if deathyear == 0, the person will be alive.
Persons::Persons(string n, char g, int bY, int dY)
{
name = n;
birthYear = bY;
deathYear = dY;
gender = g;
if (dY == 0)
{
alive = true;
}
else
{
alive = false;
}
}
string Persons::getName() const
{
return name;
}
int Persons::getBirthYear() const
{
return birthYear;
}
int Persons::getDeathYear() const
{
return deathYear;
}
char Persons::getGender() const
{
return gender;
}
bool Persons::getAlive() const
{
return alive;
}
//Overloads the = operator. Basic stuff.
void Persons::operator = (const Persons& p)
{
name = p.name;
gender = p.gender;
birthYear = p.birthYear;
deathYear = p.deathYear;
alive = p.alive;
}
//Overloads the == operator.
//Two persons are equal if and only if each
//Parameter is equal.
bool Persons::operator == (const Persons& p)
{
return name == p.name && gender == p.gender && birthYear == p.birthYear && deathYear == p.deathYear;
}
//Overloads the << (output) operator.
//writes out the name, gender, and birthyear.
//Writes out the deathyear or, if the person is alive
//writes "Alive".
ostream& operator << (ostream& out, const Persons& p)
{
out.width(26);
out << left << p.getName() << "\t" << p.getGender() << "\t" << p.getBirthYear() << "\t";
if (!p.getAlive())
{
out << p.getDeathYear() << endl;
}
else
{
out << "Alive " << endl;
}
return out;
}
//Overloads the >> (input) operator.
//Reads the name which we know ends at a ;
//Then reads the gender and birthyear.
//Reads either "Alive" or the deathyear.
istream& operator >> (istream& in, Persons& p)
{
string a = " ";
in >> ws;
getline(in, p.name, ';');
in >> p.gender >> p.birthYear >> a;
if (a == "Alive")
{
p.alive = true;
}
else
{
p.alive = false;
p.deathYear = atoi(a.c_str());
}
return in;
}
<commit_msg>sortByDeathYear lagað<commit_after>#include "persons.h"
#include <iomanip>
//Default Constructor.
//Not actually used.
Persons::Persons()
{
name = " ";
gender = ' ';
birthYear = 1980;
deathYear = 0;
alive = true;
}
//Constructor.
//if deathyear == 0, the person will be alive.
Persons::Persons(string n, char g, int bY, int dY)
{
name = n;
birthYear = bY;
deathYear = dY;
gender = g;
if (dY == 0)
{
alive = true;
}
else
{
alive = false;
}
}
string Persons::getName() const
{
return name;
}
int Persons::getBirthYear() const
{
return birthYear;
}
int Persons::getDeathYear() const
{
return deathYear;
}
char Persons::getGender() const
{
return gender;
}
bool Persons::getAlive() const
{
return alive;
}
//Overloads the = operator. Basic stuff.
void Persons::operator = (const Persons& p)
{
name = p.name;
gender = p.gender;
birthYear = p.birthYear;
deathYear = p.deathYear;
alive = p.alive;
}
//Overloads the == operator.
//Two persons are equal if and only if each
//Parameter is equal.
bool Persons::operator == (const Persons& p)
{
return name == p.name && gender == p.gender && birthYear == p.birthYear && deathYear == p.deathYear;
}
//Overloads the << (output) operator.
//writes out the name, gender, and birthyear.
//Writes out the deathyear or, if the person is alive
//writes "Alive".
ostream& operator << (ostream& out, const Persons& p)
{
out.width(26);
out << left << p.getName() << "\t" << p.getGender() << "\t" << p.getBirthYear() << "\t";
if (!p.getAlive())
{
out << p.getDeathYear() << endl;
}
else
{
out << "Alive " << endl;
}
return out;
}
//Overloads the >> (input) operator.
//Reads the name which we know ends at a ;
//Then reads the gender and birthyear.
//Reads either "Alive" or the deathyear.
istream& operator >> (istream& in, Persons& p)
{
string a = " ";
in >> ws;
getline(in, p.name, ';');
in >> p.gender >> p.birthYear >> a;
if (a == "Alive")
{
p.alive = true;
p.deathYear = 0;
}
else
{
p.alive = false;
p.deathYear = atoi(a.c_str());
}
return in;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: docprev.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2004-07-12 14:59:03 $
*
* 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 _SFX_OBJSH_HXX // SfxObjectShell
#include <sfx2/objsh.hxx>
#endif
#ifndef _SV_GDIMTF_HXX // GDIMetaFile
#include <vcl/gdimtf.hxx>
#endif
#ifndef _SV_VIRDEV_HXX // class VirtualDevice
#include <vcl/virdev.hxx>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif
#ifndef _SD_FADEDEF_H // enum FadeSpeed
#include <fadedef.h>
#endif
#ifndef _SV_CTRL_HXX // class Control
#include <vcl/ctrl.hxx>
#endif
#ifndef _SVDOUTL_HXX
#include <svx/svdoutl.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDORECT_HXX
#include <svx/svdorect.hxx>
#endif
#ifndef SD_FADER_HXX
#include "fader.hxx"
#endif
#include "docprev.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_SHOW_VIEW_HXX
#include "showview.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "sdpage.hxx"
using namespace ::com::sun::star;
const int SdDocPreviewWin::FRAME = 4;
void SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )
{
mpObj = pObj;
mnShowPage = nShowPage;
updateViewSettings();
}
SdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )
: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)
{
SetBorderStyle( WINDOW_BORDER_MONO );
svtools::ColorConfig aColorConfig;
SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );
}
SdDocPreviewWin::SdDocPreviewWin( Window* pParent )
: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)
{
SetBorderStyle( WINDOW_BORDER_MONO );
svtools::ColorConfig aColorConfig;
SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );
Resize();
Show();
}
void SdDocPreviewWin::Resize()
{
Invalidate();
}
void SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )
{
delete pMetaFile;
pMetaFile = pFile;
Invalidate();
}
void SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )
{
Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );
long nWidth = rSize.Width() - 2*FRAME;
long nHeight = rSize.Height() - 2*FRAME;
if( nWidth < 0 ) nWidth = 0;
if( nHeight < 0 ) nHeight = 0;
double dRatio=((double)aTmpSize.Width())/aTmpSize.Height();
double dRatioPreV=((double) nWidth ) / nHeight;
if (dRatio>dRatioPreV)
{
rSize=Size(nWidth, (USHORT)(nWidth/dRatio));
rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())/2));
}
else
{
rSize=Size((USHORT)(nHeight*dRatio), nHeight);
rPoint=Point((USHORT)((nWidth-rSize.Width())/2),0);
}
}
void SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )
{
Point aPoint;
Size aSize = pVDev->GetOutputSize();
Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );
CalcSizeAndPos( pFile, aSize, aPoint );
bPoint -= aPoint;
aPoint += Point( FRAME, FRAME );
svtools::ColorConfig aColorConfig;
pVDev->SetLineColor();
pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );
pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));
if( pFile )
{
pVDev->SetFillColor( maDocumentColor );
pVDev->DrawRect(Rectangle(aPoint, aSize));
pFile->WindStart();
pFile->Play( pVDev, aPoint, aSize );
}
}
void SdDocPreviewWin::Paint( const Rectangle& rRect )
{
SvtAccessibilityOptions aAccOptions;
bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();
SetDrawMode( bUseContrast
? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST
: ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );
ImpPaint( pMetaFile, (VirtualDevice*)this );
}
void SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )
{
if(bInEffect || !pMetaFile)
return;
bInEffect = TRUE;
svtools::ColorConfig aColorConfig;
SetLineColor();
SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );
DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));
Point aPoint;
Size aSize( GetOutputSize() );
Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );
CalcSizeAndPos( pMetaFile, aSize, aPoint );
bPoint -= aPoint;
aPoint += Point( FRAME, FRAME );
// virtuelle Devices anlegen
VirtualDevice* pVDev = new VirtualDevice(*this);
pVDev->SetOutputSize( GetOutputSize() );
pVDev->SetFillColor( maDocumentColor );
pVDev->DrawRect(Rectangle(aPoint, aSize));
pVDev->SetLineColor();
pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );
pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));
if( pMetaFile )
{
pVDev->SetFillColor( maDocumentColor );
pVDev->DrawRect(Rectangle(aPoint, aSize));
pMetaFile->WindStart();
pMetaFile->Play( pVDev, aPoint, aSize );
}
// ein Fader zum Ueberblenden
::sd::Fader* pFader = new ::sd::Fader(this);
pFader->SetEffect( eEffect );
pFader->SetSpeed( eSpeed );
pFader->SetSource(Rectangle(aPoint, aSize));
pFader->SetTarget(Rectangle(aPoint, aSize));
// virtuelle Devices an Fader uebergeben
pFader->SetNewVirtualDevice(pVDev);
// ueberblenden
pFader->Fade();
delete pFader;
// DrawOutDev( Point( 0,0 ), GetOutputSize(), Point( 0,0 ), GetOutputSize(), *pVDev );
delete pVDev;
/*
Point aPoint;
Size aSize = GetOutputSize();
Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );
CalcSizeAndPos( pMetaFile, aSize, aPoint );
bPoint -= aPoint;
aPoint += Point( FRAME, FRAME );
bPoint += Point( FRAME, FRAME );
svtools::ColorConfig aColorConfig;
// Hintergrund Schwarz
SetLineColor();
SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );
DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));
// korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)
// nicht mit
Size aPixelSize = PixelToLogic(Size(1,1));
aSize.Width() += aPixelSize.Width();
aSize.Height() += aPixelSize.Height();
*/
bInEffect = FALSE;
}
long SdDocPreviewWin::Notify( NotifyEvent& rNEvt )
{
if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )
{
const MouseEvent* pMEvt = rNEvt.GetMouseEvent();
if ( pMEvt->IsLeft() )
{
if( rNEvt.GetWindow() == this )
{
if(aClickHdl.IsSet())
aClickHdl.Call(this);
}
}
}
return Control::Notify( rNEvt );
}
void SdDocPreviewWin::updateViewSettings()
{
::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);
SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;
SvtAccessibilityOptions aAccOptions;
bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();
if( bUseWhiteColor )
{
maDocumentColor = Color( COL_WHITE );
}
else
{
svtools::ColorConfig aColorConfig;
maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );
}
GDIMetaFile* pMtf = NULL;
if(pDoc)
{
SdrOutliner& rOutl = pDoc->GetDrawOutliner();
Color aOldBackgroundColor = rOutl.GetBackgroundColor();
rOutl.SetBackgroundColor( maDocumentColor );
pMtf = new GDIMetaFile;
SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );
VirtualDevice aVDev;
const Fraction aFrac( pDoc->GetScaleFraction() );
const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );
aVDev.SetMapMode( aMap );
// #109058# Disable output, as we only want to record a metafile
aVDev.EnableOutput( FALSE );
pMtf->Record( &aVDev );
::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);
const Size aSize( pPage->GetSize() );
pView->SetBordVisible( FALSE );
pView->SetPageVisible( FALSE );
pView->ShowPage( pPage, Point() );
const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );
const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),
aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );
const Rectangle aClipRect( aNewOrg, aNewSize );
MapMode aVMap( aMap );
SdrPageView* pPageView = pView->GetPageView( pPage );
aVDev.Push();
aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );
aVDev.SetRelativeMapMode( aVMap );
aVDev.IntersectClipRegion( aClipRect );
// Use new StandardCheckVisisbilityRedirector
StandardCheckVisisbilityRedirector aRedirector;
for (USHORT i=0; i<pView->GetPageViewCount(); i++)
{
SdrPageView* pPV=pView->GetPageViewPvNum(i);
pPV->CompleteRedraw(&aVDev, Region(Rectangle(Point(), aNewSize)), 0, &aRedirector);
}
aVDev.Pop();
pMtf->Stop();
pMtf->WindStart();
pMtf->SetPrefMapMode( aMap );
pMtf->SetPrefSize( aNewSize );
rOutl.SetBackgroundColor( aOldBackgroundColor );
delete pView;
}
delete pMetaFile;
pMetaFile = pMtf;
Invalidate();
}
void SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)
{
if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )
{
updateViewSettings();
}
}
void SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
updateViewSettings();
}
}
<commit_msg>INTEGRATION: CWS presentationengine01 (1.12.12); FILE MERGED 2004/09/30 16:09:40 cl 1.12.12.2: added new preview for wizard 2004/08/25 15:24:04 cl 1.12.12.1: replaced old FuSlideShow with new SlideShow<commit_after>/*************************************************************************
*
* $RCSfile: docprev.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2004-11-26 20:02:12 $
*
* 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 _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_
#include <com/sun/star/drawing/XDrawPage.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_
#include <com/sun/star/animations/XAnimationNode.hpp>
#endif
#ifndef _SD_SLIDESHOW_HXX
#include "slideshow.hxx"
#endif
#ifndef _SFX_OBJSH_HXX // SfxObjectShell
#include <sfx2/objsh.hxx>
#endif
#ifndef _SV_GDIMTF_HXX // GDIMetaFile
#include <vcl/gdimtf.hxx>
#endif
#ifndef _SV_VIRDEV_HXX // class VirtualDevice
#include <vcl/virdev.hxx>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif
#ifndef _SD_FADEDEF_H // enum FadeSpeed
#include <fadedef.h>
#endif
#ifndef _SV_CTRL_HXX // class Control
#include <vcl/ctrl.hxx>
#endif
#ifndef _SVDOUTL_HXX
#include <svx/svdoutl.hxx>
#endif
#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif
#ifndef _SVDORECT_HXX
#include <svx/svdorect.hxx>
#endif
#include "docprev.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_SHOW_VIEW_HXX
#include "showview.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "sdpage.hxx"
using ::com::sun::star::drawing::XDrawPage;
using ::com::sun::star::animations::XAnimationNode;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
const int SdDocPreviewWin::FRAME = 4;
void SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )
{
mpObj = pObj;
mnShowPage = nShowPage;
delete mpSlideShow;
mpSlideShow = 0;
updateViewSettings();
}
SdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )
: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)
{
mpSlideShow = 0;
SetBorderStyle( WINDOW_BORDER_MONO );
svtools::ColorConfig aColorConfig;
SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );
}
SdDocPreviewWin::SdDocPreviewWin( Window* pParent )
: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)
{
mpSlideShow = 0;
SetBorderStyle( WINDOW_BORDER_MONO );
svtools::ColorConfig aColorConfig;
SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );
Resize();
Show();
}
void SdDocPreviewWin::Resize()
{
Invalidate();
if( mpSlideShow )
mpSlideShow->resize( GetSizePixel() );
}
void SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )
{
delete pMetaFile;
pMetaFile = pFile;
Invalidate();
}
void SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )
{
Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );
long nWidth = rSize.Width() - 2*FRAME;
long nHeight = rSize.Height() - 2*FRAME;
if( nWidth < 0 ) nWidth = 0;
if( nHeight < 0 ) nHeight = 0;
double dRatio=((double)aTmpSize.Width())/aTmpSize.Height();
double dRatioPreV=((double) nWidth ) / nHeight;
if (dRatio>dRatioPreV)
{
rSize=Size(nWidth, (USHORT)(nWidth/dRatio));
rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())/2));
}
else
{
rSize=Size((USHORT)(nHeight*dRatio), nHeight);
rPoint=Point((USHORT)((nWidth-rSize.Width())/2),0);
}
}
void SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )
{
Point aPoint;
Size aSize = pVDev->GetOutputSize();
Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );
CalcSizeAndPos( pFile, aSize, aPoint );
bPoint -= aPoint;
aPoint += Point( FRAME, FRAME );
svtools::ColorConfig aColorConfig;
pVDev->SetLineColor();
pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );
pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));
if( pFile )
{
pVDev->SetFillColor( maDocumentColor );
pVDev->DrawRect(Rectangle(aPoint, aSize));
pFile->WindStart();
pFile->Play( pVDev, aPoint, aSize );
}
}
void SdDocPreviewWin::Paint( const Rectangle& rRect )
{
SvtAccessibilityOptions aAccOptions;
bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();
SetDrawMode( bUseContrast
? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST
: ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );
ImpPaint( pMetaFile, (VirtualDevice*)this );
}
void SdDocPreviewWin::startPreview()
{
if( mpSlideShow )
delete mpSlideShow;
::sd::DrawDocShell* pDocShell = dynamic_cast< ::sd::DrawDocShell * >( mpObj );
if( mpObj )
{
SdDrawDocument* pDoc = pDocShell->GetDoc();
if( pDoc )
{
SdPage* pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );
if( pPage )
{
mpSlideShow = new sd::Slideshow( 0, 0, pDoc );
Reference< XDrawPage > xDrawPage( pPage->getUnoPage(), UNO_QUERY );
Reference< XAnimationNode > xAnimationNode;
mpSlideShow->startPreview( xDrawPage, xAnimationNode, this );
}
}
}
}
long SdDocPreviewWin::Notify( NotifyEvent& rNEvt )
{
if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )
{
const MouseEvent* pMEvt = rNEvt.GetMouseEvent();
if ( pMEvt->IsLeft() )
{
if( rNEvt.GetWindow() == this )
{
if(aClickHdl.IsSet())
aClickHdl.Call(this);
}
}
}
return Control::Notify( rNEvt );
}
void SdDocPreviewWin::updateViewSettings()
{
::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);
SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;
SvtAccessibilityOptions aAccOptions;
bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();
if( bUseWhiteColor )
{
maDocumentColor = Color( COL_WHITE );
}
else
{
svtools::ColorConfig aColorConfig;
maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );
}
GDIMetaFile* pMtf = NULL;
if(pDoc)
{
SdrOutliner& rOutl = pDoc->GetDrawOutliner();
Color aOldBackgroundColor = rOutl.GetBackgroundColor();
rOutl.SetBackgroundColor( maDocumentColor );
pMtf = new GDIMetaFile;
SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );
VirtualDevice aVDev;
const Fraction aFrac( pDoc->GetScaleFraction() );
const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );
aVDev.SetMapMode( aMap );
// #109058# Disable output, as we only want to record a metafile
aVDev.EnableOutput( FALSE );
pMtf->Record( &aVDev );
::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);
const Size aSize( pPage->GetSize() );
pView->SetBordVisible( FALSE );
pView->SetPageVisible( FALSE );
pView->ShowPage( pPage, Point() );
const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );
const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),
aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );
const Rectangle aClipRect( aNewOrg, aNewSize );
MapMode aVMap( aMap );
SdrPageView* pPageView = pView->GetPageView( pPage );
aVDev.Push();
aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );
aVDev.SetRelativeMapMode( aVMap );
aVDev.IntersectClipRegion( aClipRect );
// Use new StandardCheckVisisbilityRedirector
StandardCheckVisisbilityRedirector aRedirector;
for (USHORT i=0; i<pView->GetPageViewCount(); i++)
{
SdrPageView* pPV=pView->GetPageViewPvNum(i);
pPV->CompleteRedraw(&aVDev, Region(Rectangle(Point(), aNewSize)), 0, &aRedirector);
}
aVDev.Pop();
pMtf->Stop();
pMtf->WindStart();
pMtf->SetPrefMapMode( aMap );
pMtf->SetPrefSize( aNewSize );
rOutl.SetBackgroundColor( aOldBackgroundColor );
delete pView;
}
delete pMetaFile;
pMetaFile = pMtf;
Invalidate();
}
void SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)
{
if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )
{
updateViewSettings();
}
}
void SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
updateViewSettings();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fuchar.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2000-09-21 16:11:55 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <svx/editdata.hxx>
#include <svx/svxids.hrc>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#include "dlg_char.hxx"
#include "sdview.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "drviewsh.hxx"
#include "viewshel.hxx"
#include "docshell.hxx"
#include "fuchar.hxx"
TYPEINIT1( FuChar, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuChar::FuChar(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aEditAttr( pDoc->GetPool() );
pView->GetAttributes( aEditAttr );
SfxItemSet aNewAttr( pViewSh->GetPool(),
EE_ITEMS_START, EE_ITEMS_END );
aNewAttr.Put( aEditAttr, FALSE );
SdCharDlg* pDlg = new SdCharDlg( NULL, &aNewAttr, pDoc->GetDocSh() );
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
rReq.Done( *( pDlg->GetOutputItemSet() ) );
pArgs = rReq.GetArgs();
}
break;
default:
{
delete pDlg;
}
return; // Abbruch
}
delete( pDlg );
}
pView->SetAttributes(*pArgs);
// invalidieren der Slots, die in der DrTxtObjBar auftauchen
static USHORT SidArray[] = {
SID_ATTR_CHAR_FONT,
SID_ATTR_CHAR_POSTURE,
SID_ATTR_CHAR_WEIGHT,
SID_ATTR_CHAR_UNDERLINE,
SID_ATTR_CHAR_FONTHEIGHT,
SID_ATTR_CHAR_COLOR,
SID_SET_SUPER_SCRIPT,
SID_SET_SUB_SCRIPT,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
<commit_msg>#94797# Start online spelling if language changed<commit_after>/*************************************************************************
*
* $RCSfile: fuchar.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dl $ $Date: 2001-11-16 10:03:51 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <svx/editdata.hxx>
#include <svx/svxids.hrc>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#include "dlg_char.hxx"
#include "sdview.hxx"
#include "drawview.hxx"
#include "drawdoc.hxx"
#include "drviewsh.hxx"
#include "viewshel.hxx"
#include "docshell.hxx"
#include "fuchar.hxx"
TYPEINIT1( FuChar, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuChar::FuChar(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aEditAttr( pDoc->GetPool() );
pView->GetAttributes( aEditAttr );
SfxItemSet aNewAttr( pViewSh->GetPool(),
EE_ITEMS_START, EE_ITEMS_END );
aNewAttr.Put( aEditAttr, FALSE );
SdCharDlg* pDlg = new SdCharDlg( NULL, &aNewAttr, pDoc->GetDocSh() );
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
{
rReq.Done( *( pDlg->GetOutputItemSet() ) );
pArgs = rReq.GetArgs();
}
break;
default:
{
delete pDlg;
}
return; // Abbruch
}
delete( pDlg );
}
pView->SetAttributes(*pArgs);
// invalidieren der Slots, die in der DrTxtObjBar auftauchen
static USHORT SidArray[] = {
SID_ATTR_CHAR_FONT,
SID_ATTR_CHAR_POSTURE,
SID_ATTR_CHAR_WEIGHT,
SID_ATTR_CHAR_UNDERLINE,
SID_ATTR_CHAR_FONTHEIGHT,
SID_ATTR_CHAR_COLOR,
SID_SET_SUPER_SCRIPT,
SID_SET_SUB_SCRIPT,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
if( pDoc->GetOnlineSpell() )
{
const SfxPoolItem* pItem;
if( SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE, FALSE, &pItem ) ||
SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CJK, FALSE, &pItem ) ||
SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CTL, FALSE, &pItem ) )
{
pDoc->StopOnlineSpelling();
pDoc->StartOnlineSpelling();
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuvect.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-12-14 17:06:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "fuvect.hxx"
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif
#pragma hdrstop
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "strings.hrc"
#include "sdresid.hxx"
//CHINA001 #include "vectdlg.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "vectdlg.hrc" //CHINA001
namespace sd {
TYPEINIT1( FuVectorize, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuVectorize::FuVectorize (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuVectorize::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuVectorize( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuVectorize::DoExecute( SfxRequest& rReq )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();
if( pObj && pObj->ISA( SdrGrafObj ) )
{
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
AbstractSdVectorizeDlg* pDlg = pFact ? pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWindow, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh ) : 0;
DBG_ASSERT(pDlg, "Dialogdiet fail!");
if( pDlg && pDlg->Execute() == RET_OK )
{
const GDIMetaFile& rMtf = pDlg->GetGDIMetaFile(); //CHINA001 const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView && rMtf.GetActionCount() )
{
SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
pView->BegUndo( aStr );
pVectObj->SetGraphic( rMtf );
pView->ReplaceObject( pObj, *pPageView, pVectObj );
pView->EndUndo();
}
}
delete pDlg;
}
}
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS aw035 (1.7.182); FILE MERGED 2006/07/13 16:05:15 aw 1.7.182.1: #126320# SdrMark::GetObj() -> SdrMark::GetMarkedSdrObj() for isolating selection handling<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuvect.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2006-07-25 11:43:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "fuvect.hxx"
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif
#pragma hdrstop
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "strings.hrc"
#include "sdresid.hxx"
//CHINA001 #include "vectdlg.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "vectdlg.hrc" //CHINA001
namespace sd {
TYPEINIT1( FuVectorize, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuVectorize::FuVectorize (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuVectorize::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuVectorize( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuVectorize::DoExecute( SfxRequest& rReq )
{
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
if( rMarkList.GetMarkCount() == 1 )
{
SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();
if( pObj && pObj->ISA( SdrGrafObj ) )
{
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
AbstractSdVectorizeDlg* pDlg = pFact ? pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWindow, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh ) : 0;
DBG_ASSERT(pDlg, "Dialogdiet fail!");
if( pDlg && pDlg->Execute() == RET_OK )
{
const GDIMetaFile& rMtf = pDlg->GetGDIMetaFile(); //CHINA001 const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();
SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );
if( pPageView && rMtf.GetActionCount() )
{
SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
String aStr( pView->GetDescriptionOfMarkedObjects() );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
pView->BegUndo( aStr );
pVectObj->SetGraphic( rMtf );
pView->ReplaceObject( pObj, *pPageView, pVectObj );
pView->EndUndo();
}
}
delete pDlg;
}
}
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <pthread.h>
#include "slre.h"
#include "../../utils/timer.h"
#include "../../utils/memoryman.h"
#define MAXCAPS 1000000
#define EXPRESSIONS 100
#define QUESTIONS 200
/* Data */
char *exps[256];
struct slre *slre[EXPRESSIONS];
char *bufs[MAXCAPS];
int temp[512], buf_len[512];
struct cap **caps;
int iterations;
int NTHREADS;
int numQs;
int numExps;
int s_max = 512;
void *slre_thread(void *tid) {
int start, end, *mytid;
mytid = (int *)tid;
start = (*mytid * iterations);
end = start + iterations;
for (int i = start; i < end; ++i) {
for (int j = 0; j < numQs; ++j) {
slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]);
}
}
return NULL;
}
int fill(FILE *f, char **toFill, int *bufLen, int len) {
int i = 0;
while (i < len) {
int ch = getc(f);
if (ch == EOF) return i;
bufLen[i] = 0;
char *s = (char *)sirius_malloc(5000 + 1);
while (1) {
s[bufLen[i]] = ch;
++bufLen[i];
ch = getc(f);
if (ch == '\n') {
s[bufLen[i]] = 0;
toFill[i] = s;
++i;
break;
}
}
}
return i;
}
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n");
fprintf(stderr,
"Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\n\n",
argv[0]);
exit(0);
}
/* Timing */
STATS_INIT("kernel", "regular_expression");
PRINT_STAT_STRING("abrv", "pthread_regex");
NTHREADS = atoi(argv[1]);
PRINT_STAT_INT("threads", NTHREADS);
FILE *f = fopen(argv[2], "r");
if (f == 0) {
fprintf(stderr, "File %s not found\n", argv[1]);
exit(1);
}
numExps = fill(f, exps, temp, EXPRESSIONS);
PRINT_STAT_INT("expressions", numExps);
FILE *f1 = fopen(argv[3], "r");
if (f1 == 0) {
fprintf(stderr, "File %s not found\n", argv[2]);
exit(1);
}
numQs = fill(f1, bufs, buf_len, QUESTIONS);
PRINT_STAT_INT("questions", numQs);
tic();
for (int i = 0; i < numExps; ++i) {
slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre));
if (!slre_compile(slre[i], exps[i])) {
printf("error compiling: %s\n", exps[i]);
}
}
PRINT_STAT_DOUBLE("regex_compile", toc());
caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap));
for (int i = 0; i < numExps * numQs; ++i) {
char *s = (char *)sirius_malloc(s_max);
struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap));
z->ptr = s;
caps[i] = z;
}
tic();
int tids[NTHREADS];
pthread_t threads[NTHREADS];
pthread_attr_t attr;
iterations = numExps / NTHREADS;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < NTHREADS; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]);
}
for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL);
PRINT_STAT_DOUBLE("pthread_regex", toc());
#ifdef TESTING
f = fopen("../input/regex_slre.pthread", "w");
for (int i = 0; i < numExps * numQs; ++i) fprintf(f, "%s\n", caps[i]->ptr);
fclose(f);
#endif
sirius_free(caps);
STATS_END();
return 0;
}
<commit_msg>sirius-suite/regex/pthread/main.cpp: fix resource leak<commit_after>#include <stdio.h>
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <pthread.h>
#include "slre.h"
#include "../../utils/timer.h"
#include "../../utils/memoryman.h"
#define MAXCAPS 1000000
#define EXPRESSIONS 100
#define QUESTIONS 200
/* Data */
char *exps[256];
struct slre *slre[EXPRESSIONS];
char *bufs[MAXCAPS];
int temp[512], buf_len[512];
struct cap **caps;
int iterations;
int NTHREADS;
int numQs;
int numExps;
int s_max = 512;
void *slre_thread(void *tid) {
int start, end, *mytid;
mytid = (int *)tid;
start = (*mytid * iterations);
end = start + iterations;
for (int i = start; i < end; ++i) {
for (int j = 0; j < numQs; ++j) {
slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]);
}
}
return NULL;
}
int fill(FILE *f, char **toFill, int *bufLen, int len) {
int i = 0;
while (i < len) {
int ch = getc(f);
if (ch == EOF) return i;
bufLen[i] = 0;
char *s = (char *)sirius_malloc(5000 + 1);
while (1) {
s[bufLen[i]] = ch;
++bufLen[i];
ch = getc(f);
if (ch == '\n') {
s[bufLen[i]] = 0;
toFill[i] = s;
++i;
break;
}
}
}
return i;
}
int main(int argc, char *argv[]) {
if (argc < 4) {
fprintf(stderr, "[ERROR] Invalid arguments provided.\n\n");
fprintf(stderr,
"Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\n\n",
argv[0]);
exit(0);
}
/* Timing */
STATS_INIT("kernel", "regular_expression");
PRINT_STAT_STRING("abrv", "pthread_regex");
NTHREADS = atoi(argv[1]);
PRINT_STAT_INT("threads", NTHREADS);
FILE *f = fopen(argv[2], "r");
if (f == 0) {
fprintf(stderr, "File %s not found\n", argv[1]);
exit(1);
}
numExps = fill(f, exps, temp, EXPRESSIONS);
PRINT_STAT_INT("expressions", numExps);
FILE *f1 = fopen(argv[3], "r");
if (f1 == 0) {
fprintf(stderr, "File %s not found\n", argv[2]);
exit(1);
}
numQs = fill(f1, bufs, buf_len, QUESTIONS);
PRINT_STAT_INT("questions", numQs);
tic();
for (int i = 0; i < numExps; ++i) {
slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre));
if (!slre_compile(slre[i], exps[i])) {
printf("error compiling: %s\n", exps[i]);
}
}
PRINT_STAT_DOUBLE("regex_compile", toc());
caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap));
for (int i = 0; i < numExps * numQs; ++i) {
char *s = (char *)sirius_malloc(s_max);
struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap));
z->ptr = s;
caps[i] = z;
}
tic();
int tids[NTHREADS];
pthread_t threads[NTHREADS];
pthread_attr_t attr;
iterations = numExps / NTHREADS;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < NTHREADS; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]);
}
for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL);
PRINT_STAT_DOUBLE("pthread_regex", toc());
#ifdef TESTING
fclose(f);
f = fopen("../input/regex_slre.pthread", "w");
for (int i = 0; i < numExps * numQs; ++i) fprintf(f, "%s\n", caps[i]->ptr);
#endif
fclose(f);
fclose(f1);
sirius_free(caps);
STATS_END();
return 0;
}
<|endoftext|>
|
<commit_before>#include "cosine_tree.h"
// L2 norm of a specific column in a matrix
double columnNormL2(const Matrix& A, index_t i_col) {
Vector col;
A.MakeColumnVector(i_col, &col);
return la::LengthEuclidean(col);
}
// Zero tolerance
#define eps (1e-16)
bool isZero(double d) {
return (d<eps) && (d>-eps);
}
// Init a root cosine node from a matrix
CosineNode::CosineNode(const Matrix& A) {
this->A_.Alias(A);
origIndices_.reserve(A_.n_cols());
norms_.reserve(A_.n_cols());
int newval = A_.n_cols();
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
origIndices_.push_back(0);
norms_.push_back(0);
}
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
origIndices_[i_col] = i_col;
norms_[i_col] = columnNormL2(A_, i_col);
}
parent_ = NULL;
left_ = NULL;
right_ = NULL;
isLeft_ = false;
CalStats();
}
// Init a child cosine node from its parent and a set of the parent's columns
CosineNode::CosineNode(CosineNode& parent,
const std::vector<int>& indices, bool isLeft) {
A_.Alias(parent.A_);
origIndices_.reserve(indices.size());
norms_.reserve(n_cols());
for(index_t i_col = 0; i_col < indices.size(); i_col++) {
norms_.push_back(0);
origIndices_.push_back(0);
}
for (index_t i_col = 0; i_col < origIndices_.size(); i_col++) {
origIndices_[i_col] = parent.origIndices_[indices[i_col]];
norms_[i_col] = parent.norms_[indices[i_col]];
}
parent_ = &parent;
left_ = NULL;
right_ = NULL;
isLeft_ = isLeft;
if (isLeft) parent.left_ = this;
else parent.right_ = this;
CalStats();
}
void CosineNode::CalStats() {
// Calculate cummlulative sum square of L2 norms
cum_norms_.reserve(A_.n_cols());
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
cum_norms_.push_back(0);
}
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
cum_norms_[i_col] = ((i_col > 0) ? cum_norms_[i_col-1]:0)
+ math::Sqr(norms_[i_col]);
}
// Calculate mean vector
mean_.Init(A_.n_rows()); mean_.SetZero();
for (index_t i_col = 0; i_col < n_cols(); i_col++) {
Vector col;
GetColumn(i_col, &col);
la::AddTo(col, &mean_);
}
la::Scale(1.0/(double)origIndices_.size(), &mean_);
}
void CosineNode::ChooseCenter(Vector* center) {
double r = (double)rand()/RAND_MAX * cum_norms_[n_cols()-1];
index_t i_col;
for (i_col = 0; i_col < n_cols(); i_col++)
if (cum_norms_[i_col] >= r) break;
GetColumn(i_col, center);
}
void CosineNode::CalCosines(const Vector& center,
std::vector<double>* cosines) {
for(index_t i_col=0; i_col < n_cols(); i_col++) {
(*cosines).push_back(0);
}
double centerL2 = la::LengthEuclidean(center);
for (index_t i_col = 0; i_col < n_cols(); i_col++)
{
// if col is a zero vector then push it to the left node
if (isZero(norms_[i_col]))
(*cosines)[i_col] = 2;
else {
Vector col;
GetColumn(i_col, &col);
double numerator = la::Dot(center, col);
double denominator = centerL2 * norms_[i_col];
(*cosines)[i_col] = numerator/denominator;
}
}
}
void CosineNode::CreateIndices(std::vector<int>* indices) {
indices->reserve(n_cols());
for (index_t i_col = 0; i_col < n_cols(); i_col++)
{
(*indices).push_back(0);
}
for (index_t i_col = 0; i_col < n_cols(); i_col++)
(*indices)[i_col] = i_col;
}
// Quicksort partitioning procedure
index_t qpartition(std::vector<double>& key, std::vector<int>& data,
index_t left, index_t right) {
index_t j = left;
double x = key[left];
for (index_t i = left+1; i <= right; i++)
{
if (key[i] >= x) {
j++;
double tmp_d = key[i]; key[i] = key[j]; key[j] = tmp_d;
index_t tmp_i = data[i]; data[i] = data[j]; data[j] = tmp_i;
}
}
double tmp_d = key[left]; key[left] = key[j]; key[j] = tmp_d;
index_t tmp_i = data[left]; data[left] = data[j]; data[j] = tmp_i;
return j;
}
// Quicksort on the cosine values
void qsort(std::vector<double>& key, std::vector<int>& data,
index_t left, index_t right) {
if (left >= right) return;
index_t middle = qpartition(key, data, left, right);
qsort(key, data, left, middle-1);
qsort(key, data, middle+1, right);
}
void Sort(std::vector<double>& key, std::vector<int>& data) {
qsort(key, data, 0, key.size()-1);
}
// Calculate the split point where the cosines values are closer
// to the minimum cosine value than the maximum cosine value
index_t calSplitPoint(const std::vector<double>& key) {
double leftKey = key[0];
double rightKey = key[key.size()-1];
index_t i = 0;
while (leftKey - key[i] <= key[i] - rightKey && i < key.size()) i++;
//printf("i = %d\n", i);
return i;
}
// Init a subcopy of an array list
void InitSubCopy(const std::vector<int>& src, index_t pos, index_t size,
std::vector<int>* dst) {
dst->reserve(size);
for (index_t i = 0; i < size; i++)
(*dst).push_back(0);
for (index_t i = 0; i < size; i++)
(*dst)[i] = src[pos+i];
}
// Split the indices at the split point
void splitIndices(std::vector<int>& indices, int leftSize,
std::vector<int>* leftIdx, std::vector<int>* rightIdx) {
InitSubCopy(indices, 0, leftSize, leftIdx);
InitSubCopy(indices, leftSize, indices.size()-leftSize, rightIdx);
}
// Split a cosine tree node by choose a random center, and sort
// the cosine values decreasingly, then choose a split point
// by calling calSplitPoint()
// This procedure won't split a node if either child has the same
// set of columns as the parent
void CosineNode::Split() {
if (n_cols() < 2) return;
Vector center;
std::vector<double> cosines;
std::vector<int> indices, leftIdx, rightIdx;
ChooseCenter(¢er);
CalCosines(center, &cosines);
CreateIndices(&indices);
Sort(cosines, indices);
index_t leftSize = calSplitPoint(cosines);
if (leftSize == n_cols() || leftSize == 0) return;
splitIndices(indices, leftSize, &leftIdx, &rightIdx);
left_ = new CosineNode(*this, leftIdx, true);
right_ = new CosineNode(*this, rightIdx, false);
}
<commit_msg>--Convert to boost unit test framework, ticket 85; replace reserve with resize()<commit_after>#include "cosine_tree.h"
// L2 norm of a specific column in a matrix
double columnNormL2(const Matrix& A, index_t i_col) {
Vector col;
A.MakeColumnVector(i_col, &col);
return la::LengthEuclidean(col);
}
// Zero tolerance
#define eps (1e-16)
bool isZero(double d) {
return (d<eps) && (d>-eps);
}
// Init a root cosine node from a matrix
CosineNode::CosineNode(const Matrix& A) {
this->A_.Alias(A);
origIndices_.resize(A_.n_cols());
norms_.resize(A_.n_cols());
int newval = A_.n_cols();
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
origIndices_[i_col] = i_col;
norms_[i_col] = columnNormL2(A_, i_col);
}
parent_ = NULL;
left_ = NULL;
right_ = NULL;
isLeft_ = false;
CalStats();
}
// Init a child cosine node from its parent and a set of the parent's columns
CosineNode::CosineNode(CosineNode& parent,
const std::vector<int>& indices, bool isLeft) {
A_.Alias(parent.A_);
origIndices_.resize(indices.size());
norms_.resize(n_cols());
for (index_t i_col = 0; i_col < origIndices_.size(); i_col++) {
origIndices_[i_col] = parent.origIndices_[indices[i_col]];
norms_[i_col] = parent.norms_[indices[i_col]];
}
parent_ = &parent;
left_ = NULL;
right_ = NULL;
isLeft_ = isLeft;
if (isLeft) parent.left_ = this;
else parent.right_ = this;
CalStats();
}
void CosineNode::CalStats() {
// Calculate cummlulative sum square of L2 norms
cum_norms_.resize(A_.n_cols());
for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {
cum_norms_[i_col] = ((i_col > 0) ? cum_norms_[i_col-1]:0)
+ math::Sqr(norms_[i_col]);
}
// Calculate mean vector
mean_.Init(A_.n_rows()); mean_.SetZero();
for (index_t i_col = 0; i_col < n_cols(); i_col++) {
Vector col;
GetColumn(i_col, &col);
la::AddTo(col, &mean_);
}
la::Scale(1.0/(double)origIndices_.size(), &mean_);
}
void CosineNode::ChooseCenter(Vector* center) {
double r = (double)rand()/RAND_MAX * cum_norms_[n_cols()-1];
index_t i_col;
for (i_col = 0; i_col < n_cols(); i_col++)
if (cum_norms_[i_col] >= r) break;
GetColumn(i_col, center);
}
void CosineNode::CalCosines(const Vector& center,
std::vector<double>* cosines) {
double centerL2 = la::LengthEuclidean(center);
for (index_t i_col = 0; i_col < n_cols(); i_col++)
{
// if col is a zero vector then push it to the left node
if (isZero(norms_[i_col]))
(*cosines)[i_col] = 2;
else {
Vector col;
GetColumn(i_col, &col);
double numerator = la::Dot(center, col);
double denominator = centerL2 * norms_[i_col];
(*cosines)[i_col] = numerator/denominator;
}
}
}
void CosineNode::CreateIndices(std::vector<int>* indices) {
indices->resize(n_cols());
for (index_t i_col = 0; i_col < n_cols(); i_col++)
(*indices)[i_col] = i_col;
}
// Quicksort partitioning procedure
index_t qpartition(std::vector<double>& key, std::vector<int>& data,
index_t left, index_t right) {
index_t j = left;
double x = key[left];
for (index_t i = left+1; i <= right; i++)
{
if (key[i] >= x) {
j++;
double tmp_d = key[i]; key[i] = key[j]; key[j] = tmp_d;
index_t tmp_i = data[i]; data[i] = data[j]; data[j] = tmp_i;
}
}
double tmp_d = key[left]; key[left] = key[j]; key[j] = tmp_d;
index_t tmp_i = data[left]; data[left] = data[j]; data[j] = tmp_i;
return j;
}
// Quicksort on the cosine values
void qsort(std::vector<double>& key, std::vector<int>& data,
index_t left, index_t right) {
if (left >= right) return;
index_t middle = qpartition(key, data, left, right);
qsort(key, data, left, middle-1);
qsort(key, data, middle+1, right);
}
void Sort(std::vector<double>& key, std::vector<int>& data) {
qsort(key, data, 0, key.size()-1);
}
// Calculate the split point where the cosines values are closer
// to the minimum cosine value than the maximum cosine value
index_t calSplitPoint(const std::vector<double>& key) {
double leftKey = key[0];
double rightKey = key[key.size()-1];
index_t i = 0;
while (leftKey - key[i] <= key[i] - rightKey && i < key.size()) i++;
//printf("i = %d\n", i);
return i;
}
// Init a subcopy of an array list
void InitSubCopy(const std::vector<int>& src, index_t pos, index_t size,
std::vector<int>* dst) {
dst->resize(size);
for (index_t i = 0; i < size; i++)
(*dst)[i] = src[pos+i];
}
// Split the indices at the split point
void splitIndices(std::vector<int>& indices, int leftSize,
std::vector<int>* leftIdx, std::vector<int>* rightIdx) {
InitSubCopy(indices, 0, leftSize, leftIdx);
InitSubCopy(indices, leftSize, indices.size()-leftSize, rightIdx);
}
// Split a cosine tree node by choose a random center, and sort
// the cosine values decreasingly, then choose a split point
// by calling calSplitPoint()
// This procedure won't split a node if either child has the same
// set of columns as the parent
void CosineNode::Split() {
if (n_cols() < 2) return;
Vector center;
std::vector<double> cosines;
std::vector<int> indices, leftIdx, rightIdx;
ChooseCenter(¢er);
CalCosines(center, &cosines);
CreateIndices(&indices);
Sort(cosines, indices);
index_t leftSize = calSplitPoint(cosines);
if (leftSize == n_cols() || leftSize == 0) return;
splitIndices(indices, leftSize, &leftIdx, &rightIdx);
left_ = new CosineNode(*this, leftIdx, true);
right_ = new CosineNode(*this, rightIdx, false);
}
<|endoftext|>
|
<commit_before>#include "selfdrive/ui/replay/route.h"
#include <QDir>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegExp>
#include <QtConcurrent>
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/replay/replay.h"
#include "selfdrive/ui/replay/util.h"
Route::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) {
route_ = parseRoute(route);
}
RouteIdentifier Route::parseRoute(const QString &str) {
QRegExp rx(R"(^([a-z0-9]{16})([|_/])(\d{4}-\d{2}-\d{2}--\d{2}-\d{2}-\d{2})(?:(--|/)(\d*))?$)");
if (rx.indexIn(str) == -1) return {};
const QStringList list = rx.capturedTexts();
return {list[1], list[3], list[5].toInt(), list[1] + "|" + list[3]};
}
bool Route::load() {
if (route_.str.isEmpty()) {
qInfo() << "invalid route format";
return false;
}
return data_dir_.isEmpty() ? loadFromServer() : loadFromLocal();
}
bool Route::loadFromServer() {
QEventLoop loop;
HttpRequest http(nullptr, !Hardware::PC());
QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success) {
loop.exit(success ? loadFromJson(json) : 0);
});
http.sendRequest("https://api.commadotai.com/v1/route/" + route_.str + "/files");
return loop.exec();
}
bool Route::loadFromJson(const QString &json) {
QRegExp rx(R"(\/(\d+)\/)");
for (const auto &value : QJsonDocument::fromJson(json.trimmed().toUtf8()).object()) {
for (const auto &url : value.toArray()) {
QString url_str = url.toString();
if (rx.indexIn(url_str) != -1) {
addFileToSegment(rx.cap(1).toInt(), url_str);
}
}
}
return !segments_.empty();
}
bool Route::loadFromLocal() {
QDir log_dir(data_dir_);
for (const auto &folder : log_dir.entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot, QDir::NoSort)) {
int pos = folder.lastIndexOf("--");
if (pos != -1 && folder.left(pos) == route_.timestamp) {
const int seg_num = folder.mid(pos + 2).toInt();
QDir segment_dir(log_dir.filePath(folder));
for (const auto &f : segment_dir.entryList(QDir::Files)) {
addFileToSegment(seg_num, segment_dir.absoluteFilePath(f));
}
}
}
return !segments_.empty();
}
void Route::addFileToSegment(int n, const QString &file) {
const QString name = QUrl(file).fileName();
if (name == "rlog.bz2") {
segments_[n].rlog = file;
} else if (name == "qlog.bz2") {
segments_[n].qlog = file;
} else if (name == "fcamera.hevc") {
segments_[n].road_cam = file;
} else if (name == "dcamera.hevc") {
segments_[n].driver_cam = file;
} else if (name == "ecamera.hevc") {
segments_[n].wide_road_cam = file;
} else if (name == "qcamera.ts") {
segments_[n].qcamera = file;
}
}
// class Segment
Segment::Segment(int n, const SegmentFile &files, uint32_t flags) : seg_num(n), flags(flags) {
// [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera/qlog
const QString file_list[] = {
(flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam,
flags & REPLAY_FLAG_DCAM ? files.driver_cam : "",
flags & REPLAY_FLAG_ECAM ? files.wide_road_cam : "",
files.rlog.isEmpty() ? files.qlog : files.rlog,
};
for (int i = 0; i < std::size(file_list); i++) {
if (!file_list[i].isEmpty()) {
loading_++;
synchronizer_.addFuture(QtConcurrent::run([=] { loadFile(i, file_list[i].toStdString()); }));
}
}
}
Segment::~Segment() {
disconnect();
abort_ = true;
synchronizer_.setCancelOnWait(true);
synchronizer_.waitForFinished();
}
void Segment::loadFile(int id, const std::string file) {
const bool local_cache = !(flags & REPLAY_FLAG_NO_FILE_CACHE);
bool success = false;
if (id < MAX_CAMERAS) {
frames[id] = std::make_unique<FrameReader>();
success = frames[id]->load(file, flags & REPLAY_FLAG_NO_CUDA, &abort_, local_cache, 20 * 1024 * 1024, 3);
} else {
log = std::make_unique<LogReader>();
success = log->load(file, &abort_, local_cache, 0, 3);
}
if (!success) {
// abort all loading jobs.
abort_ = true;
}
if (--loading_ == 0) {
emit loadFinished(!abort_);
}
}
<commit_msg>replay/segment: pass member function pointer to QtConcurrent::run (#23312)<commit_after>#include "selfdrive/ui/replay/route.h"
#include <QDir>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegExp>
#include <QtConcurrent>
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/replay/replay.h"
#include "selfdrive/ui/replay/util.h"
Route::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) {
route_ = parseRoute(route);
}
RouteIdentifier Route::parseRoute(const QString &str) {
QRegExp rx(R"(^([a-z0-9]{16})([|_/])(\d{4}-\d{2}-\d{2}--\d{2}-\d{2}-\d{2})(?:(--|/)(\d*))?$)");
if (rx.indexIn(str) == -1) return {};
const QStringList list = rx.capturedTexts();
return {list[1], list[3], list[5].toInt(), list[1] + "|" + list[3]};
}
bool Route::load() {
if (route_.str.isEmpty()) {
qInfo() << "invalid route format";
return false;
}
return data_dir_.isEmpty() ? loadFromServer() : loadFromLocal();
}
bool Route::loadFromServer() {
QEventLoop loop;
HttpRequest http(nullptr, !Hardware::PC());
QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success) {
loop.exit(success ? loadFromJson(json) : 0);
});
http.sendRequest("https://api.commadotai.com/v1/route/" + route_.str + "/files");
return loop.exec();
}
bool Route::loadFromJson(const QString &json) {
QRegExp rx(R"(\/(\d+)\/)");
for (const auto &value : QJsonDocument::fromJson(json.trimmed().toUtf8()).object()) {
for (const auto &url : value.toArray()) {
QString url_str = url.toString();
if (rx.indexIn(url_str) != -1) {
addFileToSegment(rx.cap(1).toInt(), url_str);
}
}
}
return !segments_.empty();
}
bool Route::loadFromLocal() {
QDir log_dir(data_dir_);
for (const auto &folder : log_dir.entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot, QDir::NoSort)) {
int pos = folder.lastIndexOf("--");
if (pos != -1 && folder.left(pos) == route_.timestamp) {
const int seg_num = folder.mid(pos + 2).toInt();
QDir segment_dir(log_dir.filePath(folder));
for (const auto &f : segment_dir.entryList(QDir::Files)) {
addFileToSegment(seg_num, segment_dir.absoluteFilePath(f));
}
}
}
return !segments_.empty();
}
void Route::addFileToSegment(int n, const QString &file) {
const QString name = QUrl(file).fileName();
if (name == "rlog.bz2") {
segments_[n].rlog = file;
} else if (name == "qlog.bz2") {
segments_[n].qlog = file;
} else if (name == "fcamera.hevc") {
segments_[n].road_cam = file;
} else if (name == "dcamera.hevc") {
segments_[n].driver_cam = file;
} else if (name == "ecamera.hevc") {
segments_[n].wide_road_cam = file;
} else if (name == "qcamera.ts") {
segments_[n].qcamera = file;
}
}
// class Segment
Segment::Segment(int n, const SegmentFile &files, uint32_t flags) : seg_num(n), flags(flags) {
// [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera/qlog
const std::array file_list = {
(flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam,
flags & REPLAY_FLAG_DCAM ? files.driver_cam : "",
flags & REPLAY_FLAG_ECAM ? files.wide_road_cam : "",
files.rlog.isEmpty() ? files.qlog : files.rlog,
};
for (int i = 0; i < file_list.size(); ++i) {
if (!file_list[i].isEmpty()) {
++loading_;
synchronizer_.addFuture(QtConcurrent::run(this, &Segment::loadFile, i, file_list[i].toStdString()));
}
}
}
Segment::~Segment() {
disconnect();
abort_ = true;
synchronizer_.setCancelOnWait(true);
synchronizer_.waitForFinished();
}
void Segment::loadFile(int id, const std::string file) {
const bool local_cache = !(flags & REPLAY_FLAG_NO_FILE_CACHE);
bool success = false;
if (id < MAX_CAMERAS) {
frames[id] = std::make_unique<FrameReader>();
success = frames[id]->load(file, flags & REPLAY_FLAG_NO_CUDA, &abort_, local_cache, 20 * 1024 * 1024, 3);
} else {
log = std::make_unique<LogReader>();
success = log->load(file, &abort_, local_cache, 0, 3);
}
if (!success) {
// abort all loading jobs.
abort_ = true;
}
if (--loading_ == 0) {
emit loadFinished(!abort_);
}
}
<|endoftext|>
|
<commit_before>//===-- ARMSubtarget.cpp - ARM Subtarget Information ------------*- C++ -*-===//
//
// 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 ARM specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "ARMSubtarget.h"
#include "ARMGenSubtarget.inc"
#include "ARMBaseRegisterInfo.h"
#include "llvm/GlobalValue.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;
static cl::opt<bool>
ReserveR9("arm-reserve-r9", cl::Hidden,
cl::desc("Reserve R9, making it unavailable as GPR"));
static cl::opt<bool>
DarwinUseMOVT("arm-darwin-use-movt", cl::init(true), cl::Hidden);
static cl::opt<bool>
StrictAlign("arm-strict-align", cl::Hidden,
cl::desc("Disallow all unaligned memory accesses"));
ARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, bool isT)
: ARMArchVersion(V4)
, ARMProcFamily(Others)
, ARMFPUType(None)
, UseNEONForSinglePrecisionFP(false)
, SlowFPVMLx(false)
, HasVMLxForwarding(false)
, SlowFPBrcc(false)
, IsThumb(isT)
, ThumbMode(Thumb1)
, NoARM(false)
, PostRAScheduler(false)
, IsR9Reserved(ReserveR9)
, UseMovt(false)
, HasFP16(false)
, HasD16(false)
, HasHardwareDivide(false)
, HasT2ExtractPack(false)
, HasDataBarrier(false)
, Pref32BitThumb(false)
, AvoidCPSRPartialUpdate(false)
, HasMPExtension(false)
, FPOnlySP(false)
, AllowsUnalignedMem(false)
, stackAlignment(4)
, CPUString(CPU)
, TargetTriple(TT)
, TargetABI(ARM_ABI_APCS) {
// Determine default and user specified characteristics
// When no arch is specified either by CPU or by attributes, make the default
// ARMv4T.
const char *ARMArchFeature = "";
if (CPUString.empty())
CPUString = "generic";
if (CPUString == "generic" && (FS.empty() || FS == "generic")) {
ARMArchVersion = V4T;
ARMArchFeature = "+v4t";
}
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
unsigned Len = TT.length();
unsigned Idx = 0;
if (Len >= 5 && TT.substr(0, 4) == "armv")
Idx = 4;
else if (Len >= 6 && TT.substr(0, 5) == "thumb") {
IsThumb = true;
if (Len >= 7 && TT[5] == 'v')
Idx = 6;
}
if (Idx) {
unsigned SubVer = TT[Idx];
if (SubVer >= '7' && SubVer <= '9') {
ARMArchVersion = V7A;
ARMArchFeature = "+v7a";
if (Len >= Idx+2 && TT[Idx+1] == 'm') {
ARMArchVersion = V7M;
ARMArchFeature = "+v7m";
}
} else if (SubVer == '6') {
ARMArchVersion = V6;
ARMArchFeature = "+v6";
if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == '2') {
ARMArchVersion = V6T2;
ARMArchFeature = "+v6t2";
}
} else if (SubVer == '5') {
ARMArchVersion = V5T;
ARMArchFeature = "+v5t";
if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == 'e') {
ARMArchVersion = V5TE;
ARMArchFeature = "+v5te";
}
} else if (SubVer == '4') {
if (Len >= Idx+2 && TT[Idx+1] == 't') {
ARMArchVersion = V4T;
ARMArchFeature = "+v4t";
} else {
ARMArchVersion = V4;
ARMArchFeature = "";
}
}
}
if (TT.find("eabi") != std::string::npos)
TargetABI = ARM_ABI_AAPCS;
// Parse features string. If the first entry in FS (the CPU) is missing,
// insert the architecture feature derived from the target triple. This is
// important for setting features that are implied based on the architecture
// version.
std::string FSWithArch;
if (FS.empty())
FSWithArch = std::string(ARMArchFeature);
else if (FS.find(',') == 0)
FSWithArch = std::string(ARMArchFeature) + FS;
else
FSWithArch = FS;
ParseSubtargetFeatures(FSWithArch, CPUString);
// After parsing Itineraries, set ItinData.IssueWidth.
computeIssueWidth();
// Thumb2 implies at least V6T2.
if (ARMArchVersion >= V6T2)
ThumbMode = Thumb2;
else if (ThumbMode >= Thumb2)
ARMArchVersion = V6T2;
if (isAAPCS_ABI())
stackAlignment = 8;
if (!isTargetDarwin())
UseMovt = hasV6T2Ops();
else {
IsR9Reserved = ReserveR9 | (ARMArchVersion < V6);
UseMovt = DarwinUseMOVT && hasV6T2Ops();
}
if (!isThumb() || hasThumb2())
PostRAScheduler = true;
// v6+ may or may not support unaligned mem access depending on the system
// configuration.
if (!StrictAlign && hasV6Ops() && isTargetDarwin())
AllowsUnalignedMem = true;
}
/// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.
bool
ARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,
Reloc::Model RelocM) const {
if (RelocM == Reloc::Static)
return false;
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
if (!isTargetDarwin()) {
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return false;
return true;
} else {
if (RelocM == Reloc::PIC_) {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage())
// Hidden $non_lazy_ptr reference.
return true;
return false;
} else {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
}
}
return false;
}
unsigned ARMSubtarget::getMispredictionPenalty() const {
// If we have a reasonable estimate of the pipeline depth, then we can
// estimate the penalty of a misprediction based on that.
if (isCortexA8())
return 13;
else if (isCortexA9())
return 8;
// Otherwise, just return a sensible default.
return 10;
}
void ARMSubtarget::computeIssueWidth() {
unsigned allStage1Units = 0;
for (const InstrItinerary *itin = InstrItins.Itineraries;
itin->FirstStage != ~0U; ++itin) {
const InstrStage *IS = InstrItins.Stages + itin->FirstStage;
allStage1Units |= IS->getUnits();
}
InstrItins.IssueWidth = 0;
while (allStage1Units) {
++InstrItins.IssueWidth;
// clear the lowest bit
allStage1Units ^= allStage1Units & ~(allStage1Units - 1);
}
assert(InstrItins.IssueWidth <= 2 && "itinerary bug, too many stage 1 units");
}
bool ARMSubtarget::enablePostRAScheduler(
CodeGenOpt::Level OptLevel,
TargetSubtarget::AntiDepBreakMode& Mode,
RegClassVector& CriticalPathRCs) const {
Mode = TargetSubtarget::ANTIDEP_CRITICAL;
CriticalPathRCs.clear();
CriticalPathRCs.push_back(&ARM::GPRRegClass);
return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
}
<commit_msg>Fix ARMSubtarget feature parsing.<commit_after>//===-- ARMSubtarget.cpp - ARM Subtarget Information ------------*- C++ -*-===//
//
// 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 ARM specific subclass of TargetSubtarget.
//
//===----------------------------------------------------------------------===//
#include "ARMSubtarget.h"
#include "ARMGenSubtarget.inc"
#include "ARMBaseRegisterInfo.h"
#include "llvm/GlobalValue.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;
static cl::opt<bool>
ReserveR9("arm-reserve-r9", cl::Hidden,
cl::desc("Reserve R9, making it unavailable as GPR"));
static cl::opt<bool>
DarwinUseMOVT("arm-darwin-use-movt", cl::init(true), cl::Hidden);
static cl::opt<bool>
StrictAlign("arm-strict-align", cl::Hidden,
cl::desc("Disallow all unaligned memory accesses"));
ARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,
const std::string &FS, bool isT)
: ARMArchVersion(V4)
, ARMProcFamily(Others)
, ARMFPUType(None)
, UseNEONForSinglePrecisionFP(false)
, SlowFPVMLx(false)
, HasVMLxForwarding(false)
, SlowFPBrcc(false)
, IsThumb(isT)
, ThumbMode(Thumb1)
, NoARM(false)
, PostRAScheduler(false)
, IsR9Reserved(ReserveR9)
, UseMovt(false)
, HasFP16(false)
, HasD16(false)
, HasHardwareDivide(false)
, HasT2ExtractPack(false)
, HasDataBarrier(false)
, Pref32BitThumb(false)
, AvoidCPSRPartialUpdate(false)
, HasMPExtension(false)
, FPOnlySP(false)
, AllowsUnalignedMem(false)
, stackAlignment(4)
, CPUString(CPU)
, TargetTriple(TT)
, TargetABI(ARM_ABI_APCS) {
// Determine default and user specified characteristics
// When no arch is specified either by CPU or by attributes, make the default
// ARMv4T.
const char *ARMArchFeature = "";
if (CPUString.empty())
CPUString = "generic";
if (CPUString == "generic" && (FS.empty() || FS == "generic")) {
ARMArchVersion = V4T;
ARMArchFeature = "+v4t";
}
// Set the boolean corresponding to the current target triple, or the default
// if one cannot be determined, to true.
unsigned Len = TT.length();
unsigned Idx = 0;
if (Len >= 5 && TT.substr(0, 4) == "armv")
Idx = 4;
else if (Len >= 6 && TT.substr(0, 5) == "thumb") {
IsThumb = true;
if (Len >= 7 && TT[5] == 'v')
Idx = 6;
}
if (Idx) {
unsigned SubVer = TT[Idx];
if (SubVer >= '7' && SubVer <= '9') {
ARMArchVersion = V7A;
ARMArchFeature = "+v7a";
if (Len >= Idx+2 && TT[Idx+1] == 'm') {
ARMArchVersion = V7M;
ARMArchFeature = "+v7m";
}
} else if (SubVer == '6') {
ARMArchVersion = V6;
ARMArchFeature = "+v6";
if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == '2') {
ARMArchVersion = V6T2;
ARMArchFeature = "+v6t2";
}
} else if (SubVer == '5') {
ARMArchVersion = V5T;
ARMArchFeature = "+v5t";
if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == 'e') {
ARMArchVersion = V5TE;
ARMArchFeature = "+v5te";
}
} else if (SubVer == '4') {
if (Len >= Idx+2 && TT[Idx+1] == 't') {
ARMArchVersion = V4T;
ARMArchFeature = "+v4t";
} else {
ARMArchVersion = V4;
ARMArchFeature = "";
}
}
}
if (TT.find("eabi") != std::string::npos)
TargetABI = ARM_ABI_AAPCS;
// Insert the architecture feature derived from the target triple into the
// feature string. This is important for setting features that are implied
// based on the architecture version.
std::string FSWithArch = std::string(ARMArchFeature);
if (FSWithArch.empty())
FSWithArch = FS;
else if (!FS.empty())
FSWithArch = FSWithArch + "," + FS;
ParseSubtargetFeatures(FSWithArch, CPUString);
// After parsing Itineraries, set ItinData.IssueWidth.
computeIssueWidth();
// Thumb2 implies at least V6T2.
if (ARMArchVersion >= V6T2)
ThumbMode = Thumb2;
else if (ThumbMode >= Thumb2)
ARMArchVersion = V6T2;
if (isAAPCS_ABI())
stackAlignment = 8;
if (!isTargetDarwin())
UseMovt = hasV6T2Ops();
else {
IsR9Reserved = ReserveR9 | (ARMArchVersion < V6);
UseMovt = DarwinUseMOVT && hasV6T2Ops();
}
if (!isThumb() || hasThumb2())
PostRAScheduler = true;
// v6+ may or may not support unaligned mem access depending on the system
// configuration.
if (!StrictAlign && hasV6Ops() && isTargetDarwin())
AllowsUnalignedMem = true;
}
/// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.
bool
ARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,
Reloc::Model RelocM) const {
if (RelocM == Reloc::Static)
return false;
// Materializable GVs (in JIT lazy compilation mode) do not require an extra
// load from stub.
bool isDecl = GV->hasAvailableExternallyLinkage();
if (GV->isDeclaration() && !GV->isMaterializable())
isDecl = true;
if (!isTargetDarwin()) {
// Extra load is needed for all externally visible.
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return false;
return true;
} else {
if (RelocM == Reloc::PIC_) {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
// If symbol visibility is hidden, we have a stub for common symbol
// references and external declarations.
if (isDecl || GV->hasCommonLinkage())
// Hidden $non_lazy_ptr reference.
return true;
return false;
} else {
// If this is a strong reference to a definition, it is definitely not
// through a stub.
if (!isDecl && !GV->isWeakForLinker())
return false;
// Unless we have a symbol with hidden visibility, we have to go through a
// normal $non_lazy_ptr stub because this symbol might be resolved late.
if (!GV->hasHiddenVisibility()) // Non-hidden $non_lazy_ptr reference.
return true;
}
}
return false;
}
unsigned ARMSubtarget::getMispredictionPenalty() const {
// If we have a reasonable estimate of the pipeline depth, then we can
// estimate the penalty of a misprediction based on that.
if (isCortexA8())
return 13;
else if (isCortexA9())
return 8;
// Otherwise, just return a sensible default.
return 10;
}
void ARMSubtarget::computeIssueWidth() {
unsigned allStage1Units = 0;
for (const InstrItinerary *itin = InstrItins.Itineraries;
itin->FirstStage != ~0U; ++itin) {
const InstrStage *IS = InstrItins.Stages + itin->FirstStage;
allStage1Units |= IS->getUnits();
}
InstrItins.IssueWidth = 0;
while (allStage1Units) {
++InstrItins.IssueWidth;
// clear the lowest bit
allStage1Units ^= allStage1Units & ~(allStage1Units - 1);
}
assert(InstrItins.IssueWidth <= 2 && "itinerary bug, too many stage 1 units");
}
bool ARMSubtarget::enablePostRAScheduler(
CodeGenOpt::Level OptLevel,
TargetSubtarget::AntiDepBreakMode& Mode,
RegClassVector& CriticalPathRCs) const {
Mode = TargetSubtarget::ANTIDEP_CRITICAL;
CriticalPathRCs.clear();
CriticalPathRCs.push_back(&ARM::GPRRegClass);
return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
}
<|endoftext|>
|
<commit_before>#pragma once
#include "motion/TrapezoidalMotion.hpp"
#include "MotionConstraints.hpp"
#include "MotionInstant.hpp"
#include <Configuration.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include <Geometry2d/Segment.hpp>
#include <planning/Path.hpp>
namespace Planning
{
/**
* @brief Represents a straight-line path with a trapezoidal velocity profile
*
* @details The path represents a function of position given time that the robot should follow.
* The path is made up of other Paths and can be made up of CompositePaths.
*/
class TrapezoidalPath: public Path
{
private:
const Geometry2d::Point startPos, endPos;
const Geometry2d::Point pathDirection;
const float startSpeed, endSpeed;
const float pathLength;
const float maxAcc;
const float maxSpeed;
public:
TrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, float maxAcc, float maxSpeed) :
startPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),
pathLength((startPos - endPos).mag()), maxAcc(maxAcc), maxSpeed(maxSpeed),
pathDirection((endPos - startPos).normalized()){
}
/** default path is empty */
TrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, const MotionConstraints& constraints) :
startPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),
pathLength((startPos - endPos).mag()), maxAcc(constraints.maxAcceleration), maxSpeed(constraints.maxSpeed),
pathDirection((endPos - startPos).normalized()){
float minSpeed = maxSpeed;
if (startSpeed<minSpeed) {
startSpeed = minSpeed;
}
}
virtual bool evaluate(float time, MotionInstant &targetMotionInstant) const override {
float distance;
float speedOut;
bool valid = TrapezoidalMotion(
pathLength, //PathLength
maxSpeed, //maxSpeed
maxAcc, //maxAcc
time, //time
startSpeed, //startSpeed
endSpeed, //endSpeed
distance, //posOut
speedOut); //speedOut
targetMotionInstant.pos = pathDirection * distance + startPos;
targetMotionInstant.vel = pathDirection * speedOut;
return valid;
}
virtual bool hit(const Geometry2d::CompositeShape &shape, float &hitTime, float startTime = 0) const override {
throw std::logic_error("This function is not implemented");
}
virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const override {
Packet::DebugPath *dbg = state->logFrame->add_debug_paths();
dbg->set_layer(state->findDebugLayer(layer));
*dbg->add_points() = startPos;
*dbg->add_points() = endPos;
}
virtual float getDuration() const override {
static float duration = Trapezoidal::getTime(
pathLength, //distance
pathLength, //pathLength
maxSpeed,
maxAcc,
startSpeed,
endSpeed);
return duration;
}
virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override {
debugThrow("This function is not implemented");
return nullptr;
}
virtual boost::optional<MotionInstant> destination() const override {
static MotionInstant destination = MotionInstant(endPos, pathDirection*endSpeed);
return destination;
}
virtual std::unique_ptr<Path> clone() const override {
return std::unique_ptr<Path>(new TrapezoidalPath(startPos,startSpeed,endPos, endSpeed, maxAcc, maxSpeed));
}
};
}
<commit_msg>Fix TrapezoidalPath memoization<commit_after>#pragma once
#include "motion/TrapezoidalMotion.hpp"
#include "MotionConstraints.hpp"
#include "MotionInstant.hpp"
#include <Configuration.hpp>
#include <Geometry2d/CompositeShape.hpp>
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include <Geometry2d/Segment.hpp>
#include <planning/Path.hpp>
namespace Planning
{
/**
* @brief Represents a straight-line path with a trapezoidal velocity profile
*
* @details The path represents a function of position given time that the robot should follow.
* The path is made up of other Paths and can be made up of CompositePaths.
*/
class TrapezoidalPath: public Path
{
private:
const Geometry2d::Point startPos, endPos;
const Geometry2d::Point pathDirection;
const float startSpeed, endSpeed;
const float pathLength;
const float maxAcc;
const float maxSpeed;
float duration;
public:
TrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, const MotionConstraints& constraints) :
startPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),
pathLength((startPos - endPos).mag()), maxAcc(constraints.maxAcceleration), maxSpeed(constraints.maxSpeed),
pathDirection((endPos - startPos).normalized()) {
float minSpeed = maxSpeed;
if (startSpeed<minSpeed) {
startSpeed = minSpeed;
}
//Precalculate the duration of the path
duration = Trapezoidal::getTime(
pathLength, //distance
pathLength, //pathLength
maxSpeed,
maxAcc,
startSpeed,
endSpeed);
}
virtual bool evaluate(float time, MotionInstant &targetMotionInstant) const override {
float distance;
float speedOut;
bool valid = TrapezoidalMotion(
pathLength, //PathLength
maxSpeed, //maxSpeed
maxAcc, //maxAcc
time, //time
startSpeed, //startSpeed
endSpeed, //endSpeed
distance, //posOut
speedOut); //speedOut
targetMotionInstant.pos = pathDirection * distance + startPos;
targetMotionInstant.vel = pathDirection * speedOut;
return valid;
}
virtual bool hit(const Geometry2d::CompositeShape &shape, float &hitTime, float startTime = 0) const override {
throw std::logic_error("This function is not implemented");
}
virtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = "Motion") const override {
Packet::DebugPath *dbg = state->logFrame->add_debug_paths();
dbg->set_layer(state->findDebugLayer(layer));
*dbg->add_points() = startPos;
*dbg->add_points() = endPos;
}
virtual float getDuration() const override {
return duration;
}
virtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override {
debugThrow("This function is not implemented");
return nullptr;
}
virtual boost::optional<MotionInstant> destination() const override {
return MotionInstant(endPos, pathDirection*endSpeed);
}
virtual std::unique_ptr<Path> clone() const override {
debugThrow("This function is not implemented");
return nullptr;
}
};
}
<|endoftext|>
|
<commit_before>
#pragma once
namespace globjects
{
enum class UniformType : unsigned char
{
NONE,
FLOAT,
INT,
UNSIGNED_INT,
BOOL,
FLOAT_VEC2,
FLOAT_VEC3,
FLOAT_VEC4,
INT_VEC2,
INT_VEC3,
INT_VEC4,
UNSIGNED_INT_VEC2,
UNSIGNED_INT_VEC3,
UNSIGNED_INT_VEC4,
FLOAT_MAT2,
FLOAT_MAT3,
FLOAT_MAT4,
FLOAT_MAT2x3,
FLOAT_MAT3x2,
FLOAT_MAT2x4,
FLOAT_MAT4x2,
FLOAT_MAT3x4,
FLOAT_MAT4x3,
UNSIGNED_INT64,
TEXTURE_HANDLE,
VECTOR_FLOAT,
VECTOR_INT,
VECTOR_UNSIGNED_INT,
VECTOR_BOOL,
VECTOR_FLOAT_VEC2,
VECTOR_FLOAT_VEC3,
VECTOR_FLOAT_VEC4,
VECTOR_INT_VEC2,
VECTOR_INT_VEC3,
VECTOR_INT_VEC4,
VECTOR_UNSIGNED_INT_VEC2,
VECTOR_UNSIGNED_INT_VEC3,
VECTOR_UNSIGNED_INT_VEC4,
VECTOR_FLOAT_MAT2,
VECTOR_FLOAT_MAT3,
VECTOR_FLOAT_MAT4,
VECTOR_FLOAT_MAT2x3,
VECTOR_FLOAT_MAT3x2,
VECTOR_FLOAT_MAT2x4,
VECTOR_FLOAT_MAT4x2,
VECTOR_FLOAT_MAT3x4,
VECTOR_FLOAT_MAT4x3,
VECTOR_UNSIGNED_INT64,
VECTOR_TEXTURE_HANDLE,
ARRAY_FLOAT,
ARRAY_INT,
ARRAY_UNSIGNED_INT,
ARRAY_BOOL,
ARRAY_FLOAT_VEC2,
ARRAY_FLOAT_VEC3,
ARRAY_FLOAT_VEC4,
ARRAY_INT_VEC2,
ARRAY_INT_VEC3,
ARRAY_INT_VEC4,
ARRAY_UNSIGNED_INT_VEC2,
ARRAY_UNSIGNED_INT_VEC3,
ARRAY_UNSIGNED_INT_VEC4,
ARRAY_FLOAT_MAT2,
ARRAY_FLOAT_MAT3,
ARRAY_FLOAT_MAT4,
ARRAY_FLOAT_MAT2x3,
ARRAY_FLOAT_MAT3x2,
ARRAY_FLOAT_MAT2x4,
ARRAY_FLOAT_MAT4x2,
ARRAY_FLOAT_MAT3x4,
ARRAY_FLOAT_MAT4x3,
ARRAY_UNSIGNED_INT64,
ARRAY_TEXTURE_HANDLE
};
template <typename ValueType>
struct UniformTypeHelper
{
static const UniformType value = UniformType::NONE;
};
template <>
struct UniformTypeHelper<float>
{
static const UniformType value = UniformType::FLOAT;
};
template <>
struct UniformTypeHelper<int>
{
static const UniformType value = UniformType::INT;
};
template <>
struct UniformTypeHelper<unsigned int>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<bool>
{
static const UniformType value = UniformType::BOOL;
};
template <>
struct UniformTypeHelper<glm::vec2>
{
static const UniformType value = UniformType::FLOAT_VEC2;
};
template <>
struct UniformTypeHelper<glm::vec3>
{
static const UniformType value = UniformType::FLOAT_VEC3;
};
template <>
struct UniformTypeHelper<glm::vec4>
{
static const UniformType value = UniformType::FLOAT_VEC4;
};
template <>
struct UniformTypeHelper<glm::ivec2>
{
static const UniformType value = UniformType::INT_VEC2;
};
template <>
struct UniformTypeHelper<glm::ivec3>
{
static const UniformType value = UniformType::INT_VEC3;
};
template <>
struct UniformTypeHelper<glm::ivec4>
{
static const UniformType value = UniformType::INT_VEC4;
};
template <>
struct UniformTypeHelper<glm::uvec2>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC2;
};
template <>
struct UniformTypeHelper<glm::uvec3>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC3;
};
template <>
struct UniformTypeHelper<glm::uvec4>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC4;
};
template <>
struct UniformTypeHelper<glm::mat2>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat3>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat4>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat2x3>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat3x2>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat2x4>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat4x2>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat3x4>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<glm::mat4x3>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<gl::GLuint64>
{
static const UniformType value = UniformType::UNSIGNED_INT64;
};
template <>
struct UniformTypeHelper<TextureHandle>
{
static const UniformType value = UniformType::TEXTURE_HANDLE;
};
template <>
struct UniformTypeHelper<std::vector<float>>
{
static const UniformType value = UniformType::VECTOR_FLOAT;
};
template <>
struct UniformTypeHelper<std::vector<int>>
{
static const UniformType value = UniformType::VECTOR_INT;
};
template <>
struct UniformTypeHelper<std::vector<unsigned int>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<bool>>
{
static const UniformType value = UniformType::VECTOR_BOOL;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec2>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec3>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec4>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec2>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec3>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec4>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec2>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec3>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec4>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2x3>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3x2>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2x4>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4x2>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3x4>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4x3>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<gl::GLuint64>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT64;
};
template <>
struct UniformTypeHelper<std::vector<TextureHandle>>
{
static const UniformType value = UniformType::VECTOR_TEXTURE_HANDLE;
};
template <size_t Count>
struct UniformTypeHelper<std::array<float, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<int, Count>>
{
static const UniformType value = UniformType::ARRAY_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<unsigned int, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<bool, Count>>
{
static const UniformType value = UniformType::ARRAY_BOOL;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec2, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec3, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec4, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec2, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec3, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec4, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec2, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec3, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec4, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2x3, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3x2, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2x4, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4x2, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3x4, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4x3, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<gl::GLuint64, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT64;
};
template <size_t Count>
struct UniformTypeHelper<std::array<TextureHandle, Count>>
{
static const UniformType value = UniformType::ARRAY_TEXTURE_HANDLE;
};
template <typename T, std::size_t Count>
void AbstractUniform::setValue(const gl::GLint location, const std::array<T, Count> & value) const
{
setValue(location, std::vector<T>(value.data(), value.data()+Count));
}
} // namespace globjects
<commit_msg>Fix uniform helper types (closes #391)<commit_after>
#pragma once
namespace globjects
{
enum class UniformType : unsigned char
{
NONE,
FLOAT,
INT,
UNSIGNED_INT,
BOOL,
FLOAT_VEC2,
FLOAT_VEC3,
FLOAT_VEC4,
INT_VEC2,
INT_VEC3,
INT_VEC4,
UNSIGNED_INT_VEC2,
UNSIGNED_INT_VEC3,
UNSIGNED_INT_VEC4,
FLOAT_MAT2,
FLOAT_MAT3,
FLOAT_MAT4,
FLOAT_MAT2x3,
FLOAT_MAT3x2,
FLOAT_MAT2x4,
FLOAT_MAT4x2,
FLOAT_MAT3x4,
FLOAT_MAT4x3,
UNSIGNED_INT64,
TEXTURE_HANDLE,
VECTOR_FLOAT,
VECTOR_INT,
VECTOR_UNSIGNED_INT,
VECTOR_BOOL,
VECTOR_FLOAT_VEC2,
VECTOR_FLOAT_VEC3,
VECTOR_FLOAT_VEC4,
VECTOR_INT_VEC2,
VECTOR_INT_VEC3,
VECTOR_INT_VEC4,
VECTOR_UNSIGNED_INT_VEC2,
VECTOR_UNSIGNED_INT_VEC3,
VECTOR_UNSIGNED_INT_VEC4,
VECTOR_FLOAT_MAT2,
VECTOR_FLOAT_MAT3,
VECTOR_FLOAT_MAT4,
VECTOR_FLOAT_MAT2x3,
VECTOR_FLOAT_MAT3x2,
VECTOR_FLOAT_MAT2x4,
VECTOR_FLOAT_MAT4x2,
VECTOR_FLOAT_MAT3x4,
VECTOR_FLOAT_MAT4x3,
VECTOR_UNSIGNED_INT64,
VECTOR_TEXTURE_HANDLE,
ARRAY_FLOAT,
ARRAY_INT,
ARRAY_UNSIGNED_INT,
ARRAY_BOOL,
ARRAY_FLOAT_VEC2,
ARRAY_FLOAT_VEC3,
ARRAY_FLOAT_VEC4,
ARRAY_INT_VEC2,
ARRAY_INT_VEC3,
ARRAY_INT_VEC4,
ARRAY_UNSIGNED_INT_VEC2,
ARRAY_UNSIGNED_INT_VEC3,
ARRAY_UNSIGNED_INT_VEC4,
ARRAY_FLOAT_MAT2,
ARRAY_FLOAT_MAT3,
ARRAY_FLOAT_MAT4,
ARRAY_FLOAT_MAT2x3,
ARRAY_FLOAT_MAT3x2,
ARRAY_FLOAT_MAT2x4,
ARRAY_FLOAT_MAT4x2,
ARRAY_FLOAT_MAT3x4,
ARRAY_FLOAT_MAT4x3,
ARRAY_UNSIGNED_INT64,
ARRAY_TEXTURE_HANDLE
};
template <typename ValueType>
struct UniformTypeHelper
{
static const UniformType value = UniformType::NONE;
};
template <>
struct UniformTypeHelper<float>
{
static const UniformType value = UniformType::FLOAT;
};
template <>
struct UniformTypeHelper<int>
{
static const UniformType value = UniformType::INT;
};
template <>
struct UniformTypeHelper<unsigned int>
{
static const UniformType value = UniformType::UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<bool>
{
static const UniformType value = UniformType::BOOL;
};
template <>
struct UniformTypeHelper<glm::vec2>
{
static const UniformType value = UniformType::FLOAT_VEC2;
};
template <>
struct UniformTypeHelper<glm::vec3>
{
static const UniformType value = UniformType::FLOAT_VEC3;
};
template <>
struct UniformTypeHelper<glm::vec4>
{
static const UniformType value = UniformType::FLOAT_VEC4;
};
template <>
struct UniformTypeHelper<glm::ivec2>
{
static const UniformType value = UniformType::INT_VEC2;
};
template <>
struct UniformTypeHelper<glm::ivec3>
{
static const UniformType value = UniformType::INT_VEC3;
};
template <>
struct UniformTypeHelper<glm::ivec4>
{
static const UniformType value = UniformType::INT_VEC4;
};
template <>
struct UniformTypeHelper<glm::uvec2>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC2;
};
template <>
struct UniformTypeHelper<glm::uvec3>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC3;
};
template <>
struct UniformTypeHelper<glm::uvec4>
{
static const UniformType value = UniformType::UNSIGNED_INT_VEC4;
};
template <>
struct UniformTypeHelper<glm::mat2>
{
static const UniformType value = UniformType::FLOAT_MAT2;
};
template <>
struct UniformTypeHelper<glm::mat3>
{
static const UniformType value = UniformType::FLOAT_MAT3;
};
template <>
struct UniformTypeHelper<glm::mat4>
{
static const UniformType value = UniformType::FLOAT_MAT4;
};
template <>
struct UniformTypeHelper<glm::mat2x3>
{
static const UniformType value = UniformType::FLOAT_MAT2x3;
};
template <>
struct UniformTypeHelper<glm::mat3x2>
{
static const UniformType value = UniformType::FLOAT_MAT3x2;
};
template <>
struct UniformTypeHelper<glm::mat2x4>
{
static const UniformType value = UniformType::FLOAT_MAT2x4;
};
template <>
struct UniformTypeHelper<glm::mat4x2>
{
static const UniformType value = UniformType::FLOAT_MAT4x2;
};
template <>
struct UniformTypeHelper<glm::mat3x4>
{
static const UniformType value = UniformType::FLOAT_MAT3x4;
};
template <>
struct UniformTypeHelper<glm::mat4x3>
{
static const UniformType value = UniformType::FLOAT_MAT4x3;
};
template <>
struct UniformTypeHelper<gl::GLuint64>
{
static const UniformType value = UniformType::UNSIGNED_INT64;
};
template <>
struct UniformTypeHelper<TextureHandle>
{
static const UniformType value = UniformType::TEXTURE_HANDLE;
};
template <>
struct UniformTypeHelper<std::vector<float>>
{
static const UniformType value = UniformType::VECTOR_FLOAT;
};
template <>
struct UniformTypeHelper<std::vector<int>>
{
static const UniformType value = UniformType::VECTOR_INT;
};
template <>
struct UniformTypeHelper<std::vector<unsigned int>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;
};
template <>
struct UniformTypeHelper<std::vector<bool>>
{
static const UniformType value = UniformType::VECTOR_BOOL;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec2>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec3>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::vec4>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec2>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec3>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::ivec4>>
{
static const UniformType value = UniformType::VECTOR_INT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec2>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC2;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec3>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC3;
};
template <>
struct UniformTypeHelper<std::vector<glm::uvec4>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC4;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT2;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT3;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT4;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2x3>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT2x3;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3x2>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT3x2;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat2x4>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT2x4;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4x2>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT4x2;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat3x4>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT3x4;
};
template <>
struct UniformTypeHelper<std::vector<glm::mat4x3>>
{
static const UniformType value = UniformType::VECTOR_FLOAT_MAT4x3;
};
template <>
struct UniformTypeHelper<std::vector<gl::GLuint64>>
{
static const UniformType value = UniformType::VECTOR_UNSIGNED_INT64;
};
template <>
struct UniformTypeHelper<std::vector<TextureHandle>>
{
static const UniformType value = UniformType::VECTOR_TEXTURE_HANDLE;
};
template <size_t Count>
struct UniformTypeHelper<std::array<float, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<int, Count>>
{
static const UniformType value = UniformType::ARRAY_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<unsigned int, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;
};
template <size_t Count>
struct UniformTypeHelper<std::array<bool, Count>>
{
static const UniformType value = UniformType::ARRAY_BOOL;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec2, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec3, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::vec4, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec2, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec3, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::ivec4, Count>>
{
static const UniformType value = UniformType::ARRAY_INT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec2, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec3, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::uvec4, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2x3, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT2x3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3x2, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT3x2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat2x4, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT2x4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4x2, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT4x2;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat3x4, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT3x4;
};
template <size_t Count>
struct UniformTypeHelper<std::array<glm::mat4x3, Count>>
{
static const UniformType value = UniformType::ARRAY_FLOAT_MAT4x3;
};
template <size_t Count>
struct UniformTypeHelper<std::array<gl::GLuint64, Count>>
{
static const UniformType value = UniformType::ARRAY_UNSIGNED_INT64;
};
template <size_t Count>
struct UniformTypeHelper<std::array<TextureHandle, Count>>
{
static const UniformType value = UniformType::ARRAY_TEXTURE_HANDLE;
};
template <typename T, std::size_t Count>
void AbstractUniform::setValue(const gl::GLint location, const std::array<T, Count> & value) const
{
setValue(location, std::vector<T>(value.data(), value.data()+Count));
}
} // namespace globjects
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Christian Surlykke
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QtCore/QRect>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QPalette>
#include "mainwindow.h"
#include "loginform.h"
MainWindow::MainWindow(int screen, QWidget *parent)
: QWidget(parent)
{
setObjectName(QString("MainWindow_%1").arg(screen));
QRect screenRect = QApplication::desktop()->screenGeometry(screen);
setGeometry(screenRect);
QImage image(QString(SHARE_DIR) + "/themes/light/simple_blue_widescreen.png");
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(image.scaled(screenRect.width(), screenRect.right())));
this->setPalette(palette);
// display login dialog only in the main screen
m_main = screen == QApplication::desktop()->primaryScreen();
if (m_main)
{
LoginForm *loginForm = new LoginForm(this);
int offsetX = 2*screenRect.width()/5 - loginForm->width()/2;
if (offsetX < 40)
{
offsetX = 40;
}
int offsetY = screenRect.height()/2 - loginForm->height()/2;
loginForm->move(offsetX, offsetY);
loginForm->show();
}
}
MainWindow::~MainWindow()
{
}
<commit_msg>lightdm: move cursor to the center of screen for miltiple screens seat - it allows to handle key-focus<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Christian Surlykke
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include <QtCore/QRect>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QPalette>
#include <QtGui/QX11Info>
#include "mainwindow.h"
#include "loginform.h"
MainWindow::MainWindow(int screen, QWidget *parent)
: QWidget(parent)
{
setObjectName(QString("MainWindow_%1").arg(screen));
QRect screenRect = QApplication::desktop()->screenGeometry(screen);
setGeometry(screenRect);
QImage image(QString(SHARE_DIR) + "/themes/light/simple_blue_widescreen.png");
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(image.scaled(screenRect.width(), screenRect.right())));
this->setPalette(palette);
// display login dialog only in the main screen
m_main = screen == QApplication::desktop()->primaryScreen();
if (m_main)
{
LoginForm *loginForm = new LoginForm(this);
int offsetX = 2*screenRect.width()/5 - loginForm->width()/2;
if (offsetX < 40)
{
offsetX = 40;
}
int offsetY = screenRect.height()/2 - loginForm->height()/2;
loginForm->move(offsetX, offsetY);
loginForm->show();
// This hack ensures that the primary screen will have focus
// if there are more screens (move the mouse cursor in the center
// of primary screen - not in the center of all X area). It
// won't affect single-screen environments.
int centerX = screenRect.width()/2 + screenRect.x();
int centerY = screenRect.height()/2 + screenRect.y();
QCursor::setPos(centerX, centerY);
}
}
MainWindow::~MainWindow()
{
}
<|endoftext|>
|
<commit_before>
#include <QLineSeries>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QFile>
#include <QDateTime>
#include <QMessageBox>
#include <QDateTimeAxis>
#include <QValueAxis>
#include <QPrinter>
#include <QPrintDialog>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QPushButton>
#include <QToolButton>
#include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->frame->hide();
mChart = new QtCharts::QChart();
mXaxis = new QtCharts::QDateTimeAxis();
mXaxis->setTitleFont(QFont("", 12, QFont::Bold));
mXaxis->setLabelsAngle(20);
mChart->addAxis(mXaxis, Qt::AlignBottom);
mYaxis = new QtCharts::QValueAxis();
mYaxis->setTitleFont(QFont("", 12, QFont::Bold));
mYaxis->setLabelFormat("%i");
mYaxis->setTitleText("Values");
mChart->addAxis(mYaxis, Qt::AlignLeft);
ui->chartView->setChart(mChart);
ui->chartView->setRenderHint(QPainter::Antialiasing);
setupActions();
setupMenus();
connect(ui->minDate, &QDateTimeEdit::dateTimeChanged, [this](){
QDateTime minDate = ui->minDate->dateTime();
ui->maxDate->setMinimumDateTime(minDate);
});
connect(ui->maxDate, &QDateTimeEdit::dateTimeChanged, [this](){
QDateTime maxDate = ui->maxDate->dateTime();
ui->minDate->setMaximumDateTime(maxDate);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::selectDataDialog(QWidget *parent, QList<QAction *> actions)
{
QDialog *dialog = new QDialog(parent);
QVBoxLayout *layout = new QVBoxLayout(dialog);
QLabel *lbl_select = new QLabel("Select Data:", dialog);
QFrame *frame = new QFrame(dialog);
QVBoxLayout *frameLayout = new QVBoxLayout(frame);
layout->addWidget(lbl_select);
layout->addWidget(frame);
QHBoxLayout *btnLayout = new QHBoxLayout(dialog);
QPushButton *okBtn = new QPushButton("OK");
connect (okBtn, &QPushButton::clicked, [dialog](){
dialog->close();
});
QSpacerItem *spacer = new QSpacerItem(50,30, QSizePolicy::Expanding);
btnLayout->addSpacerItem(spacer);
btnLayout->addWidget(okBtn);
layout->addLayout(btnLayout);
foreach (QAction *action, actions)
{
QCheckBox *chkBox = new QCheckBox(action->text(), dialog);
chkBox->setChecked(true);
connect(chkBox, &QCheckBox::toggled, [action](bool clicked){
action->toggle();
});
frameLayout->addWidget(chkBox);
}
dialog->exec();
}
void MainWindow::setupActions()
{
mOpenFile = new QAction("Open File", this);
connect(mOpenFile, &QAction::triggered, [this](){
QString fileName = QFileDialog::getOpenFileName(this, "Open CSV file", "", tr("CSV Files (*.csv)"));
if (!fileName.isEmpty())
{
readCSVFile(fileName);
}
});
mPrintAction = new QAction("Print");
connect(mPrintAction, &QAction::triggered, [this](){
QPrinter printer;
QPrintDialog dialog(&printer, this);
dialog.setWindowTitle(tr("Print Document"));
if (dialog.exec() != QDialog::Accepted) {
return;
}
printer.setOrientation(QPrinter::Landscape);
printer.setFullPage(true);
QPainter painter;
painter.begin(&printer);
//double xscale = printer.pageRect().width()/double(ui->chartView->width());
//double yscale = printer.pageRect().height()/double(ui->chartView->height());
//double scale = qMin(xscale, yscale);
//painter.translate(printer.paperRect().x() + printer.pageRect().width()/2,
// printer.paperRect().y() + printer.pageRect().height()/2);
//painter.scale(scale, scale);
//painter.translate(-ui->chartView->width()/2, -ui->chartView->height()/2);
ui->chartView->render(&painter);
painter.drawRect(printer.pageRect());
//painter.drawRect(printer.paperRect());
});
}
void MainWindow::setupMenus()
{
mFileMenu = new QMenu("File", this);
mFileMenu->addAction(mOpenFile);
mDataMenu = new QMenu("Data", this);
mLinesMenu = new QMenu("Lines", this);
mDataMenu->addMenu(mLinesMenu);
mPrintMenu = new QMenu("Print", this);
mPrintMenu->addAction(mPrintAction);
ui->menuBar->addMenu(mFileMenu);
ui->menuBar->addMenu(mDataMenu);
ui->menuBar->addMenu(mPrintMenu);
}
void MainWindow::readCSVFile(const QString &fileName)
{
QFile file(fileName);
if (file.open(QIODevice::ReadOnly))
{
QStringList dataSeries;
QMap<QString, QList<float>> dataValues;
if (!file.atEnd())
{
//read header
QString header = file.readLine();
QStringList headers = header.split(",");
for (int i=1; i<headers.size(); i++)
{
dataSeries.append(headers[i]);
dataValues.insert(headers[i], QList<float>());
}
}
QList<QDateTime> timeStamps;
QDateTime minDate, maxDate;
while(!file.atEnd())
{
QString line = file.readLine();
QStringList data = line.split(",");
QDateTime ts = QDateTime::fromString(data[0], "M/d/yyyy hh:mm:ss AP");
if (!ts.isValid())
continue;
timeStamps.append(ts);
if (data.size()-1 != dataSeries.size())
{
/*QMessageBox::critical(this, "Error", "Error in csv file data");
return;*/
continue;
}
for (int i=1; i<data.size(); i++)
{
dataValues[dataSeries[i-1]].append(data[i].toFloat());
}
}
if (!timeStamps.isEmpty())
{
maxDate = timeStamps[0];
minDate = timeStamps[0];
}
foreach (QDateTime focusDate, timeStamps)
{
minDate = (focusDate < minDate)? focusDate : minDate;
maxDate = (focusDate > maxDate)? focusDate : maxDate;
}
mSeriesMax.clear();
mSeriesMin.clear();
//min max calulcation
QMapIterator<QString, QList<float>> i(dataValues);
while (i.hasNext())
{
i.next();
QString sName = i.key();
QList<float> data = i.value();
float min_ = *std::min_element(data.begin(), data.end());
float max_ = *std::max_element(data.begin(), data.end());
mSeriesMax[sName] = max_;
mSeriesMin[sName] = min_;
}
mChart->removeAllSeries();
mLinesMenu->clear();
mShownSeries.clear();
for (int i=0; i<dataSeries.size(); i++)
{
QString seriesName = dataSeries[i];
QList<float> data = dataValues[seriesName];
QtCharts::QLineSeries *series = new QtCharts::QLineSeries();
series->setName(seriesName);
for (int j=0; j<timeStamps.size(); j++)
{
series->append(timeStamps[j].toMSecsSinceEpoch(), data[j]);
}
mChart->addSeries(series);
series->attachAxis(mXaxis);
series->attachAxis(mYaxis);
QAction *showSeries = new QAction(seriesName);
showSeries->setCheckable(true);
showSeries->setChecked(true);
mShownSeries.insert(seriesName);
connect(showSeries, &QAction::toggled, [this, series, dataValues](bool checked){
float maximum = 0;
float minimum = 65000;
QString sName = series->name();
if (checked)
{
mShownSeries.insert(sName);
foreach (QString seriesName, mShownSeries)
{
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
mYaxis->setRange(minimum, maximum + 10);
mChart->addSeries(series);
series->attachAxis(mXaxis);
series->attachAxis(mYaxis);
}
else
{
mShownSeries.remove(sName);
foreach (QString seriesName, mShownSeries)
{
;
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
mYaxis->setRange(minimum, maximum + 10);
mChart->removeSeries(series);
}
});
mLinesMenu->addAction(showSeries);
}
ui->chartView->setChart(mChart);
float maximum = 0;
float minimum = 65000;
foreach (QString seriesName, mShownSeries)
{
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
QFileInfo fInfo(fileName);
mChart->setTitleFont(QFont("Times New Roman", 14));
mChart->setTitle("<b>" + fInfo.baseName()+ "</b>");
mYaxis->setRange(minimum, maximum + 10);
mXaxis->setTickCount(10);
mXaxis->setGridLineVisible();
mXaxis->setFormat("yy-MM-d hh:mm");
mXaxis->setTitleText("Date");
ui->maxDate->setMinimumDateTime(minDate);
ui->maxDate->setMaximumDateTime(maxDate);
ui->maxDate->setDateTime(maxDate);
ui->minDate->setMinimumDateTime(minDate);
ui->minDate->setMaximumDateTime(maxDate);
ui->minDate->setDateTime(minDate);
ui->frame->setVisible(true);
selectDataDialog(this, mLinesMenu->actions());
}
}
void MainWindow::on_pushButton_clicked()
{
QDateTime minDate = ui->minDate->dateTime();
QDateTime maxDate = ui->maxDate->dateTime();
if (minDate < maxDate)
{
mXaxis->setRange(minDate, maxDate);
}
else
{
QMessageBox::warning(this, "Invalid Range", "Invalid range please check");
}
}
<commit_msg>full page printing<commit_after>
#include <QLineSeries>
#include <QMenu>
#include <QAction>
#include <QFileDialog>
#include <QFile>
#include <QDateTime>
#include <QMessageBox>
#include <QDateTimeAxis>
#include <QValueAxis>
#include <QPrinter>
#include <QPrintDialog>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QPushButton>
#include <QToolButton>
#include <QDebug>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->frame->hide();
mChart = new QtCharts::QChart();
mXaxis = new QtCharts::QDateTimeAxis();
mXaxis->setTitleFont(QFont("", 12, QFont::Bold));
mXaxis->setLabelsAngle(20);
mChart->addAxis(mXaxis, Qt::AlignBottom);
mYaxis = new QtCharts::QValueAxis();
mYaxis->setTitleFont(QFont("", 12, QFont::Bold));
mYaxis->setLabelFormat("%i");
mYaxis->setTitleText("Values");
mChart->addAxis(mYaxis, Qt::AlignLeft);
ui->chartView->setChart(mChart);
ui->chartView->setRenderHint(QPainter::Antialiasing);
setupActions();
setupMenus();
connect(ui->minDate, &QDateTimeEdit::dateTimeChanged, [this](){
QDateTime minDate = ui->minDate->dateTime();
ui->maxDate->setMinimumDateTime(minDate);
});
connect(ui->maxDate, &QDateTimeEdit::dateTimeChanged, [this](){
QDateTime maxDate = ui->maxDate->dateTime();
ui->minDate->setMaximumDateTime(maxDate);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::selectDataDialog(QWidget *parent, QList<QAction *> actions)
{
QDialog *dialog = new QDialog(parent);
QVBoxLayout *layout = new QVBoxLayout(dialog);
QLabel *lbl_select = new QLabel("Select Data:", dialog);
QFrame *frame = new QFrame(dialog);
QVBoxLayout *frameLayout = new QVBoxLayout(frame);
layout->addWidget(lbl_select);
layout->addWidget(frame);
QHBoxLayout *btnLayout = new QHBoxLayout(dialog);
QPushButton *okBtn = new QPushButton("OK");
connect (okBtn, &QPushButton::clicked, [dialog](){
dialog->close();
});
QSpacerItem *spacer = new QSpacerItem(50,30, QSizePolicy::Expanding);
btnLayout->addSpacerItem(spacer);
btnLayout->addWidget(okBtn);
layout->addLayout(btnLayout);
foreach (QAction *action, actions)
{
QCheckBox *chkBox = new QCheckBox(action->text(), dialog);
chkBox->setChecked(true);
connect(chkBox, &QCheckBox::toggled, [action](bool clicked){
action->toggle();
});
frameLayout->addWidget(chkBox);
}
dialog->exec();
}
void MainWindow::setupActions()
{
mOpenFile = new QAction("Open File", this);
connect(mOpenFile, &QAction::triggered, [this](){
QString fileName = QFileDialog::getOpenFileName(this, "Open CSV file", "", tr("CSV Files (*.csv)"));
if (!fileName.isEmpty())
{
readCSVFile(fileName);
}
});
mPrintAction = new QAction("Print");
connect(mPrintAction, &QAction::triggered, [this](){
QPrinter printer;
QPrintDialog dialog(&printer, this);
dialog.setWindowTitle(tr("Print Document"));
if (dialog.exec() != QDialog::Accepted) {
return;
}
printer.setOrientation(QPrinter::Landscape);
printer.setFullPage(true);
QPainter painter;
painter.begin(&printer);
//double xscale = printer.pageRect().width()/double(ui->chartView->width());
//double yscale = printer.pageRect().height()/double(ui->chartView->height());
//double scale = qMin(xscale, yscale);
//painter.translate(printer.paperRect().x() + printer.pageRect().width()/2,
// printer.paperRect().y() + printer.pageRect().height()/2);
//painter.scale(scale, scale);
//painter.translate(-ui->chartView->width()/2, -ui->chartView->height()/2);
ui->chartView->render(&painter, printer.pageRect(), ui->chartView->rect(),Qt::IgnoreAspectRatio);
painter.drawRect(printer.pageRect());
//painter.drawRect(printer.paperRect());
});
}
void MainWindow::setupMenus()
{
mFileMenu = new QMenu("File", this);
mFileMenu->addAction(mOpenFile);
mDataMenu = new QMenu("Data", this);
mLinesMenu = new QMenu("Lines", this);
mDataMenu->addMenu(mLinesMenu);
mPrintMenu = new QMenu("Print", this);
mPrintMenu->addAction(mPrintAction);
ui->menuBar->addMenu(mFileMenu);
ui->menuBar->addMenu(mDataMenu);
ui->menuBar->addMenu(mPrintMenu);
}
void MainWindow::readCSVFile(const QString &fileName)
{
QFile file(fileName);
if (file.open(QIODevice::ReadOnly))
{
QStringList dataSeries;
QMap<QString, QList<float>> dataValues;
if (!file.atEnd())
{
//read header
QString header = file.readLine();
QStringList headers = header.split(",");
for (int i=1; i<headers.size(); i++)
{
dataSeries.append(headers[i]);
dataValues.insert(headers[i], QList<float>());
}
}
QList<QDateTime> timeStamps;
QDateTime minDate, maxDate;
while(!file.atEnd())
{
QString line = file.readLine();
QStringList data = line.split(",");
QDateTime ts = QDateTime::fromString(data[0], "M/d/yyyy hh:mm:ss AP");
if (!ts.isValid())
continue;
timeStamps.append(ts);
if (data.size()-1 != dataSeries.size())
{
/*QMessageBox::critical(this, "Error", "Error in csv file data");
return;*/
continue;
}
for (int i=1; i<data.size(); i++)
{
dataValues[dataSeries[i-1]].append(data[i].toFloat());
}
}
if (!timeStamps.isEmpty())
{
maxDate = timeStamps[0];
minDate = timeStamps[0];
}
foreach (QDateTime focusDate, timeStamps)
{
minDate = (focusDate < minDate)? focusDate : minDate;
maxDate = (focusDate > maxDate)? focusDate : maxDate;
}
mSeriesMax.clear();
mSeriesMin.clear();
//min max calulcation
QMapIterator<QString, QList<float>> i(dataValues);
while (i.hasNext())
{
i.next();
QString sName = i.key();
QList<float> data = i.value();
float min_ = *std::min_element(data.begin(), data.end());
float max_ = *std::max_element(data.begin(), data.end());
mSeriesMax[sName] = max_;
mSeriesMin[sName] = min_;
}
mChart->removeAllSeries();
mLinesMenu->clear();
mShownSeries.clear();
for (int i=0; i<dataSeries.size(); i++)
{
QString seriesName = dataSeries[i];
QList<float> data = dataValues[seriesName];
QtCharts::QLineSeries *series = new QtCharts::QLineSeries();
series->setName(seriesName);
for (int j=0; j<timeStamps.size(); j++)
{
series->append(timeStamps[j].toMSecsSinceEpoch(), data[j]);
}
mChart->addSeries(series);
series->attachAxis(mXaxis);
series->attachAxis(mYaxis);
QAction *showSeries = new QAction(seriesName);
showSeries->setCheckable(true);
showSeries->setChecked(true);
mShownSeries.insert(seriesName);
connect(showSeries, &QAction::toggled, [this, series, dataValues](bool checked){
float maximum = 0;
float minimum = 65000;
QString sName = series->name();
if (checked)
{
mShownSeries.insert(sName);
foreach (QString seriesName, mShownSeries)
{
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
mYaxis->setRange(minimum, maximum + 10);
mChart->addSeries(series);
series->attachAxis(mXaxis);
series->attachAxis(mYaxis);
}
else
{
mShownSeries.remove(sName);
foreach (QString seriesName, mShownSeries)
{
;
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
mYaxis->setRange(minimum, maximum + 10);
mChart->removeSeries(series);
}
});
mLinesMenu->addAction(showSeries);
}
ui->chartView->setChart(mChart);
float maximum = 0;
float minimum = 65000;
foreach (QString seriesName, mShownSeries)
{
minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;
maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;
}
QFileInfo fInfo(fileName);
mChart->setTitleFont(QFont("Times New Roman", 14));
mChart->setTitle("<b>" + fInfo.baseName()+ "</b>");
mYaxis->setRange(minimum, maximum + 10);
mXaxis->setTickCount(10);
mXaxis->setGridLineVisible();
mXaxis->setFormat("yy-MM-d hh:mm");
mXaxis->setTitleText("Date");
ui->maxDate->setMinimumDateTime(minDate);
ui->maxDate->setMaximumDateTime(maxDate);
ui->maxDate->setDateTime(maxDate);
ui->minDate->setMinimumDateTime(minDate);
ui->minDate->setMaximumDateTime(maxDate);
ui->minDate->setDateTime(minDate);
ui->frame->setVisible(true);
selectDataDialog(this, mLinesMenu->actions());
}
}
void MainWindow::on_pushButton_clicked()
{
QDateTime minDate = ui->minDate->dateTime();
QDateTime maxDate = ui->maxDate->dateTime();
if (minDate < maxDate)
{
mXaxis->setRange(minDate, maxDate);
}
else
{
QMessageBox::warning(this, "Invalid Range", "Invalid range please check");
}
}
<|endoftext|>
|
<commit_before>//===-- asan_mem_test.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
template<typename T>
void MemSetOOBTestTemplate(size_t length) {
if (length == 0) return;
size_t size = Ident(sizeof(T) * length);
T *array = Ident((T*)malloc(size));
int element = Ident(42);
int zero = Ident(0);
void *(*MEMSET)(void *s, int c, size_t n) = Ident(memset);
// memset interval inside array
MEMSET(array, element, size);
MEMSET(array, element, size - 1);
MEMSET(array + length - 1, element, sizeof(T));
MEMSET(array, element, 1);
// memset 0 bytes
MEMSET(array - 10, element, zero);
MEMSET(array - 1, element, zero);
MEMSET(array, element, zero);
MEMSET(array + length, 0, zero);
MEMSET(array + length + 1, 0, zero);
// try to memset bytes to the right of array
EXPECT_DEATH(MEMSET(array, 0, size + 1),
RightOOBWriteMessage(0));
EXPECT_DEATH(MEMSET((char*)(array + length) - 1, element, 6),
RightOOBWriteMessage(0));
EXPECT_DEATH(MEMSET(array + 1, element, size + sizeof(T)),
RightOOBWriteMessage(0));
// whole interval is to the right
EXPECT_DEATH(MEMSET(array + length + 1, 0, 10),
RightOOBWriteMessage(sizeof(T)));
// try to memset bytes to the left of array
EXPECT_DEATH(MEMSET((char*)array - 1, element, size),
LeftOOBWriteMessage(1));
EXPECT_DEATH(MEMSET((char*)array - 5, 0, 6),
LeftOOBWriteMessage(5));
if (length >= 100) {
// Large OOB, we find it only if the redzone is large enough.
EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
LeftOOBWriteMessage(5 * sizeof(T)));
}
// whole interval is to the left
EXPECT_DEATH(MEMSET(array - 2, 0, sizeof(T)),
LeftOOBWriteMessage(2 * sizeof(T)));
// try to memset bytes both to the left & to the right
EXPECT_DEATH(MEMSET((char*)array - 2, element, size + 4),
LeftOOBWriteMessage(2));
free(array);
}
TEST(AddressSanitizer, MemSetOOBTest) {
MemSetOOBTestTemplate<char>(100);
MemSetOOBTestTemplate<int>(5);
MemSetOOBTestTemplate<double>(256);
// We can test arrays of structres/classes here, but what for?
}
// Try to allocate two arrays of 'size' bytes that are near each other.
// Strictly speaking we are not guaranteed to find such two pointers,
// but given the structure of asan's allocator we will.
static bool AllocateTwoAdjacentArrays(char **x1, char **x2, size_t size) {
vector<char *> v;
bool res = false;
for (size_t i = 0; i < 1000U && !res; i++) {
v.push_back(new char[size]);
if (i == 0) continue;
sort(v.begin(), v.end());
for (size_t j = 1; j < v.size(); j++) {
assert(v[j] > v[j-1]);
if ((size_t)(v[j] - v[j-1]) < size * 2) {
*x2 = v[j];
*x1 = v[j-1];
res = true;
break;
}
}
}
for (size_t i = 0; i < v.size(); i++) {
if (res && v[i] == *x1) continue;
if (res && v[i] == *x2) continue;
delete [] v[i];
}
return res;
}
TEST(AddressSanitizer, LargeOOBInMemset) {
for (size_t size = 200; size < 100000; size += size / 2) {
char *x1, *x2;
if (!Ident(AllocateTwoAdjacentArrays)(&x1, &x2, size))
continue;
// fprintf(stderr, " large oob memset: %p %p %zd\n", x1, x2, size);
// Do a memset on x1 with huge out-of-bound access that will end up in x2.
EXPECT_DEATH(Ident(memset)(x1, 0, size * 2),
"is located 0 bytes to the right");
delete [] x1;
delete [] x2;
return;
}
assert(0 && "Did not find two adjacent malloc-ed pointers");
}
// Same test for memcpy and memmove functions
template <typename T, class M>
void MemTransferOOBTestTemplate(size_t length) {
if (length == 0) return;
size_t size = Ident(sizeof(T) * length);
T *src = Ident((T*)malloc(size));
T *dest = Ident((T*)malloc(size));
int zero = Ident(0);
// valid transfer of bytes between arrays
M::transfer(dest, src, size);
M::transfer(dest + 1, src, size - sizeof(T));
M::transfer(dest, src + length - 1, sizeof(T));
M::transfer(dest, src, 1);
// transfer zero bytes
M::transfer(dest - 1, src, 0);
M::transfer(dest + length, src, zero);
M::transfer(dest, src - 1, zero);
M::transfer(dest, src, zero);
// try to change mem to the right of dest
EXPECT_DEATH(M::transfer(dest + 1, src, size),
RightOOBWriteMessage(0));
EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
RightOOBWriteMessage(0));
// try to change mem to the left of dest
EXPECT_DEATH(M::transfer(dest - 2, src, size),
LeftOOBWriteMessage(2 * sizeof(T)));
EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
LeftOOBWriteMessage(3));
// try to access mem to the right of src
EXPECT_DEATH(M::transfer(dest, src + 2, size),
RightOOBReadMessage(0));
EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
RightOOBReadMessage(0));
// try to access mem to the left of src
EXPECT_DEATH(M::transfer(dest, src - 1, size),
LeftOOBReadMessage(sizeof(T)));
EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
LeftOOBReadMessage(6));
// Generally we don't need to test cases where both accessing src and writing
// to dest address to poisoned memory.
T *big_src = Ident((T*)malloc(size * 2));
T *big_dest = Ident((T*)malloc(size * 2));
// try to change mem to both sides of dest
EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
LeftOOBWriteMessage(sizeof(T)));
// try to access mem to both sides of src
EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
LeftOOBReadMessage(2 * sizeof(T)));
free(src);
free(dest);
free(big_src);
free(big_dest);
}
class MemCpyWrapper {
public:
static void* transfer(void *to, const void *from, size_t size) {
return Ident(memcpy)(to, from, size);
}
};
TEST(AddressSanitizer, MemCpyOOBTest) {
MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
}
class MemMoveWrapper {
public:
static void* transfer(void *to, const void *from, size_t size) {
return Ident(memmove)(to, from, size);
}
};
TEST(AddressSanitizer, MemMoveOOBTest) {
MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
}
TEST(AddressSanitizer, MemCmpOOBTest) {
size_t size = Ident(100);
char *s1 = MallocAndMemsetString(size);
char *s2 = MallocAndMemsetString(size);
// Normal memcmp calls.
Ident(memcmp(s1, s2, size));
Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
Ident(memcmp(s1 - 1, s2 - 1, 0));
// One of arguments points to not allocated memory.
EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
// Hit unallocated memory and die.
EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
// Zero bytes are not terminators and don't prevent from OOB.
s1[size - 1] = '\0';
s2[size - 1] = '\0';
EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
// Even if the buffers differ in the first byte, we still assume that
// memcmp may access the whole buffer and thus reporting the overflow here:
s1[0] = 1;
s2[0] = 123;
EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
free(s1);
free(s2);
}
<commit_msg>[asan] remove UB (comparison of two unrelated pointers) from a test<commit_after>//===-- asan_mem_test.cc --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
//===----------------------------------------------------------------------===//
#include "asan_test_utils.h"
template<typename T>
void MemSetOOBTestTemplate(size_t length) {
if (length == 0) return;
size_t size = Ident(sizeof(T) * length);
T *array = Ident((T*)malloc(size));
int element = Ident(42);
int zero = Ident(0);
void *(*MEMSET)(void *s, int c, size_t n) = Ident(memset);
// memset interval inside array
MEMSET(array, element, size);
MEMSET(array, element, size - 1);
MEMSET(array + length - 1, element, sizeof(T));
MEMSET(array, element, 1);
// memset 0 bytes
MEMSET(array - 10, element, zero);
MEMSET(array - 1, element, zero);
MEMSET(array, element, zero);
MEMSET(array + length, 0, zero);
MEMSET(array + length + 1, 0, zero);
// try to memset bytes to the right of array
EXPECT_DEATH(MEMSET(array, 0, size + 1),
RightOOBWriteMessage(0));
EXPECT_DEATH(MEMSET((char*)(array + length) - 1, element, 6),
RightOOBWriteMessage(0));
EXPECT_DEATH(MEMSET(array + 1, element, size + sizeof(T)),
RightOOBWriteMessage(0));
// whole interval is to the right
EXPECT_DEATH(MEMSET(array + length + 1, 0, 10),
RightOOBWriteMessage(sizeof(T)));
// try to memset bytes to the left of array
EXPECT_DEATH(MEMSET((char*)array - 1, element, size),
LeftOOBWriteMessage(1));
EXPECT_DEATH(MEMSET((char*)array - 5, 0, 6),
LeftOOBWriteMessage(5));
if (length >= 100) {
// Large OOB, we find it only if the redzone is large enough.
EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),
LeftOOBWriteMessage(5 * sizeof(T)));
}
// whole interval is to the left
EXPECT_DEATH(MEMSET(array - 2, 0, sizeof(T)),
LeftOOBWriteMessage(2 * sizeof(T)));
// try to memset bytes both to the left & to the right
EXPECT_DEATH(MEMSET((char*)array - 2, element, size + 4),
LeftOOBWriteMessage(2));
free(array);
}
TEST(AddressSanitizer, MemSetOOBTest) {
MemSetOOBTestTemplate<char>(100);
MemSetOOBTestTemplate<int>(5);
MemSetOOBTestTemplate<double>(256);
// We can test arrays of structres/classes here, but what for?
}
// Try to allocate two arrays of 'size' bytes that are near each other.
// Strictly speaking we are not guaranteed to find such two pointers,
// but given the structure of asan's allocator we will.
static bool AllocateTwoAdjacentArrays(char **x1, char **x2, size_t size) {
vector<uintptr_t> v;
bool res = false;
for (size_t i = 0; i < 1000U && !res; i++) {
v.push_back(reinterpret_cast<uintptr_t>(new char[size]));
if (i == 0) continue;
sort(v.begin(), v.end());
for (size_t j = 1; j < v.size(); j++) {
assert(v[j] > v[j-1]);
if ((size_t)(v[j] - v[j-1]) < size * 2) {
*x2 = reinterpret_cast<char*>(v[j]);
*x1 = reinterpret_cast<char*>(v[j-1]);
res = true;
break;
}
}
}
for (size_t i = 0; i < v.size(); i++) {
char *p = reinterpret_cast<char *>(v[i]);
if (res && p == *x1) continue;
if (res && p == *x2) continue;
delete [] p;
}
return res;
}
TEST(AddressSanitizer, LargeOOBInMemset) {
for (size_t size = 200; size < 100000; size += size / 2) {
char *x1, *x2;
if (!Ident(AllocateTwoAdjacentArrays)(&x1, &x2, size))
continue;
// fprintf(stderr, " large oob memset: %p %p %zd\n", x1, x2, size);
// Do a memset on x1 with huge out-of-bound access that will end up in x2.
EXPECT_DEATH(Ident(memset)(x1, 0, size * 2),
"is located 0 bytes to the right");
delete [] x1;
delete [] x2;
return;
}
assert(0 && "Did not find two adjacent malloc-ed pointers");
}
// Same test for memcpy and memmove functions
template <typename T, class M>
void MemTransferOOBTestTemplate(size_t length) {
if (length == 0) return;
size_t size = Ident(sizeof(T) * length);
T *src = Ident((T*)malloc(size));
T *dest = Ident((T*)malloc(size));
int zero = Ident(0);
// valid transfer of bytes between arrays
M::transfer(dest, src, size);
M::transfer(dest + 1, src, size - sizeof(T));
M::transfer(dest, src + length - 1, sizeof(T));
M::transfer(dest, src, 1);
// transfer zero bytes
M::transfer(dest - 1, src, 0);
M::transfer(dest + length, src, zero);
M::transfer(dest, src - 1, zero);
M::transfer(dest, src, zero);
// try to change mem to the right of dest
EXPECT_DEATH(M::transfer(dest + 1, src, size),
RightOOBWriteMessage(0));
EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),
RightOOBWriteMessage(0));
// try to change mem to the left of dest
EXPECT_DEATH(M::transfer(dest - 2, src, size),
LeftOOBWriteMessage(2 * sizeof(T)));
EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),
LeftOOBWriteMessage(3));
// try to access mem to the right of src
EXPECT_DEATH(M::transfer(dest, src + 2, size),
RightOOBReadMessage(0));
EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),
RightOOBReadMessage(0));
// try to access mem to the left of src
EXPECT_DEATH(M::transfer(dest, src - 1, size),
LeftOOBReadMessage(sizeof(T)));
EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),
LeftOOBReadMessage(6));
// Generally we don't need to test cases where both accessing src and writing
// to dest address to poisoned memory.
T *big_src = Ident((T*)malloc(size * 2));
T *big_dest = Ident((T*)malloc(size * 2));
// try to change mem to both sides of dest
EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),
LeftOOBWriteMessage(sizeof(T)));
// try to access mem to both sides of src
EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),
LeftOOBReadMessage(2 * sizeof(T)));
free(src);
free(dest);
free(big_src);
free(big_dest);
}
class MemCpyWrapper {
public:
static void* transfer(void *to, const void *from, size_t size) {
return Ident(memcpy)(to, from, size);
}
};
TEST(AddressSanitizer, MemCpyOOBTest) {
MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);
MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);
}
class MemMoveWrapper {
public:
static void* transfer(void *to, const void *from, size_t size) {
return Ident(memmove)(to, from, size);
}
};
TEST(AddressSanitizer, MemMoveOOBTest) {
MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);
MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);
}
TEST(AddressSanitizer, MemCmpOOBTest) {
size_t size = Ident(100);
char *s1 = MallocAndMemsetString(size);
char *s2 = MallocAndMemsetString(size);
// Normal memcmp calls.
Ident(memcmp(s1, s2, size));
Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));
Ident(memcmp(s1 - 1, s2 - 1, 0));
// One of arguments points to not allocated memory.
EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));
EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));
EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));
EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));
// Hit unallocated memory and die.
EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));
EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));
// Zero bytes are not terminators and don't prevent from OOB.
s1[size - 1] = '\0';
s2[size - 1] = '\0';
EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
// Even if the buffers differ in the first byte, we still assume that
// memcmp may access the whole buffer and thus reporting the overflow here:
s1[0] = 1;
s2[0] = 123;
EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));
free(s1);
free(s2);
}
<|endoftext|>
|
<commit_before>
#include "glew.h"
#include <GL/glew.h>
#include <iostream>
namespace
{
#include "gltest_data.inl"
bool errors = false;
}
void glew_init()
{
glewInit();
glGetError();
}
inline void glError()
{
GLenum error = glGetError();
if (error != GL_NO_ERROR)
std::cout << "Error: 0x" << std::hex << error << std::endl;
}
void glew_test()
{
if (errors)
{
#include "gltest_error.inl"
}
else
{
#include "gltest.inl"
}
}
void glew_error(bool enable)
{
errors = enable;
}
<commit_msg>Fix CID #41484<commit_after>
#include "glew.h"
#include <GL/glew.h>
#include <iostream>
namespace
{
#include "gltest_data.inl"
bool errors = false;
}
void glew_init()
{
glewInit();
glGetError();
}
inline void glError()
{
GLenum error = glGetError();
if (error != GL_NO_ERROR)
std::cout << "Error: " << error << std::endl;
}
void glew_test()
{
if (errors)
{
#include "gltest_error.inl"
}
else
{
#include "gltest.inl"
}
}
void glew_error(bool enable)
{
errors = enable;
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
* 2007 Tobias Pfeiffer <tgpfeiffer@web.de>
* 2009 Evgeny Egorochkin <phreedom.stdin@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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "flacthroughanalyzer.h"
#include <strigi/strigiconfig.h>
#include "analysisresult.h"
#include "textutils.h"
#include <iostream>
#include <cctype>
#include <cstring>
using namespace Strigi;
using namespace std;
#define NMM_PROPOSAL "http://www.semanticdesktop.org/ontologies/nmm#"
const string
typePropertyName(
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
fullnamePropertyName(
"http://www.semanticdesktop.org/ontologies/2007/03/22/nco#fullname"),
titlePropertyName(
"http://www.semanticdesktop.org/ontologies/2007/01/19/nie#title"),
musicClassName(
NMM_PROPOSAL "MusicPiece"),
albumClassName(
NMM_PROPOSAL "MusicAlbum"),
contactClassName(
"http://www.semanticdesktop.org/ontologies/2007/03/22/nco#Contact");
void
FlacThroughAnalyzerFactory::registerFields(FieldRegister& r) {
fields["title"] = r.registerField(titlePropertyName);
albumField = r.registerField(NMM_PROPOSAL "musicAlbum");
artistField = r.registerField("http://www.semanticdesktop.org/ontologies/2007/03/22/nco#creator");
fields["genre"] = r.registerField("http://freedesktop.org/standards/xesam/1.0/core#genre");
fields["codec"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#codec");
composerField = r.registerField(NMM_PROPOSAL "composer");
performerField = r.registerField(NMM_PROPOSAL "performer");
fields["date"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#contentCreated");
fields["description"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#description");
fields["tracknumber"] = r.registerField(NMM_PROPOSAL "trackNumber");
fields["version"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#version");
fields["isrc"] = r.registerField(NMM_PROPOSAL "internationalStandardRecordingCode");
fields["copyright"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#copyright");
fields["license"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#license");
// ogg spec fields left unimplemented: ORGANIZATION, LOCATION, CONTACT
fields["type"] = r.typeField;
}
#undef NMM_PROPOSAL
void
FlacThroughAnalyzer::setIndexable(AnalysisResult* i) {
indexable = i;
}
InputStream*
FlacThroughAnalyzer::connectInputStream(InputStream* in) {
if(!in) {
return in;
}
const char* buf;
char blocktype;
int32_t nreq = 8;
int32_t nread = in->read(buf, nreq, nreq);
int32_t blocksize = 4;
// check the header for Flac signature
// the first ogg page starts at position 0, the second at position 58
if (nread < nreq || strncmp("fLaC", buf,4)) {
in->reset(0);
return in;
}
cerr<< "found a flac file!";
do {
blocktype = buf[blocksize];
blocksize = readBigEndianUInt32(buf+blocksize)& 0xFFFFFF;
//if this isn't the last block, read the header of the next block as well
nreq = (blocktype & 0x80 ? blocksize : blocksize+4);
nread = in->read(buf, nreq, nreq);
// we are looking for the comments block only
if ((blocktype&0x7F)==4) {
const char *p2 = buf + 4 + readLittleEndianUInt32(buf); //skip vendor string. maybe put it into metadata as soon as there's some place for it
const char *end = buf + blocksize;
uint32_t nfields = readLittleEndianUInt32(p2);
// read all the comments
p2 += 4;
for (uint32_t i = 0; p2 < end && i < nfields; ++i) {
// read the comment length
uint32_t size = readLittleEndianUInt32(p2);
p2 += 4;
if (size <= (uint32_t)(end - p2)) {
uint32_t eq = 1;
while (eq < size && p2[eq] != '=') eq++;
if (size > eq) {
string name(p2, eq);
// convert field name to lower case
const int length = name.length();
for(int k=0; k!=length; ++k) {
name[k] = std::tolower(name[k]);
}
// check if we can handle this field and if so handle it
map<string, const RegisteredField*>::const_iterator iter
= factory->fields.find(name);
string value(p2+eq+1, size-eq-1);
if (iter != factory->fields.end()) {
indexable->addValue(iter->second, value);
} else if(name=="artist") {
string artistUri = indexable->newAnonymousUri();
indexable->addValue(factory->artistField, artistUri);
indexable->addTriplet(artistUri, typePropertyName, contactClassName);
indexable->addTriplet(artistUri, fullnamePropertyName, value);
} else if(name=="album") {
string albumUri = indexable->newAnonymousUri();
indexable->addValue(factory->albumField, albumUri);
indexable->addTriplet(albumUri, typePropertyName, albumClassName);
indexable->addTriplet(albumUri, titlePropertyName, value);
} else if(name=="composer") {
string composerUri = indexable->newAnonymousUri();
indexable->addValue(factory->composerField, composerUri);
indexable->addTriplet(composerUri, typePropertyName, contactClassName);
indexable->addTriplet(composerUri, fullnamePropertyName, value);
} else if(name=="performer") {
string performerUri = indexable->newAnonymousUri();
indexable->addValue(factory->performerField, performerUri);
indexable->addTriplet(performerUri, typePropertyName, contactClassName);
indexable->addTriplet(performerUri, fullnamePropertyName, value);
}
}
} else {
cerr << "problem with tag size of " << size << endl;
in->reset(0);
return in;
}
p2 += size;
}
// set the "codec" value
indexable->addValue(factory->fields.find("codec")->second, "FLAC");
indexable->addValue(factory->fields.find("type")->second, musicClassName);
}
} while( !(blocktype & 0x80) );
in->reset(0);
return in;
}
bool
FlacThroughAnalyzer::isReadyWithStream() {
return true;
}
<commit_msg>A quick security(buffer oveflow) fix for the FLAC analyzer.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
* 2007 Tobias Pfeiffer <tgpfeiffer@web.de>
* 2009 Evgeny Egorochkin <phreedom.stdin@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.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "flacthroughanalyzer.h"
#include <strigi/strigiconfig.h>
#include "analysisresult.h"
#include "textutils.h"
#include <iostream>
#include <cctype>
#include <cstring>
using namespace Strigi;
using namespace std;
#define NMM_PROPOSAL "http://www.semanticdesktop.org/ontologies/nmm#"
const string
typePropertyName(
"http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
fullnamePropertyName(
"http://www.semanticdesktop.org/ontologies/2007/03/22/nco#fullname"),
titlePropertyName(
"http://www.semanticdesktop.org/ontologies/2007/01/19/nie#title"),
musicClassName(
NMM_PROPOSAL "MusicPiece"),
albumClassName(
NMM_PROPOSAL "MusicAlbum"),
contactClassName(
"http://www.semanticdesktop.org/ontologies/2007/03/22/nco#Contact");
void
FlacThroughAnalyzerFactory::registerFields(FieldRegister& r) {
fields["title"] = r.registerField(titlePropertyName);
albumField = r.registerField(NMM_PROPOSAL "musicAlbum");
artistField = r.registerField("http://www.semanticdesktop.org/ontologies/2007/03/22/nco#creator");
fields["genre"] = r.registerField("http://freedesktop.org/standards/xesam/1.0/core#genre");
fields["codec"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#codec");
composerField = r.registerField(NMM_PROPOSAL "composer");
performerField = r.registerField(NMM_PROPOSAL "performer");
fields["date"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#contentCreated");
fields["description"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#description");
fields["tracknumber"] = r.registerField(NMM_PROPOSAL "trackNumber");
fields["version"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#version");
fields["isrc"] = r.registerField(NMM_PROPOSAL "internationalStandardRecordingCode");
fields["copyright"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#copyright");
fields["license"] = r.registerField("http://www.semanticdesktop.org/ontologies/2007/01/19/nie#license");
// ogg spec fields left unimplemented: ORGANIZATION, LOCATION, CONTACT
fields["type"] = r.typeField;
}
#undef NMM_PROPOSAL
void
FlacThroughAnalyzer::setIndexable(AnalysisResult* i) {
indexable = i;
}
InputStream*
FlacThroughAnalyzer::connectInputStream(InputStream* in) {
if(!in) {
return in;
}
const char* buf;
char blocktype;
int32_t nreq = 8;
int32_t nread = in->read(buf, nreq, nreq);
int32_t blocksize = 4;
// check the header for Flac signature
// the first ogg page starts at position 0, the second at position 58
if (nread < nreq || strncmp("fLaC", buf,4)) {
in->reset(0);
return in;
}
cerr<< "found a flac file!";
do {
blocktype = buf[blocksize];
blocksize = readBigEndianUInt32(buf+blocksize)& 0xFFFFFF;
//if this isn't the last block, read the header of the next block as well
nreq = (blocktype & 0x80 ? blocksize : blocksize+4);
nread = in->read(buf, nreq, nreq);
if (nread!=nreq) {
in->reset(0);
return in;
}
// we are looking for the comments block only
if ((blocktype&0x7F)==4) {
const char *p2 = buf + 4 + readLittleEndianUInt32(buf); //skip vendor string. maybe put it into metadata as soon as there's some place for it
const char *end = buf + blocksize;
uint32_t nfields = readLittleEndianUInt32(p2);
// read all the comments
p2 += 4;
for (uint32_t i = 0; p2 < end && i < nfields; ++i) {
// read the comment length
uint32_t size = readLittleEndianUInt32(p2);
p2 += 4;
if (size <= (uint32_t)(end - p2)) {
uint32_t eq = 1;
while (eq < size && p2[eq] != '=') eq++;
if (size > eq) {
string name(p2, eq);
// convert field name to lower case
const int length = name.length();
for(int k=0; k!=length; ++k) {
name[k] = std::tolower(name[k]);
}
// check if we can handle this field and if so handle it
map<string, const RegisteredField*>::const_iterator iter
= factory->fields.find(name);
string value(p2+eq+1, size-eq-1);
if (iter != factory->fields.end()) {
indexable->addValue(iter->second, value);
} else if(name=="artist") {
string artistUri = indexable->newAnonymousUri();
indexable->addValue(factory->artistField, artistUri);
indexable->addTriplet(artistUri, typePropertyName, contactClassName);
indexable->addTriplet(artistUri, fullnamePropertyName, value);
} else if(name=="album") {
string albumUri = indexable->newAnonymousUri();
indexable->addValue(factory->albumField, albumUri);
indexable->addTriplet(albumUri, typePropertyName, albumClassName);
indexable->addTriplet(albumUri, titlePropertyName, value);
} else if(name=="composer") {
string composerUri = indexable->newAnonymousUri();
indexable->addValue(factory->composerField, composerUri);
indexable->addTriplet(composerUri, typePropertyName, contactClassName);
indexable->addTriplet(composerUri, fullnamePropertyName, value);
} else if(name=="performer") {
string performerUri = indexable->newAnonymousUri();
indexable->addValue(factory->performerField, performerUri);
indexable->addTriplet(performerUri, typePropertyName, contactClassName);
indexable->addTriplet(performerUri, fullnamePropertyName, value);
}
}
} else {
cerr << "problem with tag size of " << size << endl;
in->reset(0);
return in;
}
p2 += size;
}
// set the "codec" value
indexable->addValue(factory->fields.find("codec")->second, "FLAC");
indexable->addValue(factory->fields.find("type")->second, musicClassName);
}
} while( !(blocktype & 0x80) );
in->reset(0);
return in;
}
bool
FlacThroughAnalyzer::isReadyWithStream() {
return true;
}
<|endoftext|>
|
<commit_before>#include <babylon/misc/highdynamicrange/hdr_tools.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/misc/highdynamicrange/panorama_to_cube_map_tools.h>
#include <babylon/misc/string_tools.h>
namespace BABYLON {
float HDRTools::Ldexp(float mantissa, float exponent)
{
if (exponent > 1023.f) {
return mantissa * std::pow(2.f, 1023.f) * std::pow(2.f, exponent - 1023.f);
}
if (exponent < -1074.f) {
return mantissa * std::pow(2.f, -1074.f) * std::pow(2.f, exponent + 1074.f);
}
return mantissa * std::pow(2.f, exponent);
}
void HDRTools::Rgbe2float(Float32Array& float32array, float red, float green, float blue,
float exponent, size_t index)
{
if (exponent > 0.f) { /*nonzero pixel*/
exponent = Ldexp(1.f, exponent - (128.f + 8.f));
float32array[index + 0] = red * exponent;
float32array[index + 1] = green * exponent;
float32array[index + 2] = blue * exponent;
}
else {
float32array[index + 0] = 0.f;
float32array[index + 1] = 0.f;
float32array[index + 2] = 0.f;
}
}
std::string HDRTools::readStringLine(const Uint8Array& uint8array, size_t startIndex)
{
std::ostringstream line;
std::string character;
for (size_t i = startIndex; i < uint8array.size() - startIndex; ++i) {
character = StringTools::fromCharCode(uint8array[i]);
if (character == "\n") {
break;
}
line << character;
}
return line.str();
}
HDRInfo HDRTools::RGBE_ReadHeader(const Uint8Array& uint8array)
{
HDRInfo headerInfo;
auto height = 0ull;
auto width = 0ull;
auto line = readStringLine(uint8array, 0);
if (line.at(0) != '#' || line.at(1) != '?') {
throw std::runtime_error("Bad HDR Format.");
}
auto endOfHeader = false;
auto findFormat = false;
auto lineIndex = 0ull;
do {
lineIndex += (line.size() + 1);
line = readStringLine(uint8array, lineIndex);
if (line == "FORMAT=32-bit_rle_rgbe") {
findFormat = true;
}
else if (line.empty()) {
endOfHeader = true;
}
} while (!endOfHeader);
if (!findFormat) {
throw std::runtime_error("HDR Bad header format, unsupported FORMAT");
}
lineIndex += (line.size() + 1);
line = readStringLine(uint8array, lineIndex);
const std::regex sizeRegexp("^\\-Y (.*) \\+X (.*)$", std::regex::optimize);
std::smatch match;
if (std::regex_search(line, match, sizeRegexp) && (match.size() == 3)) {
// Shader include found
width = std::stoul(match.str(2));
height = std::stoul(match.str(1));
}
else {
throw std::runtime_error("HDR Bad header format, no size");
}
if (width < 8 || width > 0x7fff) {
throw std::runtime_error("HDR Bad header format, unsupported size");
}
lineIndex += (line.size() + 1);
headerInfo.height = height;
headerInfo.width = width;
headerInfo.dataPosition = lineIndex;
return headerInfo;
}
CubeMapInfo HDRTools::GetCubeMapTextureData(const Uint8Array& buffer, size_t size)
{
auto hdrInfo = RGBE_ReadHeader(buffer);
auto data = RGBE_ReadPixels(buffer, hdrInfo);
return PanoramaToCubeMapTools::ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height,
size);
}
Float32Array HDRTools::RGBE_ReadPixels(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
return RGBE_ReadPixels_RLE(uint8array, hdrInfo);
}
Float32Array HDRTools::RGBE_ReadPixels_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
auto num_scanlines = hdrInfo.height;
auto scanline_width = hdrInfo.width;
std::uint8_t a, b, c, d, count;
auto dataIndex = hdrInfo.dataPosition;
auto index = 0ull, endIndex = 0ull, i = 0ull;
ArrayBuffer scanLineArrayBuffer(scanline_width * 4); // four channel R G B E
auto scanLineArray = stl_util::to_array<uint8_t>(scanLineArrayBuffer);
// 3 channels of 4 bytes per pixel in float.
ArrayBuffer resultBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
auto resultArray = stl_util::to_array<float>(resultBuffer);
// read in each successive scanline
while (num_scanlines > 0) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
if (a != 2 || b != 2 || (c & 0x80) || hdrInfo.width < 8 || hdrInfo.width > 32767) {
return HDRTools::RGBE_ReadPixels_NOT_RLE(uint8array, hdrInfo);
}
if (static_cast<size_t>((c << 8) | d) != scanline_width) {
throw std::runtime_error("HDR Bad header format, wrong scan line width");
}
index = 0;
// read each of the four channels for the scanline into the buffer
for (i = 0; i < 4; i++) {
endIndex = (i + 1) * scanline_width;
while (index < endIndex) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
if (a > 128) {
// a run of the same value
count = static_cast<std::uint8_t>(a - 128);
if ((count == 0) || (count > endIndex - index)) {
throw std::runtime_error("HDR Bad Format, bad scanline data (run)");
}
while (count-- > 0) {
scanLineArray[index++] = b;
}
}
else {
// a non-run
count = a;
if ((count == 0) || (count > endIndex - index)) {
throw std::runtime_error("HDR Bad Format, bad scanline data (non-run)");
}
scanLineArray[index++] = b;
if (--count > 0) {
for (size_t j = 0; j < count; ++j) {
scanLineArray[index++] = uint8array[dataIndex++];
}
}
}
}
}
// now convert data from buffer into floats
for (i = 0; i < scanline_width; ++i) {
a = scanLineArray[i];
b = scanLineArray[i + scanline_width];
c = scanLineArray[i + 2 * scanline_width];
d = scanLineArray[i + 3 * scanline_width];
Rgbe2float(resultArray, a, b, c, d,
(hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
}
--num_scanlines;
}
return resultArray;
}
Float32Array HDRTools::RGBE_ReadPixels_NOT_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
// this file is not run length encoded
// read values sequentially
auto num_scanlines = hdrInfo.height;
const auto scanline_width = hdrInfo.width;
uint8_t a = 0, b = 0, c = 0, d = 0;
auto i = 0ull;
auto dataIndex = hdrInfo.dataPosition;
// 3 channels of 4 bytes per pixel in float.
Float32Array resultArray(hdrInfo.width * hdrInfo.height * 4 * 3);
// read in each successive scanline
while (num_scanlines > 0) {
for (i = 0; i < hdrInfo.width; i++) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
Rgbe2float(resultArray, //
a, b, c, d, //
(hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
}
--num_scanlines;
}
return resultArray;
}
} // end of namespace BABYLON
<commit_msg>const correctness<commit_after>#include <babylon/misc/highdynamicrange/hdr_tools.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/misc/highdynamicrange/panorama_to_cube_map_tools.h>
#include <babylon/misc/string_tools.h>
namespace BABYLON {
float HDRTools::Ldexp(float mantissa, float exponent)
{
if (exponent > 1023.f) {
return mantissa * std::pow(2.f, 1023.f) * std::pow(2.f, exponent - 1023.f);
}
if (exponent < -1074.f) {
return mantissa * std::pow(2.f, -1074.f) * std::pow(2.f, exponent + 1074.f);
}
return mantissa * std::pow(2.f, exponent);
}
void HDRTools::Rgbe2float(Float32Array& float32array, float red, float green, float blue,
float exponent, size_t index)
{
if (exponent > 0.f) { /*nonzero pixel*/
exponent = Ldexp(1.f, exponent - (128.f + 8.f));
float32array[index + 0] = red * exponent;
float32array[index + 1] = green * exponent;
float32array[index + 2] = blue * exponent;
}
else {
float32array[index + 0] = 0.f;
float32array[index + 1] = 0.f;
float32array[index + 2] = 0.f;
}
}
std::string HDRTools::readStringLine(const Uint8Array& uint8array, size_t startIndex)
{
std::ostringstream line;
std::string character;
for (size_t i = startIndex; i < uint8array.size() - startIndex; ++i) {
character = StringTools::fromCharCode(uint8array[i]);
if (character == "\n") {
break;
}
line << character;
}
return line.str();
}
HDRInfo HDRTools::RGBE_ReadHeader(const Uint8Array& uint8array)
{
HDRInfo headerInfo;
auto height = 0ull;
auto width = 0ull;
auto line = readStringLine(uint8array, 0);
if (line.at(0) != '#' || line.at(1) != '?') {
throw std::runtime_error("Bad HDR Format.");
}
auto endOfHeader = false;
auto findFormat = false;
auto lineIndex = 0ull;
do {
lineIndex += (line.size() + 1);
line = readStringLine(uint8array, lineIndex);
if (line == "FORMAT=32-bit_rle_rgbe") {
findFormat = true;
}
else if (line.empty()) {
endOfHeader = true;
}
} while (!endOfHeader);
if (!findFormat) {
throw std::runtime_error("HDR Bad header format, unsupported FORMAT");
}
lineIndex += (line.size() + 1);
line = readStringLine(uint8array, lineIndex);
const std::regex sizeRegexp("^\\-Y (.*) \\+X (.*)$", std::regex::optimize);
std::smatch match;
if (std::regex_search(line, match, sizeRegexp) && (match.size() == 3)) {
// Shader include found
width = std::stoul(match.str(2));
height = std::stoul(match.str(1));
}
else {
throw std::runtime_error("HDR Bad header format, no size");
}
if (width < 8 || width > 0x7fff) {
throw std::runtime_error("HDR Bad header format, unsupported size");
}
lineIndex += (line.size() + 1);
headerInfo.height = height;
headerInfo.width = width;
headerInfo.dataPosition = lineIndex;
return headerInfo;
}
CubeMapInfo HDRTools::GetCubeMapTextureData(const Uint8Array& buffer, size_t size)
{
const auto hdrInfo = RGBE_ReadHeader(buffer);
const auto data = RGBE_ReadPixels(buffer, hdrInfo);
return PanoramaToCubeMapTools::ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height,
size);
}
Float32Array HDRTools::RGBE_ReadPixels(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
return RGBE_ReadPixels_RLE(uint8array, hdrInfo);
}
Float32Array HDRTools::RGBE_ReadPixels_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
auto num_scanlines = hdrInfo.height;
const auto scanline_width = hdrInfo.width;
std::uint8_t a, b, c, d, count;
auto dataIndex = hdrInfo.dataPosition;
auto index = 0ull, endIndex = 0ull, i = 0ull;
ArrayBuffer scanLineArrayBuffer(scanline_width * 4); // four channel R G B E
auto scanLineArray = stl_util::to_array<uint8_t>(scanLineArrayBuffer);
// 3 channels of 4 bytes per pixel in float.
ArrayBuffer resultBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
auto resultArray = stl_util::to_array<float>(resultBuffer);
// read in each successive scanline
while (num_scanlines > 0) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
if (a != 2 || b != 2 || (c & 0x80) || hdrInfo.width < 8 || hdrInfo.width > 32767) {
return HDRTools::RGBE_ReadPixels_NOT_RLE(uint8array, hdrInfo);
}
if (static_cast<size_t>((c << 8) | d) != scanline_width) {
throw std::runtime_error("HDR Bad header format, wrong scan line width");
}
index = 0;
// read each of the four channels for the scanline into the buffer
for (i = 0; i < 4; i++) {
endIndex = (i + 1) * scanline_width;
while (index < endIndex) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
if (a > 128) {
// a run of the same value
count = static_cast<std::uint8_t>(a - 128);
if ((count == 0) || (count > endIndex - index)) {
throw std::runtime_error("HDR Bad Format, bad scanline data (run)");
}
while (count-- > 0) {
scanLineArray[index++] = b;
}
}
else {
// a non-run
count = a;
if ((count == 0) || (count > endIndex - index)) {
throw std::runtime_error("HDR Bad Format, bad scanline data (non-run)");
}
scanLineArray[index++] = b;
if (--count > 0) {
for (size_t j = 0; j < count; ++j) {
scanLineArray[index++] = uint8array[dataIndex++];
}
}
}
}
}
// now convert data from buffer into floats
for (i = 0; i < scanline_width; ++i) {
a = scanLineArray[i];
b = scanLineArray[i + scanline_width];
c = scanLineArray[i + 2 * scanline_width];
d = scanLineArray[i + 3 * scanline_width];
Rgbe2float(resultArray, a, b, c, d,
(hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
}
--num_scanlines;
}
return resultArray;
}
Float32Array HDRTools::RGBE_ReadPixels_NOT_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)
{
// this file is not run length encoded
// read values sequentially
auto num_scanlines = hdrInfo.height;
const auto scanline_width = hdrInfo.width;
uint8_t a = 0, b = 0, c = 0, d = 0;
auto i = 0ull;
auto dataIndex = hdrInfo.dataPosition;
// 3 channels of 4 bytes per pixel in float.
Float32Array resultArray(hdrInfo.width * hdrInfo.height * 4 * 3);
// read in each successive scanline
while (num_scanlines > 0) {
for (i = 0; i < hdrInfo.width; i++) {
a = uint8array[dataIndex++];
b = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
Rgbe2float(resultArray, //
a, b, c, d, //
(hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
}
--num_scanlines;
}
return resultArray;
}
} // end of namespace BABYLON
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.