text
stringlengths
54
60.6k
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file CommonEth.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "CommonEth.h" #include <random> #include <libdevcrypto/SHA3.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace eth { const unsigned c_protocolVersion = 53; const unsigned c_databaseVersion = 5; template <size_t n> constexpr u256 exp10() { return exp10<n - 1>() * u256(10); } template <> constexpr u256 exp10<0>() { return u256(1); } vector<pair<u256, string>> const& units() { static const vector<pair<u256, string>> s_units = { {exp10<54>(), "Uether"}, {exp10<51>(), "Vether"}, {exp10<48>(), "Dether"}, {exp10<45>(), "Nether"}, {exp10<42>(), "Yether"}, {exp10<39>(), "Zether"}, {exp10<36>(), "Eether"}, {exp10<33>(), "Pether"}, {exp10<30>(), "Tether"}, {exp10<27>(), "Gether"}, {exp10<24>(), "Mether"}, {exp10<21>(), "grand"}, {exp10<18>(), "ether"}, {exp10<15>(), "finney"}, {exp10<12>(), "szabo"}, {exp10<9>(), "Gwei"}, {exp10<6>(), "Mwei"}, {exp10<3>(), "Kwei"}, {exp10<0>(), "wei"} }; return s_units; } std::string formatBalance(bigint const& _b) { ostringstream ret; u256 b; if (_b < 0) { ret << "-"; b = (u256)-_b; } else b = (u256)_b; if (b > units()[0].first * 10000) { ret << (b / units()[0].first) << " " << units()[0].second; return ret.str(); } ret << setprecision(5); for (auto const& i: units()) if (i.first != 1 && b >= i.first * 100) { ret << (double(b / (i.first / 1000)) / 1000.0) << " " << i.second; return ret.str(); } ret << b << " wei"; return ret.str(); } }} <commit_msg>MSVC constexpr fix.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file CommonEth.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "CommonEth.h" #include <random> #include <libdevcrypto/SHA3.h> #include "Exceptions.h" using namespace std; using namespace dev; using namespace dev::eth; namespace dev { namespace eth { const unsigned c_protocolVersion = 53; const unsigned c_databaseVersion = 5; template <size_t n> u256 exp10() { return exp10<n - 1>() * u256(10); } template <> u256 exp10<0>() { return u256(1); } vector<pair<u256, string>> const& units() { static const vector<pair<u256, string>> s_units = { {exp10<54>(), "Uether"}, {exp10<51>(), "Vether"}, {exp10<48>(), "Dether"}, {exp10<45>(), "Nether"}, {exp10<42>(), "Yether"}, {exp10<39>(), "Zether"}, {exp10<36>(), "Eether"}, {exp10<33>(), "Pether"}, {exp10<30>(), "Tether"}, {exp10<27>(), "Gether"}, {exp10<24>(), "Mether"}, {exp10<21>(), "grand"}, {exp10<18>(), "ether"}, {exp10<15>(), "finney"}, {exp10<12>(), "szabo"}, {exp10<9>(), "Gwei"}, {exp10<6>(), "Mwei"}, {exp10<3>(), "Kwei"}, {exp10<0>(), "wei"} }; return s_units; } std::string formatBalance(bigint const& _b) { ostringstream ret; u256 b; if (_b < 0) { ret << "-"; b = (u256)-_b; } else b = (u256)_b; if (b > units()[0].first * 10000) { ret << (b / units()[0].first) << " " << units()[0].second; return ret.str(); } ret << setprecision(5); for (auto const& i: units()) if (i.first != 1 && b >= i.first * 100) { ret << (double(b / (i.first / 1000)) / 1000.0) << " " << i.second; return ret.str(); } ret << b << " wei"; return ret.str(); } }} <|endoftext|>
<commit_before>#include <stdio.h> #include <ctype.h> #include <metaSurface.h> int testMetaSurface(int argc, char *argv[]) { std::cout << "Creating test file ..."; MetaSurface* surface = new MetaSurface(3); surface->ID(0); SurfacePnt* pnt; unsigned int i; for(i=0;i<10;i++) { pnt = new SurfacePnt(3); pnt->m_X[0]=(float)0.2; pnt->m_X[1]=i; pnt->m_X[2]=i; pnt->m_V[0]=(float)0.8; pnt->m_V[1]=i; pnt->m_V[2]=i; surface->GetPoints().push_back(pnt); } std::cout << "Writing ASCII test file ..."; surface->Write("mySurface.meta"); std::cout << "done" << std::endl; std::cout << "Reading ASCII test file ..."; surface->Clear(); surface->Read("mySurface.meta"); surface->PrintInfo(); MetaSurface::PointListType list = surface->GetPoints(); MetaSurface::PointListType::const_iterator it = list.begin(); unsigned int d=0; while(it != list.end()) { for(d = 0; d < 3; d++) { std::cout << (*it)->m_X[d] << " "; } std::cout << std::endl; for(d = 0; d < 3; d++) { std::cout << (*it)->m_V[d] << " "; } std::cout << std::endl; it++; } std::cout << "Writing Binary test file ..."; surface->BinaryData(true); surface->ElementType(MET_FLOAT); surface->Write("mySurface.meta"); std::cout << "done" << std::endl; std::cout << "Reading Binary test file ..."; surface->Clear(); surface->Read("mySurface.meta"); surface->PrintInfo(); MetaSurface::PointListType list2 = surface->GetPoints(); it = list2.begin(); while(it != list2.end()) { for(d = 0; d < 3; d++) { std::cout << (*it)->m_X[d] << " "; } std::cout << std::endl; for(d = 0; d < 3; d++) { std::cout << (*it)->m_V[d] << " "; } std::cout << std::endl; it++; } std::cout << "done" << std::endl; return 1; } <commit_msg>ERR: pass should return 0, not 1.<commit_after>#include <stdio.h> #include <ctype.h> #include <metaSurface.h> int testMetaSurface(int argc, char *argv[]) { std::cout << "Creating test file ..."; MetaSurface* surface = new MetaSurface(3); surface->ID(0); SurfacePnt* pnt; unsigned int i; for(i=0;i<10;i++) { pnt = new SurfacePnt(3); pnt->m_X[0]=(float)0.2; pnt->m_X[1]=i; pnt->m_X[2]=i; pnt->m_V[0]=(float)0.8; pnt->m_V[1]=i; pnt->m_V[2]=i; surface->GetPoints().push_back(pnt); } std::cout << "Writing ASCII test file ..."; surface->Write("mySurface.meta"); std::cout << "done" << std::endl; std::cout << "Reading ASCII test file ..."; surface->Clear(); surface->Read("mySurface.meta"); surface->PrintInfo(); MetaSurface::PointListType list = surface->GetPoints(); MetaSurface::PointListType::const_iterator it = list.begin(); unsigned int d=0; while(it != list.end()) { for(d = 0; d < 3; d++) { std::cout << (*it)->m_X[d] << " "; } std::cout << std::endl; for(d = 0; d < 3; d++) { std::cout << (*it)->m_V[d] << " "; } std::cout << std::endl; it++; } std::cout << "Writing Binary test file ..."; surface->BinaryData(true); surface->ElementType(MET_FLOAT); surface->Write("mySurface.meta"); std::cout << "done" << std::endl; std::cout << "Reading Binary test file ..."; surface->Clear(); surface->Read("mySurface.meta"); surface->PrintInfo(); MetaSurface::PointListType list2 = surface->GetPoints(); it = list2.begin(); while(it != list2.end()) { for(d = 0; d < 3; d++) { std::cout << (*it)->m_X[d] << " "; } std::cout << std::endl; for(d = 0; d < 3; d++) { std::cout << (*it)->m_V[d] << " "; } std::cout << std::endl; it++; } std::cout << "done" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2012 Coherent Theory LLC * * 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, 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 Library 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 "participantratingsjobmodel.h" #include "participantratingsjob.h" #include "session.h" #include "networkjob.h" #include <QtCore/QVariant> #include <QtCore/QDebug> #include <QtCore/QMetaEnum> #include <QDebug> namespace Bodega { class ParticipantRatingsJobModel::Private { public: Private(ParticipantRatingsJobModel *parent); ParticipantRatingsJobModel *q; Session *session; void fetchRatings(); void participantRatingsJobFinished(Bodega::NetworkJob *job); QList<ParticipantRatings> participantRatings; }; ParticipantRatingsJobModel::Private::Private(ParticipantRatingsJobModel *parent) : q(parent), session(0) { ParticipantRatingsJob *job = session->participantRatings(); q->beginResetModel(); participantRatings.clear(); q->endResetModel(); connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), q, SLOT(participantRatingsJobFinished(Bodega::NetworkJob *))); } void ParticipantRatingsJobModel::Private::participantRatingsJobFinished(Bodega::NetworkJob *job) { ParticipantRatingsJob *participantRatingsJob = qobject_cast<ParticipantRatingsJob*>(job); if (!participantRatingsJob) { return; } participantRatingsJob->deleteLater(); if (participantRatingsJob->failed()) { return; } const int begin = 0; const int end = qMax(begin, participantRatings.count() + begin -1); q->beginInsertRows(QModelIndex(), begin, end); participantRatings= participantRatingsJob->ratings(); q->endInsertRows(); } ParticipantRatingsJobModel::ParticipantRatingsJobModel(QObject *parent) : QAbstractItemModel(parent), d(new Private(this)) { // set the role names based on the values of the DisplayRoles enum for // the sake of QML QHash<int, QByteArray> roles; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } setRoleNames(roles); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(modelReset()), this, SIGNAL(countChanged())); } ParticipantRatingsJobModel::~ParticipantRatingsJobModel() { delete d; } int ParticipantRatingsJobModel::columnCount(const QModelIndex &parent) const { return 1; } QVariant ParticipantRatingsJobModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->participantRatings.count()) { return QVariant(); } switch (role) { case AttributeId: { return d->participantRatings.at(index.row()).attributeId; } case AssetId: { return d->participantRatings.at(index.row()).assetId; } case Rating: { return d->participantRatings.at(index.row()).rating; } default: { return QVariant(); } } } Qt::ItemFlags ParticipantRatingsJobModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } else { return Qt::NoItemFlags; } } bool ParticipantRatingsJobModel::hasChildren(const QModelIndex &parent) const { Q_UNUSED(parent) return false; } QVariant ParticipantRatingsJobModel::headerData(int section, Qt::Orientation orientation, int role) const { return QVariant(); } QModelIndex ParticipantRatingsJobModel::index(int row, int column, const QModelIndex &parent) const { if (column > 0) { return QModelIndex(); } if (row < 0 || row >= d->participantRatings.count()) { return QModelIndex(); } return createIndex(row, column); } QMap<int, QVariant> ParticipantRatingsJobModel::itemData(const QModelIndex &index) const { return QMap<int, QVariant>(); } QModelIndex ParticipantRatingsJobModel::parent(const QModelIndex &index) const { return QModelIndex(); } int ParticipantRatingsJobModel::rowCount(const QModelIndex &parent) const { return d->participantRatings.size(); } void ParticipantRatingsJobModel::setSession(Session *session) { if (session == d->session) { return; } if (d->session) { //not connected directly, so disconnect everything d->session->disconnect(this); } d->session = session; if (!d->session) { return; } } Session *ParticipantRatingsJobModel::session() const { return d->session; } } #include "participantratingsjobmodel.moc" <commit_msg>move the code in order the request to be made only when the session if valid<commit_after>/* * Copyright 2012 Coherent Theory LLC * * 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, 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 Library 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 "participantratingsjobmodel.h" #include "participantratingsjob.h" #include "session.h" #include "networkjob.h" #include <QtCore/QVariant> #include <QtCore/QDebug> #include <QtCore/QMetaEnum> #include <QDebug> namespace Bodega { class ParticipantRatingsJobModel::Private { public: Private(ParticipantRatingsJobModel *parent); ParticipantRatingsJobModel *q; Session *session; void fetchParticipantRatings(); void participantRatingsJobFinished(Bodega::NetworkJob *job); QList<ParticipantRatings> participantRatings; }; ParticipantRatingsJobModel::Private::Private(ParticipantRatingsJobModel *parent) : q(parent), session(0) { } void ParticipantRatingsJobModel::Private::fetchParticipantRatings() { ParticipantRatingsJob *job = session->participantRatings(); q->beginResetModel(); participantRatings.clear(); q->endResetModel(); connect(job, SIGNAL(jobFinished(Bodega::NetworkJob *)), q, SLOT(participantRatingsJobFinished(Bodega::NetworkJob *))); } void ParticipantRatingsJobModel::Private::participantRatingsJobFinished(Bodega::NetworkJob *job) { ParticipantRatingsJob *participantRatingsJob = qobject_cast<ParticipantRatingsJob*>(job); if (!participantRatingsJob) { return; } participantRatingsJob->deleteLater(); if (participantRatingsJob->failed()) { return; } const int begin = 0; const int end = qMax(begin, participantRatings.count() + begin -1); q->beginInsertRows(QModelIndex(), begin, end); participantRatings= participantRatingsJob->ratings(); q->endInsertRows(); } ParticipantRatingsJobModel::ParticipantRatingsJobModel(QObject *parent) : QAbstractItemModel(parent), d(new Private(this)) { // set the role names based on the values of the DisplayRoles enum for // the sake of QML QHash<int, QByteArray> roles; QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles")); for (int i = 0; i < e.keyCount(); ++i) { roles.insert(e.value(i), e.key(i)); } setRoleNames(roles); connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(countChanged())); connect(this, SIGNAL(modelReset()), this, SIGNAL(countChanged())); } ParticipantRatingsJobModel::~ParticipantRatingsJobModel() { delete d; } int ParticipantRatingsJobModel::columnCount(const QModelIndex &parent) const { return 1; } QVariant ParticipantRatingsJobModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() >= d->participantRatings.count()) { return QVariant(); } switch (role) { case AttributeId: { return d->participantRatings.at(index.row()).attributeId; } case AssetId: { return d->participantRatings.at(index.row()).assetId; } case Rating: { return d->participantRatings.at(index.row()).rating; } default: { return QVariant(); } } } Qt::ItemFlags ParticipantRatingsJobModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } else { return Qt::NoItemFlags; } } bool ParticipantRatingsJobModel::hasChildren(const QModelIndex &parent) const { Q_UNUSED(parent) return false; } QVariant ParticipantRatingsJobModel::headerData(int section, Qt::Orientation orientation, int role) const { return QVariant(); } QModelIndex ParticipantRatingsJobModel::index(int row, int column, const QModelIndex &parent) const { if (column > 0) { return QModelIndex(); } if (row < 0 || row >= d->participantRatings.count()) { return QModelIndex(); } return createIndex(row, column); } QMap<int, QVariant> ParticipantRatingsJobModel::itemData(const QModelIndex &index) const { return QMap<int, QVariant>(); } QModelIndex ParticipantRatingsJobModel::parent(const QModelIndex &index) const { return QModelIndex(); } int ParticipantRatingsJobModel::rowCount(const QModelIndex &parent) const { return d->participantRatings.size(); } void ParticipantRatingsJobModel::setSession(Session *session) { if (session == d->session) { return; } if (d->session) { //not connected directly, so disconnect everything d->session->disconnect(this); } d->session = session; if (!d->session) { return; } d->fetchParticipantRatings(); } Session *ParticipantRatingsJobModel::session() const { return d->session; } } #include "participantratingsjobmodel.moc" <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file RLPXHandshake.cpp * @author Alex Leverington <nessence@gmail.com> * @date 2015 */ #include "Host.h" #include "Session.h" #include "Peer.h" #include "RLPxHandshake.h" using namespace std; using namespace dev; using namespace dev::p2p; using namespace CryptoPP; void RLPXHandshake::writeAuth() { clog(NetP2PConnect) << "p2p.connect.egress sending auth to " << m_socket->remoteEndpoint(); m_auth.resize(Signature::size + h256::size + Public::size + h256::size + 1); bytesRef sig(&m_auth[0], Signature::size); bytesRef hepubk(&m_auth[Signature::size], h256::size); bytesRef pubk(&m_auth[Signature::size + h256::size], Public::size); bytesRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size); // E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0) Secret staticShared; crypto::ecdh::agree(m_host->m_alias.sec(), m_remote, staticShared); sign(m_ecdhe.seckey(), staticShared ^ m_nonce).ref().copyTo(sig); sha3(m_ecdhe.pubkey().ref(), hepubk); m_host->m_alias.pub().ref().copyTo(pubk); m_nonce.ref().copyTo(nonce); m_auth[m_auth.size() - 1] = 0x0; encryptECIES(m_remote, &m_auth, m_authCipher); auto self(shared_from_this()); ba::async_write(m_socket->ref(), ba::buffer(m_authCipher), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } void RLPXHandshake::writeAck() { clog(NetP2PConnect) << "p2p.connect.ingress sending ack to " << m_socket->remoteEndpoint(); m_ack.resize(Public::size + h256::size + 1); bytesRef epubk(&m_ack[0], Public::size); bytesRef nonce(&m_ack[Public::size], h256::size); m_ecdhe.pubkey().ref().copyTo(epubk); m_nonce.ref().copyTo(nonce); m_ack[m_ack.size() - 1] = 0x0; encryptECIES(m_remote, &m_ack, m_ackCipher); auto self(shared_from_this()); ba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } void RLPXHandshake::readAuth() { clog(NetP2PConnect) << "p2p.connect.ingress recving auth from " << m_socket->remoteEndpoint(); m_authCipher.resize(307); auto self(shared_from_this()); ba::async_read(m_socket->ref(), ba::buffer(m_authCipher, 307), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_authCipher), m_auth)) { bytesConstRef sig(&m_auth[0], Signature::size); bytesConstRef hepubk(&m_auth[Signature::size], h256::size); bytesConstRef pubk(&m_auth[Signature::size + h256::size], Public::size); bytesConstRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size); pubk.copyTo(m_remote.ref()); nonce.copyTo(m_remoteNonce.ref()); Secret sharedSecret; crypto::ecdh::agree(m_host->m_alias.sec(), m_remote, sharedSecret); m_remoteEphemeral = recover(*(Signature*)sig.data(), sharedSecret ^ m_remoteNonce); if (sha3(m_remoteEphemeral) != *(h256*)hepubk.data()) clog(NetP2PConnect) << "p2p.connect.ingress auth failed (invalid: hash mismatch) for" << m_socket->remoteEndpoint(); transition(); } else { clog(NetP2PConnect) << "p2p.connect.ingress recving auth decrypt failed for" << m_socket->remoteEndpoint(); m_nextState = Error; transition(); } }); } void RLPXHandshake::readAck() { clog(NetP2PConnect) << "p2p.connect.egress recving ack from " << m_socket->remoteEndpoint(); m_ackCipher.resize(210); auto self(shared_from_this()); ba::async_read(m_socket->ref(), ba::buffer(m_ackCipher, 210), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_ackCipher), m_ack)) { bytesConstRef(&m_ack).cropped(0, Public::size).copyTo(m_remoteEphemeral.ref()); bytesConstRef(&m_ack).cropped(Public::size, h256::size).copyTo(m_remoteNonce.ref()); transition(); } else { clog(NetP2PConnect) << "p2p.connect.egress recving ack decrypt failed for " << m_socket->remoteEndpoint(); m_nextState = Error; transition(); } }); } void RLPXHandshake::error() { auto connected = m_socket->isConnected(); if (connected && !m_socket->remoteEndpoint().address().is_unspecified()) clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Failed)"; else clog(NetP2PConnect) << "Handshake Failed (Connection reset by peer)"; m_socket->close(); if (m_io != nullptr) delete m_io; } void RLPXHandshake::transition(boost::system::error_code _ech) { // reset timeout m_idleTimer.cancel(); if (_ech || m_nextState == Error || m_cancel) { clog(NetP2PConnect) << "Handshake Failed (I/O Error:" << _ech.message() << ")"; return error(); } auto self(shared_from_this()); if (m_nextState == New) { m_nextState = AckAuth; if (m_originated) writeAuth(); else readAuth(); } else if (m_nextState == AckAuth) { m_nextState = WriteHello; if (m_originated) readAck(); else writeAck(); } else if (m_nextState == WriteHello) { m_nextState = ReadHello; clog(NetP2PConnect) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "sending capabilities handshake"; /// This pointer will be freed if there is an error otherwise /// it will be passed to Host which will take ownership. m_io = new RLPXFrameCoder(*this); // old packet format // 5 arguments, HelloPacket RLPStream s; s.append((unsigned)HelloPacket).appendList(5) << dev::p2p::c_protocolVersion << m_host->m_clientVersion << m_host->caps() << m_host->listenPort() << m_host->id(); bytes packet; s.swapOut(packet); m_io->writeSingleFramePacket(&packet, m_handshakeOutBuffer); ba::async_write(m_socket->ref(), ba::buffer(m_handshakeOutBuffer), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } else if (m_nextState == ReadHello) { // Authenticate and decrypt initial hello frame with initial RLPXFrameCoder // and request m_host to start session. m_nextState = StartSession; // read frame header unsigned const handshakeSize = 32; m_handshakeInBuffer.resize(handshakeSize); ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, handshakeSize), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else { /// authenticate and decrypt header if (!m_io->authAndDecryptHeader(bytesRef(m_handshakeInBuffer.data(), m_handshakeInBuffer.size()))) { m_nextState = Error; transition(); return; } clog(NetP2PNote) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "recvd hello header"; /// check frame size bytes& header = m_handshakeInBuffer; uint32_t frameSize = (uint32_t)(header[2]) | (uint32_t)(header[1])<<8 | (uint32_t)(header[0])<<16; if (frameSize > 1024) { // all future frames: 16777216 clog(NetP2PWarn) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame is too large" << frameSize; m_nextState = Error; transition(); return; } /// rlp of header has protocol-type, sequence-id[, total-packet-size] bytes headerRLP(header.size() - 3 - h128::size); // this is always 32 - 3 - 16 = 13. wtf? bytesConstRef(&header).cropped(3).copyTo(&headerRLP); /// read padded frame and mac m_handshakeInBuffer.resize(frameSize + ((16 - (frameSize % 16)) % 16) + h128::size); ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, m_handshakeInBuffer.size()), [this, self, headerRLP](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else { bytesRef frame(&m_handshakeInBuffer); if (!m_io->authAndDecryptFrame(frame)) { clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: decrypt failed"; m_nextState = Error; transition(); return; } PacketType packetType = frame[0] == 0x80 ? HelloPacket : (PacketType)frame[0]; if (packetType != HelloPacket) { clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: invalid packet type"; m_nextState = Error; transition(); return; } clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: success. starting session."; try { RLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall); m_host->startPeerSession(m_remote, rlp, m_io, m_socket); return; } catch (std::exception const& _e) { clog(NetWarn) << "Handshake causing an exception:" << _e.what(); m_nextState = Error; transition(); } } }); } }); } if (m_nextState != Error) { m_idleTimer.expires_from_now(c_timeout); m_idleTimer.async_wait([this, self](boost::system::error_code const& _ec) { if (!_ec) { if (!m_socket->remoteEndpoint().address().is_unspecified()) clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Timeout)"; cancel(); } }); } } <commit_msg>Don't reschedule handshake timeout during last phase of handshake.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file RLPXHandshake.cpp * @author Alex Leverington <nessence@gmail.com> * @date 2015 */ #include "Host.h" #include "Session.h" #include "Peer.h" #include "RLPxHandshake.h" using namespace std; using namespace dev; using namespace dev::p2p; using namespace CryptoPP; void RLPXHandshake::writeAuth() { clog(NetP2PConnect) << "p2p.connect.egress sending auth to " << m_socket->remoteEndpoint(); m_auth.resize(Signature::size + h256::size + Public::size + h256::size + 1); bytesRef sig(&m_auth[0], Signature::size); bytesRef hepubk(&m_auth[Signature::size], h256::size); bytesRef pubk(&m_auth[Signature::size + h256::size], Public::size); bytesRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size); // E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0) Secret staticShared; crypto::ecdh::agree(m_host->m_alias.sec(), m_remote, staticShared); sign(m_ecdhe.seckey(), staticShared ^ m_nonce).ref().copyTo(sig); sha3(m_ecdhe.pubkey().ref(), hepubk); m_host->m_alias.pub().ref().copyTo(pubk); m_nonce.ref().copyTo(nonce); m_auth[m_auth.size() - 1] = 0x0; encryptECIES(m_remote, &m_auth, m_authCipher); auto self(shared_from_this()); ba::async_write(m_socket->ref(), ba::buffer(m_authCipher), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } void RLPXHandshake::writeAck() { clog(NetP2PConnect) << "p2p.connect.ingress sending ack to " << m_socket->remoteEndpoint(); m_ack.resize(Public::size + h256::size + 1); bytesRef epubk(&m_ack[0], Public::size); bytesRef nonce(&m_ack[Public::size], h256::size); m_ecdhe.pubkey().ref().copyTo(epubk); m_nonce.ref().copyTo(nonce); m_ack[m_ack.size() - 1] = 0x0; encryptECIES(m_remote, &m_ack, m_ackCipher); auto self(shared_from_this()); ba::async_write(m_socket->ref(), ba::buffer(m_ackCipher), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } void RLPXHandshake::readAuth() { clog(NetP2PConnect) << "p2p.connect.ingress recving auth from " << m_socket->remoteEndpoint(); m_authCipher.resize(307); auto self(shared_from_this()); ba::async_read(m_socket->ref(), ba::buffer(m_authCipher, 307), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_authCipher), m_auth)) { bytesConstRef sig(&m_auth[0], Signature::size); bytesConstRef hepubk(&m_auth[Signature::size], h256::size); bytesConstRef pubk(&m_auth[Signature::size + h256::size], Public::size); bytesConstRef nonce(&m_auth[Signature::size + h256::size + Public::size], h256::size); pubk.copyTo(m_remote.ref()); nonce.copyTo(m_remoteNonce.ref()); Secret sharedSecret; crypto::ecdh::agree(m_host->m_alias.sec(), m_remote, sharedSecret); m_remoteEphemeral = recover(*(Signature*)sig.data(), sharedSecret ^ m_remoteNonce); if (sha3(m_remoteEphemeral) != *(h256*)hepubk.data()) clog(NetP2PConnect) << "p2p.connect.ingress auth failed (invalid: hash mismatch) for" << m_socket->remoteEndpoint(); transition(); } else { clog(NetP2PConnect) << "p2p.connect.ingress recving auth decrypt failed for" << m_socket->remoteEndpoint(); m_nextState = Error; transition(); } }); } void RLPXHandshake::readAck() { clog(NetP2PConnect) << "p2p.connect.egress recving ack from " << m_socket->remoteEndpoint(); m_ackCipher.resize(210); auto self(shared_from_this()); ba::async_read(m_socket->ref(), ba::buffer(m_ackCipher, 210), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else if (decryptECIES(m_host->m_alias.sec(), bytesConstRef(&m_ackCipher), m_ack)) { bytesConstRef(&m_ack).cropped(0, Public::size).copyTo(m_remoteEphemeral.ref()); bytesConstRef(&m_ack).cropped(Public::size, h256::size).copyTo(m_remoteNonce.ref()); transition(); } else { clog(NetP2PConnect) << "p2p.connect.egress recving ack decrypt failed for " << m_socket->remoteEndpoint(); m_nextState = Error; transition(); } }); } void RLPXHandshake::error() { m_idleTimer.cancel(); auto connected = m_socket->isConnected(); if (connected && !m_socket->remoteEndpoint().address().is_unspecified()) clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Failed)"; else clog(NetP2PConnect) << "Handshake Failed (Connection reset by peer)"; m_socket->close(); if (m_io != nullptr) delete m_io; } void RLPXHandshake::transition(boost::system::error_code _ech) { // reset timeout m_idleTimer.cancel(); if (_ech || m_nextState == Error || m_cancel) { clog(NetP2PConnect) << "Handshake Failed (I/O Error:" << _ech.message() << ")"; return error(); } auto self(shared_from_this()); assert(m_nextState != StartSession); m_idleTimer.expires_from_now(c_timeout); m_idleTimer.async_wait([this, self](boost::system::error_code const& _ec) { if (!_ec) { if (!m_socket->remoteEndpoint().address().is_unspecified()) clog(NetP2PConnect) << "Disconnecting " << m_socket->remoteEndpoint() << " (Handshake Timeout)"; cancel(); } }); if (m_nextState == New) { m_nextState = AckAuth; if (m_originated) writeAuth(); else readAuth(); } else if (m_nextState == AckAuth) { m_nextState = WriteHello; if (m_originated) readAck(); else writeAck(); } else if (m_nextState == WriteHello) { m_nextState = ReadHello; clog(NetP2PConnect) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "sending capabilities handshake"; /// This pointer will be freed if there is an error otherwise /// it will be passed to Host which will take ownership. m_io = new RLPXFrameCoder(*this); // old packet format // 5 arguments, HelloPacket RLPStream s; s.append((unsigned)HelloPacket).appendList(5) << dev::p2p::c_protocolVersion << m_host->m_clientVersion << m_host->caps() << m_host->listenPort() << m_host->id(); bytes packet; s.swapOut(packet); m_io->writeSingleFramePacket(&packet, m_handshakeOutBuffer); ba::async_write(m_socket->ref(), ba::buffer(m_handshakeOutBuffer), [this, self](boost::system::error_code ec, std::size_t) { transition(ec); }); } else if (m_nextState == ReadHello) { // Authenticate and decrypt initial hello frame with initial RLPXFrameCoder // and request m_host to start session. m_nextState = StartSession; // read frame header unsigned const handshakeSize = 32; m_handshakeInBuffer.resize(handshakeSize); ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, handshakeSize), [this, self](boost::system::error_code ec, std::size_t) { if (ec) transition(ec); else { /// authenticate and decrypt header if (!m_io->authAndDecryptHeader(bytesRef(m_handshakeInBuffer.data(), m_handshakeInBuffer.size()))) { m_nextState = Error; transition(); return; } clog(NetP2PNote) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "recvd hello header"; /// check frame size bytes& header = m_handshakeInBuffer; uint32_t frameSize = (uint32_t)(header[2]) | (uint32_t)(header[1])<<8 | (uint32_t)(header[0])<<16; if (frameSize > 1024) { // all future frames: 16777216 clog(NetP2PWarn) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame is too large" << frameSize; m_nextState = Error; transition(); return; } /// rlp of header has protocol-type, sequence-id[, total-packet-size] bytes headerRLP(header.size() - 3 - h128::size); // this is always 32 - 3 - 16 = 13. wtf? bytesConstRef(&header).cropped(3).copyTo(&headerRLP); /// read padded frame and mac m_handshakeInBuffer.resize(frameSize + ((16 - (frameSize % 16)) % 16) + h128::size); ba::async_read(m_socket->ref(), boost::asio::buffer(m_handshakeInBuffer, m_handshakeInBuffer.size()), [this, self, headerRLP](boost::system::error_code ec, std::size_t) { m_idleTimer.cancel(); if (ec) transition(ec); else { bytesRef frame(&m_handshakeInBuffer); if (!m_io->authAndDecryptFrame(frame)) { clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: decrypt failed"; m_nextState = Error; transition(); return; } PacketType packetType = frame[0] == 0x80 ? HelloPacket : (PacketType)frame[0]; if (packetType != HelloPacket) { clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: invalid packet type"; m_nextState = Error; transition(); return; } clog(NetTriviaSummary) << (m_originated ? "p2p.connect.egress" : "p2p.connect.ingress") << "hello frame: success. starting session."; try { RLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall); m_host->startPeerSession(m_remote, rlp, m_io, m_socket); } catch (std::exception const& _e) { clog(NetWarn) << "Handshake causing an exception:" << _e.what(); m_nextState = Error; transition(); } } }); } }); } } <|endoftext|>
<commit_before>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/binarystring> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Test binarystring functionality. // // Usage: test062 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { const string TestStr = "Nasty\n\030Test\n\t String with \200\277 weird bytes " "\r\0 and Trailer\\\\\0"; connection C(argv[1]); work T(C, "test62"); T.exec("CREATE TEMP TABLE pqxxbin (binfield bytea)"); const string Esc = escape_binary(TestStr); T.exec("INSERT INTO pqxxbin VALUES ('" + Esc + "')"); result R = T.exec("SELECT * from pqxxbin"); T.exec("DELETE FROM pqxxbin"); binarystring B( R.at(0).at(0) ); if (B.empty()) throw logic_error("Binary string became empty in conversion"); if (B.size() != TestStr.size()) throw logic_error("Binary string got changed from " + to_string(TestStr.size()) + " to " + to_string(B.size()) + " bytes"); if (strncmp(TestStr.c_str(), B.c_ptr(), B.size()) != 0) throw logic_error("Binary string was changed before first zero byte: " "'" + string(B.c_ptr(), B.size()) + "'"); binarystring::const_iterator c; binarystring::size_type i; for (i=0, c=B.begin(); i<B.size(); ++i, ++c) { if (c == B.end()) throw logic_error("Premature end to binary string at " + to_string(i)); if (char(B.data()[i]) != TestStr.at(i)) throw logic_error("Binary string byte " + to_string(i) + " " "got changed from '" + to_string(char(TestStr[i])) + "' " "to '" + to_string(char(B.data()[i])) + "'"); if (B.at(i) != B.data()[i]) throw logic_error("Inconsistent byte at offset " + to_string(i) + ": " "operator[] says '" + to_string(char(B.at(i))) + "', " "data() says '" + to_string(char(B.data()[i])) + "'"); } if (B.at(0) != B.front()) throw logic_error("Something wrong with binarystring::front()"); if (c != B.end()) throw logic_error("end() of binary string not reached"); --c; if (*c != B.back()) throw logic_error("Something wrong with binarystring::back()"); #ifdef PQXX_HAVE_REVERSE_ITERATOR binarystring::const_reverse_iterator r; for (i=B.length(), r=B.rbegin(); i>0; --i, ++r) { if (r == B.rend()) throw logic_error("Premature rend to binary string at " + to_string(i)); if (char(B[i-1]) != char(TestStr.at(i-1))) throw logic_error("Reverse iterator differs at " + to_string(i)); } if (r != B.rend()) throw logic_error("rend() of binary string not reached"); #endif if (B.str() != TestStr) throw logic_error("Binary string got mangled: '" + B.str() + "'"); const string TestStr2("(More conventional text)"); T.exec("INSERT INTO pqxxbin VALUES ('" + TestStr2 + "')"); R = T.exec("SELECT * FROM pqxxbin"); binarystring B2(R.front().front()); if (B2 == B) throw logic_error("Two different binarystrings say they're equal!"); if (!(B2 != B)) throw logic_error("Problem with binarystring::operator!="); binarystring B1c(B), B2c(B2); if (B1c != B) throw logic_error("Copied binarystring differs from original"); if (!(B2c == B2)) throw logic_error("Copied binarystring not equal to original"); B1c.swap(B2c); if (B2c == B1c) throw logic_error("Swapped binarystrings say they're identical!"); if (B2c != B) throw logic_error("Problem with binarystring::swap()"); if (!(B1c == B2)) throw logic_error("Problem with one of two swapped binarystrings"); } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Used locale-sensitive strncmp() on binary data, causing false failures<commit_after>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/binarystring> #include <pqxx/connection> #include <pqxx/transaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Example program for libpqxx. Test binarystring functionality. // // Usage: test062 [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { const string TestStr = "Nasty\n\030Test\n\t String with \200\277 weird bytes " "\r\0 and Trailer\\\\\0"; connection C(argv[1]); work T(C, "test62"); T.exec("CREATE TEMP TABLE pqxxbin (binfield bytea)"); const string Esc = escape_binary(TestStr); T.exec("INSERT INTO pqxxbin VALUES ('" + Esc + "')"); result R = T.exec("SELECT * from pqxxbin"); T.exec("DELETE FROM pqxxbin"); binarystring B( R.at(0).at(0) ); if (B.empty()) throw logic_error("Binary string became empty in conversion"); cout << "original: " << TestStr << endl << "returned: " << B.c_ptr() << endl; if (B.size() != TestStr.size()) throw logic_error("Binary string got changed from " + to_string(TestStr.size()) + " to " + to_string(B.size()) + " bytes"); binarystring::const_iterator c; binarystring::size_type i; for (i=0, c=B.begin(); i<B.size(); ++i, ++c) { if (c == B.end()) throw logic_error("Premature end to binary string at " + to_string(i)); const char x = TestStr.at(i), y = B.at(i); if (x != y) { const unsigned char ux = x, uy = y; const unsigned int uix = ux, uiy = uy; throw logic_error("Binary string byte " + to_string(i) + " " "got changed from '" + to_string(x) + "' " "(" + to_string(uix) + ") " "to '" + to_string(y) + "' " "(" + to_string(uiy) + ")"); } if (y != B.data()[i]) throw logic_error("Inconsistent byte at offset " + to_string(i) + ": " "operator[] says '" + to_string(y) + "', " "data() says '" + to_string(char(B.data()[i])) + "'"); } if (B.at(0) != B.front()) throw logic_error("Something wrong with binarystring::front()"); if (c != B.end()) throw logic_error("end() of binary string not reached"); --c; if (*c != B.back()) throw logic_error("Something wrong with binarystring::back()"); #ifdef PQXX_HAVE_REVERSE_ITERATOR binarystring::const_reverse_iterator r; for (i=B.length(), r=B.rbegin(); i>0; --i, ++r) { if (r == B.rend()) throw logic_error("Premature rend to binary string at " + to_string(i)); if (char(B[i-1]) != char(TestStr.at(i-1))) throw logic_error("Reverse iterator differs at " + to_string(i)); } if (r != B.rend()) throw logic_error("rend() of binary string not reached"); #endif if (B.str() != TestStr) throw logic_error("Binary string got mangled: '" + B.str() + "'"); const string TestStr2("(More conventional text)"); T.exec("INSERT INTO pqxxbin VALUES ('" + TestStr2 + "')"); R = T.exec("SELECT * FROM pqxxbin"); binarystring B2(R.front().front()); if (B2 == B) throw logic_error("Two different binarystrings say they're equal!"); if (!(B2 != B)) throw logic_error("Problem with binarystring::operator!="); binarystring B1c(B), B2c(B2); if (B1c != B) throw logic_error("Copied binarystring differs from original"); if (!(B2c == B2)) throw logic_error("Copied binarystring not equal to original"); B1c.swap(B2c); if (B2c == B1c) throw logic_error("Swapped binarystrings say they're identical!"); if (B2c != B) throw logic_error("Problem with binarystring::swap()"); if (!(B1c == B2)) throw logic_error("Problem with one of two swapped binarystrings"); } catch (const sql_error &e) { // If we're interested in the text of a failed query, we can write separate // exception handling code for this type of exception cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { // All exceptions thrown by libpqxx are derived from std::exception cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { // This is really unexpected (see above) cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>#include <core/stdafx.h> #include <core/propertyBag/registryPropertyBag.h> #include <core/mapi/mapiFunctions.h> #include <core/utility/strings.h> #include <core/utility/registry.h> #include <core/utility/error.h> #include <core/interpret/proptags.h> #include <core/property/parseProperty.h> namespace propertybag { registryPropertyBag::registryPropertyBag(HKEY hKey) { m_hKey = hKey; } registryPropertyBag ::~registryPropertyBag() {} propBagFlags registryPropertyBag::GetFlags() const { const auto ulFlags = propBagFlags::None; return ulFlags; } bool registryPropertyBag::IsEqual(const std::shared_ptr<IMAPIPropertyBag> lpPropBag) const { if (!lpPropBag) return false; if (GetType() != lpPropBag->GetType()) return false; const auto lpOther = std::dynamic_pointer_cast<registryPropertyBag>(lpPropBag); if (lpOther) { // Can two different hKeys be the same reg key? if (m_hKey != lpOther->m_hKey) return false; return true; } return false; } ULONG nameToPropTag(_In_ const std::wstring& name) { if (name.size() != 8) return 0; ULONG num{}; if (strings::tryWstringToUlong(num, name, 16, false)) { // abuse some macros to swap the order of the tag return PROP_TAG(PROP_ID(num), PROP_TYPE(num)); } return 0; } _Check_return_ std::vector<std::shared_ptr<model::mapiRowModel>> registryPropertyBag::GetAllModels() { auto models = std::vector<std::shared_ptr<model::mapiRowModel>>{}; auto cchMaxValueNameLen = DWORD{}; // Param in RegQueryInfoKeyW is misnamed auto cValues = DWORD{}; auto hRes = WC_W32(RegQueryInfoKeyW( m_hKey, nullptr, // lpClass nullptr, // lpcchClass nullptr, // lpReserved nullptr, // lpcSubKeys nullptr, // lpcbMaxSubKeyLen nullptr, // lpcbMaxClassLen &cValues, // lpcValues &cchMaxValueNameLen, // lpcbMaxValueNameLen nullptr, // lpcbMaxValueLen nullptr, // lpcbSecurityDescriptor nullptr)); // lpftLastWriteTime if (cValues && cchMaxValueNameLen) { auto szBuf = std::wstring(cchMaxValueNameLen, L'\0'); cchMaxValueNameLen++; // For null terminator for (DWORD dwIndex = 0; dwIndex < cValues; dwIndex++) { auto dwType = DWORD{}; auto cchValLen = cchMaxValueNameLen; szBuf.clear(); hRes = WC_W32(RegEnumValueW( m_hKey, dwIndex, const_cast<wchar_t*>(szBuf.c_str()), &cchValLen, nullptr, // lpReserved &dwType, // lpType nullptr, // lpData nullptr)); // lpcbData if (hRes == S_OK) { const auto valName = std::wstring(szBuf.c_str()); // szBuf.size() is 0, so make a copy with a proper size const auto ulPropTag = nameToPropTag(valName); auto dwVal = DWORD{}; auto bVal = bool{}; auto szVal = std::wstring{}; auto binVal = std::vector<BYTE>{}; switch (dwType) { case REG_BINARY: binVal = registry::ReadBinFromRegistry(m_hKey, valName); break; case REG_DWORD: dwVal = registry::ReadDWORDFromRegistry(m_hKey, valName); break; case REG_SZ: szVal = registry::ReadStringFromRegistry(m_hKey, valName); break; } models.push_back(regToModel(valName, ulPropTag, dwType, dwVal, szVal, binVal)); } } } return models; } _Check_return_ std::shared_ptr<model::mapiRowModel> registryPropertyBag::GetOneModel(_In_ ULONG ulPropTag) { // TODO Implement return {}; } _Check_return_ LPSPropValue registryPropertyBag::GetOneProp(ULONG ulPropTag) { // TODO: Implement return nullptr; } _Check_return_ HRESULT registryPropertyBag::SetProps(ULONG cValues, LPSPropValue lpPropArray) { if (!cValues || !lpPropArray) return MAPI_E_INVALID_PARAMETER; return E_NOTIMPL; } _Check_return_ HRESULT registryPropertyBag::SetProp(LPSPropValue lpProp) { return E_NOTIMPL; } // TODO: Identify prop tags in the value name // Use type from tag to determine how to read data // Also use lpType // Convert data read to a MAPI prop Value // Figure out way to deal with S props // Figure out way to deal with named props _Check_return_ std::shared_ptr<model::mapiRowModel> registryPropertyBag::regToModel( _In_ const std::wstring& name, ULONG ulPropTag, DWORD dwType, DWORD dwVal, _In_ const std::wstring& szVal, _In_ const std::vector<BYTE>& binVal) { auto ret = std::make_shared<model::mapiRowModel>(); if (ulPropTag != 0) { ret->ulPropTag(ulPropTag); const auto propTagNames = proptags::PropTagToPropName(ulPropTag, false); if (!propTagNames.bestGuess.empty()) { ret->name(propTagNames.bestGuess); } if (!propTagNames.otherMatches.empty()) { ret->otherName(propTagNames.otherMatches); } } else { ret->name(name); ret->otherName(strings::format(L"%d", dwType)); // Just shoving in model to see it } switch (dwType) { case REG_BINARY: { auto bSkipParse = false; auto prop = SPropValue{}; prop.ulPropTag = ulPropTag; switch (PROP_TYPE(ulPropTag)) { case PT_CLSID: if (binVal.size() == 16) { prop.Value.lpguid = reinterpret_cast<LPGUID>(const_cast<LPBYTE>(binVal.data())); } break; case PT_SYSTIME: if (binVal.size() == 8) { prop.Value.ft = *reinterpret_cast<LPFILETIME>(const_cast<LPBYTE>(binVal.data())); } break; case PT_I8: if (binVal.size() == 8) { prop.Value.li.QuadPart = static_cast<LONGLONG>(*binVal.data()); } break; case PT_LONG: if (binVal.size() == 4) { prop.Value.l = static_cast<DWORD>(*binVal.data()); } break; case PT_BOOLEAN: if (binVal.size() == 2) { prop.Value.b = static_cast<WORD>(*binVal.data()); } break; case PT_BINARY: prop.Value.bin.cb = binVal.size(); prop.Value.bin.lpb = const_cast<LPBYTE>(binVal.data()); break; case PT_UNICODE: prop.Value.lpszW = reinterpret_cast<LPWSTR>(const_cast<LPBYTE>(binVal.data())); break; default: bSkipParse = true; ret->value(strings::BinToHexString(binVal, true)); ret->altValue(strings::BinToTextString(binVal, true)); break; } if (!bSkipParse) { std::wstring PropString; std::wstring AltPropString; property::parseProperty(&prop, &PropString, &AltPropString); ret->value(PropString); ret->altValue(AltPropString); } } break; case REG_DWORD: ret->value(strings::format(L"0x%08X", dwVal)); break; case REG_SZ: ret->value(szVal); break; } // For debugging purposes right now ret->namedPropName(strings::BinToHexString(binVal, true)); ret->namedPropGuid(strings::BinToTextString(binVal, true)); //const auto propTagNames = proptags::PropTagToPropName(ulPropTag, bIsAB); //const auto namePropNames = cache::NameIDToStrings(ulPropTag, lpProp, nullptr, sig, bIsAB); //if (!propTagNames.bestGuess.empty()) //{ // ret->name(propTagNames.bestGuess); //} //else if (!namePropNames.bestPidLid.empty()) //{ // ret->name(namePropNames.bestPidLid); //} //else if (!namePropNames.name.empty()) //{ // ret->name(namePropNames.name); //} //if (!namePropNames.name.empty()) ret->namedPropName(namePropNames.name); //if (!namePropNames.guid.empty()) ret->namedPropGuid(namePropNames.guid); //const auto szSmartView = smartview::parsePropertySmartView(lpPropVal, lpProp, lpNameID, sig, bIsAB, false); //if (!szSmartView.empty()) ret->smartView(szSmartView); return ret; } } // namespace propertybag<commit_msg>add smartview parsing to reg model<commit_after>#include <core/stdafx.h> #include <core/propertyBag/registryPropertyBag.h> #include <core/mapi/mapiFunctions.h> #include <core/utility/strings.h> #include <core/utility/registry.h> #include <core/utility/error.h> #include <core/interpret/proptags.h> #include <core/property/parseProperty.h> #include <core/smartview/SmartView.h> namespace propertybag { registryPropertyBag::registryPropertyBag(HKEY hKey) { m_hKey = hKey; } registryPropertyBag ::~registryPropertyBag() {} propBagFlags registryPropertyBag::GetFlags() const { const auto ulFlags = propBagFlags::None; return ulFlags; } bool registryPropertyBag::IsEqual(const std::shared_ptr<IMAPIPropertyBag> lpPropBag) const { if (!lpPropBag) return false; if (GetType() != lpPropBag->GetType()) return false; const auto lpOther = std::dynamic_pointer_cast<registryPropertyBag>(lpPropBag); if (lpOther) { // Can two different hKeys be the same reg key? if (m_hKey != lpOther->m_hKey) return false; return true; } return false; } ULONG nameToPropTag(_In_ const std::wstring& name) { if (name.size() != 8) return 0; ULONG num{}; if (strings::tryWstringToUlong(num, name, 16, false)) { // abuse some macros to swap the order of the tag return PROP_TAG(PROP_ID(num), PROP_TYPE(num)); } return 0; } _Check_return_ std::vector<std::shared_ptr<model::mapiRowModel>> registryPropertyBag::GetAllModels() { auto models = std::vector<std::shared_ptr<model::mapiRowModel>>{}; auto cchMaxValueNameLen = DWORD{}; // Param in RegQueryInfoKeyW is misnamed auto cValues = DWORD{}; auto hRes = WC_W32(RegQueryInfoKeyW( m_hKey, nullptr, // lpClass nullptr, // lpcchClass nullptr, // lpReserved nullptr, // lpcSubKeys nullptr, // lpcbMaxSubKeyLen nullptr, // lpcbMaxClassLen &cValues, // lpcValues &cchMaxValueNameLen, // lpcbMaxValueNameLen nullptr, // lpcbMaxValueLen nullptr, // lpcbSecurityDescriptor nullptr)); // lpftLastWriteTime if (cValues && cchMaxValueNameLen) { auto szBuf = std::wstring(cchMaxValueNameLen, L'\0'); cchMaxValueNameLen++; // For null terminator for (DWORD dwIndex = 0; dwIndex < cValues; dwIndex++) { auto dwType = DWORD{}; auto cchValLen = cchMaxValueNameLen; szBuf.clear(); hRes = WC_W32(RegEnumValueW( m_hKey, dwIndex, const_cast<wchar_t*>(szBuf.c_str()), &cchValLen, nullptr, // lpReserved &dwType, // lpType nullptr, // lpData nullptr)); // lpcbData if (hRes == S_OK) { const auto valName = std::wstring(szBuf.c_str()); // szBuf.size() is 0, so make a copy with a proper size const auto ulPropTag = nameToPropTag(valName); auto dwVal = DWORD{}; auto bVal = bool{}; auto szVal = std::wstring{}; auto binVal = std::vector<BYTE>{}; switch (dwType) { case REG_BINARY: binVal = registry::ReadBinFromRegistry(m_hKey, valName); break; case REG_DWORD: dwVal = registry::ReadDWORDFromRegistry(m_hKey, valName); break; case REG_SZ: szVal = registry::ReadStringFromRegistry(m_hKey, valName); break; } models.push_back(regToModel(valName, ulPropTag, dwType, dwVal, szVal, binVal)); } } } return models; } _Check_return_ std::shared_ptr<model::mapiRowModel> registryPropertyBag::GetOneModel(_In_ ULONG ulPropTag) { // TODO Implement return {}; } _Check_return_ LPSPropValue registryPropertyBag::GetOneProp(ULONG ulPropTag) { // TODO: Implement return nullptr; } _Check_return_ HRESULT registryPropertyBag::SetProps(ULONG cValues, LPSPropValue lpPropArray) { if (!cValues || !lpPropArray) return MAPI_E_INVALID_PARAMETER; return E_NOTIMPL; } _Check_return_ HRESULT registryPropertyBag::SetProp(LPSPropValue lpProp) { return E_NOTIMPL; } // TODO: Identify prop tags in the value name // Use type from tag to determine how to read data // Also use lpType // Convert data read to a MAPI prop Value // Figure out way to deal with S props // Figure out way to deal with named props _Check_return_ std::shared_ptr<model::mapiRowModel> registryPropertyBag::regToModel( _In_ const std::wstring& name, ULONG ulPropTag, DWORD dwType, DWORD dwVal, _In_ const std::wstring& szVal, _In_ const std::vector<BYTE>& binVal) { auto ret = std::make_shared<model::mapiRowModel>(); if (ulPropTag != 0) { ret->ulPropTag(ulPropTag); const auto propTagNames = proptags::PropTagToPropName(ulPropTag, false); if (!propTagNames.bestGuess.empty()) { ret->name(propTagNames.bestGuess); } if (!propTagNames.otherMatches.empty()) { ret->otherName(propTagNames.otherMatches); } } else { ret->name(name); ret->otherName(strings::format(L"%d", dwType)); // Just shoving in model to see it } auto bParseMAPI = false; auto prop = SPropValue{ulPropTag}; if (dwType == REG_BINARY) { if (ulPropTag) { bParseMAPI = true; switch (PROP_TYPE(ulPropTag)) { case PT_CLSID: if (binVal.size() == 16) { prop.Value.lpguid = reinterpret_cast<LPGUID>(const_cast<LPBYTE>(binVal.data())); } break; case PT_SYSTIME: if (binVal.size() == 8) { prop.Value.ft = *reinterpret_cast<LPFILETIME>(const_cast<LPBYTE>(binVal.data())); } break; case PT_I8: if (binVal.size() == 8) { prop.Value.li.QuadPart = static_cast<LONGLONG>(*binVal.data()); } break; case PT_LONG: if (binVal.size() == 4) { prop.Value.l = static_cast<DWORD>(*binVal.data()); } break; case PT_BOOLEAN: if (binVal.size() == 2) { prop.Value.b = static_cast<WORD>(*binVal.data()); } break; case PT_BINARY: prop.Value.bin.cb = binVal.size(); prop.Value.bin.lpb = const_cast<LPBYTE>(binVal.data()); break; case PT_UNICODE: prop.Value.lpszW = reinterpret_cast<LPWSTR>(const_cast<LPBYTE>(binVal.data())); break; default: bParseMAPI = false; break; } } if (!bParseMAPI) { ret->value(strings::BinToHexString(binVal, true)); ret->altValue(strings::BinToTextString(binVal, true)); } } else if (dwType == REG_DWORD) { if (ulPropTag) { bParseMAPI = true; prop.Value.l = dwVal; } else { ret->value(strings::format(L"%d", dwVal)); ret->altValue(strings::format(L"0x%08X", dwVal)); } } else if (dwType == REG_SZ) { ret->value(szVal); } if (bParseMAPI) { std::wstring PropString; std::wstring AltPropString; property::parseProperty(&prop, &PropString, &AltPropString); ret->value(PropString); ret->altValue(AltPropString); const auto szSmartView = smartview::parsePropertySmartView(&prop, nullptr, nullptr, nullptr, false, false); if (!szSmartView.empty()) ret->smartView(szSmartView); } // For debugging purposes right now ret->namedPropName(strings::BinToHexString(binVal, true)); ret->namedPropGuid(strings::BinToTextString(binVal, true)); return ret; } } // namespace propertybag<|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 "replica.h" #include "mutation.h" #include "mutation_log.h" #include "replica_stub.h" #include <boost/filesystem.hpp> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "replica.learn" namespace dsn { namespace replication { void replica::init_learn(uint64_t signature) { check_hashed_access(); dassert (status() == PS_POTENTIAL_SECONDARY, ""); // at most one learning task running if (_potential_secondary_states.learning_round_is_running || !signature) return; if (signature != _potential_secondary_states.learning_signature) { _potential_secondary_states.cleanup(true); _potential_secondary_states.learning_signature = signature; _potential_secondary_states.learning_status = LearningWithoutPrepare; _prepare_list->reset(_app->last_committed_decree()); } else { switch (_potential_secondary_states.learning_status) { case LearningSucceeded: notify_learn_completion(); return; case LearningFailed: break; case LearningWithPrepare: if (_app->last_durable_decree() >= last_committed_decree()) { _potential_secondary_states.learning_status = LearningSucceeded; notify_learn_completion(); return; } break; case LearningWithoutPrepare: break; default: dassert (false, ""); } } _potential_secondary_states.learning_round_is_running = true; std::shared_ptr<learn_request> request(new learn_request); request->gpid = get_gpid(); request->last_committed_decree_in_app = _app->last_committed_decree(); request->last_committed_decree_in_prepare_list = _prepare_list->last_committed_decree(); request->learner = primary_address(); request->signature = _potential_secondary_states.learning_signature; _app->prepare_learning_request(request->app_specific_learn_request); _potential_secondary_states.learning_task = rpc::call_typed( _config.primary, RPC_LEARN, request, this, &replica::on_learn_reply, gpid_to_hash(get_gpid()) ); ddebug( "%s: init_learn with lastAppC/DDecree = <%llu,%llu>, lastCDecree = %llu, learnState = %s", name(), _app->last_committed_decree(), _app->last_durable_decree(), last_committed_decree(), enum_to_string(_potential_secondary_states.learning_status) ); } void replica::on_learn(const learn_request& request, __out_param learn_response& response) { check_hashed_access(); if (PS_PRIMARY != status()) { response.err = ERR_INVALID_STATE; return; } if (request.last_committed_decree_in_app > last_committed_decree()) { ddebug( "%s: on_learn %s:%d, learner state is lost due to DDD, with its appCommittedDecree = %llu vs localCommitedDecree %llu", name(), request.learner.name.c_str(), static_cast<int>(request.learner.port), request.last_committed_decree_in_app, last_committed_decree() ); ((learn_request&)request).last_committed_decree_in_app = 0; } _primary_states.get_replica_config(request.learner, response.config); auto it = _primary_states.learners.find(request.learner); if (it == _primary_states.learners.end()) { response.err = (response.config.status == PS_SECONDARY ? ERR_OK : ERR_OBJECT_NOT_FOUND); return; } else if (it->second.signature != request.signature) { response.err = ERR_OBJECT_NOT_FOUND; return; } ddebug( "%s: on_learn %s:%d with its appCommittedDecree = %llu vs localCommitedDecree %llu", name(), request.learner.name.c_str(), static_cast<int>(request.learner.port), request.last_committed_decree_in_app, last_committed_decree() ); response.prepare_start_decree = invalid_decree; response.commit_decree = last_committed_decree(); response.err = ERR_OK; if (request.last_committed_decree_in_app + _options.staleness_for_start_prepare_for_potential_secondary >= last_committed_decree()) { if (it->second.prepare_start_decree == invalid_decree) { it->second.prepare_start_decree = last_committed_decree() + 1; cleanup_preparing_mutations(true); replay_prepare_list(); ddebug( "%s: on_learn with prepare_start_decree = %llu for %s:%d", name(), last_committed_decree() + 1, request.learner.name.c_str(), static_cast<int>(request.learner.port) ); } response.prepare_start_decree = it->second.prepare_start_decree; } else { it->second.prepare_start_decree = invalid_decree; } decree decree = request.last_committed_decree_in_app + 1; int lerr = _app->get_learn_state(decree, request.app_specific_learn_request, response.state); if (lerr != 0) { derror("%s get learn state failed, error = %d", dir().c_str(), lerr); } response.err = (lerr == 0 ? ERR_OK : ERR_GET_LEARN_STATE_FALED); response.base_local_dir = _app->data_dir(); for (auto itr = response.state.files.begin(); itr != response.state.files.end(); ++itr) *itr = itr->substr(_app->data_dir().length()); } void replica::on_learn_reply(error_code err, std::shared_ptr<learn_request>& req, std::shared_ptr<learn_response>& resp) { check_hashed_access(); dassert(PS_POTENTIAL_SECONDARY == status(), ""); dassert(req->signature == _potential_secondary_states.learning_signature, ""); if (err != ERR_OK) { handle_learning_error(err); return; } ddebug( "%s: on_learn_reply with err = %s, prepare_start_decree = %llu, current learnState = %s", name(), resp->err.to_string(), resp->prepare_start_decree, enum_to_string(_potential_secondary_states.learning_status) ); if (resp->err != ERR_OK) { handle_learning_error(resp->err); return; } if (resp->config.ballot > get_ballot()) { update_local_configuration(resp->config); } if (status() != PS_POTENTIAL_SECONDARY) { return; } if (resp->prepare_start_decree != invalid_decree && _potential_secondary_states.learning_status == LearningWithoutPrepare) { _potential_secondary_states.learning_status = LearningWithPrepare; _prepare_list->reset(resp->prepare_start_decree - 1); } if (resp->state.files.size() > 0) { _potential_secondary_states.learn_remote_files_task = file::copy_remote_files(resp->config.primary, resp->base_local_dir, resp->state.files, _app->learn_dir(), true, LPC_COPY_REMOTE_DELTA_FILES, this, std::bind(&replica::on_copy_remote_state_completed, this, std::placeholders::_1, std::placeholders::_2, resp) ); } else { _potential_secondary_states.learn_remote_files_task = tasking::enqueue( LPC_LEARN_REMOTE_DELTA_FILES, this, std::bind(&replica::on_copy_remote_state_completed, this, ERR_OK, 0, resp) ); } } void replica::on_copy_remote_state_completed(error_code err2, int size, std::shared_ptr<learn_response> resp) { learn_state localState; localState.meta = resp->state.meta; end_point& server = resp->config.primary; if (err2 == ERR_OK) { for (auto itr = resp->state.files.begin(); itr != resp->state.files.end(); ++itr) { std::string file; if (dir().back() == '/' || itr->front() == '/') file = dir() + *itr; else file = dir() + '/' + *itr; localState.files.push_back(file); } // the only place where there is non-in-partition-thread update decree oldDecree = _app->last_committed_decree(); int err = _app->apply_learn_state(resp->state); ddebug( "%s: learning %d files to %s, err = %x, " "appCommit(%llu => %llu), durable(%llu), remoteC(%llu), prepStart(%llu), state(%s)", name(), resp->state.files.size(), _dir.c_str(), err, oldDecree, _app->last_committed_decree(), _app->last_durable_decree(), resp->commit_decree, resp->prepare_start_decree, enum_to_string(_potential_secondary_states.learning_status) ); if (err == 0 && _app->last_committed_decree() >= resp->commit_decree) { err = _app->flush(true); if (err == 0) { dassert (_app->last_committed_decree() == _app->last_durable_decree(), ""); } } // translate to general error code if (err != 0) { err2 = ERR_LOCAL_APP_FAILURE; } } else { derror( "%s: transfer %d files to %s failed, err = %s", name(), static_cast<int>(resp->state.files.size()), _dir.c_str(), err2.to_string() ); } _potential_secondary_states.learn_remote_files_completed_task = tasking::enqueue( LPC_LEARN_REMOTE_DELTA_FILES_COMPLETED, this, std::bind(&replica::on_learn_remote_state_completed, this, err2), gpid_to_hash(get_gpid()) ); } void replica::on_learn_remote_state_completed(error_code err) { check_hashed_access(); if (PS_POTENTIAL_SECONDARY != status()) return; _potential_secondary_states.learning_round_is_running = false; if (err != ERR_OK) { handle_learning_error(err); } else { // continue init_learn(_potential_secondary_states.learning_signature); } } void replica::handle_learning_error(error_code err) { check_hashed_access(); dwarn( "%s: learning failed with err = %s, LastCommitted = %lld", name(), err.to_string(), _app->last_committed_decree() ); _potential_secondary_states.cleanup(true); _potential_secondary_states.learning_status = LearningFailed; update_local_configuration_with_no_ballot_change(PS_ERROR); } void replica::handle_learning_succeeded_on_primary(const end_point& node, uint64_t learnSignature) { auto it = _primary_states.learners.find(node); if (it != _primary_states.learners.end() && it->second.signature == learnSignature) upgrade_to_secondary_on_primary(node); } void replica::notify_learn_completion() { group_check_response report; report.gpid = get_gpid(); report.err = ERR_OK; report.last_committed_decree_in_app = _app->last_committed_decree(); report.last_committed_decree_in_prepare_list = last_committed_decree(); report.learner_signature = _potential_secondary_states.learning_signature; report.learner_status_ = _potential_secondary_states.learning_status; report.node = primary_address(); rpc::call_one_way_typed(_config.primary, RPC_LEARN_COMPLETION_NOTIFY, report, gpid_to_hash(get_gpid())); } void replica::on_learn_completion_notification(const group_check_response& report) { check_hashed_access(); report.err.end_tracking(); if (status() != PS_PRIMARY) return; if (report.learner_status_ == LearningSucceeded) { handle_learning_succeeded_on_primary(report.node, report.learner_signature); } } void replica::on_add_learner(const group_check_request& request) { if (request.config.ballot < get_ballot()) return; if (request.config.ballot > get_ballot() || is_same_ballot_status_change_allowed(status(), request.config.status)) { update_local_configuration(request.config, true); dassert(PS_POTENTIAL_SECONDARY == status(), ""); init_learn(request.learner_signature); } } }} // namespace <commit_msg>same small fix<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 "replica.h" #include "mutation.h" #include "mutation_log.h" #include "replica_stub.h" #include <boost/filesystem.hpp> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "replica.learn" namespace dsn { namespace replication { void replica::init_learn(uint64_t signature) { check_hashed_access(); dassert (status() == PS_POTENTIAL_SECONDARY, ""); // at most one learning task running if (_potential_secondary_states.learning_round_is_running || !signature) return; if (signature != _potential_secondary_states.learning_signature) { _potential_secondary_states.cleanup(true); _potential_secondary_states.learning_signature = signature; _potential_secondary_states.learning_status = LearningWithoutPrepare; _prepare_list->reset(_app->last_committed_decree()); } else { switch (_potential_secondary_states.learning_status) { case LearningSucceeded: notify_learn_completion(); return; case LearningFailed: break; case LearningWithPrepare: if (_app->last_durable_decree() >= last_committed_decree()) { _potential_secondary_states.learning_status = LearningSucceeded; notify_learn_completion(); return; } break; case LearningWithoutPrepare: break; default: dassert (false, ""); } } _potential_secondary_states.learning_round_is_running = true; std::shared_ptr<learn_request> request(new learn_request); request->gpid = get_gpid(); request->last_committed_decree_in_app = _app->last_committed_decree(); request->last_committed_decree_in_prepare_list = _prepare_list->last_committed_decree(); request->learner = primary_address(); request->signature = _potential_secondary_states.learning_signature; _app->prepare_learning_request(request->app_specific_learn_request); _potential_secondary_states.learning_task = rpc::call_typed( _config.primary, RPC_LEARN, request, this, &replica::on_learn_reply, gpid_to_hash(get_gpid()) ); ddebug( "%s: init_learn with lastAppC/DDecree = <%llu,%llu>, lastCDecree = %llu, learnState = %s", name(), _app->last_committed_decree(), _app->last_durable_decree(), last_committed_decree(), enum_to_string(_potential_secondary_states.learning_status) ); } void replica::on_learn(const learn_request& request, __out_param learn_response& response) { check_hashed_access(); if (PS_PRIMARY != status()) { response.err = ERR_INVALID_STATE; return; } if (request.last_committed_decree_in_app > last_committed_decree()) { ddebug( "%s: on_learn %s:%d, learner state is lost due to DDD, with its appCommittedDecree = %llu vs localCommitedDecree %llu", name(), request.learner.name.c_str(), static_cast<int>(request.learner.port), request.last_committed_decree_in_app, last_committed_decree() ); ((learn_request&)request).last_committed_decree_in_app = 0; } _primary_states.get_replica_config(request.learner, response.config); auto it = _primary_states.learners.find(request.learner); if (it == _primary_states.learners.end()) { response.err = (response.config.status == PS_SECONDARY ? ERR_OK : ERR_OBJECT_NOT_FOUND); return; } else if (it->second.signature != request.signature) { response.err = ERR_OBJECT_NOT_FOUND; return; } ddebug( "%s: on_learn %s:%d with its appCommittedDecree = %llu vs localCommitedDecree %llu", name(), request.learner.name.c_str(), static_cast<int>(request.learner.port), request.last_committed_decree_in_app, last_committed_decree() ); response.prepare_start_decree = invalid_decree; response.commit_decree = last_committed_decree(); response.err = ERR_OK; if (request.last_committed_decree_in_app + _options.staleness_for_start_prepare_for_potential_secondary >= last_committed_decree()) { if (it->second.prepare_start_decree == invalid_decree) { it->second.prepare_start_decree = last_committed_decree() + 1; cleanup_preparing_mutations(true); replay_prepare_list(); ddebug( "%s: on_learn with prepare_start_decree = %llu for %s:%d", name(), last_committed_decree() + 1, request.learner.name.c_str(), static_cast<int>(request.learner.port) ); } response.prepare_start_decree = it->second.prepare_start_decree; } else { it->second.prepare_start_decree = invalid_decree; } decree decree = request.last_committed_decree_in_app + 1; int lerr = _app->get_learn_state(decree, request.app_specific_learn_request, response.state); if (lerr != 0) { response.err = ERR_GET_LEARN_STATE_FALED; derror("%s get learn state failed, error = %d", dir().c_str(), lerr); } else { response.base_local_dir = _app->data_dir(); for (auto itr = response.state.files.begin(); itr != response.state.files.end(); ++itr) *itr = itr->substr(_app->data_dir().length()); } } void replica::on_learn_reply(error_code err, std::shared_ptr<learn_request>& req, std::shared_ptr<learn_response>& resp) { check_hashed_access(); dassert(PS_POTENTIAL_SECONDARY == status(), ""); dassert(req->signature == _potential_secondary_states.learning_signature, ""); if (err != ERR_OK) { handle_learning_error(err); return; } ddebug( "%s: on_learn_reply with err = %s, prepare_start_decree = %llu, current learnState = %s", name(), resp->err.to_string(), resp->prepare_start_decree, enum_to_string(_potential_secondary_states.learning_status) ); if (resp->err != ERR_OK) { handle_learning_error(resp->err); return; } if (resp->config.ballot > get_ballot()) { update_local_configuration(resp->config); } if (status() != PS_POTENTIAL_SECONDARY) { return; } if (resp->prepare_start_decree != invalid_decree && _potential_secondary_states.learning_status == LearningWithoutPrepare) { _potential_secondary_states.learning_status = LearningWithPrepare; _prepare_list->reset(resp->prepare_start_decree - 1); } if (resp->state.files.size() > 0) { _potential_secondary_states.learn_remote_files_task = file::copy_remote_files(resp->config.primary, resp->base_local_dir, resp->state.files, _app->learn_dir(), true, LPC_COPY_REMOTE_DELTA_FILES, this, std::bind(&replica::on_copy_remote_state_completed, this, std::placeholders::_1, std::placeholders::_2, resp) ); } else { _potential_secondary_states.learn_remote_files_task = tasking::enqueue( LPC_LEARN_REMOTE_DELTA_FILES, this, std::bind(&replica::on_copy_remote_state_completed, this, ERR_OK, 0, resp) ); } } void replica::on_copy_remote_state_completed(error_code err2, int size, std::shared_ptr<learn_response> resp) { learn_state localState; localState.meta = resp->state.meta; end_point& server = resp->config.primary; if (err2 == ERR_OK) { for (auto itr = resp->state.files.begin(); itr != resp->state.files.end(); ++itr) { std::string file; if (dir().back() == '/' || itr->front() == '/') file = dir() + *itr; else file = dir() + '/' + *itr; localState.files.push_back(file); } // the only place where there is non-in-partition-thread update decree oldDecree = _app->last_committed_decree(); int err = _app->apply_learn_state(resp->state); ddebug( "%s: learning %d files to %s, err = %x, " "appCommit(%llu => %llu), durable(%llu), remoteC(%llu), prepStart(%llu), state(%s)", name(), resp->state.files.size(), _dir.c_str(), err, oldDecree, _app->last_committed_decree(), _app->last_durable_decree(), resp->commit_decree, resp->prepare_start_decree, enum_to_string(_potential_secondary_states.learning_status) ); if (err == 0 && _app->last_committed_decree() >= resp->commit_decree) { err = _app->flush(true); if (err == 0) { dassert (_app->last_committed_decree() == _app->last_durable_decree(), ""); } } // translate to general error code if (err != 0) { err2 = ERR_LOCAL_APP_FAILURE; } } else { derror( "%s: transfer %d files to %s failed, err = %s", name(), static_cast<int>(resp->state.files.size()), _dir.c_str(), err2.to_string() ); } _potential_secondary_states.learn_remote_files_completed_task = tasking::enqueue( LPC_LEARN_REMOTE_DELTA_FILES_COMPLETED, this, std::bind(&replica::on_learn_remote_state_completed, this, err2), gpid_to_hash(get_gpid()) ); } void replica::on_learn_remote_state_completed(error_code err) { check_hashed_access(); if (PS_POTENTIAL_SECONDARY != status()) return; _potential_secondary_states.learning_round_is_running = false; if (err != ERR_OK) { handle_learning_error(err); } else { // continue init_learn(_potential_secondary_states.learning_signature); } } void replica::handle_learning_error(error_code err) { check_hashed_access(); dwarn( "%s: learning failed with err = %s, LastCommitted = %lld", name(), err.to_string(), _app->last_committed_decree() ); _potential_secondary_states.cleanup(true); _potential_secondary_states.learning_status = LearningFailed; update_local_configuration_with_no_ballot_change(PS_ERROR); } void replica::handle_learning_succeeded_on_primary(const end_point& node, uint64_t learnSignature) { auto it = _primary_states.learners.find(node); if (it != _primary_states.learners.end() && it->second.signature == learnSignature) upgrade_to_secondary_on_primary(node); } void replica::notify_learn_completion() { group_check_response report; report.gpid = get_gpid(); report.err = ERR_OK; report.last_committed_decree_in_app = _app->last_committed_decree(); report.last_committed_decree_in_prepare_list = last_committed_decree(); report.learner_signature = _potential_secondary_states.learning_signature; report.learner_status_ = _potential_secondary_states.learning_status; report.node = primary_address(); rpc::call_one_way_typed(_config.primary, RPC_LEARN_COMPLETION_NOTIFY, report, gpid_to_hash(get_gpid())); } void replica::on_learn_completion_notification(const group_check_response& report) { check_hashed_access(); report.err.end_tracking(); if (status() != PS_PRIMARY) return; if (report.learner_status_ == LearningSucceeded) { handle_learning_succeeded_on_primary(report.node, report.learner_signature); } } void replica::on_add_learner(const group_check_request& request) { if (request.config.ballot < get_ballot()) return; if (request.config.ballot > get_ballot() || is_same_ballot_status_change_allowed(status(), request.config.status)) { update_local_configuration(request.config, true); dassert(PS_POTENTIAL_SECONDARY == status(), ""); init_learn(request.learner_signature); } } }} // namespace <|endoftext|>
<commit_before>#ifndef SINGLETON_HPP #define SINGLETON_HPP namespace cutehmi { namespace internal { typedef void(*singletonDestroyCallback)(); void destroySingletonInstances(); void storeSingletonDestroyCallback(singletonDestroyCallback callback); void removeSingletonDestroyCallback(singletonDestroyCallback callback); } } #endif // SINGLETON_HPP <commit_msg>Update include guards.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNAL_SINGLETON_HPP #define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_INTERNAL_SINGLETON_HPP namespace cutehmi { namespace internal { typedef void(*singletonDestroyCallback)(); void destroySingletonInstances(); void storeSingletonDestroyCallback(singletonDestroyCallback callback); void removeSingletonDestroyCallback(singletonDestroyCallback callback); } } #endif <|endoftext|>
<commit_before>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); upnp upnp_handler(ios, cc, address_v4(), user_agent, &callback); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler.set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "removing mappings" << std::endl; upnp_handler.close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <commit_msg>fixed bug in test_upnp program<commit_after>#include "libtorrent/upnp.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/connection_queue.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/intrusive_ptr.hpp> using namespace libtorrent; void callback(int tcp, int udp, std::string const& err) { std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n"; } int main(int argc, char* argv[]) { io_service ios; std::string user_agent = "test agent"; if (argc != 3) { std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl; return 1; } connection_queue cc(ios); boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback); deadline_timer timer(ios); timer.expires_from_now(seconds(2)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "broadcasting for UPnP device" << std::endl; ios.reset(); ios.run(); upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2])); timer.expires_from_now(seconds(5)); timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios))); std::cerr << "mapping ports TCP: " << argv[1] << " UDP: " << argv[2] << std::endl; ios.reset(); ios.run(); std::cerr << "removing mappings" << std::endl; upnp_handler->close(); ios.reset(); ios.run(); std::cerr << "closing" << std::endl; } <|endoftext|>
<commit_before>// @(#)root/thread:$Id$ // Author: Xavier Valls March 2016 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadExecutor #define ROOT_TThreadExecutor #include "RConfigure.h" // exclude in case ROOT does not have IMT support #ifndef R__USE_IMT // No need to error out for dictionaries. # if !defined(__ROOTCLING__) && !defined(G__DICTIONARY) # error "Cannot use ROOT::TThreadExecutor without defining R__USE_IMT." # endif #else #include "ROOT/TExecutor.hxx" #include "ROOT/TPoolManager.hxx" #include "TROOT.h" #include <functional> #include <memory> #include <numeric> namespace ROOT { class TThreadExecutor: public TExecutor<TThreadExecutor> { template<class T> friend class ParallelReductionResolver; public: explicit TThreadExecutor(); explicit TThreadExecutor(UInt_t nThreads); TThreadExecutor(TThreadExecutor &) = delete; TThreadExecutor &operator=(TThreadExecutor &) = delete; template<class F, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>; /// \cond template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>; // / \endcond using TExecutor<TThreadExecutor>::Map; // // MapReduce // // the late return types also check at compile-time whether redfunc is compatible with func, // // other than checking that func is compatible with the type of arguments. // // a static_assert check in TThreadExecutor::Reduce is used to check that redfunc is compatible with the type returned by func template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type; // /// \cond doxygen should ignore these methods template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; // /// \endcond using TExecutor<TThreadExecutor>::MapReduce; template<class T, class BINARYOP> auto Reduce(const std::vector<T> &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front())); template<class T, class R> auto Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); using TExecutor<TThreadExecutor>::Reduce; protected: template<class F, class R, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; private: void ParallelFor(unsigned start, unsigned end, unsigned step, const std::function<void(unsigned int i)> &f); double ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc); float ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc); template<class T, class R> auto SeqReduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); std::shared_ptr<ROOT::Internal::TPoolManager> fSched = nullptr; }; /************ TEMPLATE METHODS IMPLEMENTATION ******************/ ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// A vector containg executions' results is returned. /// Functions that take more than zero arguments can be executed (with /// fixed arguments) by wrapping them in a lambda or with std::bind. template<class F, class Cond> auto TThreadExecutor::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> reslist(nTimes); auto lambda = [&](unsigned int i) { reslist[i] = func(); }; ParallelFor(0U, nTimes, 1, lambda); return reslist; } template<class F, class R, class Cond> auto TThreadExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type> { if (nChunks == 0) { return Map(func, nTimes); } using retType = decltype(func()); std::vector<retType> reslist(nChunks); unsigned step = (nTimes + nChunks - 1) / nChunks; auto lambda = [&](unsigned int i) { std::vector<retType> partialResults(step); for (unsigned j = 0; j < step && (i + j) < nTimes; j++) { partialResults[j] = func(); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(0U, nTimes, step, lambda); return reslist; } template<class F, class INTEGER, class Cond> auto TThreadExecutor::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type> { unsigned start = *args.begin(); unsigned end = *args.end(); using retType = decltype(func(start)); std::vector<retType> reslist(end - start); auto lambda = [&](unsigned int i) { reslist[i] = func(i); }; ParallelFor(start, end, 1, lambda); return reslist; } template<class F, class INTEGER, class R, class Cond> auto TThreadExecutor::Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type> { if (nChunks == 0) { return Map(func, args); } unsigned start = *args.begin(); unsigned end = *args.end(); unsigned step = (end - start + nChunks - 1) / nChunks; //ceiling the division using retType = decltype(func(start)); std::vector<retType> reslist(nChunks); auto lambda = [&](unsigned int i) { std::vector<retType> partialResults(step); for (unsigned j = 0; j < step && (i + j) < end; j++) { partialResults[j] = func(i + j); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(start, end, step, lambda); return reslist; } // tell doxygen to ignore this (\endcond closes the statement) /// \cond // actual implementation of the Map method. all other calls with arguments eventually // call this one template<class F, class T, class Cond> auto TThreadExecutor::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type> { // //check whether func is callable using retType = decltype(func(args.front())); unsigned int fNToProcess = args.size(); std::vector<retType> reslist(fNToProcess); auto lambda = [&](unsigned int i) { reslist[i] = func(args[i]); }; ParallelFor(0U, fNToProcess, 1, lambda); return reslist; } template<class F, class T, class R, class Cond> auto TThreadExecutor::Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { if (nChunks == 0) { return Map(func, args); } // //check whether func is callable using retType = decltype(func(args.front())); unsigned int fNToProcess = args.size(); std::vector<retType> reslist(nChunks); unsigned step = (fNToProcess + nChunks - 1) / nChunks; //ceiling the division auto lambda = [&](unsigned int i) { std::vector<T> partialResults(step); for (unsigned j = 0; j < step && (i + j) < fNToProcess; j++) { partialResults[j] = func(args[i + j]); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(0U, fNToProcess, step, lambda); return reslist; } template<class F, class T, class R, class Cond> auto TThreadExecutor::Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { std::vector<T> vargs(std::move(args)); const auto &reslist = Map(func, vargs, redfunc, nChunks); return reslist; } // // tell doxygen to stop ignoring code // /// \endcond // ////////////////////////////////////////////////////////////////////////// // /// This method behaves just like Map, but an additional redfunc function // /// must be provided. redfunc is applied to the vector Map would return and // /// must return the same type as func. In practice, redfunc can be used to // /// "squash" the vector returned by Map into a single object by merging, // /// adding, mixing the elements of the vector. template<class F, class R, class Cond> auto TThreadExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc); } /// \cond doxygen should ignore these methods template<class F, class INTEGER, class R, class Cond> auto TThreadExecutor::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } template<class F, class T, class R, class Cond> auto TThreadExecutor::MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } template<class F, class T, class R, class Cond> auto TThreadExecutor::MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// Check that redfunc has the right signature and call it on objs template<class T, class BINARYOP> auto TThreadExecutor::Reduce(const std::vector<T> &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front())) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs.front(), objs.front())), T>::value, "redfunc does not have the correct signature"); return ParallelReduce(objs, redfunc); } template<class T, class R> auto TThreadExecutor::Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs)), T>::value, "redfunc does not have the correct signature"); return SeqReduce(objs, redfunc); } template<class T, class R> auto TThreadExecutor::SeqReduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { return redfunc(objs); } } // namespace ROOT #endif // R__USE_IMT #endif <commit_msg>Change variable name (not a class field)<commit_after>// @(#)root/thread:$Id$ // Author: Xavier Valls March 2016 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TThreadExecutor #define ROOT_TThreadExecutor #include "RConfigure.h" // exclude in case ROOT does not have IMT support #ifndef R__USE_IMT // No need to error out for dictionaries. # if !defined(__ROOTCLING__) && !defined(G__DICTIONARY) # error "Cannot use ROOT::TThreadExecutor without defining R__USE_IMT." # endif #else #include "ROOT/TExecutor.hxx" #include "ROOT/TPoolManager.hxx" #include "TROOT.h" #include <functional> #include <memory> #include <numeric> namespace ROOT { class TThreadExecutor: public TExecutor<TThreadExecutor> { template<class T> friend class ParallelReductionResolver; public: explicit TThreadExecutor(); explicit TThreadExecutor(UInt_t nThreads); TThreadExecutor(TThreadExecutor &) = delete; TThreadExecutor &operator=(TThreadExecutor &) = delete; template<class F, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type>; /// \cond template<class F, class INTEGER, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type>; // / \endcond using TExecutor<TThreadExecutor>::Map; // // MapReduce // // the late return types also check at compile-time whether redfunc is compatible with func, // // other than checking that func is compatible with the type of arguments. // // a static_assert check in TThreadExecutor::Reduce is used to check that redfunc is compatible with the type returned by func template<class F, class R, class Cond = noReferenceCond<F>> auto MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type; // /// \cond doxygen should ignore these methods template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type; // /// \endcond using TExecutor<TThreadExecutor>::MapReduce; template<class T, class BINARYOP> auto Reduce(const std::vector<T> &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front())); template<class T, class R> auto Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); using TExecutor<TThreadExecutor>::Reduce; protected: template<class F, class R, class Cond = noReferenceCond<F>> auto Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type>; template<class F, class INTEGER, class R, class Cond = noReferenceCond<F, INTEGER>> auto Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; template<class F, class T, class R, class Cond = noReferenceCond<F, T>> auto Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type>; private: void ParallelFor(unsigned start, unsigned end, unsigned step, const std::function<void(unsigned int i)> &f); double ParallelReduce(const std::vector<double> &objs, const std::function<double(double a, double b)> &redfunc); float ParallelReduce(const std::vector<float> &objs, const std::function<float(float a, float b)> &redfunc); template<class T, class R> auto SeqReduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)); std::shared_ptr<ROOT::Internal::TPoolManager> fSched = nullptr; }; /************ TEMPLATE METHODS IMPLEMENTATION ******************/ ////////////////////////////////////////////////////////////////////////// /// Execute func (with no arguments) nTimes in parallel. /// A vector containg executions' results is returned. /// Functions that take more than zero arguments can be executed (with /// fixed arguments) by wrapping them in a lambda or with std::bind. template<class F, class Cond> auto TThreadExecutor::Map(F func, unsigned nTimes) -> std::vector<typename std::result_of<F()>::type> { using retType = decltype(func()); std::vector<retType> reslist(nTimes); auto lambda = [&](unsigned int i) { reslist[i] = func(); }; ParallelFor(0U, nTimes, 1, lambda); return reslist; } template<class F, class R, class Cond> auto TThreadExecutor::Map(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F()>::type> { if (nChunks == 0) { return Map(func, nTimes); } using retType = decltype(func()); std::vector<retType> reslist(nChunks); unsigned step = (nTimes + nChunks - 1) / nChunks; auto lambda = [&](unsigned int i) { std::vector<retType> partialResults(step); for (unsigned j = 0; j < step && (i + j) < nTimes; j++) { partialResults[j] = func(); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(0U, nTimes, step, lambda); return reslist; } template<class F, class INTEGER, class Cond> auto TThreadExecutor::Map(F func, ROOT::TSeq<INTEGER> args) -> std::vector<typename std::result_of<F(INTEGER)>::type> { unsigned start = *args.begin(); unsigned end = *args.end(); using retType = decltype(func(start)); std::vector<retType> reslist(end - start); auto lambda = [&](unsigned int i) { reslist[i] = func(i); }; ParallelFor(start, end, 1, lambda); return reslist; } template<class F, class INTEGER, class R, class Cond> auto TThreadExecutor::Map(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(INTEGER)>::type> { if (nChunks == 0) { return Map(func, args); } unsigned start = *args.begin(); unsigned end = *args.end(); unsigned step = (end - start + nChunks - 1) / nChunks; //ceiling the division using retType = decltype(func(start)); std::vector<retType> reslist(nChunks); auto lambda = [&](unsigned int i) { std::vector<retType> partialResults(step); for (unsigned j = 0; j < step && (i + j) < end; j++) { partialResults[j] = func(i + j); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(start, end, step, lambda); return reslist; } // tell doxygen to ignore this (\endcond closes the statement) /// \cond // actual implementation of the Map method. all other calls with arguments eventually // call this one template<class F, class T, class Cond> auto TThreadExecutor::Map(F func, std::vector<T> &args) -> std::vector<typename std::result_of<F(T)>::type> { // //check whether func is callable using retType = decltype(func(args.front())); unsigned int nToProcess = args.size(); std::vector<retType> reslist(nToProcess); auto lambda = [&](unsigned int i) { reslist[i] = func(args[i]); }; ParallelFor(0U, nToProcess, 1, lambda); return reslist; } template<class F, class T, class R, class Cond> auto TThreadExecutor::Map(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { if (nChunks == 0) { return Map(func, args); } // //check whether func is callable using retType = decltype(func(args.front())); unsigned int nToProcess = args.size(); std::vector<retType> reslist(nChunks); unsigned step = (nToProcess + nChunks - 1) / nChunks; //ceiling the division auto lambda = [&](unsigned int i) { std::vector<T> partialResults(step); for (unsigned j = 0; j < step && (i + j) < nToProcess; j++) { partialResults[j] = func(args[i + j]); } reslist[i / step] = redfunc(partialResults); }; ParallelFor(0U, nToProcess, step, lambda); return reslist; } template<class F, class T, class R, class Cond> auto TThreadExecutor::Map(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> std::vector<typename std::result_of<F(T)>::type> { std::vector<T> vargs(std::move(args)); const auto &reslist = Map(func, vargs, redfunc, nChunks); return reslist; } // // tell doxygen to stop ignoring code // /// \endcond // ////////////////////////////////////////////////////////////////////////// // /// This method behaves just like Map, but an additional redfunc function // /// must be provided. redfunc is applied to the vector Map would return and // /// must return the same type as func. In practice, redfunc can be used to // /// "squash" the vector returned by Map into a single object by merging, // /// adding, mixing the elements of the vector. template<class F, class R, class Cond> auto TThreadExecutor::MapReduce(F func, unsigned nTimes, R redfunc, unsigned nChunks) -> typename std::result_of<F()>::type { return Reduce(Map(func, nTimes, redfunc, nChunks), redfunc); } /// \cond doxygen should ignore these methods template<class F, class INTEGER, class R, class Cond> auto TThreadExecutor::MapReduce(F func, ROOT::TSeq<INTEGER> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(INTEGER)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } template<class F, class T, class R, class Cond> auto TThreadExecutor::MapReduce(F func, std::initializer_list<T> args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } template<class F, class T, class R, class Cond> auto TThreadExecutor::MapReduce(F func, std::vector<T> &args, R redfunc, unsigned nChunks) -> typename std::result_of<F(T)>::type { return Reduce(Map(func, args, redfunc, nChunks), redfunc); } /// Check that redfunc has the right signature and call it on objs template<class T, class BINARYOP> auto TThreadExecutor::Reduce(const std::vector<T> &objs, BINARYOP redfunc) -> decltype(redfunc(objs.front(), objs.front())) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs.front(), objs.front())), T>::value, "redfunc does not have the correct signature"); return ParallelReduce(objs, redfunc); } template<class T, class R> auto TThreadExecutor::Reduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { // check we can apply reduce to objs static_assert(std::is_same<decltype(redfunc(objs)), T>::value, "redfunc does not have the correct signature"); return SeqReduce(objs, redfunc); } template<class T, class R> auto TThreadExecutor::SeqReduce(const std::vector<T> &objs, R redfunc) -> decltype(redfunc(objs)) { return redfunc(objs); } } // namespace ROOT #endif // R__USE_IMT #endif <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2003-2012 \file find_dialog.cpp \author Урусов Андрей (rdo@rk9.bmstu.ru) \date 31.12.2012 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/dialog/find_dialog.h" // -------------------------------------------------------------------------------- FindDialog::Settings::Settings() : matchCase (false) , matchWholeWord(false) , searchDown (true ) {} FindDialog::Settings::Settings(CREF(Settings) settings) : what (settings.what ) , matchCase (settings.matchCase ) , matchWholeWord(settings.matchWholeWord) , searchDown (settings.searchDown ) {} FindDialog::FindDialog(QWidget* pParent, const OnFindCallback& onFindCallback, OnCloseCallback& onCloseCallback) : QDialog(pParent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) , m_onFindCallback (onFindCallback ) , m_onCloseCallback(onCloseCallback) { setupUi(this); layout()->setSizeConstraint(QLayout::SetFixedSize); connect(findButton, SIGNAL(clicked(bool)), this, SLOT(onFindButton())); connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(lineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(onWhatEdited(const QString&))); connect(matchCase, SIGNAL(stateChanged(int)), this, SLOT(onMatchCaseChanged(int))); connect(wholeWord, SIGNAL(stateChanged(int)), this, SLOT(onMatchWholeWordChanged(int))); connect(directionDown, SIGNAL(toggled(bool)), this, SLOT(onDirectionDownToggled(bool))); setAttribute(Qt::WA_DeleteOnClose, true); } FindDialog::~FindDialog() { m_onCloseCallback(); } void FindDialog::setSettings(CREF(Settings) settings) { m_settings = settings; lineEdit->setText(m_settings.what); lineEdit->setFocus(); lineEdit->selectAll(); matchCase->setChecked(m_settings.matchCase); wholeWord->setChecked(m_settings.matchWholeWord); if (m_settings.searchDown) { directionDown->setChecked(true); } else { directionUp->setChecked(true); } } void FindDialog::onFindButton() { m_onFindCallback(m_settings); } void FindDialog::onWhatEdited(const QString& text) { m_settings.what = text; } void FindDialog::onMatchCaseChanged(int value) { m_settings.matchCase = value ? true : false; } void FindDialog::onMatchWholeWordChanged(int value) { m_settings.matchWholeWord = value ? true : false; } void FindDialog::onDirectionDownToggled(bool checked) { m_settings.searchDown = checked; } <commit_msg> - убраны макросы<commit_after>/*! \copyright (c) RDO-Team, 2003-2012 \file find_dialog.cpp \author Урусов Андрей (rdo@rk9.bmstu.ru) \date 31.12.2012 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "app/rdo_studio/pch/stdpch.h" // ----------------------------------------------------------------------- INCLUDES // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/dialog/find_dialog.h" // -------------------------------------------------------------------------------- FindDialog::Settings::Settings() : matchCase (false) , matchWholeWord(false) , searchDown (true ) {} FindDialog::Settings::Settings(CREF(Settings) settings) : what (settings.what ) , matchCase (settings.matchCase ) , matchWholeWord(settings.matchWholeWord) , searchDown (settings.searchDown ) {} FindDialog::FindDialog(QWidget* pParent, const OnFindCallback& onFindCallback, const OnCloseCallback& onCloseCallback) : QDialog(pParent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) , m_onFindCallback (onFindCallback ) , m_onCloseCallback(onCloseCallback) { setupUi(this); layout()->setSizeConstraint(QLayout::SetFixedSize); connect(findButton, SIGNAL(clicked(bool)), this, SLOT(onFindButton())); connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject())); connect(lineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(onWhatEdited(const QString&))); connect(matchCase, SIGNAL(stateChanged(int)), this, SLOT(onMatchCaseChanged(int))); connect(wholeWord, SIGNAL(stateChanged(int)), this, SLOT(onMatchWholeWordChanged(int))); connect(directionDown, SIGNAL(toggled(bool)), this, SLOT(onDirectionDownToggled(bool))); setAttribute(Qt::WA_DeleteOnClose, true); } FindDialog::~FindDialog() { m_onCloseCallback(); } void FindDialog::setSettings(CREF(Settings) settings) { m_settings = settings; lineEdit->setText(m_settings.what); lineEdit->setFocus(); lineEdit->selectAll(); matchCase->setChecked(m_settings.matchCase); wholeWord->setChecked(m_settings.matchWholeWord); if (m_settings.searchDown) { directionDown->setChecked(true); } else { directionUp->setChecked(true); } } void FindDialog::onFindButton() { m_onFindCallback(m_settings); } void FindDialog::onWhatEdited(const QString& text) { m_settings.what = text; } void FindDialog::onMatchCaseChanged(int value) { m_settings.matchCase = value ? true : false; } void FindDialog::onMatchWholeWordChanged(int value) { m_settings.matchWholeWord = value ? true : false; } void FindDialog::onDirectionDownToggled(bool checked) { m_settings.searchDown = checked; } <|endoftext|>
<commit_before>/* Copyright (C) 2003 by Eric Sunshine <sunshine@sunshineco.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; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/math.h" #include "csutil/parasiticdatabuffer.h" #include "csutil/platformfile.h" #include "csutil/physfile.h" #include "csutil/databuf.h" #include <stdlib.h> #include <sys/stat.h> class csPhysicalFile::PartialView : public scfImplementation1<PartialView, iFile> { csRef<csPhysicalFile> parent; size_t pos; size_t offset; size_t size; int status; public: PartialView (csPhysicalFile* parent, size_t offset, size_t size) : scfImplementationType (this), parent (parent), pos (0), offset (offset), size (size), status (VFS_STATUS_OK) {} char const* GetName(); size_t GetSize(); int GetStatus(); size_t Read(char* buffer, size_t nbytes); size_t Write(char const* data, size_t nbytes); void Flush(); bool AtEOF(); size_t GetPos(); bool SetPos(size_t); csPtr<iDataBuffer> GetAllData(bool nullterm = false); csPtr<iDataBuffer> GetAllData (CS::Memory::iAllocator* allocator); csPtr<iFile> GetPartialView (size_t offset, size_t size = (size_t)~0); }; int csPhysicalFile::GetStatus() { return last_error; } csPhysicalFile::csPhysicalFile(char const* apath, char const* mode) : scfImplementationType (this), fp(0), path(apath), owner(true), last_error(VFS_STATUS_OK) { struct stat buf; if (stat (apath, &buf)) { last_error = VFS_STATUS_OTHER; return; } if (!(buf.st_mode & S_IFREG)) { last_error = VFS_STATUS_OTHER; return; } fp = CS::Platform::File::Open (apath, mode); if (fp == 0) last_error = VFS_STATUS_ACCESSDENIED; } csPhysicalFile::csPhysicalFile(FILE* f, bool take_ownership, char const* n ) : scfImplementationType (this), fp(f), owner(take_ownership), last_error(VFS_STATUS_OK) { if (n != 0) path = n; if (fp == 0) last_error = VFS_STATUS_OTHER; } csPhysicalFile::~csPhysicalFile() { if (owner && fp != 0) fclose(fp); } size_t csPhysicalFile::Read(char* buff, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t rc = 0; if (fp != 0) { errno = 0; rc = fread(buff, 1, nbytes, fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return rc; } size_t csPhysicalFile::Write(char const* data, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t rc = 0; if (fp != 0) { errno = 0; rc = fwrite(data, 1, nbytes, fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return rc; } char const* csPhysicalFile::GetName() { if (!path.IsEmpty()) return path.GetData(); else return "#csPhysicalFile"; } size_t csPhysicalFile::GetSize() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t len = (size_t)-1; if (fp != 0) { errno = 0; size_t pos = ftell(fp); if (errno == 0 && fseek(fp, 0, SEEK_END) == 0) { len = ftell(fp); if (errno == 0) fseek(fp, (long)pos, SEEK_SET); } last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return len; } void csPhysicalFile::Flush() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); if (fp != 0) { int const rc = fflush(fp); last_error = (rc == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; } bool csPhysicalFile::AtEOF() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); bool rc; if (fp != 0) { rc = (feof(fp) != 0); last_error = VFS_STATUS_OK; } else { rc = true; last_error = VFS_STATUS_OTHER; } return rc; } size_t csPhysicalFile::GetPos() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t pos = (size_t)-1; if (fp != 0) { errno = 0; pos = ftell(fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return pos; } bool csPhysicalFile::SetPos(size_t p) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); bool ok = false; if (fp != 0) { errno = 0; fseek(fp, (long)p, SEEK_SET); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; ok = last_error == VFS_STATUS_OK; return ok; } csPtr<iDataBuffer> csPhysicalFile::GetAllData(bool nullterm) { csDataBuffer* data = 0; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nbytes = len + (nullterm ? 1 : 0); char* buff = new char[nbytes]; // csDataBuffer takes ownership. size_t const nread = Read(buff, len); if (GetStatus() == VFS_STATUS_OK) SetPos(pos); if (GetStatus() == VFS_STATUS_OK) { if (nullterm) buff[nread] = '\0'; data = new csDataBuffer(buff, nread + (nullterm ? 1 : 0)); } else delete[] buff; } } return csPtr<iDataBuffer>(data); } csPtr<iDataBuffer> csPhysicalFile::GetAllData(CS::Memory::iAllocator* allocator) { csRef<CS::DataBuffer<CS::Memory::AllocatorInterface> > data; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { data.AttachNew (new CS::DataBuffer<CS::Memory::AllocatorInterface> (len, CS::Memory::AllocatorInterface (allocator))); SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nread = Read(data->GetData(), len); if ((nread != len) || (GetStatus() != VFS_STATUS_OK)) data.Invalidate(); SetPos(pos); } } return csPtr<iDataBuffer>(data); } csPtr<iFile> csPhysicalFile::GetPartialView (size_t offset, size_t size) { if (!fp) return (iFile*)0; size_t const len = csMin (size, GetSize() - offset); return csPtr<iFile> (new PartialView (this, offset, len)); } //--------------------------------------------------------------------------- char const* csPhysicalFile::PartialView::GetName() { return parent->GetName(); } size_t csPhysicalFile::PartialView::GetSize() { status = VFS_STATUS_OK; return size; } int csPhysicalFile::PartialView::GetStatus() { return status; } size_t csPhysicalFile::PartialView::Read (char* buffer, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (parent->mutex); size_t readSize (csMin (nbytes, size - pos)); errno = 0; size_t oldPos (ftell (parent->fp)); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); if (status != VFS_STATUS_OK) return 0; errno = 0; fseek(parent->fp, (long)pos, SEEK_SET); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); if (status != VFS_STATUS_OK) { fseek(parent->fp, (long)oldPos, SEEK_SET); return 0; } errno = 0; size_t rc = fread (buffer, 1, readSize, parent->fp); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); fseek(parent->fp, (long)oldPos, SEEK_SET); pos += rc; return rc; } size_t csPhysicalFile::PartialView::Write(char const* data, size_t nbytes) { // Don't allow writing to views. status = VFS_STATUS_ACCESSDENIED; return 0; } void csPhysicalFile::PartialView::Flush() {} bool csPhysicalFile::PartialView::AtEOF() { return pos >= size; } size_t csPhysicalFile::PartialView::GetPos() { return pos; } bool csPhysicalFile::PartialView::SetPos(size_t p) { if (p > size) return false; pos = p; return true; } csPtr<iDataBuffer> csPhysicalFile::PartialView::GetAllData (bool nullterm) { csDataBuffer* data = 0; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nbytes = len + (nullterm ? 1 : 0); char* buff = new char[nbytes]; // csDataBuffer takes ownership. size_t const nread = Read(buff, len); if (GetStatus() == VFS_STATUS_OK) SetPos(pos); if (GetStatus() == VFS_STATUS_OK) { if (nullterm) buff[nread] = '\0'; data = new csDataBuffer(buff, nread + (nullterm ? 1 : 0)); } else delete[] buff; } } return csPtr<iDataBuffer>(data); } csPtr<iDataBuffer> csPhysicalFile::PartialView::GetAllData (CS::Memory::iAllocator* allocator) { csRef<CS::DataBuffer<CS::Memory::AllocatorInterface> > data; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { data.AttachNew (new CS::DataBuffer<CS::Memory::AllocatorInterface> (len, CS::Memory::AllocatorInterface (allocator))); SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nread = Read(data->GetData(), len); if ((nread != len) || (GetStatus() != VFS_STATUS_OK)) data.Invalidate(); SetPos(pos); } } return csPtr<iDataBuffer>(data); } csPtr<iFile> csPhysicalFile::PartialView::GetPartialView (size_t offset, size_t size) { size_t const len = csMin (size, GetSize() - offset); return parent->GetPartialView (this->offset + offset, len); } <commit_msg>csPhysicalFile: Make it possible to create files with it<commit_after>/* Copyright (C) 2003 by Eric Sunshine <sunshine@sunshineco.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; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/math.h" #include "csutil/parasiticdatabuffer.h" #include "csutil/platformfile.h" #include "csutil/physfile.h" #include "csutil/databuf.h" #include <stdlib.h> #include <sys/stat.h> class csPhysicalFile::PartialView : public scfImplementation1<PartialView, iFile> { csRef<csPhysicalFile> parent; size_t pos; size_t offset; size_t size; int status; public: PartialView (csPhysicalFile* parent, size_t offset, size_t size) : scfImplementationType (this), parent (parent), pos (0), offset (offset), size (size), status (VFS_STATUS_OK) {} char const* GetName(); size_t GetSize(); int GetStatus(); size_t Read(char* buffer, size_t nbytes); size_t Write(char const* data, size_t nbytes); void Flush(); bool AtEOF(); size_t GetPos(); bool SetPos(size_t); csPtr<iDataBuffer> GetAllData(bool nullterm = false); csPtr<iDataBuffer> GetAllData (CS::Memory::iAllocator* allocator); csPtr<iFile> GetPartialView (size_t offset, size_t size = (size_t)~0); }; int csPhysicalFile::GetStatus() { return last_error; } csPhysicalFile::csPhysicalFile(char const* apath, char const* mode) : scfImplementationType (this), fp(0), path(apath), owner(true), last_error(VFS_STATUS_OK) { bool file_must_exist (*mode == 'r'); if (file_must_exist) { struct stat buf; if (stat (apath, &buf)) { last_error = VFS_STATUS_OTHER; return; } if (!(buf.st_mode & S_IFREG)) { last_error = VFS_STATUS_OTHER; return; } } fp = CS::Platform::File::Open (apath, mode); if (fp == 0) last_error = VFS_STATUS_ACCESSDENIED; } csPhysicalFile::csPhysicalFile(FILE* f, bool take_ownership, char const* n ) : scfImplementationType (this), fp(f), owner(take_ownership), last_error(VFS_STATUS_OK) { if (n != 0) path = n; if (fp == 0) last_error = VFS_STATUS_OTHER; } csPhysicalFile::~csPhysicalFile() { if (owner && fp != 0) fclose(fp); } size_t csPhysicalFile::Read(char* buff, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t rc = 0; if (fp != 0) { errno = 0; rc = fread(buff, 1, nbytes, fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return rc; } size_t csPhysicalFile::Write(char const* data, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t rc = 0; if (fp != 0) { errno = 0; rc = fwrite(data, 1, nbytes, fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return rc; } char const* csPhysicalFile::GetName() { if (!path.IsEmpty()) return path.GetData(); else return "#csPhysicalFile"; } size_t csPhysicalFile::GetSize() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t len = (size_t)-1; if (fp != 0) { errno = 0; size_t pos = ftell(fp); if (errno == 0 && fseek(fp, 0, SEEK_END) == 0) { len = ftell(fp); if (errno == 0) fseek(fp, (long)pos, SEEK_SET); } last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return len; } void csPhysicalFile::Flush() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); if (fp != 0) { int const rc = fflush(fp); last_error = (rc == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; } bool csPhysicalFile::AtEOF() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); bool rc; if (fp != 0) { rc = (feof(fp) != 0); last_error = VFS_STATUS_OK; } else { rc = true; last_error = VFS_STATUS_OTHER; } return rc; } size_t csPhysicalFile::GetPos() { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); size_t pos = (size_t)-1; if (fp != 0) { errno = 0; pos = ftell(fp); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; return pos; } bool csPhysicalFile::SetPos(size_t p) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (mutex); bool ok = false; if (fp != 0) { errno = 0; fseek(fp, (long)p, SEEK_SET); last_error = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); } else last_error = VFS_STATUS_OTHER; ok = last_error == VFS_STATUS_OK; return ok; } csPtr<iDataBuffer> csPhysicalFile::GetAllData(bool nullterm) { csDataBuffer* data = 0; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nbytes = len + (nullterm ? 1 : 0); char* buff = new char[nbytes]; // csDataBuffer takes ownership. size_t const nread = Read(buff, len); if (GetStatus() == VFS_STATUS_OK) SetPos(pos); if (GetStatus() == VFS_STATUS_OK) { if (nullterm) buff[nread] = '\0'; data = new csDataBuffer(buff, nread + (nullterm ? 1 : 0)); } else delete[] buff; } } return csPtr<iDataBuffer>(data); } csPtr<iDataBuffer> csPhysicalFile::GetAllData(CS::Memory::iAllocator* allocator) { csRef<CS::DataBuffer<CS::Memory::AllocatorInterface> > data; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { data.AttachNew (new CS::DataBuffer<CS::Memory::AllocatorInterface> (len, CS::Memory::AllocatorInterface (allocator))); SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nread = Read(data->GetData(), len); if ((nread != len) || (GetStatus() != VFS_STATUS_OK)) data.Invalidate(); SetPos(pos); } } return csPtr<iDataBuffer>(data); } csPtr<iFile> csPhysicalFile::GetPartialView (size_t offset, size_t size) { if (!fp) return (iFile*)0; size_t const len = csMin (size, GetSize() - offset); return csPtr<iFile> (new PartialView (this, offset, len)); } //--------------------------------------------------------------------------- char const* csPhysicalFile::PartialView::GetName() { return parent->GetName(); } size_t csPhysicalFile::PartialView::GetSize() { status = VFS_STATUS_OK; return size; } int csPhysicalFile::PartialView::GetStatus() { return status; } size_t csPhysicalFile::PartialView::Read (char* buffer, size_t nbytes) { CS::Threading::ScopedLock<CS::Threading::Mutex> lock (parent->mutex); size_t readSize (csMin (nbytes, size - pos)); errno = 0; size_t oldPos (ftell (parent->fp)); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); if (status != VFS_STATUS_OK) return 0; errno = 0; fseek(parent->fp, (long)pos, SEEK_SET); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); if (status != VFS_STATUS_OK) { fseek(parent->fp, (long)oldPos, SEEK_SET); return 0; } errno = 0; size_t rc = fread (buffer, 1, readSize, parent->fp); status = (errno == 0 ? VFS_STATUS_OK : VFS_STATUS_IOERROR); fseek(parent->fp, (long)oldPos, SEEK_SET); pos += rc; return rc; } size_t csPhysicalFile::PartialView::Write(char const* data, size_t nbytes) { // Don't allow writing to views. status = VFS_STATUS_ACCESSDENIED; return 0; } void csPhysicalFile::PartialView::Flush() {} bool csPhysicalFile::PartialView::AtEOF() { return pos >= size; } size_t csPhysicalFile::PartialView::GetPos() { return pos; } bool csPhysicalFile::PartialView::SetPos(size_t p) { if (p > size) return false; pos = p; return true; } csPtr<iDataBuffer> csPhysicalFile::PartialView::GetAllData (bool nullterm) { csDataBuffer* data = 0; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nbytes = len + (nullterm ? 1 : 0); char* buff = new char[nbytes]; // csDataBuffer takes ownership. size_t const nread = Read(buff, len); if (GetStatus() == VFS_STATUS_OK) SetPos(pos); if (GetStatus() == VFS_STATUS_OK) { if (nullterm) buff[nread] = '\0'; data = new csDataBuffer(buff, nread + (nullterm ? 1 : 0)); } else delete[] buff; } } return csPtr<iDataBuffer>(data); } csPtr<iDataBuffer> csPhysicalFile::PartialView::GetAllData (CS::Memory::iAllocator* allocator) { csRef<CS::DataBuffer<CS::Memory::AllocatorInterface> > data; size_t const len = GetSize(); if (GetStatus() == VFS_STATUS_OK) { size_t const pos = GetPos(); if (GetStatus() == VFS_STATUS_OK) { data.AttachNew (new CS::DataBuffer<CS::Memory::AllocatorInterface> (len, CS::Memory::AllocatorInterface (allocator))); SetPos (0); if (GetStatus() != VFS_STATUS_OK) return (iDataBuffer*)nullptr; size_t const nread = Read(data->GetData(), len); if ((nread != len) || (GetStatus() != VFS_STATUS_OK)) data.Invalidate(); SetPos(pos); } } return csPtr<iDataBuffer>(data); } csPtr<iFile> csPhysicalFile::PartialView::GetPartialView (size_t offset, size_t size) { size_t const len = csMin (size, GetSize() - offset); return parent->GetPartialView (this->offset + offset, len); } <|endoftext|>
<commit_before>/* ** Copyright 2012 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon 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 ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <QSqlError> #include <QSqlQuery> #include <QVariant> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "test/cbd.hh" #include "test/config.hh" #include "test/engine.hh" #include "test/generate.hh" #include "test/misc.hh" #include "test/vars.hh" using namespace com::centreon::broker; #define DB_NAME "broker_tls_to_sql" /** * Check that encryption works on Broker stream. * * @return EXIT_SUCCESS on success. */ int main() { // Return value. int retval(EXIT_FAILURE); // Variables that need cleaning. std::list<host> hosts; std::list<service> services; std::string engine_config_path(tmpnam(NULL)); engine daemon; cbd broker; try { // Prepare database. QSqlDatabase db(config_db_open(DB_NAME)); // Prepare monitoring engine configuration parameters. generate_hosts(hosts, 10); generate_services(services, hosts, 5); std::string cbmod_loading; { std::ostringstream oss; oss << "broker_module=" << CBMOD_PATH << " " << PROJECT_SOURCE_DIR << "/test/cfg/tls_to_sql_1.xml\n"; cbmod_loading = oss.str(); } // Generate monitoring engine configuration files. config_write( engine_config_path.c_str(), cbmod_loading.c_str(), &hosts, &services); // Start Broker daemon. broker.set_config_file( PROJECT_SOURCE_DIR "/test/cfg/tls_to_sql_2.xml"); broker.start(); // Start engine. std::string engine_config_file(engine_config_path); engine_config_file.append("/nagios.cfg"); daemon.set_config_file(engine_config_file); daemon.start(); sleep_for(30 * MONITORING_ENGINE_INTERVAL_LENGTH); // Terminate monitoring engine. daemon.stop(); // Terminate Broker daemon. broker.stop(); // Check host count. { std::ostringstream query; query << "SELECT COUNT(host_id)" << " FROM hosts"; QSqlQuery q(db); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read host count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 10) || q.next()) throw (exceptions::msg() << "invalid host count"); } // Check service count. { std::ostringstream query; query << "SELECT COUNT(service_id)" << " FROM services"; QSqlQuery q(db); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read service count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 50) || q.next()) throw (exceptions::msg() << "invalid service count"); } // Success. retval = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } // Cleanup. daemon.stop(); broker.stop(); config_remove(engine_config_path.c_str()); config_db_close(DB_NAME); free_hosts(hosts); free_services(services); return (retval); } <commit_msg>Reduce TLS live unit test time.<commit_after>/* ** Copyright 2012 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon 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 ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <QSqlError> #include <QSqlQuery> #include <QVariant> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "test/cbd.hh" #include "test/config.hh" #include "test/engine.hh" #include "test/generate.hh" #include "test/misc.hh" #include "test/vars.hh" using namespace com::centreon::broker; #define DB_NAME "broker_tls_to_sql" /** * Check that encryption works on Broker stream. * * @return EXIT_SUCCESS on success. */ int main() { // Return value. int retval(EXIT_FAILURE); // Variables that need cleaning. std::list<host> hosts; std::list<service> services; std::string engine_config_path(tmpnam(NULL)); engine daemon; cbd broker; try { // Prepare database. QSqlDatabase db(config_db_open(DB_NAME)); // Prepare monitoring engine configuration parameters. generate_hosts(hosts, 10); generate_services(services, hosts, 5); std::string cbmod_loading; { std::ostringstream oss; oss << "broker_module=" << CBMOD_PATH << " " << PROJECT_SOURCE_DIR << "/test/cfg/tls_to_sql_1.xml\n"; cbmod_loading = oss.str(); } // Generate monitoring engine configuration files. config_write( engine_config_path.c_str(), cbmod_loading.c_str(), &hosts, &services); // Start Broker daemon. broker.set_config_file( PROJECT_SOURCE_DIR "/test/cfg/tls_to_sql_2.xml"); broker.start(); // Start engine. std::string engine_config_file(engine_config_path); engine_config_file.append("/nagios.cfg"); daemon.set_config_file(engine_config_file); daemon.start(); sleep_for(21 * MONITORING_ENGINE_INTERVAL_LENGTH); // Terminate monitoring engine. daemon.stop(); // Terminate Broker daemon. broker.stop(); // Check host count. { std::ostringstream query; query << "SELECT COUNT(host_id)" << " FROM hosts"; QSqlQuery q(db); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read host count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 10) || q.next()) throw (exceptions::msg() << "invalid host count"); } // Check service count. { std::ostringstream query; query << "SELECT COUNT(service_id)" << " FROM services"; QSqlQuery q(db); if (!q.exec(query.str().c_str())) throw (exceptions::msg() << "cannot read service count from DB: " << q.lastError().text().toStdString().c_str()); if (!q.next() || (q.value(0).toUInt() != 50) || q.next()) throw (exceptions::msg() << "invalid service count"); } // Success. retval = EXIT_SUCCESS; } catch (std::exception const& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } // Cleanup. daemon.stop(); broker.stop(); config_remove(engine_config_path.c_str()); config_db_close(DB_NAME); free_hosts(hosts); free_services(services); return (retval); } <|endoftext|>
<commit_before>/* libscratch - Multipurpose objective C++ library. Copyright (C) 2012 - 2013 Angelo Geels 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ #include <cstdio> // for printf #include <iostream> // for std::cin.get #include <Scratch.h> using namespace Scratch; static INDEX _ctTests = 0; static INDEX _ctFailed = 0; #define TEST(expr) { \ _ctTests++; \ printf(" Test #%d: (%s) ", _ctTests, #expr); \ if(!(expr)) { \ _ctFailed++; \ printf("FAILED!\n"); \ } else { \ printf("OK\n"); \ } \ } /// String testing void TestString() { printf("Testing strings\n"); CString strTest; strTest += "Lib"; strTest += "Scratch"; strTest = strTest.ToLower(); TEST(strTest == "libscratch"); strTest += " is great"; CStackArray<CString> astrParse = strTest.Split(" "); TEST(astrParse[2] == "great"); TEST(astrParse[2][1] == 'r'); CString strTest2 = strTest.Replace("great", "cool"); TEST(strTest2 == "libscratch is cool"); } /// Stack array testing void TestStackArray() { printf("Testing stack arrays\n"); CStackArray<INDEX> aiNumbers; TEST(aiNumbers.Count() == 0); aiNumbers.Push() = 5; aiNumbers.Push() = 10; aiNumbers.Push() = 15; TEST(aiNumbers.Count() == 3); TEST(aiNumbers[0] == 5); TEST(aiNumbers[1] == 10); TEST(aiNumbers[2] + aiNumbers[0] == 20); TEST(aiNumbers.Pop() == 15); TEST(aiNumbers.Count() == 2); } /// Dictionary testing void TestDictionary() { printf("Testing dictionary\n"); CDictionary<CString, INDEX> diTest; TEST(!diTest.HasKey("Test")); diTest["Test"] = 100; diTest["Test2"] = 200; TEST(diTest.HasKey("Test")); TEST(diTest["Test"] == 100); diTest.RemoveByKey("Test"); TEST(diTest.Count() == 1); TEST(!diTest.HasKey("Test")); } /// Test file stream void TestFilestream() { printf("Testing file streams\n"); // this test will create a Test.bin file, containing an integer 5 and the text "Hello!" CFileStream fsTest; fsTest.Open("Test.bin", "w"); fsTest << INDEX(5); fsTest << "Hello!"; fsTest.Close(); // as a follow-up, we will read the same file from a seperate file stream CFileStream fsTestRead; fsTestRead.Open("Test.bin", "r"); INDEX iTest = 0; fsTestRead >> iTest; TEST(iTest == 5); CString strTest; fsTestRead >> strTest; TEST(strTest == "Hello!"); // note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below fsTestRead.Close(); // remove the test file from the system unlink("Test.bin"); } /// Vector tests void TestVectors() { printf("Testing vectors\n"); Vector3f vTest(1, 0, 0); TEST(vTest.Length() == 1.0f); vTest *= 5.0f; TEST(vTest.Length() == 5.0f); vTest.x = 3; vTest.y = 4; TEST(vTest.Length() == 5.0f); vTest.Normalize(); TEST(vTest.Length() == 1.0f); } int main() { // perform tests TestString(); TestStackArray(); TestDictionary(); TestFilestream(); TestVectors(); // report test results printf("\n\nResults: %d out of %d went OK.\n\n", _ctTests - _ctFailed, _ctTests); // check if all went OK ASSERT(_ctFailed == 0); if(_ctFailed == 0) { // it did! no failures. :) printf("All OK!\n"); } std::cin.get(); return 0; } <commit_msg>Changed unlink to _unlink.<commit_after>/* libscratch - Multipurpose objective C++ library. Copyright (C) 2012 - 2013 Angelo Geels 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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/>. */ #include <cstdio> // for printf #include <iostream> // for std::cin.get #include <Scratch.h> using namespace Scratch; static INDEX _ctTests = 0; static INDEX _ctFailed = 0; #define TEST(expr) { \ _ctTests++; \ printf(" Test #%d: (%s) ", _ctTests, #expr); \ if(!(expr)) { \ _ctFailed++; \ printf("FAILED!\n"); \ } else { \ printf("OK\n"); \ } \ } /// String testing void TestString() { printf("Testing strings\n"); CString strTest; strTest += "Lib"; strTest += "Scratch"; strTest = strTest.ToLower(); TEST(strTest == "libscratch"); strTest += " is great"; CStackArray<CString> astrParse = strTest.Split(" "); TEST(astrParse[2] == "great"); TEST(astrParse[2][1] == 'r'); CString strTest2 = strTest.Replace("great", "cool"); TEST(strTest2 == "libscratch is cool"); } /// Stack array testing void TestStackArray() { printf("Testing stack arrays\n"); CStackArray<INDEX> aiNumbers; TEST(aiNumbers.Count() == 0); aiNumbers.Push() = 5; aiNumbers.Push() = 10; aiNumbers.Push() = 15; TEST(aiNumbers.Count() == 3); TEST(aiNumbers[0] == 5); TEST(aiNumbers[1] == 10); TEST(aiNumbers[2] + aiNumbers[0] == 20); TEST(aiNumbers.Pop() == 15); TEST(aiNumbers.Count() == 2); } /// Dictionary testing void TestDictionary() { printf("Testing dictionary\n"); CDictionary<CString, INDEX> diTest; TEST(!diTest.HasKey("Test")); diTest["Test"] = 100; diTest["Test2"] = 200; TEST(diTest.HasKey("Test")); TEST(diTest["Test"] == 100); diTest.RemoveByKey("Test"); TEST(diTest.Count() == 1); TEST(!diTest.HasKey("Test")); } /// Test file stream void TestFilestream() { printf("Testing file streams\n"); // this test will create a Test.bin file, containing an integer 5 and the text "Hello!" CFileStream fsTest; fsTest.Open("Test.bin", "w"); fsTest << INDEX(5); fsTest << "Hello!"; fsTest.Close(); // as a follow-up, we will read the same file from a seperate file stream CFileStream fsTestRead; fsTestRead.Open("Test.bin", "r"); INDEX iTest = 0; fsTestRead >> iTest; TEST(iTest == 5); CString strTest; fsTestRead >> strTest; TEST(strTest == "Hello!"); // note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below fsTestRead.Close(); // remove the test file from the system _unlink("Test.bin"); } /// Vector tests void TestVectors() { printf("Testing vectors\n"); Vector3f vTest(1, 0, 0); TEST(vTest.Length() == 1.0f); vTest *= 5.0f; TEST(vTest.Length() == 5.0f); vTest.x = 3; vTest.y = 4; TEST(vTest.Length() == 5.0f); vTest.Normalize(); TEST(vTest.Length() == 1.0f); } int main() { // perform tests TestString(); TestStackArray(); TestDictionary(); TestFilestream(); TestVectors(); // report test results printf("\n\nResults: %d out of %d went OK.\n\n", _ctTests - _ctFailed, _ctTests); // check if all went OK ASSERT(_ctFailed == 0); if(_ctFailed == 0) { // it did! no failures. :) printf("All OK!\n"); } std::cin.get(); return 0; } <|endoftext|>
<commit_before>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <minion.h> int main(int argc, char *argv[]) { const char *msg = "M^0001^1^108^彩票打印机脱机"; minion::MUdpSocket udpSocket; minion::MHostAddress addr("192.168.7.47", 8309); std::cout << addr << std::endl; std::cout << addr.ipv4() << std::endl; printf("%08x\n", addr.ipv4()); ssize_t len = udpSocket.sendto((const uint8_t *)msg, strlen(msg) + 1, addr); sleep(1); const char *dealing = "M^0001^2^ssq,2017105,101,1,2,1,XSLPT-20170828103056101729,00200001,2017-08-28 10:30,1"; len = udpSocket.sendto((const uint8_t *)dealing, strlen(dealing) + 1, addr); sleep(1); return 0; } <commit_msg>update new revision<commit_after>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <minion.h> int main(int argc, char *argv[]) { const char *msg = "M^0001^1^108^彩票打印机脱机"; minion::MUdpSocket udpSocket; minion::MHostAddress addr("192.168.7.47", 8309); ssize_t len = udpSocket.sendto((const uint8_t *)msg, strlen(msg) + 1, addr); std::cout << "len = " << len << std::endl; std::cout << "sendto " << std::endl; std::cout << addr << std::endl; std::cout << msg << std::endl; return 0; } <|endoftext|>
<commit_before>#include <limits> #include <omp.h> #include <stdint.h> #include <algorithm> #include <iostream> #include "boost/serialization/vector.hpp" #include "boost/serialization/utility.hpp" #include "GraphMatRuntime.h" #include "common.hpp" #ifdef GRANULA #include "granula.hpp" #endif using namespace std; struct vertex_value_type : public GraphMat::Serializable { public: int id; int triangles; std::vector<int> all_neighbors; std::vector<int> out_neighbors; double clustering_coef; //char* all_bitvector; //char* out_bitvector; public: vertex_value_type() { id = -1; triangles = 0; all_neighbors.clear(); out_neighbors.clear(); //all_bitvector = NULL; //out_bitvector = NULL; clustering_coef = 0.0; } vertex_value_type(double coef) { clustering_coef = coef; } bool operator!=(const vertex_value_type& t) const { return (t.triangles != this->triangles); //dummy } ~vertex_value_type() { all_neighbors.clear(); out_neighbors.clear(); triangles = 0; } friend ostream& operator<<(ostream& stream, const vertex_value_type &v) { stream << v.clustering_coef; return stream; } double get_output() { return clustering_coef; } friend boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & id; ar & triangles; ar & all_neighbors; ar & out_neighbors; ar & clustering_coef; } }; template<typename T> class serializable_vector : public GraphMat::Serializable { public: std::vector<T> v; public: friend boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & v; } }; typedef serializable_vector<int> collect_reduce_type; typedef int collect_msg_type; class CollectNeighborsOutProgram: public GraphMat::GraphProgram<collect_msg_type, collect_reduce_type, vertex_value_type> { public: int bitvector_size; const int num_neighbors_threshold = 1024; CollectNeighborsOutProgram(int maxvertices) { order = GraphMat::IN_EDGES; activity = GraphMat::ALL_VERTICES; process_message_requires_vertexprop = false; bitvector_size = (maxvertices)/8 + 1; //for safety } void reduce_function(collect_reduce_type& a, const collect_reduce_type& b) const { //assert(b.size() == 1); //a.push_back(b[0]); a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const collect_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, collect_reduce_type& res) const { res.v.clear(); res.v.push_back(message); } bool send_message(const vertex_value_type& vertexprop, collect_msg_type& message) const { message = vertexprop.id; return true; } void apply(const collect_reduce_type& message_out, vertex_value_type& vertexprop) { vertexprop.all_neighbors = message_out.v; vertexprop.out_neighbors = message_out.v; /*if (vertexprop.out_neighbors.size() > num_neighbors_threshold) { vertexprop.out_bitvector = new char[bitvector_size](); for (auto it = vertexprop.out_neighbors.begin(); it != vertexprop.out_neighbors.end(); ++it) { set_bit(*it, vertexprop.out_bitvector); } } else {*/ std::sort(vertexprop.out_neighbors.begin(), vertexprop.out_neighbors.end()); //} } }; class CollectNeighborsInProgram: public GraphMat::GraphProgram<collect_msg_type, collect_reduce_type, vertex_value_type> { public: int bitvector_size; const int num_neighbors_threshold = 1024; CollectNeighborsInProgram(int maxvertices) { order = GraphMat::OUT_EDGES; activity = GraphMat::ALL_VERTICES; process_message_requires_vertexprop = false; bitvector_size = (maxvertices)/8 + 1; //for safety } void reduce_function(collect_reduce_type& a, const collect_reduce_type& b) const { //assert(b.size() == 1); //a.push_back(b[0]); a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const collect_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, collect_reduce_type& res) const { res.v.clear(); res.v.push_back(message); } bool send_message(const vertex_value_type& vertexprop, collect_msg_type& message) const { message = vertexprop.id; return true; } void apply(const collect_reduce_type& message_out, vertex_value_type& vertexprop) { auto& all_neighbors = vertexprop.all_neighbors; all_neighbors.insert(all_neighbors.end(), message_out.v.begin(), message_out.v.end()); /*if (vertexprop.all_neighbors.size() > num_neighbors_threshold) { vertexprop.all_bitvector = new char[bitvector_size](); for (auto it = vertexprop.all_neighbors.begin(); it != vertexprop.all_neighbors.end(); ++it) { set_bit(*it, vertexprop.all_bitvector); } } else {*/ std::sort(all_neighbors.begin(), all_neighbors.end()); auto last = unique(all_neighbors.begin(), all_neighbors.end()); all_neighbors.erase(last, all_neighbors.end()); //} } }; //typedef int count_reduce_type; typedef vertex_value_type count_msg_type; //typedef const vertex_value_type* count_msg_type; //typedef vertex_value_type count_msg_type; //typedef serializable_vector<int> count_msg_type; typedef serializable_vector<pair< int, int> > count_reduce_type; class CountTrianglesProgram: public GraphMat::GraphProgram<count_msg_type, count_reduce_type, vertex_value_type> { public: CountTrianglesProgram() { order = GraphMat::ALL_EDGES; activity = GraphMat::ALL_VERTICES; } void reduce_function(count_reduce_type& a, const count_reduce_type& b) const { //v += w; a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const count_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, count_reduce_type& res) const { //count_reduce_type tri = 0; int tri = 0; //const vertex_value_type& neighbor = *message; const vertex_value_type& neighbor(message); /*char* bv; std::vector<int>::const_iterator itb, ite; if (vertexprop.all_bitvector != NULL) { bv = vertexprop.all_bitvector; itb = neighbor.out_neighbors.begin(); ite = neighbor.out_neighbors.end(); for (auto it = itb; it != ite; ++it) { tri += get_bit(*it, bv); } } else if (neighbor.out_bitvector != NULL) { bv = neighbor.out_bitvector; itb = vertexprop.all_neighbors.begin(); ite = vertexprop.all_neighbors.end(); for (auto it = itb; it != ite; ++it) { tri += get_bit(*it, bv); } } else {*/ int it1 = 0, it2 = 0; int it1_end = neighbor.out_neighbors.size(); //int it1_end = message.v.size(); int it2_end = vertexprop.all_neighbors.size(); while (it1 != it1_end && it2 != it2_end){ //if (message.v[it1] == vertexprop.all_neighbors[it2]) { if (neighbor.out_neighbors[it1] == vertexprop.all_neighbors[it2]) { tri++; ++it1; ++it2; //} else if (message.v[it1] < vertexprop.all_neighbors[it2]) { } else if (neighbor.out_neighbors[it1] < vertexprop.all_neighbors[it2]) { ++it1; } else { ++it2; } } //} //res = tri; int id = neighbor.id; auto x = make_pair(id, tri); res.v.clear(); res.v.push_back(x); return; } bool send_message(const vertex_value_type& vertexprop, count_msg_type& message) const { message = vertexprop; //message.v = vertexprop.out_neighbors; return true; } void apply(const count_reduce_type& message_out, vertex_value_type& vertexprop) { //vertexprop.triangles = message_out; auto v = message_out.v; std::sort(v.begin(), v.end()); auto last = unique(v.begin(), v.end()); int sum_of_elems = 0; std::for_each(v.begin(), last, [&] (pair<int, int> n) { sum_of_elems += n.second; }); vertexprop.triangles = sum_of_elems; int deg = vertexprop.all_neighbors.size(); //vertexprop.clustering_coef = (deg > 1)?(2.0*(double)message_out/(double)(deg*(deg-1))):(0.0); vertexprop.clustering_coef = (deg > 1)?((double)vertexprop.triangles/(double)(deg)/(double)(deg-1)):(0.0); } }; int main(int argc, char *argv[]) { #ifdef GRANULA granula::startMonitorProcess(getpid()); #endif if (argc < 3) { cerr << "usage: " << argv[0] << " <graph file> <isDirected> [output file]" << endl; return EXIT_FAILURE; } MPI_Init(&argc, &argv); char *filename = argv[1]; int isDirected = atoi(argv[2]); char *output = argc > 3 ? argv[3] : NULL; int nthreads = omp_get_max_threads(); cout << "num. threads: " << nthreads << endl; #ifdef GRANULA granula::linkNode(jobId); granula::linkProcess(getpid(), jobId); granula::operation graphmatJob("GraphMat", "Id.Unique", "Job", "Id.Unique"); cout<<graphmatJob.getOperationInfo("StartTime", graphmatJob.getEpoch())<<endl; granula::operation loadGraph("GraphMat", "Id.Unique", "LoadGraph", "Id.Unique"); cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl; #endif timer_start(); timer_next("load graph"); GraphMat::Graph<vertex_value_type, int> graph; graph.ReadMTX(filename); #ifdef GRANULA cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl; #endif timer_next("initialize engine"); for (size_t i = 1; i <= graph.getNumberOfVertices(); i++) { if (graph.vertexNodeOwner(i)) { vertex_value_type v; v.id = i; graph.setVertexproperty(i, v); } } CollectNeighborsOutProgram col_prog_out(graph.nvertices); CollectNeighborsInProgram col_prog_in(graph.nvertices); CountTrianglesProgram cnt_prog; auto col_ctx_out = GraphMat::graph_program_init(col_prog_out, graph); auto col_ctx_in = GraphMat::graph_program_init(col_prog_in, graph); auto cnt_ctx = GraphMat::graph_program_init(cnt_prog, graph); #ifdef GRANULA granula::operation processGraph("GraphMat", "Id.Unique", "ProcessGraph", "Id.Unique"); cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("run algorithm 1 - phase 1 & 2 (collect neighbors)"); GraphMat::run_graph_program(&col_prog_out, graph, 1, &col_ctx_out); GraphMat::run_graph_program(&col_prog_in, graph, 1, &col_ctx_in); timer_next("run algorithm 2 (count triangles)"); GraphMat::run_graph_program(&cnt_prog, graph, 1, &cnt_ctx); #ifdef GRANULA cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif #ifdef GRANULA granula::operation offloadGraph("GraphMat", "Id.Unique", "OffloadGraph", "Id.Unique"); cout<<offloadGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("print output"); //print_graph(output, graph); print_graph<vertex_value_type, int, double>(output, graph, MPI_DOUBLE); /*MPI_Barrier(MPI_COMM_WORLD); for (int i = 1; i <= graph.getNumberOfVertices(); i++) { if (graph.vertexNodeOwner(i)) { printf("%d %f %d\n", i-1, graph.getVertexproperty(i).clustering_coef, graph.getVertexproperty(i).all_neighbors.size()); } fflush(stdout); MPI_Barrier(MPI_COMM_WORLD); }*/ #ifdef GRANULA cout<<offloadGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif timer_next("deinitialize engine"); GraphMat::graph_program_clear(col_ctx_out); GraphMat::graph_program_clear(col_ctx_in); GraphMat::graph_program_clear(cnt_ctx); timer_end(); #ifdef GRANULA cout<<graphmatJob.getOperationInfo("EndTime", graphmatJob.getEpoch())<<endl; granula::stopMonitorProcess(getpid()); #endif MPI_Finalize(); return EXIT_SUCCESS; } <commit_msg>Fix potential LCC input argument issues.<commit_after>#include <limits> #include <omp.h> #include <stdint.h> #include <algorithm> #include <iostream> #include "boost/serialization/vector.hpp" #include "boost/serialization/utility.hpp" #include "GraphMatRuntime.h" #include "common.hpp" #ifdef GRANULA #include "granula.hpp" #endif using namespace std; struct vertex_value_type : public GraphMat::Serializable { public: int id; int triangles; std::vector<int> all_neighbors; std::vector<int> out_neighbors; double clustering_coef; //char* all_bitvector; //char* out_bitvector; public: vertex_value_type() { id = -1; triangles = 0; all_neighbors.clear(); out_neighbors.clear(); //all_bitvector = NULL; //out_bitvector = NULL; clustering_coef = 0.0; } vertex_value_type(double coef) { clustering_coef = coef; } bool operator!=(const vertex_value_type& t) const { return (t.triangles != this->triangles); //dummy } ~vertex_value_type() { all_neighbors.clear(); out_neighbors.clear(); triangles = 0; } friend ostream& operator<<(ostream& stream, const vertex_value_type &v) { stream << v.clustering_coef; return stream; } double get_output() { return clustering_coef; } friend boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & id; ar & triangles; ar & all_neighbors; ar & out_neighbors; ar & clustering_coef; } }; template<typename T> class serializable_vector : public GraphMat::Serializable { public: std::vector<T> v; public: friend boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & v; } }; typedef serializable_vector<int> collect_reduce_type; typedef int collect_msg_type; class CollectNeighborsOutProgram: public GraphMat::GraphProgram<collect_msg_type, collect_reduce_type, vertex_value_type> { public: int bitvector_size; const int num_neighbors_threshold = 1024; CollectNeighborsOutProgram(int maxvertices) { order = GraphMat::IN_EDGES; activity = GraphMat::ALL_VERTICES; process_message_requires_vertexprop = false; bitvector_size = (maxvertices)/8 + 1; //for safety } void reduce_function(collect_reduce_type& a, const collect_reduce_type& b) const { //assert(b.size() == 1); //a.push_back(b[0]); a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const collect_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, collect_reduce_type& res) const { res.v.clear(); res.v.push_back(message); } bool send_message(const vertex_value_type& vertexprop, collect_msg_type& message) const { message = vertexprop.id; return true; } void apply(const collect_reduce_type& message_out, vertex_value_type& vertexprop) { vertexprop.all_neighbors = message_out.v; vertexprop.out_neighbors = message_out.v; /*if (vertexprop.out_neighbors.size() > num_neighbors_threshold) { vertexprop.out_bitvector = new char[bitvector_size](); for (auto it = vertexprop.out_neighbors.begin(); it != vertexprop.out_neighbors.end(); ++it) { set_bit(*it, vertexprop.out_bitvector); } } else {*/ std::sort(vertexprop.out_neighbors.begin(), vertexprop.out_neighbors.end()); //} } }; class CollectNeighborsInProgram: public GraphMat::GraphProgram<collect_msg_type, collect_reduce_type, vertex_value_type> { public: int bitvector_size; const int num_neighbors_threshold = 1024; CollectNeighborsInProgram(int maxvertices) { order = GraphMat::OUT_EDGES; activity = GraphMat::ALL_VERTICES; process_message_requires_vertexprop = false; bitvector_size = (maxvertices)/8 + 1; //for safety } void reduce_function(collect_reduce_type& a, const collect_reduce_type& b) const { //assert(b.size() == 1); //a.push_back(b[0]); a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const collect_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, collect_reduce_type& res) const { res.v.clear(); res.v.push_back(message); } bool send_message(const vertex_value_type& vertexprop, collect_msg_type& message) const { message = vertexprop.id; return true; } void apply(const collect_reduce_type& message_out, vertex_value_type& vertexprop) { auto& all_neighbors = vertexprop.all_neighbors; all_neighbors.insert(all_neighbors.end(), message_out.v.begin(), message_out.v.end()); /*if (vertexprop.all_neighbors.size() > num_neighbors_threshold) { vertexprop.all_bitvector = new char[bitvector_size](); for (auto it = vertexprop.all_neighbors.begin(); it != vertexprop.all_neighbors.end(); ++it) { set_bit(*it, vertexprop.all_bitvector); } } else {*/ std::sort(all_neighbors.begin(), all_neighbors.end()); auto last = unique(all_neighbors.begin(), all_neighbors.end()); all_neighbors.erase(last, all_neighbors.end()); //} } }; //typedef int count_reduce_type; typedef vertex_value_type count_msg_type; //typedef const vertex_value_type* count_msg_type; //typedef vertex_value_type count_msg_type; //typedef serializable_vector<int> count_msg_type; typedef serializable_vector<pair< int, int> > count_reduce_type; class CountTrianglesProgram: public GraphMat::GraphProgram<count_msg_type, count_reduce_type, vertex_value_type> { public: CountTrianglesProgram() { order = GraphMat::ALL_EDGES; activity = GraphMat::ALL_VERTICES; } void reduce_function(count_reduce_type& a, const count_reduce_type& b) const { //v += w; a.v.insert(a.v.end(), b.v.begin(), b.v.end()); } void process_message(const count_msg_type& message, const int edge_val, const vertex_value_type& vertexprop, count_reduce_type& res) const { //count_reduce_type tri = 0; int tri = 0; //const vertex_value_type& neighbor = *message; const vertex_value_type& neighbor(message); /*char* bv; std::vector<int>::const_iterator itb, ite; if (vertexprop.all_bitvector != NULL) { bv = vertexprop.all_bitvector; itb = neighbor.out_neighbors.begin(); ite = neighbor.out_neighbors.end(); for (auto it = itb; it != ite; ++it) { tri += get_bit(*it, bv); } } else if (neighbor.out_bitvector != NULL) { bv = neighbor.out_bitvector; itb = vertexprop.all_neighbors.begin(); ite = vertexprop.all_neighbors.end(); for (auto it = itb; it != ite; ++it) { tri += get_bit(*it, bv); } } else {*/ int it1 = 0, it2 = 0; int it1_end = neighbor.out_neighbors.size(); //int it1_end = message.v.size(); int it2_end = vertexprop.all_neighbors.size(); while (it1 != it1_end && it2 != it2_end){ //if (message.v[it1] == vertexprop.all_neighbors[it2]) { if (neighbor.out_neighbors[it1] == vertexprop.all_neighbors[it2]) { tri++; ++it1; ++it2; //} else if (message.v[it1] < vertexprop.all_neighbors[it2]) { } else if (neighbor.out_neighbors[it1] < vertexprop.all_neighbors[it2]) { ++it1; } else { ++it2; } } //} //res = tri; int id = neighbor.id; auto x = make_pair(id, tri); res.v.clear(); res.v.push_back(x); return; } bool send_message(const vertex_value_type& vertexprop, count_msg_type& message) const { message = vertexprop; //message.v = vertexprop.out_neighbors; return true; } void apply(const count_reduce_type& message_out, vertex_value_type& vertexprop) { //vertexprop.triangles = message_out; auto v = message_out.v; std::sort(v.begin(), v.end()); auto last = unique(v.begin(), v.end()); int sum_of_elems = 0; std::for_each(v.begin(), last, [&] (pair<int, int> n) { sum_of_elems += n.second; }); vertexprop.triangles = sum_of_elems; int deg = vertexprop.all_neighbors.size(); //vertexprop.clustering_coef = (deg > 1)?(2.0*(double)message_out/(double)(deg*(deg-1))):(0.0); vertexprop.clustering_coef = (deg > 1)?((double)vertexprop.triangles/(double)(deg)/(double)(deg-1)):(0.0); } }; int main(int argc, char *argv[]) { #ifdef GRANULA granula::startMonitorProcess(getpid()); #endif if (argc < 4) { cerr << "usage: " << argv[0] << " <graph file> <job id> <isDirected> [output file]" << endl; return EXIT_FAILURE; } MPI_Init(&argc, &argv); char *filename = argv[1]; string jobId = argc > 2 ? argv[2] : "DefaultJobId"; int isDirected = argc > 3 ? atoi(argv[3]) : NULL; char *output = argc > 4 ? argv[4] : NULL; int nthreads = omp_get_max_threads(); cout << "num. threads: " << nthreads << endl; #ifdef GRANULA granula::linkNode(jobId); granula::linkProcess(getpid(), jobId); granula::operation graphmatJob("GraphMat", "Id.Unique", "Job", "Id.Unique"); cout<<graphmatJob.getOperationInfo("StartTime", graphmatJob.getEpoch())<<endl; granula::operation loadGraph("GraphMat", "Id.Unique", "LoadGraph", "Id.Unique"); cout<<loadGraph.getOperationInfo("StartTime", loadGraph.getEpoch())<<endl; #endif timer_start(); timer_next("load graph"); GraphMat::Graph<vertex_value_type, int> graph; graph.ReadMTX(filename); #ifdef GRANULA cout<<loadGraph.getOperationInfo("EndTime", loadGraph.getEpoch())<<endl; #endif timer_next("initialize engine"); for (size_t i = 1; i <= graph.getNumberOfVertices(); i++) { if (graph.vertexNodeOwner(i)) { vertex_value_type v; v.id = i; graph.setVertexproperty(i, v); } } CollectNeighborsOutProgram col_prog_out(graph.nvertices); CollectNeighborsInProgram col_prog_in(graph.nvertices); CountTrianglesProgram cnt_prog; auto col_ctx_out = GraphMat::graph_program_init(col_prog_out, graph); auto col_ctx_in = GraphMat::graph_program_init(col_prog_in, graph); auto cnt_ctx = GraphMat::graph_program_init(cnt_prog, graph); #ifdef GRANULA granula::operation processGraph("GraphMat", "Id.Unique", "ProcessGraph", "Id.Unique"); cout<<processGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("run algorithm 1 - phase 1 & 2 (collect neighbors)"); GraphMat::run_graph_program(&col_prog_out, graph, 1, &col_ctx_out); GraphMat::run_graph_program(&col_prog_in, graph, 1, &col_ctx_in); timer_next("run algorithm 2 (count triangles)"); GraphMat::run_graph_program(&cnt_prog, graph, 1, &cnt_ctx); #ifdef GRANULA cout<<processGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif #ifdef GRANULA granula::operation offloadGraph("GraphMat", "Id.Unique", "OffloadGraph", "Id.Unique"); cout<<offloadGraph.getOperationInfo("StartTime", processGraph.getEpoch())<<endl; #endif timer_next("print output"); //print_graph(output, graph); print_graph<vertex_value_type, int, double>(output, graph, MPI_DOUBLE); /*MPI_Barrier(MPI_COMM_WORLD); for (int i = 1; i <= graph.getNumberOfVertices(); i++) { if (graph.vertexNodeOwner(i)) { printf("%d %f %d\n", i-1, graph.getVertexproperty(i).clustering_coef, graph.getVertexproperty(i).all_neighbors.size()); } fflush(stdout); MPI_Barrier(MPI_COMM_WORLD); }*/ #ifdef GRANULA cout<<offloadGraph.getOperationInfo("EndTime", processGraph.getEpoch())<<endl; #endif timer_next("deinitialize engine"); GraphMat::graph_program_clear(col_ctx_out); GraphMat::graph_program_clear(col_ctx_in); GraphMat::graph_program_clear(cnt_ctx); timer_end(); #ifdef GRANULA cout<<graphmatJob.getOperationInfo("EndTime", graphmatJob.getEpoch())<<endl; granula::stopMonitorProcess(getpid()); #endif MPI_Finalize(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2016 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "cql3/statements/create_type_statement.hh" #include "prepared_statement.hh" #include "database.hh" #include "service/migration_manager.hh" #include "user_types_metadata.hh" namespace cql3 { namespace statements { create_type_statement::create_type_statement(const ut_name& name, bool if_not_exists) : _name{name} , _if_not_exists{if_not_exists} { } void create_type_statement::prepare_keyspace(const service::client_state& state) { if (!_name.has_keyspace()) { _name.set_keyspace(state.get_keyspace()); } } void create_type_statement::add_definition(::shared_ptr<column_identifier> name, ::shared_ptr<cql3_type::raw> type) { _column_names.emplace_back(name); _column_types.emplace_back(type); } future<> create_type_statement::check_access(const service::client_state& state) { return state.has_keyspace_access(keyspace(), auth::permission::CREATE); } inline bool create_type_statement::type_exists_in(::keyspace& ks) { auto&& keyspace_types = ks.metadata()->user_types()->get_all_types(); return keyspace_types.find(_name.get_user_type_name()) != keyspace_types.end(); } void create_type_statement::validate(service::storage_proxy& proxy, const service::client_state& state) { try { auto&& ks = proxy.get_db().local().find_keyspace(keyspace()); if (type_exists_in(ks) && !_if_not_exists) { throw exceptions::invalid_request_exception(format("A user type of name {} already exists", _name.to_string())); } } catch (no_such_keyspace& e) { throw exceptions::invalid_request_exception(format("Cannot add type in unknown keyspace {}", keyspace())); } if (_column_types.size() > max_udt_fields) { throw exceptions::invalid_request_exception(format("A user type cannot have more than {} fields", max_udt_fields)); } for (auto&& type : _column_types) { if (type->is_counter()) { throw exceptions::invalid_request_exception(format("A user type cannot contain counters")); } } } void create_type_statement::check_for_duplicate_names(user_type type) { auto names = type->field_names(); for (auto i = names.cbegin(); i < names.cend() - 1; ++i) { for (auto j = i + 1; j < names.cend(); ++j) { if (*i == *j) { throw exceptions::invalid_request_exception( format("Duplicate field name {} in type {}", to_hex(*i), type->get_name_as_string())); } } } } const sstring& create_type_statement::keyspace() const { return _name.get_keyspace(); } inline user_type create_type_statement::create_type(database& db) { std::vector<bytes> field_names; std::vector<data_type> field_types; for (auto&& column_name : _column_names) { field_names.push_back(column_name->name()); } for (auto&& column_type : _column_types) { field_types.push_back(column_type->prepare(db, keyspace()).get_type()); } return user_type_impl::get_instance(keyspace(), _name.get_user_type_name(), std::move(field_names), std::move(field_types), false); } future<shared_ptr<cql_transport::event::schema_change>> create_type_statement::announce_migration(service::storage_proxy& proxy, bool is_local_only) { auto&& db = proxy.get_db().local(); // Keyspace exists or we wouldn't have validated otherwise auto&& ks = db.find_keyspace(keyspace()); // Can happen with if_not_exists if (type_exists_in(ks)) { return make_ready_future<::shared_ptr<cql_transport::event::schema_change>>(); } auto type = create_type(db); check_for_duplicate_names(type); return service::get_local_migration_manager().announce_new_type(type, is_local_only).then([this] { using namespace cql_transport; return make_shared<event::schema_change>( event::schema_change::change_type::CREATED, event::schema_change::target_type::TYPE, keyspace(), _name.get_string_type_name()); }); } std::unique_ptr<cql3::statements::prepared_statement> create_type_statement::prepare(database& db, cql_stats& stats) { return std::make_unique<prepared_statement>(make_shared<create_type_statement>(*this)); } } } <commit_msg>cql3: check for nested non-frozen UDTs in create_type_statement.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2016 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "cql3/statements/create_type_statement.hh" #include "prepared_statement.hh" #include "database.hh" #include "service/migration_manager.hh" #include "user_types_metadata.hh" namespace cql3 { namespace statements { create_type_statement::create_type_statement(const ut_name& name, bool if_not_exists) : _name{name} , _if_not_exists{if_not_exists} { } void create_type_statement::prepare_keyspace(const service::client_state& state) { if (!_name.has_keyspace()) { _name.set_keyspace(state.get_keyspace()); } } void create_type_statement::add_definition(::shared_ptr<column_identifier> name, ::shared_ptr<cql3_type::raw> type) { _column_names.emplace_back(name); _column_types.emplace_back(type); } future<> create_type_statement::check_access(const service::client_state& state) { return state.has_keyspace_access(keyspace(), auth::permission::CREATE); } inline bool create_type_statement::type_exists_in(::keyspace& ks) { auto&& keyspace_types = ks.metadata()->user_types()->get_all_types(); return keyspace_types.find(_name.get_user_type_name()) != keyspace_types.end(); } void create_type_statement::validate(service::storage_proxy& proxy, const service::client_state& state) { try { auto&& ks = proxy.get_db().local().find_keyspace(keyspace()); if (type_exists_in(ks) && !_if_not_exists) { throw exceptions::invalid_request_exception(format("A user type of name {} already exists", _name.to_string())); } } catch (no_such_keyspace& e) { throw exceptions::invalid_request_exception(format("Cannot add type in unknown keyspace {}", keyspace())); } if (_column_types.size() > max_udt_fields) { throw exceptions::invalid_request_exception(format("A user type cannot have more than {} fields", max_udt_fields)); } for (auto&& type : _column_types) { if (type->is_counter()) { throw exceptions::invalid_request_exception("A user type cannot contain counters"); } if (type->is_user_type() && !type->is_frozen()) { throw exceptions::invalid_request_exception("A user type cannot contain non-frozen user type fields"); } } } void create_type_statement::check_for_duplicate_names(user_type type) { auto names = type->field_names(); for (auto i = names.cbegin(); i < names.cend() - 1; ++i) { for (auto j = i + 1; j < names.cend(); ++j) { if (*i == *j) { throw exceptions::invalid_request_exception( format("Duplicate field name {} in type {}", to_hex(*i), type->get_name_as_string())); } } } } const sstring& create_type_statement::keyspace() const { return _name.get_keyspace(); } inline user_type create_type_statement::create_type(database& db) { std::vector<bytes> field_names; std::vector<data_type> field_types; for (auto&& column_name : _column_names) { field_names.push_back(column_name->name()); } for (auto&& column_type : _column_types) { field_types.push_back(column_type->prepare(db, keyspace()).get_type()); } return user_type_impl::get_instance(keyspace(), _name.get_user_type_name(), std::move(field_names), std::move(field_types), false); } future<shared_ptr<cql_transport::event::schema_change>> create_type_statement::announce_migration(service::storage_proxy& proxy, bool is_local_only) { auto&& db = proxy.get_db().local(); // Keyspace exists or we wouldn't have validated otherwise auto&& ks = db.find_keyspace(keyspace()); // Can happen with if_not_exists if (type_exists_in(ks)) { return make_ready_future<::shared_ptr<cql_transport::event::schema_change>>(); } auto type = create_type(db); check_for_duplicate_names(type); return service::get_local_migration_manager().announce_new_type(type, is_local_only).then([this] { using namespace cql_transport; return make_shared<event::schema_change>( event::schema_change::change_type::CREATED, event::schema_change::target_type::TYPE, keyspace(), _name.get_string_type_name()); }); } std::unique_ptr<cql3::statements::prepared_statement> create_type_statement::prepare(database& db, cql_stats& stats) { return std::make_unique<prepared_statement>(make_shared<create_type_statement>(*this)); } } } <|endoftext|>
<commit_before>/** * \file * \brief DeferredThreadDeleter class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ #include "distortos/distortosConfiguration.h" #ifdef CONFIG_THREAD_DETACH_ENABLE #include "distortos/Mutex.hpp" namespace distortos { namespace internal { /// DeferredThreadDeleter class can be used to defer deletion of dynamic detached threads class DeferredThreadDeleter { public: /** * \brief DeferredThreadDeleter's constructor */ constexpr DeferredThreadDeleter() : list_{}, mutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, notEmpty_{} { } /** * \brief DeferredThreadDeleter's function call operator * * Adds thread to internal list of threads scheduled for deferred deletion and marks the list as "not empty". * * \note The object must be locked (with a successful call to DeferredThreadDeleter::lock()) before this function is * used! * * \param [in] threadControlBlock is a reference to ThreadControlBlock object associated with dynamic and detached * thread that has terminated its execution * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::unlock(); */ int operator()(ThreadControlBlock& threadControlBlock); /** * \brief Locks the object, preparing it for adding thread to internal list. * * Locks the mutex that synchronizes access to internal list. Locking (performed in this function) and unlocking * (performed at the end of function call operator) are separated, because the locking must be done while the thread * is still runnable, while the transfer to internal list is performed when the thread is not in this state. * * \note This function must be called before function call operator is used! * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::lock(); */ int lock(); /** * \brief Tries to perform deferred deletion of threads. * * Does nothing is the list is not marked as "not empty". Otherwise this function first tries to lock following two * mutexes: * - mutex that protects dynamic memory allocator; * - mutex that synchronizes access to list of threads scheduled for deferred deletion; * If any Mutex::tryLock() call fails, this function just returns (unlocking any mutexes is necessary). Otherwise * the threads are removed from the list and deleted, while the list's "not empty" marker is cleared. * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::tryLock(); * - error codes returned by Mutex::unlock(); */ int tryCleanup(); private: /** * \brief Internals of tryCleanup(). * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::tryLock(); * - error codes returned by Mutex::unlock(); */ int tryCleanupInternal(); /// list of threads scheduled for deferred deletion ThreadList::UnsortedIntrusiveList list_; /// mutex that synchronizes access to the \a list_ Mutex mutex_; /// true if \a list_ is not empty, false otherwise bool notEmpty_; }; } // namespace internal } // namespace distortos #endif // def CONFIG_THREAD_DETACH_ENABLE #endif // INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ <commit_msg>Declare DeferredThreadDeleter::notEmpty_ as volatile<commit_after>/** * \file * \brief DeferredThreadDeleter class header * * \author Copyright (C) 2015-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ #define INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ #include "distortos/distortosConfiguration.h" #ifdef CONFIG_THREAD_DETACH_ENABLE #include "distortos/Mutex.hpp" namespace distortos { namespace internal { /// DeferredThreadDeleter class can be used to defer deletion of dynamic detached threads class DeferredThreadDeleter { public: /** * \brief DeferredThreadDeleter's constructor */ constexpr DeferredThreadDeleter() : list_{}, mutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance}, notEmpty_{} { } /** * \brief DeferredThreadDeleter's function call operator * * Adds thread to internal list of threads scheduled for deferred deletion and marks the list as "not empty". * * \note The object must be locked (with a successful call to DeferredThreadDeleter::lock()) before this function is * used! * * \param [in] threadControlBlock is a reference to ThreadControlBlock object associated with dynamic and detached * thread that has terminated its execution * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::unlock(); */ int operator()(ThreadControlBlock& threadControlBlock); /** * \brief Locks the object, preparing it for adding thread to internal list. * * Locks the mutex that synchronizes access to internal list. Locking (performed in this function) and unlocking * (performed at the end of function call operator) are separated, because the locking must be done while the thread * is still runnable, while the transfer to internal list is performed when the thread is not in this state. * * \note This function must be called before function call operator is used! * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::lock(); */ int lock(); /** * \brief Tries to perform deferred deletion of threads. * * Does nothing is the list is not marked as "not empty". Otherwise this function first tries to lock following two * mutexes: * - mutex that protects dynamic memory allocator; * - mutex that synchronizes access to list of threads scheduled for deferred deletion; * If any Mutex::tryLock() call fails, this function just returns (unlocking any mutexes is necessary). Otherwise * the threads are removed from the list and deleted, while the list's "not empty" marker is cleared. * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::tryLock(); * - error codes returned by Mutex::unlock(); */ int tryCleanup(); private: /** * \brief Internals of tryCleanup(). * * \return 0 on success, error code otherwise: * - error codes returned by Mutex::tryLock(); * - error codes returned by Mutex::unlock(); */ int tryCleanupInternal(); /// list of threads scheduled for deferred deletion ThreadList::UnsortedIntrusiveList list_; /// mutex that synchronizes access to the \a list_ Mutex mutex_; /// true if \a list_ is not empty, false otherwise volatile bool notEmpty_; }; } // namespace internal } // namespace distortos #endif // def CONFIG_THREAD_DETACH_ENABLE #endif // INCLUDE_DISTORTOS_INTERNAL_MEMORY_DEFERREDTHREADDELETER_HPP_ <|endoftext|>
<commit_before>/** * File : A.cpp * Author : Kazune Takahashi * Created : 2018-2-17 14:09:03 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <chrono> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; const int dx[5] = {1, 0, -1, 0, 0}; const int dy[5] = {0, 1, 0, -1, 0}; // const int C = 1e6+10; // const ll M = 1000000007; random_device rd; mt19937 mt(rd()); const int N = 100; typedef tuple<int, int, ll> press; ll A[100][100]; bool valid(int x, int y) { return (0 <= x && x < N && 0 <= y && y < N); } ll calc_score(const vector<vector<ll>> &C) { ll ans = 200000000; for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { ans -= abs(A[i][j] - C[i][j]); } } return ans; } ll plus_score(vector<vector<ll>> &C, int X, int Y, ll H) { for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { C[i][j] += max(0ll, H - abs(i - X) - abs(j - Y)); } } return calc_score(C); } ll minus_score(vector<vector<ll>> &C, int X, int Y, ll H) { return plus_score(C, X, Y, H); } class state { public: vector<vector<ll>> B; vector<press> V; ll score; bool operator<(const state &rhs) const { return score < rhs.score; } state() { B = vector<vector<ll>>(N, vector<ll>(N, 0)); score = calc_score(B); } void add_press(press p) { int X = get<0>(p); int Y = get<1>(p); ll H = get<2>(p); score = plus_score(B, X, Y, H); V.push_back(p); } void del_press(int k) { assert(0 <= k && k < (int)V.size()); auto it = V.begin() + k; int X = get<0>(*it); int Y = get<1>(*it); ll H = get<2>(*it); score = minus_score(B, X, Y, H); V.erase(it); } void show_V() { cout << V.size() << endl; for (auto e : V) { cout << get<0>(e) << " " << get<1>(e) << " " << get<2>(e) << endl; } } // ここから直す void improve() { int k = rd() % ((int)V.size()); int x = get<0>(V[k]); int y = get<1>(V[k]); ll h = get<2>(V[k]); vector<tuple<ll, int, int>> X; vector<vector<ll>> C = B; minus_score(C, x, y, h); for (auto i = 0; i < 5; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (!valid(nx, ny)) continue; for (auto j = -1; j <= 1; j++) { ll nh = h + j; if (!(1 <= nh && nh <= N)) continue; ll ns = plus_score(C, nx, ny, nh); X.push_back(make_tuple(ns, i, j)); } } auto it = max_element(X.begin(), X.end()); int i = get<1>(*it); int j = get<2>(*it); press p = make_tuple(x + dx[i], y + dy[i], h + j); del_press(k); add_press(p); } }; vector<state> W; int main() { auto start_time = std::chrono::system_clock::now(); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cin >> A[i][j]; } } // ここから直す for (auto i = 0; i < 100; i++) { state S = state(); for (auto j = 0; j < 1000; j++) { int x = rd() % N; int y = rd() % N; ll h = rd() % N + 1; S.add_press(make_tuple(x, y, h)); } W.push_back(S); } sort(W.begin(), W.end()); reverse(W.begin(), W.end()); auto end_time = std::chrono::system_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); while (true) { end_time = std::chrono::system_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); if (elapsed > 5950) { auto it = max_element(W.begin(), W.end()); (*it).show_V(); return 0; } if (W.size() > 100) { sort(W.begin(), W.end()); reverse(W.begin(), W.end()); vector<state> WW; for (auto i = 0; i < 10; i++) { WW.push_back(W[i]); } W = WW; } int num = rd() % ((int)W.size()); state S = W[num]; for (auto i = 0; i < 100; i++) { S.improve(); } W.push_back(S); } }<commit_msg>submit A.cpp to 'A - 山型足し算' (future-contest-2018-qual) [C++14 (GCC 5.4.1)]<commit_after>/** * File : A.cpp * Author : Kazune Takahashi * Created : 2018-2-17 14:09:03 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <chrono> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; const int dx[5] = {1, 0, -1, 0, 0}; const int dy[5] = {0, 1, 0, -1, 0}; // const int C = 1e6+10; // const ll M = 1000000007; random_device rd; mt19937 mt(rd()); const int N = 100; typedef tuple<int, int, ll> press; ll A[100][100]; bool valid(int x, int y) { return (0 <= x && x < N && 0 <= y && y < N); } ll calc_score(const vector<vector<ll>> &C) { ll ans = 200000000; for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { ans -= abs(A[i][j] - C[i][j]); } } return ans; } ll plus_score(vector<vector<ll>> &C, int X, int Y, ll H) { for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { C[i][j] += max(0ll, H - abs(i - X) - abs(j - Y)); } } return calc_score(C); } ll minus_score(vector<vector<ll>> &C, int X, int Y, ll H) { return plus_score(C, X, Y, H); } class state { public: vector<vector<ll>> B; vector<press> V; ll score; bool operator<(const state &rhs) const { return score < rhs.score; } state() { B = vector<vector<ll>>(N, vector<ll>(N, 0)); score = calc_score(B); } void add_press(press p) { int X = get<0>(p); int Y = get<1>(p); ll H = get<2>(p); score = plus_score(B, X, Y, H); V.push_back(p); } void del_press(int k) { assert(0 <= k && k < (int)V.size()); auto it = V.begin() + k; int X = get<0>(*it); int Y = get<1>(*it); ll H = get<2>(*it); score = minus_score(B, X, Y, H); V.erase(it); } void show_V() { cout << V.size() << endl; for (auto e : V) { cout << get<0>(e) << " " << get<1>(e) << " " << get<2>(e) << endl; } } // ここから直す void improve() { int k = rd() % ((int)V.size()); int x = get<0>(V[k]); int y = get<1>(V[k]); ll h = get<2>(V[k]); vector<tuple<ll, int, int>> X; vector<vector<ll>> C = B; minus_score(C, x, y, h); for (auto i = 0; i < 5; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (!valid(nx, ny)) continue; for (auto j = -1; j <= 1; j++) { ll nh = h + j; if (!(1 <= nh && nh <= N)) continue; ll ns = plus_score(C, nx, ny, nh); X.push_back(make_tuple(ns, i, j)); minus_score(C, nx, ny, nh); } } auto it = max_element(X.begin(), X.end()); int i = get<1>(*it); int j = get<2>(*it); press p = make_tuple(x + dx[i], y + dy[i], h + j); del_press(k); add_press(p); } }; vector<state> W; int main() { auto start_time = std::chrono::system_clock::now(); for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cin >> A[i][j]; } } // ここから直す for (auto i = 0; i < 100; i++) { state S = state(); for (auto j = 0; j < 1000; j++) { int x = rd() % N; int y = rd() % N; ll h = rd() % N + 1; S.add_press(make_tuple(x, y, h)); } W.push_back(S); } sort(W.begin(), W.end()); reverse(W.begin(), W.end()); auto end_time = std::chrono::system_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); while (true) { end_time = std::chrono::system_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count(); if (elapsed > 5950) { auto it = max_element(W.begin(), W.end()); (*it).show_V(); return 0; } if (W.size() > 100) { sort(W.begin(), W.end()); reverse(W.begin(), W.end()); vector<state> WW; for (auto i = 0; i < 10; i++) { WW.push_back(W[i]); } W = WW; } int num = rd() % ((int)W.size()); state S = W[num]; for (auto i = 0; i < 100; i++) { S.improve(); } W.push_back(S); } }<|endoftext|>
<commit_before>/** * Touhou Community Reliant Automatic Patcher * Tasogare Frontier support plugin * * ---- * * Image patching for nsml engine. */ #include <thcrap.h> #include "./png.h" #include "thcrap_tasofro.h" #include "nsml_images.h" size_t get_image_data_size(const char *fn, bool fill_alpha_for_24bpp) { VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height, rowbytes; uint8_t bpp; bool IHDR_read = png_image_get_IHDR(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!IHDR_read) { return 0; } if (fill_alpha_for_24bpp) { rowbytes = width * 4; } else { rowbytes = width * bpp / 8; if (rowbytes % 4 != 0) { rowbytes += 4 - (rowbytes % 4); } } return rowbytes * height; } size_t get_cv2_size(const char *fn, json_t*, size_t) { return 17 + get_image_data_size(fn, true); } int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*) { BYTE *file_out = (BYTE*)file_inout; VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height; uint8_t bpp; BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!row_pointers) { return 0; } if (17 + width * height * 4 > size_out) { log_print("Destination buffer too small!\n"); free(row_pointers); return -1; } file_out[0] = bpp; DWORD *header = (DWORD*)(file_out + 1); header[0] = width; header[1] = height; header[2] = width; header[3] = 0; for (unsigned int h = 0; h < height; h++) { for (unsigned int w = 0; w < width; w++) { file_out[17 + h * width * 4 + w * 4 + 0] = row_pointers[h][w * bpp / 8 + 2]; file_out[17 + h * width * 4 + w * 4 + 1] = row_pointers[h][w * bpp / 8 + 1]; file_out[17 + h * width * 4 + w * 4 + 2] = row_pointers[h][w * bpp / 8 + 0]; if (bpp == 32) { file_out[17 + h * width * 4 + w * 4 + 3] = row_pointers[h][w * bpp / 8 + 3]; } else { file_out[17 + h * width * 4 + w * 4 + 3] = 0xFF; } } } free(row_pointers); return 1; } int patch_dat_for_png(void *file_inout, size_t, size_t size_in, const char *fn, json_t*) { if (size_in < 8) { return 0; } BYTE* file_in = (BYTE*)file_inout; DWORD magic = *(DWORD*)file_in; if (magic != 4) { return 0; } char path[MAX_PATH]; strcpy(path, fn); char *path_fn = strrchr(path, '/') + 1; DWORD nb_files = *(DWORD*)(file_in + 4); file_in += 8; size_in -= 8; for (DWORD i = 0; i < nb_files; i++) { if (size_in < 4) { return 0; } DWORD fn_size = *(DWORD*)file_in; file_in += 4; size_in -= 4; if (size_in < fn_size + 16) { return 0; } memcpy(path_fn, file_in, fn_size); path_fn[fn_size] = '\0'; file_in += fn_size; size_in -= fn_size; // Retrieve the PNG width/height strcpy(PathFindExtensionA(path_fn), ".png"); uint32_t width, height; bool IHDR_read = png_image_get_IHDR(path, &width, &height, nullptr); if (!IHDR_read) { file_in += 16; size_in -= 16; continue; } DWORD x = *(DWORD*)file_in; DWORD y = *(DWORD*)(file_in + 4); *(DWORD*)(file_in + 8) = width; *(DWORD*)(file_in + 12) = height; file_in += 16; size_in -= 16; } return 1; } size_t get_bmp_size(const char *fn, json_t*, size_t) { return sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + get_image_data_size(fn, false); } int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*) { VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height, rowbytes; uint8_t bpp; BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!row_pointers) { return 0; } rowbytes = width * bpp / 8; if (rowbytes % 4 != 0) { rowbytes += 4 - (rowbytes % 4); } if (size_out < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height) { log_print("Destination buffer too small!\n"); free(row_pointers); return -1; } BITMAPFILEHEADER *bpFile = (BITMAPFILEHEADER*)file_inout; BITMAPINFOHEADER *bpInfo = (BITMAPINFOHEADER*)(bpFile + 1); BYTE *bpData = (BYTE*)(bpInfo + 1); bpFile->bfType = 0x4D42; bpFile->bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height; bpFile->bfReserved1 = 0; bpFile->bfReserved2 = 0; bpFile->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); bpInfo->biSize = sizeof(BITMAPINFOHEADER); bpInfo->biWidth = width; bpInfo->biHeight = height; bpInfo->biPlanes = 1; bpInfo->biBitCount = bpp; bpInfo->biCompression = (bpp == 32 ? BI_BITFIELDS : BI_RGB); bpInfo->biSizeImage = rowbytes * height; bpInfo->biXPelsPerMeter = 65535; bpInfo->biYPelsPerMeter = 65535; bpInfo->biClrUsed = 0; bpInfo->biClrImportant = 0; for (unsigned int h = 0; h < height; h++) { unsigned int pos = 0; for (unsigned int w = 0; w < width; w++) { bpData[h * rowbytes + pos + 0] = row_pointers[height - h - 1][w * bpp / 8 + 2]; bpData[h * rowbytes + pos + 1] = row_pointers[height - h - 1][w * bpp / 8 + 1]; bpData[h * rowbytes + pos + 2] = row_pointers[height - h - 1][w * bpp / 8 + 0]; if (bpp == 32) { bpData[h * rowbytes + pos + 3] = row_pointers[height - h - 1][w * bpp / 8 + 3]; } pos += bpp / 8; } // Padding while (pos % 4) { bpData[h * rowbytes + pos] = 0; pos++; } } free(row_pointers); return 1; } <commit_msg>thcrap_tasofro: patch dat files only when we actually change something in them.<commit_after>/** * Touhou Community Reliant Automatic Patcher * Tasogare Frontier support plugin * * ---- * * Image patching for nsml engine. */ #include <thcrap.h> #include "./png.h" #include "thcrap_tasofro.h" #include "nsml_images.h" size_t get_image_data_size(const char *fn, bool fill_alpha_for_24bpp) { VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height, rowbytes; uint8_t bpp; bool IHDR_read = png_image_get_IHDR(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!IHDR_read) { return 0; } if (fill_alpha_for_24bpp) { rowbytes = width * 4; } else { rowbytes = width * bpp / 8; if (rowbytes % 4 != 0) { rowbytes += 4 - (rowbytes % 4); } } return rowbytes * height; } size_t get_cv2_size(const char *fn, json_t*, size_t) { return 17 + get_image_data_size(fn, true); } int patch_cv2(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*) { BYTE *file_out = (BYTE*)file_inout; VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height; uint8_t bpp; BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!row_pointers) { return 0; } if (17 + width * height * 4 > size_out) { log_print("Destination buffer too small!\n"); free(row_pointers); return -1; } file_out[0] = bpp; DWORD *header = (DWORD*)(file_out + 1); header[0] = width; header[1] = height; header[2] = width; header[3] = 0; for (unsigned int h = 0; h < height; h++) { for (unsigned int w = 0; w < width; w++) { file_out[17 + h * width * 4 + w * 4 + 0] = row_pointers[h][w * bpp / 8 + 2]; file_out[17 + h * width * 4 + w * 4 + 1] = row_pointers[h][w * bpp / 8 + 1]; file_out[17 + h * width * 4 + w * 4 + 2] = row_pointers[h][w * bpp / 8 + 0]; if (bpp == 32) { file_out[17 + h * width * 4 + w * 4 + 3] = row_pointers[h][w * bpp / 8 + 3]; } else { file_out[17 + h * width * 4 + w * 4 + 3] = 0xFF; } } } free(row_pointers); return 1; } int patch_dat_for_png(void *file_inout, size_t, size_t size_in, const char *fn, json_t*) { if (size_in < 8) { return 0; } BYTE* file_in = (BYTE*)file_inout; DWORD magic = *(DWORD*)file_in; if (magic != 4) { return 0; } char path[MAX_PATH]; strcpy(path, fn); char *path_fn = strrchr(path, '/') + 1; DWORD nb_files = *(DWORD*)(file_in + 4); file_in += 8; size_in -= 8; int file_changed = 0; for (DWORD i = 0; i < nb_files; i++) { if (size_in < 4) { return 0; } DWORD fn_size = *(DWORD*)file_in; file_in += 4; size_in -= 4; if (size_in < fn_size + 16) { return 0; } memcpy(path_fn, file_in, fn_size); path_fn[fn_size] = '\0'; file_in += fn_size; size_in -= fn_size; // Retrieve the PNG width/height strcpy(PathFindExtensionA(path_fn), ".png"); uint32_t width, height; bool IHDR_read = png_image_get_IHDR(path, &width, &height, nullptr); if (!IHDR_read) { file_in += 16; size_in -= 16; continue; } DWORD x = *(DWORD*)file_in; DWORD y = *(DWORD*)(file_in + 4); DWORD w = *(DWORD*)(file_in + 8); DWORD h = *(DWORD*)(file_in + 12); if (w != width && h != height) { *(DWORD*)(file_in + 8) = width; *(DWORD*)(file_in + 12) = height; file_changed = 1; } file_in += 16; size_in -= 16; } return file_changed; } size_t get_bmp_size(const char *fn, json_t*, size_t) { return sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + get_image_data_size(fn, false); } int patch_bmp(void *file_inout, size_t size_out, size_t size_in, const char *fn, json_t*) { VLA(char, fn_png, strlen(fn) + 1); strcpy(fn_png, fn); strcpy(PathFindExtensionA(fn_png), ".png"); uint32_t width, height, rowbytes; uint8_t bpp; BYTE** row_pointers = png_image_read(fn_png, &width, &height, &bpp); VLA_FREE(fn_png); if (!row_pointers) { return 0; } rowbytes = width * bpp / 8; if (rowbytes % 4 != 0) { rowbytes += 4 - (rowbytes % 4); } if (size_out < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height) { log_print("Destination buffer too small!\n"); free(row_pointers); return -1; } BITMAPFILEHEADER *bpFile = (BITMAPFILEHEADER*)file_inout; BITMAPINFOHEADER *bpInfo = (BITMAPINFOHEADER*)(bpFile + 1); BYTE *bpData = (BYTE*)(bpInfo + 1); bpFile->bfType = 0x4D42; bpFile->bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + rowbytes * height; bpFile->bfReserved1 = 0; bpFile->bfReserved2 = 0; bpFile->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); bpInfo->biSize = sizeof(BITMAPINFOHEADER); bpInfo->biWidth = width; bpInfo->biHeight = height; bpInfo->biPlanes = 1; bpInfo->biBitCount = bpp; bpInfo->biCompression = (bpp == 32 ? BI_BITFIELDS : BI_RGB); bpInfo->biSizeImage = rowbytes * height; bpInfo->biXPelsPerMeter = 65535; bpInfo->biYPelsPerMeter = 65535; bpInfo->biClrUsed = 0; bpInfo->biClrImportant = 0; for (unsigned int h = 0; h < height; h++) { unsigned int pos = 0; for (unsigned int w = 0; w < width; w++) { bpData[h * rowbytes + pos + 0] = row_pointers[height - h - 1][w * bpp / 8 + 2]; bpData[h * rowbytes + pos + 1] = row_pointers[height - h - 1][w * bpp / 8 + 1]; bpData[h * rowbytes + pos + 2] = row_pointers[height - h - 1][w * bpp / 8 + 0]; if (bpp == 32) { bpData[h * rowbytes + pos + 3] = row_pointers[height - h - 1][w * bpp / 8 + 3]; } pos += bpp / 8; } // Padding while (pos % 4) { bpData[h * rowbytes + pos] = 0; pos++; } } free(row_pointers); return 1; } <|endoftext|>
<commit_before>/* * Copyright 2013 Arma2NET Developers * * 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 "Utils.h" #include "Addin.h" using namespace System; using namespace System::Collections::Concurrent; using namespace System::Threading::Tasks; namespace Arma2Net { public ref class AsyncAddinInvocationMethod : public IAddinInvocationMethod { private: initonly Addin^ addin; initonly ConcurrentQueue<String^>^ results = gcnew ConcurrentQueue<String^>; Exception^ exception; void InvokeImpl(Object^ obj) { auto tuple = (Tuple<String^, int>^)obj; auto result = addin->Invoke(tuple->Item1, tuple->Item2); results->Enqueue(result); } bool HandleException(Exception^ e) { exception = e; return true; } String^ TaskFaulted(Task^ task) { task->Exception->Handle(gcnew Func<Exception^, bool>(this, &AsyncAddinInvocationMethod::HandleException)); return nullptr; } public: AsyncAddinInvocationMethod(Addin^ addin) { this->addin = addin; } virtual String^ Invoke(String^ args, int maxResultSize) { if (exception != nullptr) { Exception^ e = exception; exception = nullptr; throw e; } if (args != nullptr && args->Equals("getresult", StringComparison::OrdinalIgnoreCase)) { String^ result; results->TryDequeue(result); return result; } auto tuple = Tuple::Create(args, maxResultSize); auto task = gcnew Task(gcnew Action<Object^>(this, &AsyncAddinInvocationMethod::InvokeImpl), tuple); task->ContinueWith(gcnew Func<Task^, String^>(this, &AsyncAddinInvocationMethod::TaskFaulted), TaskContinuationOptions::OnlyOnFaulted); task->Start(); return nullptr; } }; }<commit_msg>Add flag for optionally storing results from async addins<commit_after>/* * Copyright 2013 Arma2NET Developers * * 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 "Utils.h" #include "Addin.h" using namespace System; using namespace System::Collections::Concurrent; using namespace System::Threading::Tasks; namespace Arma2Net { public ref class AsyncAddinInvocationMethod : public IAddinInvocationMethod { private: initonly Addin^ addin; initonly bool storeResults = false; initonly ConcurrentQueue<String^>^ results = gcnew ConcurrentQueue<String^>; Exception^ exception; void InvokeImpl(Object^ obj) { auto tuple = (Tuple<String^, int>^)obj; auto result = addin->Invoke(tuple->Item1, tuple->Item2); if (storeResults) results->Enqueue(result); } bool HandleException(Exception^ e) { exception = e; return true; } String^ TaskFaulted(Task^ task) { task->Exception->Handle(gcnew Func<Exception^, bool>(this, &AsyncAddinInvocationMethod::HandleException)); return nullptr; } public: AsyncAddinInvocationMethod(Addin^ addin) { this->addin = addin; } AsyncAddinInvocationMethod(Addin^ addin, bool storeResults) { this->addin = addin; this->storeResults = storeResults; } virtual String^ Invoke(String^ args, int maxResultSize) { if (exception != nullptr) { Exception^ e = exception; exception = nullptr; throw e; } if (args != nullptr && args->Equals("getresult", StringComparison::OrdinalIgnoreCase)) { String^ result; results->TryDequeue(result); return result; } auto tuple = Tuple::Create(args, maxResultSize); auto task = gcnew Task(gcnew Action<Object^>(this, &AsyncAddinInvocationMethod::InvokeImpl), tuple); task->ContinueWith(gcnew Func<Task^, String^>(this, &AsyncAddinInvocationMethod::TaskFaulted), TaskContinuationOptions::OnlyOnFaulted); task->Start(); return nullptr; } }; }<|endoftext|>
<commit_before>#include <QGraphicsItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QKeyEvent> #include <QDebug> #include <QMessageBox> #include <QFileDialog> #include <cassert> #include <cmath> #include <vector> #include <unordered_map> #include <fstream> #include <string> #include "mainwindow.h" #include "ui_mainwindow.h" #include "gui/vertex_graphics_item.h" #include "gui/edge_graphics_item.h" #include "lib/bfs.hpp" #include "lib/logger.hpp" MainWindow::MainWindow(Graph *graph, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), graph_(graph) { ui->setupUi(this); scene = new QGraphicsScene(this); scene->setSceneRect(-1500, -1500, 3000, 3000); ui->graphicsView->setScene(scene); ui->graphicsView->setRenderHints(QPainter::Antialiasing); ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag); global_logger_logView_ = ui->txtLogView; reloadModel(); } MainWindow::~MainWindow() { delete ui; } static bool reloading = false; /// Reloads the whole UI based on the model. Everything is first removed, /// and then re-created in the same coordinates, so that the user notice anything. void MainWindow::reloadModel() { qDebug() << "Reloading model"; reloading = true; int selectedVertexValue = -1; if (scene->selectedItems().size() == 1) { VertexGraphicsItem* selection = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0)); if (selection) { selectedVertexValue = selection->value(); } } // TODO - promyslet // selectedVertex_ = nullptr; vertices_.clear(); scene->clear(); std::unordered_map<Vertex *, VertexGraphicsItem *> vgi_map; int i = 0; for (std::unique_ptr<Vertex> &v : graph_->list) { auto vgi = new VertexGraphicsItem(v.get()); if (!vgi->hasCoordinates()) { vgi->setCoordinates(80 * (i / 5 + 1) * std::cos(i), 80 * (i / 5 + 1) * std::sin(i)); } vertices_.push_back(vgi); scene->addItem(vgi); if (v->value == selectedVertexValue) { vgi->setSelected(true); } vgi_map[v.get()] = vgi; i++; } for (std::unique_ptr<Vertex> &v : graph_->list) { Vertex *vertex = v.get(); VertexGraphicsItem *vgi = vgi_map[vertex]; for (Edge &e : vertex->edges) { graphConnect(vgi, vgi_map[e.to]); vgi->repaintEdges(); } } reloading = false; } void MainWindow::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_A) { on_addVertex_clicked(); } else if (e->key() == Qt::Key_C) { on_addEdge_clicked(); } else if (e->key() == Qt::Key_D) { delete_selection(); } else if (e->key() == Qt::Key_F) { searchToggle(true); } else if (e->key() == Qt::Key_T) { searchToggle(false); } else if (e->key() == Qt::Key_N) { searchStep(); } else if (e->key() == Qt::Key_R) { if (graph_->start() && graph_->end()) { bfs_ = new BFS(*graph_, graph_->start(), graph_->end()); graph_->clear_metadata(); scene->update(); } } } void MainWindow::delete_selection() { if (scene->selectedItems().size() == 1) { QGraphicsItem *selectedItem = scene->selectedItems().at(0); if (VertexGraphicsItem *vgi = dynamic_cast<VertexGraphicsItem *>(selectedItem)) { if (connectionVertex_ == vgi->value()) { connectionVertex_ = -1; } graph_->removeVertex(vgi->vertex); } else if (EdgeGraphicsItem *egi = dynamic_cast<EdgeGraphicsItem *>(selectedItem)) { auto from = egi->from; auto to = egi->to; graph_->disconnect(from->vertex->value, to->vertex->value); } else { qDebug() << "Trying to delete something unknown"; } } reloadModel(); } void MainWindow::on_addVertex_clicked() { auto v = graph_->add_vertex(); auto pos = ui->graphicsView->mapToScene(mapFromGlobal(QCursor::pos())); v->x = pos.x(); v->y = pos.y(); reloadModel(); } void MainWindow::on_addEdge_clicked() { VertexGraphicsItem* current = selectedVertex(); if (current) { // If we already had one selected, revert the selection color if (connectionVertex_ != -1) { if (current->value() != connectionVertex_) { for (VertexGraphicsItem* vgi : vertices_) { if (vgi->value() == connectionVertex_) { vgi->selected(false); } } graph_->connect(current->value(), connectionVertex_); // Reset the selection after we connect the vertices connectionVertex_ = -1; reloadModel(); log_event("Edge added"); } } else { current->selected(true); connectionVertex_ = current->value(); reloadModel(); } } } /// isStart - true for start vertex, false for end vertex void MainWindow::searchToggle(bool isStart) { VertexGraphicsItem* current = selectedVertex(); if (current) { if (isStart) { graph_->set_start(current->vertex); } else { graph_->set_end(current->vertex); } reloadModel(); } else { QMessageBox box; box.setText("Select a vertex to begin search."); box.exec(); } } void MainWindow::searchStep() { if (graph_->search_ready() && bfs_) { qDebug () << "Stepping search" << bfs_->step(); reloadModel(); } else { qDebug() << "Search isn't ready yet."; } } /// Returns a selected vertex if there is one, otherwise nullptr. VertexGraphicsItem* MainWindow::selectedVertex() const { VertexGraphicsItem* current = nullptr; if (scene->selectedItems().size() > 0) { current = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0)); } return current; } void MainWindow::on_actionNew_clicked() { log_event("New graph"); graph_ = new Graph(); connectionVertex_ = -1; reloadModel(); } void MainWindow::on_actionSave_clicked() { log_event("Save"); } void MainWindow::on_actionSaveAs_clicked() { auto file = QFileDialog::getSaveFileName(); if (!file.isNull()) { std::ofstream fs(file.toStdString()); fs << *graph_; log_event("Graph saved"); } else { log_event("Dialog canceled"); } } void MainWindow::on_actionOpen_clicked() { // TODO - nastavit vsem streamum aby vyhazovaly vyjimky auto file = QFileDialog::getOpenFileName(); if (!file.isNull()) { std::ifstream fs(file.toStdString()); graph_ = Graph::parse_stream(fs); connectionVertex_ = -1; reloadModel(); log_event("Graph loaded"); } else { log_event("Dialog canceled"); } } /// Used to add a graphical edge between two vertices. Only ever call this from reloadModel. void MainWindow::graphConnect(VertexGraphicsItem *v1, VertexGraphicsItem *v2) { assert(reloading); auto edge = new EdgeGraphicsItem(v1, v2); scene->addItem(edge); v1->edges.push_back(edge); v2->edges.push_back(edge); } <commit_msg>Fix search restart<commit_after>#include <QGraphicsItem> #include <QGraphicsScene> #include <QGraphicsView> #include <QKeyEvent> #include <QDebug> #include <QMessageBox> #include <QFileDialog> #include <cassert> #include <cmath> #include <vector> #include <unordered_map> #include <fstream> #include <string> #include "mainwindow.h" #include "ui_mainwindow.h" #include "gui/vertex_graphics_item.h" #include "gui/edge_graphics_item.h" #include "lib/bfs.hpp" #include "lib/logger.hpp" MainWindow::MainWindow(Graph *graph, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), graph_(graph) { ui->setupUi(this); scene = new QGraphicsScene(this); scene->setSceneRect(-1500, -1500, 3000, 3000); ui->graphicsView->setScene(scene); ui->graphicsView->setRenderHints(QPainter::Antialiasing); ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag); global_logger_logView_ = ui->txtLogView; reloadModel(); } MainWindow::~MainWindow() { delete ui; } static bool reloading = false; /// Reloads the whole UI based on the model. Everything is first removed, /// and then re-created in the same coordinates, so that the user notice anything. void MainWindow::reloadModel() { qDebug() << "Reloading model"; reloading = true; int selectedVertexValue = -1; if (scene->selectedItems().size() == 1) { VertexGraphicsItem* selection = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0)); if (selection) { selectedVertexValue = selection->value(); } } // TODO - promyslet // selectedVertex_ = nullptr; vertices_.clear(); scene->clear(); std::unordered_map<Vertex *, VertexGraphicsItem *> vgi_map; int i = 0; for (std::unique_ptr<Vertex> &v : graph_->list) { auto vgi = new VertexGraphicsItem(v.get()); if (!vgi->hasCoordinates()) { vgi->setCoordinates(80 * (i / 5 + 1) * std::cos(i), 80 * (i / 5 + 1) * std::sin(i)); } vertices_.push_back(vgi); scene->addItem(vgi); if (v->value == selectedVertexValue) { vgi->setSelected(true); } vgi_map[v.get()] = vgi; i++; } for (std::unique_ptr<Vertex> &v : graph_->list) { Vertex *vertex = v.get(); VertexGraphicsItem *vgi = vgi_map[vertex]; for (Edge &e : vertex->edges) { graphConnect(vgi, vgi_map[e.to]); vgi->repaintEdges(); } } reloading = false; } void MainWindow::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_A) { on_addVertex_clicked(); } else if (e->key() == Qt::Key_C) { on_addEdge_clicked(); } else if (e->key() == Qt::Key_D) { delete_selection(); } else if (e->key() == Qt::Key_F) { searchToggle(true); } else if (e->key() == Qt::Key_T) { searchToggle(false); } else if (e->key() == Qt::Key_N) { searchStep(); } else if (e->key() == Qt::Key_R) { if (graph_->start() && graph_->end()) { graph_->clear_metadata(); bfs_ = new BFS(*graph_, graph_->start(), graph_->end()); reloadModel(); } } } void MainWindow::delete_selection() { if (scene->selectedItems().size() == 1) { QGraphicsItem *selectedItem = scene->selectedItems().at(0); if (VertexGraphicsItem *vgi = dynamic_cast<VertexGraphicsItem *>(selectedItem)) { if (connectionVertex_ == vgi->value()) { connectionVertex_ = -1; } graph_->removeVertex(vgi->vertex); } else if (EdgeGraphicsItem *egi = dynamic_cast<EdgeGraphicsItem *>(selectedItem)) { auto from = egi->from; auto to = egi->to; graph_->disconnect(from->vertex->value, to->vertex->value); } else { qDebug() << "Trying to delete something unknown"; } } reloadModel(); } void MainWindow::on_addVertex_clicked() { auto v = graph_->add_vertex(); auto pos = ui->graphicsView->mapToScene(mapFromGlobal(QCursor::pos())); v->x = pos.x(); v->y = pos.y(); reloadModel(); } void MainWindow::on_addEdge_clicked() { VertexGraphicsItem* current = selectedVertex(); if (current) { // If we already had one selected, revert the selection color if (connectionVertex_ != -1) { if (current->value() != connectionVertex_) { for (VertexGraphicsItem* vgi : vertices_) { if (vgi->value() == connectionVertex_) { vgi->selected(false); } } graph_->connect(current->value(), connectionVertex_); // Reset the selection after we connect the vertices connectionVertex_ = -1; reloadModel(); log_event("Edge added"); } } else { current->selected(true); connectionVertex_ = current->value(); reloadModel(); } } } /// isStart - true for start vertex, false for end vertex void MainWindow::searchToggle(bool isStart) { VertexGraphicsItem* current = selectedVertex(); if (current) { if (isStart) { graph_->set_start(current->vertex); } else { graph_->set_end(current->vertex); } reloadModel(); } else { QMessageBox box; box.setText("Select a vertex to begin search."); box.exec(); } } void MainWindow::searchStep() { if (graph_->search_ready() && bfs_) { qDebug () << "Stepping search" << bfs_->step(); reloadModel(); } else { qDebug() << "Search isn't ready yet."; } } /// Returns a selected vertex if there is one, otherwise nullptr. VertexGraphicsItem* MainWindow::selectedVertex() const { VertexGraphicsItem* current = nullptr; if (scene->selectedItems().size() > 0) { current = dynamic_cast<VertexGraphicsItem*>(scene->selectedItems().at(0)); } return current; } void MainWindow::on_actionNew_clicked() { graph_ = new Graph(); connectionVertex_ = -1; reloadModel(); log_event("New graph"); } void MainWindow::on_actionSave_clicked() { log_event("Save"); } void MainWindow::on_actionSaveAs_clicked() { auto file = QFileDialog::getSaveFileName(); if (!file.isNull()) { std::ofstream fs(file.toStdString()); fs << *graph_; log_event("Graph saved"); } else { log_event("Dialog canceled"); } } void MainWindow::on_actionOpen_clicked() { // TODO - nastavit vsem streamum aby vyhazovaly vyjimky auto file = QFileDialog::getOpenFileName(); if (!file.isNull()) { std::ifstream fs(file.toStdString()); graph_ = Graph::parse_stream(fs); connectionVertex_ = -1; reloadModel(); log_event("Graph loaded"); } else { log_event("Dialog canceled"); } } /// Used to add a graphical edge between two vertices. Only ever call this from reloadModel. void MainWindow::graphConnect(VertexGraphicsItem *v1, VertexGraphicsItem *v2) { assert(reloading); auto edge = new EdgeGraphicsItem(v1, v2); scene->addItem(edge); v1->edges.push_back(edge); v2->edges.push_back(edge); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "music.h" #include "alarm.h" #include "calendar.h" #include <cstring> #include <string> #include <memory> #include <QFile> MainWindow::MainWindow(Config cfg, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , alarmer(new AlarmPersistence(cfg, this)) , timer(new QTimer(this)) , config(std::move(cfg)) , configRefresh(new QTimer(this)) , alarmWindow(new Alarm(alarmer, config, this)) { ui->setupUi(this); // External Stylesheet for customize by Users QFile File("stylesheet.qss"); File.open(QFile::ReadOnly); QString StyleSheet = QLatin1String(File.readAll()); qApp->setStyleSheet(StyleSheet); //setStyleSheet(StyleSheet); set_alarm_status(config.cget().alarmActive); connect(timer, SIGNAL(timeout()), this, SLOT(on_timer())); connect(configRefresh, SIGNAL(timeout()), this, SLOT(refresh_config())); connect(alarmWindow, SIGNAL(activity_toggle(bool)), this, SLOT(set_alarm_status(bool))); timer->start(1000); configRefresh->start(10000); } MainWindow::~MainWindow() { delete ui; } void MainWindow::refresh_config() { config.load(); alarmWindow->on_config_update(); } void MainWindow::on_timer() { auto currentTime = alarmer->getCurrentTime(); auto time = std::chrono::system_clock::to_time_t(currentTime); auto local = localtime(&time); QString timeString; timeString.sprintf("%02d:%02d:%02d", local->tm_hour, local->tm_min, local->tm_sec); ui->uhrzeit->setText(timeString); } void MainWindow::set_alarm_status(bool status) { if (status) { ui->alarm_status->setText("ON"); ui->alarm_status->setStyleSheet("color: rgb(0, 255, 0);"); } else { ui->alarm_status->setText("OFF"); ui->alarm_status->setStyleSheet("color: rgb(255, 0, 0);"); } } void MainWindow::on_music_button_clicked() { std::unique_ptr<Music> musicWindow (new Music (config)); musicWindow->setModal(true); musicWindow->exec(); } void MainWindow::on_alarm_button_clicked() { alarmWindow->exec(); } void MainWindow::on_calendar_button_clicked() { std::unique_ptr<Calendar> calendarWindow (new Calendar); calendarWindow->setModal(true); calendarWindow->exec(); } <commit_msg>the music now keeps playing after closing the window, which means "Music" ain't modal anymore.<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "calendar.h" #include <cstring> #include <string> #include <memory> #include <QFile> MainWindow::MainWindow(Config cfg, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , alarmer(new AlarmPersistence(cfg, this)) , timer(new QTimer(this)) , config(std::move(cfg)) , configRefresh(new QTimer(this)) , musicWindow(new Music(config, this)) , alarmWindow(new Alarm(alarmer, musicWindow, config, this)) { ui->setupUi(this); // External Stylesheet for customize by Users QFile File("stylesheet.qss"); File.open(QFile::ReadOnly); QString StyleSheet = QLatin1String(File.readAll()); qApp->setStyleSheet(StyleSheet); //setStyleSheet(StyleSheet); set_alarm_status(config.cget().alarmActive); connect(timer, SIGNAL(timeout()), this, SLOT(on_timer())); connect(configRefresh, SIGNAL(timeout()), this, SLOT(refresh_config())); connect(alarmWindow, SIGNAL(activity_toggle(bool)), this, SLOT(set_alarm_status(bool))); timer->start(1000); configRefresh->start(10000); } MainWindow::~MainWindow() { delete ui; } void MainWindow::refresh_config() { config.load(); alarmWindow->on_config_update(); } void MainWindow::on_timer() { auto currentTime = alarmer->getCurrentTime(); auto time = std::chrono::system_clock::to_time_t(currentTime); auto local = localtime(&time); QString timeString; timeString.sprintf("%02d:%02d:%02d", local->tm_hour, local->tm_min, local->tm_sec); ui->uhrzeit->setText(timeString); } void MainWindow::set_alarm_status(bool status) { if (status) { ui->alarm_status->setText("ON"); ui->alarm_status->setStyleSheet("color: rgb(0, 255, 0);"); } else { ui->alarm_status->setText("OFF"); ui->alarm_status->setStyleSheet("color: rgb(255, 0, 0);"); } } void MainWindow::on_music_button_clicked() { musicWindow->show(); } void MainWindow::on_alarm_button_clicked() { alarmWindow->exec(); } void MainWindow::on_calendar_button_clicked() { std::unique_ptr<Calendar> calendarWindow (new Calendar); calendarWindow->setModal(true); calendarWindow->exec(); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <stdio.h> #include <QScrollBar> #include <QFileDialog> #include "hardware/camera/qopencvcamera.h" #include "hardware/projector/seconddisplayprojector.h" #include "geom/triangulator.h" #include "hardware/projector/gridpattern.h" #include "hardware/projector/flatcolorpattern.h" #include "hardware/standards/dotmatrixstandard.h" #include "hardware/standards/chessboardstandard.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), calib(new CalibrationDialog), debugWin(new QPlainTextEdit), graycode(new GrayCodePattern(1,false)), dbgIm(new ImageViewWidget), singleCal(new SingleCalibrationDialog) { ui->setupUi(this); debugWin->setPlainText(QString("ScanStudio started.")); debugWin->setWindowTitle(QString("Debugging info")); debugWin->setWindowIcon( QIcon(tr(":/icons/oxygen/camera-web-64.png"))); debugWin->setWindowFlags(Qt::WindowStaysOnTopHint); debugWin->setReadOnly(true); connect(&stdSettings,SIGNAL(accept()),this,SLOT(adjustCalStd())); connect(&camSettings, SIGNAL(debug(QString)), this, SLOT(debug(QString))); connect(&camSettings, SIGNAL(acceptedCameras(QCamera*,QCamera*)), this, SLOT(cameraSettingsChanged(QCamera*,QCamera*))); ui->modelView->zoomFit(); dbgIm->setWindowTitle("Debugging -- camera view"); QOpenCVCamera *capCam = new QOpenCVCamera(2); connect(capCam, SIGNAL(debug(QString)), this, SLOT(debug(QString))); capCam->setResolution(1600,1200); capCam->setPrincipalPoint(800,600); capCam->setFocalLength(1300); capCam->setPosition(cv::Vec3d(-0.24,-0.01,0)); capCam->setOrientation(cv::Vec3d(0,M_PI/6.5,0)); camera = capCam; QOpenCVCamera *capCam2 = new QOpenCVCamera(1); connect(capCam2, SIGNAL(debug(QString)), this, SLOT(debug(QString))); capCam2->setResolution(1600,1200); capCam2->setPrincipalPoint(800,600); capCam2->setFocalLength(1300); capCam2->setPosition(cv::Vec3d(0.2,0,0)); capCam2->setOrientation(cv::Vec3d(0,-0.1,0)); camera2 = capCam2; SecondDisplayProjector *pj = new SecondDisplayProjector(); pj->setScreen(1); pj->setResolution(848,480); pj->setPrincipalPoint(848/2,480/2); pj->setPosition(cv::Vec3d(0.0,0,0)); pj->setOrientation(cv::Vec3d(-0*M_PI/180,0.0,0.0)); pj->setFocalLength(3000); GridPattern *grid = new GridPattern(); pj->queue(grid); // FlatColorPattern *flat = new FlatColorPattern(); // pj->queue(flat); projector = pj; capCam->connectProjector(pj); capCam2->connectProjector(pj); compiler = new BinaryCompiler(capCam); compiler->setProjector(pj); singleCal->setCamera(capCam); // debug our components connect(pj, SIGNAL(debug(QString)), this, SLOT(debug(QString))); // connect(compiler, // SIGNAL(visualBinaryFrame(cv::Mat)), // this, // SLOT(debugImage(cv::Mat))); connect(compiler, SIGNAL(visualBinaryFrame(cv::Mat)), this, SLOT(writeDebugImg1(cv::Mat))); connect(compiler, SIGNAL(binaryFrameCaptured(cv::Mat,bool)), this, SLOT(binaryImageCaptured(cv::Mat,bool))); connect(compiler, SIGNAL(debug(QString)), this, SLOT(debug(QString))); connect(calib, SIGNAL(debug(QString)), this, SLOT(debug(QString))); // standard = new DotMatrixStandard(cv::Size(6,7), // 0.91*20e-3, 0.91*17e-3, // 0.91*10e-3); standard = new ChessboardStandard(cv::Size(9,12),20e-3); singleCal->setStandard(standard); } MainWindow::~MainWindow() { delete ui; QCoreApplication::exit(0); } void MainWindow::debug(QString str) { debugWin->setPlainText(QString("%1\n%2") .arg(debugWin->toPlainText()) .arg(str)); QScrollBar *sb = debugWin->verticalScrollBar(); sb->setValue(sb->maximum()); } void MainWindow::debug(const char *str) { debug(QString(str)); } void MainWindow::showDebug() { debugWin->show(); } void MainWindow::cameraSettingsChanged(QCamera *first, QCamera *) { QOpenCVCamera *cv = dynamic_cast<QOpenCVCamera*>(first); if(!cv) return; connect(first, SIGNAL(frameCaptured(cv::Mat,QCamera::FrameType,QCamera*)), this, SLOT(debugImage(cv::Mat,QCamera::FrameType,QCamera*))); cv->startStream(); } void MainWindow::debugImage(cv::Mat im, QCamera*, QProjector::Pattern*) { debug("User interface displays image."); if(im.channels()==3){ cv::Mat3b img; im.convertTo(img,CV_8UC3); dbgIm->displayImage(img,true); dbgIm->show(); return; } cv::Mat_<double> m; im.convertTo(m,CV_64F); dbgIm->displayImage(m,true); dbgIm->show(); dbgIm->raise(); } void MainWindow::debugImage(cv::Mat im) { debugImage(im,0,0); } void MainWindow::binaryImageCaptured(cv::Mat binary, bool) { if(calib->isVisible()) return; geom = Triangulator::computeSheet( binary, camera, projector, 1); geom->removeNonManifold(); ui->modelView->setData(geom); } void MainWindow::writeDebugImg1(cv::Mat im) { cv::imwrite("/home/ryan/Documents/mqp-data/debug/cam1.png",im); } void MainWindow::writeDebugImg2(cv::Mat im) { cv::imwrite("/home/ryan/Documents/mqp-data/debug/cam2.png",im); } void MainWindow::saveSTL() { QString fnm; fnm = QFileDialog::getSaveFileName( this, tr("Save STL"), QDir::homePath(), tr("Standard Tesselation Language(*.stl)")); if(fnm.length()>0){ if(!fnm.endsWith(".stl")){ fnm = fnm.append(".stl"); } geom->saveSTL(fnm.toLocal8Bit().data()); } } void MainWindow::showAbout() { about.show(); } void MainWindow::setFullScreen(bool fs) { if(fs){ showFullScreen(); }else{ showNormal(); } } void MainWindow::showCameraSettings() { debug("Showing camera settings."); singleCal->open(); enableCalibrate(); } void MainWindow::showProjectorSettings() { projSettings.show(); } void MainWindow::showCalStdSettings() { debug("Show calibration standard settings."); stdSettings.show(); } void MainWindow::showCalibrationDialog() { calib->setLeft(camera); calib->setRight(camera2); calib->setProjector(projector); calib->setBinary(compiler); calib->show(); } void MainWindow::quitProgram() { QCoreApplication::exit(0); } void MainWindow::adjustCalStd() { enableCalibrate(); } void MainWindow::takeFrame() { compiler->requestFrame(11); } void MainWindow::closeEvent(QCloseEvent *) { quitProgram(); } void MainWindow::enableCalibrate() { ui->actionCalibrate->setEnabled(true); } <commit_msg>small mods for testing<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <stdio.h> #include <QScrollBar> #include <QFileDialog> #include "hardware/camera/qopencvcamera.h" #include "hardware/projector/seconddisplayprojector.h" #include "geom/triangulator.h" #include "hardware/projector/gridpattern.h" #include "hardware/projector/flatcolorpattern.h" #include "hardware/standards/dotmatrixstandard.h" #include "hardware/standards/chessboardstandard.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), calib(new CalibrationDialog), debugWin(new QPlainTextEdit), graycode(new GrayCodePattern(1,false)), dbgIm(new ImageViewWidget), singleCal(new SingleCalibrationDialog) { ui->setupUi(this); debugWin->setPlainText(QString("ScanStudio started.")); debugWin->setWindowTitle(QString("Debugging info")); debugWin->setWindowIcon( QIcon(tr(":/icons/oxygen/camera-web-64.png"))); debugWin->setWindowFlags(Qt::WindowStaysOnTopHint); debugWin->setReadOnly(true); connect(&stdSettings,SIGNAL(accept()),this,SLOT(adjustCalStd())); connect(&camSettings, SIGNAL(debug(QString)), this, SLOT(debug(QString))); connect(&camSettings, SIGNAL(acceptedCameras(QCamera*,QCamera*)), this, SLOT(cameraSettingsChanged(QCamera*,QCamera*))); ui->modelView->zoomFit(); dbgIm->setWindowTitle("Debugging -- camera view"); QOpenCVCamera *capCam = new QOpenCVCamera(2); connect(capCam, SIGNAL(debug(QString)), this, SLOT(debug(QString))); capCam->setResolution(1600,1200); capCam->setPrincipalPoint(800,600); capCam->setFocalLength(1300); capCam->setPosition(cv::Vec3d(-0.25,-0.01,0)); capCam->setOrientation(cv::Vec3d(0,M_PI/12,0)); camera = capCam; QOpenCVCamera *capCam2 = new QOpenCVCamera(1); connect(capCam2, SIGNAL(debug(QString)), this, SLOT(debug(QString))); capCam2->setResolution(1600,1200); capCam2->setPrincipalPoint(800,600); capCam2->setFocalLength(1300); capCam2->setPosition(cv::Vec3d(0.2,0,0)); capCam2->setOrientation(cv::Vec3d(0,-0.1,0)); camera2 = capCam2; SecondDisplayProjector *pj = new SecondDisplayProjector(); pj->setScreen(1); pj->setResolution(848,480); pj->setPrincipalPoint(848/2,480/2); pj->setPosition(cv::Vec3d(0.0,0,0)); pj->setOrientation(cv::Vec3d(-0*M_PI/180,0.0,0.0)); pj->setFocalLength(3600); GridPattern *grid = new GridPattern(); pj->queue(grid); // FlatColorPattern *flat = new FlatColorPattern(); // pj->queue(flat); projector = pj; capCam->connectProjector(pj); capCam2->connectProjector(pj); compiler = new BinaryCompiler(capCam); compiler->setProjector(pj); singleCal->setCamera(capCam); // debug our components connect(pj, SIGNAL(debug(QString)), this, SLOT(debug(QString))); // connect(compiler, // SIGNAL(visualBinaryFrame(cv::Mat)), // this, // SLOT(debugImage(cv::Mat))); connect(compiler, SIGNAL(visualBinaryFrame(cv::Mat)), this, SLOT(writeDebugImg1(cv::Mat))); connect(compiler, SIGNAL(binaryFrameCaptured(cv::Mat,bool)), this, SLOT(binaryImageCaptured(cv::Mat,bool))); connect(compiler, SIGNAL(debug(QString)), this, SLOT(debug(QString))); connect(calib, SIGNAL(debug(QString)), this, SLOT(debug(QString))); // standard = new DotMatrixStandard(cv::Size(6,7), // 0.91*20e-3, 0.91*17e-3, // 0.91*10e-3); standard = new ChessboardStandard(cv::Size(9,12),20e-3); singleCal->setStandard(standard); } MainWindow::~MainWindow() { delete ui; QCoreApplication::exit(0); } void MainWindow::debug(QString str) { debugWin->setPlainText(QString("%1\n%2") .arg(debugWin->toPlainText()) .arg(str)); QScrollBar *sb = debugWin->verticalScrollBar(); sb->setValue(sb->maximum()); } void MainWindow::debug(const char *str) { debug(QString(str)); } void MainWindow::showDebug() { debugWin->show(); } void MainWindow::cameraSettingsChanged(QCamera *first, QCamera *) { QOpenCVCamera *cv = dynamic_cast<QOpenCVCamera*>(first); if(!cv) return; connect(first, SIGNAL(frameCaptured(cv::Mat,QCamera::FrameType,QCamera*)), this, SLOT(debugImage(cv::Mat,QCamera::FrameType,QCamera*))); cv->startStream(); } void MainWindow::debugImage(cv::Mat im, QCamera*, QProjector::Pattern*) { debug("User interface displays image."); if(im.channels()==3){ cv::Mat3b img; im.convertTo(img,CV_8UC3); dbgIm->displayImage(img,true); dbgIm->show(); return; } cv::Mat_<double> m; im.convertTo(m,CV_64F); dbgIm->displayImage(m,true); dbgIm->show(); dbgIm->raise(); } void MainWindow::debugImage(cv::Mat im) { debugImage(im,0,0); } void MainWindow::binaryImageCaptured(cv::Mat binary, bool) { if(calib->isVisible()) return; geom = Triangulator::computeSheet( binary, camera, projector, 1); // geom->removeNonManifold(); ui->modelView->setData(geom); } void MainWindow::writeDebugImg1(cv::Mat im) { cv::imwrite("/home/ryan/Documents/mqp-data/debug/cam1.png",im); } void MainWindow::writeDebugImg2(cv::Mat im) { cv::imwrite("/home/ryan/Documents/mqp-data/debug/cam2.png",im); } void MainWindow::saveSTL() { QString fnm; fnm = QFileDialog::getSaveFileName( this, tr("Save STL"), QDir::homePath(), tr("Standard Tesselation Language(*.stl)")); if(fnm.length()>0){ if(!fnm.endsWith(".stl")){ fnm = fnm.append(".stl"); } geom->saveSTL(fnm.toLocal8Bit().data()); } } void MainWindow::showAbout() { about.show(); } void MainWindow::setFullScreen(bool fs) { if(fs){ showFullScreen(); }else{ showNormal(); } } void MainWindow::showCameraSettings() { debug("Showing camera settings."); singleCal->open(); enableCalibrate(); } void MainWindow::showProjectorSettings() { projSettings.show(); } void MainWindow::showCalStdSettings() { debug("Show calibration standard settings."); stdSettings.show(); } void MainWindow::showCalibrationDialog() { calib->setLeft(camera); calib->setRight(camera2); calib->setProjector(projector); calib->setBinary(compiler); calib->show(); } void MainWindow::quitProgram() { QCoreApplication::exit(0); } void MainWindow::adjustCalStd() { enableCalibrate(); } void MainWindow::takeFrame() { compiler->requestFrame(11); } void MainWindow::closeEvent(QCloseEvent *) { quitProgram(); } void MainWindow::enableCalibrate() { ui->actionCalibrate->setEnabled(true); } <|endoftext|>
<commit_before>#include "gvki/UnderlyingCaller.h" #include <iostream> #include <cstdlib> #ifndef MACRO_LIB #include <dlfcn.h> #endif using namespace gvki; #ifdef MACRO_LIB #define SET_FCN_PTR(F) F ## U = &(::F); #else #include <unistd.h> #define SET_FCN_PTR(F) dlerror(); /* clear any old errors */ \ F ## U = reinterpret_cast<F ## Ty>(::dlsym(RTLD_NEXT, #F)); \ errorMsg = dlerror(); \ if ( errorMsg != NULL) { \ std::cerr << "Failed to dlsym(\"" #F "\"): " << errorMsg << std::endl; \ _exit(255); \ } \ if ( F ## U == NULL) { \ std::cerr << "Function pointer for \"" #F "\" cannot be NULL" << std::endl; \ _exit(255); \ } #endif UnderlyingCaller::UnderlyingCaller() { const char* errorMsg = 0; SET_FCN_PTR(clCreateBuffer) SET_FCN_PTR(clCreateSubBuffer) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // In OpenCL 1.2 these are deprecated. Don't warn about this. SET_FCN_PTR(clCreateImage2D) SET_FCN_PTR(clCreateImage3D) #pragma GCC diagnostic pop SET_FCN_PTR(clCreateSampler) SET_FCN_PTR(clCreateProgramWithSource) SET_FCN_PTR(clBuildProgram) SET_FCN_PTR(clCreateKernel) SET_FCN_PTR(clSetKernelArg) SET_FCN_PTR(clEnqueueNDRangeKernel) }; <commit_msg>Under OSX add an underscore prefix for the function name being passed to dlsym(). [1] suggests this shouldn't be necessary but testing seems to have shown that dlsym() wasn't working under OSX. This is an attempt to see if this fixes the issue<commit_after>#include "gvki/UnderlyingCaller.h" #include <iostream> #include <cstdlib> #ifndef MACRO_LIB #include <dlfcn.h> #endif using namespace gvki; #ifdef MACRO_LIB #define SET_FCN_PTR(functionName) functionName ## U = &(::functionName); #else #include <unistd.h> #define _SET_FCN_PTR(functionName, symbol) dlerror(); /* clear any old errors */ \ functionName ## U = reinterpret_cast<functionName ## Ty>(::dlsym(RTLD_NEXT, #symbol)); \ errorMsg = dlerror(); \ if ( errorMsg != NULL) { \ std::cerr << "Failed to dlsym(\"" #symbol "\"): " << errorMsg << std::endl; \ _exit(255); \ } \ if ( functionName ## U == NULL) { \ std::cerr << "Function pointer for \"" #functionName "\" cannot be NULL" << std::endl; \ _exit(255); \ } #ifdef __APPLE__ // Under OSX the OpenCL symbols are prefixed with an underscore [1] claims that // dlsym() is supposed to handle that for us but testing by others seemed to // suggest this wasn't the case. // // [1] https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/dlsym.3.html #define SET_FCN_PTR(functionName) _SET_FCN_PTR(functionName, _ ## functionName) #else #define SET_FCN_PTR(functionName) _SET_FCN_PTR(functionName, functionName) #endif #endif UnderlyingCaller::UnderlyingCaller() { const char* errorMsg = 0; SET_FCN_PTR(clCreateBuffer) SET_FCN_PTR(clCreateSubBuffer) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // In OpenCL 1.2 these are deprecated. Don't warn about this. SET_FCN_PTR(clCreateImage2D) SET_FCN_PTR(clCreateImage3D) #pragma GCC diagnostic pop SET_FCN_PTR(clCreateSampler) SET_FCN_PTR(clCreateProgramWithSource) SET_FCN_PTR(clBuildProgram) SET_FCN_PTR(clCreateKernel) SET_FCN_PTR(clSetKernelArg) SET_FCN_PTR(clEnqueueNDRangeKernel) }; <|endoftext|>
<commit_before>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(2, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h) { random_t<coord_t> rng(2, std::min(w / 4, h / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height()); } image_t make_filled_rect(coord_t rows, coord_t cols) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, make_light_color()); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, make_light_color()); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) / scalar_t(8)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); // generate random image background image_t image(irows(), icols(), color()); image.fill(make_light_color()); image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols); break; case 2: shape = make_hollow_rect(rows, cols); break; default: break; } image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <commit_msg>draw filled circles<commit_after>#include "task_synthetic_shapes.h" #include "libnanocv/loss.h" #include "libnanocv/util/math.hpp" #include "libnanocv/util/random.hpp" namespace ncv { synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration) : task_t(configuration), m_rows(math::clamp(text::from_params<size_t>(configuration, "rows", 32), 16, 32)), m_cols(math::clamp(text::from_params<size_t>(configuration, "cols", 32), 16, 32)), m_outputs(math::clamp(text::from_params<size_t>(configuration, "dims", 4), 2, 16)), m_folds(1), m_color(text::from_params<color_mode>(configuration, "color", color_mode::rgba)), m_size(math::clamp(text::from_params<size_t>(configuration, "size", 1024), 256, 16 * 1024)) { } namespace { rgba_t make_transparent_color() { return 0; } rgba_t make_light_color() { random_t<rgba_t> rng_red(175, 255); random_t<rgba_t> rng_green(175, 255); random_t<rgba_t> rng_blue(175, 255); return color::make_rgba(rng_red(), rng_green(), rng_blue()); } rect_t make_rect(coord_t rows, coord_t cols) { random_t<coord_t> rng(2, std::min(rows / 4, cols / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(dx, dy, cols - dx - dw, rows - dy - dh); } rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h) { random_t<coord_t> rng(2, std::min(w / 4, h / 4)); const coord_t dx = rng(); const coord_t dy = rng(); const coord_t dw = rng(); const coord_t dh = rng(); return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh); } rect_t make_interior_rect(const rect_t& rect) { return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height()); } image_t make_filled_rect(coord_t rows, coord_t cols) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, make_light_color()); return image; } image_t make_hollow_rect(coord_t rows, coord_t cols) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); image.fill(rect, make_light_color()); image.fill(make_interior_rect(rect), make_transparent_color()); return image; } void fill_circle(image_t& image, const rect_t& rect) { const point_t center = rect.center(); const coord_t cx = center.x(); const coord_t cy = center.y(); const coord_t radius = (std::min(rect.width(), rect.height()) + 1) / 2; const rgba_t rgba = make_light_color(); for (coord_t x = rect.left(); x < rect.right(); x ++) { for (coord_t y = rect.top(); y < rect.bottom(); y ++) { if (math::square(x - cx) + math::square(y - cy) < radius * radius) { image.set(y, x, rgba); } } } } image_t make_filled_circle(coord_t rows, coord_t cols) { const rect_t rect = make_rect(rows, cols); image_t image(rows, cols, color_mode::rgba); image.fill(make_transparent_color()); fill_circle(image, rect); return image; } } bool synthetic_shapes_task_t::load(const string_t &) { random_t<size_t> rng_protocol(1, 10); random_t<size_t> rng_output(1, osize()); random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) / scalar_t(8)); const coord_t rows = static_cast<coord_t>(irows()); const coord_t cols = static_cast<coord_t>(icols()); clear_memory(0); for (size_t f = 0; f < fsize(); f ++) { for (size_t i = 0; i < m_size; i ++) { // random protocol: train vs. test const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test; // random output class: #dots const size_t o = rng_output(); // generate random image background image_t image(irows(), icols(), color()); image.fill(make_light_color()); image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss()); // generate random shapes image_t shape; switch (o) { case 1: shape = make_filled_rect(rows, cols); break; case 2: shape = make_hollow_rect(rows, cols); break; case 3: shape = make_filled_circle(rows, cols); break; default: break; } image.alpha_blend(shape.rgba()); add_image(image); // generate sample sample_t sample(n_images() - 1, sample_region(0, 0)); switch (o) { case 1: sample.m_label = "filled_rectangle"; break; case 2: sample.m_label = "hollow_rectangle"; break; case 3: sample.m_label = "filled_circle"; break; default: sample.m_label = "unkown"; break; } sample.m_target = ncv::class_target(o - 1, osize()); sample.m_fold = {f, p}; add_sample(sample); } } return true; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <algorithm> #include <graphene/chain/protocol/fee_schedule.hpp> #include <fc/smart_ref_impl.hpp> namespace fc { // explicitly instantiate the smart_ref, gcc fails to instantiate it in some release builds //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(smart_ref<graphene::chain::fee_schedule>&&); //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(U&&); //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(const smart_ref&); //template smart_ref<graphene::chain::fee_schedule>::smart_ref(); //template const graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator*() const; } #define MAX_FEE_STABILIZATION_ITERATION 4 namespace graphene { namespace chain { typedef fc::smart_ref<fee_schedule> smart_fee_schedule; static smart_fee_schedule tmp; fee_schedule::fee_schedule() { } fee_schedule fee_schedule::get_default() { fee_schedule result; for( int i = 0; i < fee_parameters().count(); ++i ) { fee_parameters x; x.set_which(i); result.parameters.insert(x); } return result; } struct fee_schedule_validate_visitor { typedef void result_type; template<typename T> void operator()( const T& p )const { //p.validate(); } }; void fee_schedule::validate()const { for( const auto& f : parameters ) f.visit( fee_schedule_validate_visitor() ); } struct calc_fee_visitor { typedef uint64_t result_type; const fee_parameters& param; calc_fee_visitor( const fee_parameters& p ):param(p){} template<typename OpType> result_type operator()( const OpType& op )const { return op.calculate_fee( param.get<typename OpType::fee_parameters_type>() ).value; } }; struct set_fee_visitor { typedef void result_type; asset _fee; set_fee_visitor( asset f ):_fee(f){} template<typename OpType> void operator()( OpType& op )const { op.fee = _fee; } }; struct zero_fee_visitor { typedef void result_type; template<typename ParamType> result_type operator()( ParamType& op )const { memset( (char*)&op, 0, sizeof(op) ); } }; void fee_schedule::zero_all_fees() { *this = get_default(); for( fee_parameters& i : parameters ) i.visit( zero_fee_visitor() ); this->scale = 0; } asset fee_schedule::calculate_fee( const operation& op, const price& core_exchange_rate )const { //idump( (op)(core_exchange_rate) ); fee_parameters params; params.set_which(op.which()); auto itr = parameters.find(params); if( itr != parameters.end() ) params = *itr; auto base_value = op.visit( calc_fee_visitor( params ) ); auto scaled = fc::uint128(base_value) * scale; scaled /= GRAPHENE_100_PERCENT; FC_ASSERT( scaled <= GRAPHENE_MAX_SHARE_SUPPLY ); //idump( (base_value)(scaled)(core_exchange_rate) ); auto result = asset( scaled.to_uint64(), asset_id_type(0) ) * core_exchange_rate; //FC_ASSERT( result * core_exchange_rate >= asset( scaled.to_uint64()) ); while( result * core_exchange_rate < asset( scaled.to_uint64()) ) result.amount++; FC_ASSERT( result.amount <= GRAPHENE_MAX_SHARE_SUPPLY ); return result; } asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const { auto f = calculate_fee( op, core_exchange_rate ); auto f_max = f; for( int i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ ) { op.visit( set_fee_visitor( f_max ) ); auto f2 = calculate_fee( op, core_exchange_rate ); if( f == f2 ) break; f_max = std::max( f_max, f2 ); f = f2; if( i == 0 ) { // no need for warnings on later iterations wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}", ("p", core_exchange_rate) ("op", op) ); } } return f_max; } void chain_parameters::validate()const { current_fees->validate(); FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL ); FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL ); FC_ASSERT( block_interval > 0 ); FC_ASSERT( maintenance_interval > block_interval, "Maintenance interval must be longer than block interval" ); FC_ASSERT( maintenance_interval % block_interval == 0, "Maintenance interval must be a multiple of block interval" ); FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT, "Transaction size limit is too low" ); FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT, "Block size limit is too low" ); FC_ASSERT( maximum_time_until_expiration > block_interval, "Maximum transaction expiration time must be greater than a block interval" ); FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval, "Committee proposal review period must be less than the maximum proposal lifetime" ); } } } // graphene::chain <commit_msg>soft fork to deal bug of Max fee of proprole operation<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <algorithm> #include <graphene/chain/protocol/fee_schedule.hpp> #include <fc/smart_ref_impl.hpp> namespace fc { // explicitly instantiate the smart_ref, gcc fails to instantiate it in some release builds //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(smart_ref<graphene::chain::fee_schedule>&&); //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(U&&); //template graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator=(const smart_ref&); //template smart_ref<graphene::chain::fee_schedule>::smart_ref(); //template const graphene::chain::fee_schedule& smart_ref<graphene::chain::fee_schedule>::operator*() const; } #define MAX_FEE_STABILIZATION_ITERATION 4 namespace graphene { namespace chain { typedef fc::smart_ref<fee_schedule> smart_fee_schedule; static smart_fee_schedule tmp; fee_schedule::fee_schedule() { } fee_schedule fee_schedule::get_default() { fee_schedule result; for( int i = 0; i < fee_parameters().count(); ++i ) { fee_parameters x; x.set_which(i); result.parameters.insert(x); } return result; } struct fee_schedule_validate_visitor { typedef void result_type; template<typename T> void operator()( const T& p )const { //p.validate(); } }; void fee_schedule::validate()const { for( const auto& f : parameters ) f.visit( fee_schedule_validate_visitor() ); } struct calc_fee_visitor { typedef uint64_t result_type; const fee_parameters& param; calc_fee_visitor( const fee_parameters& p ):param(p){} template<typename OpType> result_type operator()( const OpType& op )const { return op.calculate_fee( param.get<typename OpType::fee_parameters_type>() ).value; } }; struct set_fee_visitor { typedef void result_type; asset _fee; set_fee_visitor( asset f ):_fee(f){} template<typename OpType> void operator()( OpType& op )const { op.fee = _fee; } }; struct zero_fee_visitor { typedef void result_type; template<typename ParamType> result_type operator()( ParamType& op )const { memset( (char*)&op, 0, sizeof(op) ); } }; void fee_schedule::zero_all_fees() { *this = get_default(); for( fee_parameters& i : parameters ) i.visit( zero_fee_visitor() ); this->scale = 0; } asset fee_schedule::calculate_fee( const operation& op, const price& core_exchange_rate )const { //idump( (op)(core_exchange_rate) ); fee_parameters params; params.set_which(op.which()); auto itr = parameters.find(params); if( itr != parameters.end() ) params = *itr; auto base_value = op.visit( calc_fee_visitor( params ) ); auto scaled = fc::uint128(base_value) * scale; scaled /= GRAPHENE_100_PERCENT; //soft fork to deal bug of Max fee of proprole operation { if( scaled >=GRAPHENE_MAX_SHARE_SUPPLY) { auto which=op.which(); if(which>=operation::tag< proposal_create_operation >::value && which<=operation::tag< proposal_delete_operation >::value ){ uint64_t temp_fee=300000000LL;//1*RAPHENE_BLOCKCHAIN_PRECISION scaled=scaled-1000000000000000000LL+temp_fee; } if(which==operation::tag< asset_create_operation >::value){ uint64_t temp_fee=10000000000000LL;//100000*GRAPHENE_BLOCKCHAIN_PRECISION scaled=scaled-1000000000000000000LL+temp_fee; } } } FC_ASSERT( scaled <= GRAPHENE_MAX_SHARE_SUPPLY ); //idump( (base_value)(scaled)(core_exchange_rate) ); auto result = asset( scaled.to_uint64(), asset_id_type(0) ) * core_exchange_rate; //FC_ASSERT( result * core_exchange_rate >= asset( scaled.to_uint64()) ); while( result * core_exchange_rate < asset( scaled.to_uint64()) ) result.amount++; FC_ASSERT( result.amount <= GRAPHENE_MAX_SHARE_SUPPLY ); return result; } asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const { auto f = calculate_fee( op, core_exchange_rate ); auto f_max = f; for( int i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ ) { op.visit( set_fee_visitor( f_max ) ); auto f2 = calculate_fee( op, core_exchange_rate ); if( f == f2 ) break; f_max = std::max( f_max, f2 ); f = f2; if( i == 0 ) { // no need for warnings on later iterations wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}", ("p", core_exchange_rate) ("op", op) ); } } return f_max; } void chain_parameters::validate()const { current_fees->validate(); FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT ); FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL ); FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL ); FC_ASSERT( block_interval > 0 ); FC_ASSERT( maintenance_interval > block_interval, "Maintenance interval must be longer than block interval" ); FC_ASSERT( maintenance_interval % block_interval == 0, "Maintenance interval must be a multiple of block interval" ); FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT, "Transaction size limit is too low" ); FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT, "Block size limit is too low" ); FC_ASSERT( maximum_time_until_expiration > block_interval, "Maximum transaction expiration time must be greater than a block interval" ); FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval, "Committee proposal review period must be less than the maximum proposal lifetime" ); } } } // graphene::chain <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: NekMemoryManager.hpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // // A memory manager that allocates memory from thread specific pools. // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H #define NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H #include <LibUtilities/ThreadSpecificPool.hpp> #include <LibUtilities/ErrorUtil.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/list_c.hpp> #include <boost/shared_ptr.hpp> #include <boost/shared_array.hpp> #include <boost/utility/enable_if.hpp> #include <boost/mpl/integral_c.hpp> #include <boost/bind.hpp> #include <boost/type_traits.hpp> #include <iostream> using namespace std; namespace Nektar { /// \brief General purpose memory allocation routines with the ability /// to allocate from thread specific memory pools. /// /// Allows the allocation of pointers, shared pointers, arrays, and /// shared arrays. Each of these options can also be allocated with /// the default C++ new/delete or with thread specific memory pools. /// These memory pools alow multiple threads to use /// the same manager object without blocking while waiting for memory /// allocation from the system. /// /// If you wish to use the memory pool with user defined data types, then /// you must create a static const MemoryPoolEnabler data member in your /// class and set it to eEnabled. Once this is done all uses of the /// MemoryManager with your class will use the memory pool. If you do not /// wish to use the memory manager then set this data member to eDisabled. /// /// For example: /// \code /// /// // This class doesn't use the pool. /// class Disabled /// { /// public: /// Disabled() {} /// /// static const MemoryManager::MemoryPoolEnabler MemoryPoolEnabled = MemoryManager::eDisabled; /// }; /// /// // This class uses the pool. /// class Enabled /// { /// public: /// Enabled() {} /// /// static const MemoryManager::MemoryPoolEnabler MemoryPoolEnabled = MemoryManager::eEnabled; /// }; /// \endcode /// /// class MemoryManager { public: /// \brief Used by clients to mark classes that should use memory pools. enum MemoryPoolEnabler { eDisabled, eEnabled }; //////////////////////////////////////////////////////////////////// /// \name Object Allocation /// Routines to allocate and deallocate individual objects. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Deallocate a pointer allocated by the /// MemoryManager without a memory pool. template<typename DataType> static void Deallocate(DataType*& data, typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { delete data; data = NULL; } /// \brief Deallocate a pointer allocated by the Memory /// Manager with a memory pool. template<typename DataType> static void Deallocate(DataType*& data, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { data->~DataType(); ThreadSpecificPool<sizeof(DataType)>::Deallocate(data); data = NULL; } /// \brief Allocate a pointer to an object of type /// DataType*. /// /// This method based heavily on the boost object pool code. template<typename DataType> static DataType* Allocate( typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType; } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } template<typename DataType, typename Arg1Type> static DataType* Allocate(const Arg1Type& arg1, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType(arg1); } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } template<typename DataType, typename Arg1Type, typename Arg2Type> static DataType* Allocate(const Arg1Type& arg1, const Arg2Type& arg2, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType(arg1, arg2); } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } /// \brief Allocate a pointer without using the memory /// pool. template<typename DataType> static DataType* Allocate( typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { return new DataType(); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Shared Pointer Allocation /// Routines to allocate a single object in a shared pointer. In /// all cases the shared pointer will correctly release memory, /// regardless of how the memory was allocated. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Custom deletion policy for shared pointers. template<typename DataType> static void DeallocateSharedPtr(DataType* data) { Deallocate<DataType>(data); } /// \brief Allocate an object in a shared pointer. template<typename DataType> static boost::shared_ptr<DataType> AllocateSharedPtr() { DataType* data = Allocate<DataType>(); return boost::shared_ptr<DataType>(data, &MemoryManager::DeallocateSharedPtr<DataType>); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Array Allocation /// Allocates an array of user specified data. /// /// Care must be taken when deleting arrays. The ArraySize template /// parameter must match the ArraySize parameter used when allocating /// the array. A mismatch will cause undefined behavior. For this /// reason, the use of the shared_array versions is preferred. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Deallocate a pointer allocated by the MemoryManager without a memory pool. /// \param data The data to be deleted. This parameter will be set to /// NULL when the method is finished. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); delete [] data; data = NULL; } /// \brief Deallocates arrays of fundamental data types. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::enable_if<boost::is_fundamental<DataType> >::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); ThreadSpecificPool<sizeof(DataType)*ArraySize>::Deallocate(data); data = NULL; } /// \brief Deallocate a pointer allocated by the Memory Manager with a memory pool. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); for(unsigned int i = 0; i < ArraySize; ++i) { DataType* memLocation = &data[i]; memLocation->~DataType(); } // Dangerous if I pass in the wrong array size. ThreadSpecificPool<sizeof(DataType)*sizeof(ArraySize)>::Deallocate(data); data = NULL; } /// \brief Allocate ArraySize values in an array of /// DataType using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)*ArraySize>::Allocate()); if( result ) { unsigned int nextObjectToCreate = 0; try { for(unsigned int i = 0; i < ArraySize; ++i) { DataType* memLocation = &result[i]; new (memLocation) DataType; ++nextObjectToCreate; } } catch(...) { for(unsigned int i = 0; i < nextObjectToCreate; ++i) { DataType* memLocation = &result[i]; memLocation->~DataType(); } ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } /// \brief Create an array without using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); return new DataType[ArraySize]; } /// \brief Creates an array of fundamental type using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::enable_if<boost::is_fundamental<DataType> >::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); return static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)*ArraySize>::Allocate()); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Shared Array Allocation /// \{ //////////////////////////////////////////////////////////////////// /// \brief Custom deletion policy for shared arrays. template<unsigned int ArraySize, typename DataType> static void DeallocateSharedArray(DataType* data) { BOOST_STATIC_ASSERT(ArraySize > 0); DeallocateArray<ArraySize, DataType>(data); } /// \brief Allocate a shared array of given size and type. template<unsigned int ArraySize, typename DataType> static boost::shared_array<DataType> AllocateSharedArray() { DataType* data = AllocateArray<ArraySize, DataType>(); void (*deallocator)(DataType *) = &MemoryManager::DeallocateSharedArray<ArraySize, DataType>; return boost::shared_array<DataType>(data, deallocator); } template<typename DataType> static boost::shared_array<DataType> AllocateSharedArray(unsigned int arraySize) { if( arraySize < 10 ) { return MemoryManager::AllocateSharedArray<10, DataType>(); } else if( arraySize < 20 ) { return MemoryManager::AllocateSharedArray<20, DataType>(); } else if( arraySize < 30 ) { return MemoryManager::AllocateSharedArray<30, DataType>(); } else if( arraySize < 40 ) { return MemoryManager::AllocateSharedArray<40, DataType>(); } else if( arraySize < 50 ) { return MemoryManager::AllocateSharedArray<50, DataType>(); } else if( arraySize < 60 ) { return MemoryManager::AllocateSharedArray<60, DataType>(); } else { return boost::shared_array<DataType>(new DataType[arraySize]); } } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// }; // typedef boost access for use in temporary memory allocation typedef boost::shared_array<double> BstShrDArray; typedef boost::shared_array<int> BstShrIArray; inline BstShrDArray GetDoubleTmpSpace(const int size) { return MemoryManager::AllocateSharedArray<double>(size); } inline BstShrIArray GetIntTmpSpace(const int size) { return MemoryManager::AllocateSharedArray<int>(size); } } #endif //NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H /** $Log: NekMemoryManager.hpp,v $ Revision 1.3 2006/05/14 21:31:49 bnelson Modified the upper bound on static shared array allocation. Revision 1.2 2006/05/06 20:36:16 sherwin Modifications to get LocalRegions/Project1D working Revision 1.1 2006/05/04 18:57:43 kirby *** empty log message *** Revision 1.5 2006/04/25 20:17:39 jfrazier Fixed a .Net issue with the deallocator function passed to shared_array. Revision 1.4 2006/04/01 22:00:11 sherwin Changed definition of ASSERT Revision 1.3 2006/03/21 09:21:31 sherwin Introduced NekMemoryManager Revision 1.2 2006/02/26 21:11:40 bnelson Added a variable sized array allocator. Revision 1.1 2006/02/23 07:53:23 bnelson *** empty log message *** **/ <commit_msg>Added allocation functions that pass arguments to the constructors of the objects being created.<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: NekMemoryManager.hpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // // A memory manager that allocates memory from thread specific pools. // //////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H #define NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H #include <LibUtilities/ThreadSpecificPool.hpp> #include <LibUtilities/ErrorUtil.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/list_c.hpp> #include <boost/shared_ptr.hpp> #include <boost/shared_array.hpp> #include <boost/utility/enable_if.hpp> #include <boost/mpl/integral_c.hpp> #include <boost/bind.hpp> #include <boost/type_traits.hpp> namespace Nektar { /// \brief General purpose memory allocation routines with the ability /// to allocate from thread specific memory pools. /// /// Allows the allocation of pointers, shared pointers, arrays, and /// shared arrays. Each of these options can also be allocated with /// the default C++ new/delete or with thread specific memory pools. /// These memory pools alow multiple threads to use /// the same manager object without blocking while waiting for memory /// allocation from the system. /// /// If you wish to use the memory pool with user defined data types, then /// you must create a static const MemoryPoolEnabler data member in your /// class and set it to eEnabled. Once this is done all uses of the /// MemoryManager with your class will use the memory pool. If you do not /// wish to use the memory manager then set this data member to eDisabled. /// /// For example: /// \code /// /// // This class doesn't use the pool. /// class Disabled /// { /// public: /// Disabled() {} /// /// static const MemoryManager::MemoryPoolEnabler MemoryPoolEnabled = MemoryManager::eDisabled; /// }; /// /// // This class uses the pool. /// class Enabled /// { /// public: /// Enabled() {} /// /// static const MemoryManager::MemoryPoolEnabler MemoryPoolEnabled = MemoryManager::eEnabled; /// }; /// \endcode /// /// class MemoryManager { public: /// \brief Used by clients to mark classes that should use memory pools. enum MemoryPoolEnabler { eDisabled, eEnabled }; //////////////////////////////////////////////////////////////////// /// \name Object Allocation /// Routines to allocate and deallocate individual objects. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Deallocate a pointer allocated by the /// MemoryManager without a memory pool. template<typename DataType> static void Deallocate(DataType*& data, typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { delete data; data = NULL; } /// \brief Deallocate a pointer allocated by the Memory /// Manager with a memory pool. template<typename DataType> static void Deallocate(DataType*& data, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { data->~DataType(); ThreadSpecificPool<sizeof(DataType)>::Deallocate(data); data = NULL; } /// \brief Allocate a pointer to an object of type /// DataType*. /// /// This method based heavily on the boost object pool code. template<typename DataType> static DataType* Allocate( typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType; } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } template<typename DataType, typename Arg1Type> static DataType* Allocate(const Arg1Type& arg1, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType(arg1); } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } template<typename DataType, typename Arg1Type, typename Arg2Type> static DataType* Allocate(const Arg1Type& arg1, const Arg2Type& arg2, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)>::Allocate()); if( result ) { try { // This is placement new, constructing the // object inside the memory returned by the // pool. new (result) DataType(arg1, arg2); } catch(...) { // Clean up the memory since the object didn't // get created successfully. Note that we // don't call the destructor here because the // object wasn't fully created. ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } /// \brief Allocate a pointer without using the memory /// pool. template<typename DataType> static DataType* Allocate( typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { return new DataType(); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Shared Pointer Allocation /// Routines to allocate a single object in a shared pointer. In /// all cases the shared pointer will correctly release memory, /// regardless of how the memory was allocated. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Custom deletion policy for shared pointers. template<typename DataType> static void DeallocateSharedPtr(DataType* data) { Deallocate<DataType>(data); } /// \brief Allocate an object in a shared pointer. template<typename DataType> static boost::shared_ptr<DataType> AllocateSharedPtr() { DataType* data = Allocate<DataType>(); return boost::shared_ptr<DataType>(data, &MemoryManager::DeallocateSharedPtr<DataType>); } template<typename DataType, typename Arg1Type> static boost::shared_ptr<DataType> AllocateSharedPtr(const Arg1Type& arg1) { DataType* data = Allocate<DataType>(arg1); return boost::shared_ptr<DataType>(data, &MemoryManager::DeallocateSharedPtr<DataType>); } template<typename DataType, typename Arg1Type, typename Arg2Type> static boost::shared_ptr<DataType> AllocateSharedPtr(const Arg1Type& arg1, const Arg2Type& arg2) { DataType* data = Allocate<DataType>(arg1, arg2); return boost::shared_ptr<DataType>(data, &MemoryManager::DeallocateSharedPtr<DataType>); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Array Allocation /// Allocates an array of user specified data. /// /// Care must be taken when deleting arrays. The ArraySize template /// parameter must match the ArraySize parameter used when allocating /// the array. A mismatch will cause undefined behavior. For this /// reason, the use of the shared_array versions is preferred. /// \{ //////////////////////////////////////////////////////////////////// /// \brief Deallocate a pointer allocated by the MemoryManager without a memory pool. /// \param data The data to be deleted. This parameter will be set to /// NULL when the method is finished. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); delete [] data; data = NULL; } /// \brief Deallocates arrays of fundamental data types. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::enable_if<boost::is_fundamental<DataType> >::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); ThreadSpecificPool<sizeof(DataType)*ArraySize>::Deallocate(data); data = NULL; } /// \brief Deallocate a pointer allocated by the Memory Manager with a memory pool. template<unsigned int ArraySize, typename DataType> static void DeallocateArray(DataType*& data, typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); for(unsigned int i = 0; i < ArraySize; ++i) { DataType* memLocation = &data[i]; memLocation->~DataType(); } // Dangerous if I pass in the wrong array size. ThreadSpecificPool<sizeof(DataType)*sizeof(ArraySize)>::Deallocate(data); data = NULL; } /// \brief Allocate ArraySize values in an array of /// DataType using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::enable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); DataType* result = static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)*ArraySize>::Allocate()); if( result ) { unsigned int nextObjectToCreate = 0; try { for(unsigned int i = 0; i < ArraySize; ++i) { DataType* memLocation = &result[i]; new (memLocation) DataType; ++nextObjectToCreate; } } catch(...) { for(unsigned int i = 0; i < nextObjectToCreate; ++i) { DataType* memLocation = &result[i]; memLocation->~DataType(); } ThreadSpecificPool<sizeof(DataType)>::Deallocate(result); throw; } } return result; } /// \brief Create an array without using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::disable_if_c<DataType::MemoryPoolEnabled>::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); return new DataType[ArraySize]; } /// \brief Creates an array of fundamental type using the memory pool. template<unsigned int ArraySize, typename DataType> static DataType* AllocateArray( typename boost::enable_if<boost::is_fundamental<DataType> >::type* p = NULL) { BOOST_STATIC_ASSERT(ArraySize > 0); return static_cast<DataType*>(ThreadSpecificPool<sizeof(DataType)*ArraySize>::Allocate()); } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// \name Shared Array Allocation /// \{ //////////////////////////////////////////////////////////////////// /// \brief Custom deletion policy for shared arrays. template<unsigned int ArraySize, typename DataType> static void DeallocateSharedArray(DataType* data) { BOOST_STATIC_ASSERT(ArraySize > 0); DeallocateArray<ArraySize, DataType>(data); } /// \brief Allocate a shared array of given size and type. template<unsigned int ArraySize, typename DataType> static boost::shared_array<DataType> AllocateSharedArray() { DataType* data = AllocateArray<ArraySize, DataType>(); void (*deallocator)(DataType *) = &MemoryManager::DeallocateSharedArray<ArraySize, DataType>; return boost::shared_array<DataType>(data, deallocator); } template<typename DataType> static boost::shared_array<DataType> AllocateSharedArray(unsigned int arraySize) { if( arraySize < 10 ) { return MemoryManager::AllocateSharedArray<10, DataType>(); } else if( arraySize < 20 ) { return MemoryManager::AllocateSharedArray<20, DataType>(); } else if( arraySize < 30 ) { return MemoryManager::AllocateSharedArray<30, DataType>(); } else if( arraySize < 40 ) { return MemoryManager::AllocateSharedArray<40, DataType>(); } else if( arraySize < 50 ) { return MemoryManager::AllocateSharedArray<50, DataType>(); } else if( arraySize < 60 ) { return MemoryManager::AllocateSharedArray<60, DataType>(); } else { return boost::shared_array<DataType>(new DataType[arraySize]); } } //////////////////////////////////////////////////////////////////// /// \} //////////////////////////////////////////////////////////////////// }; // typedef boost access for use in temporary memory allocation typedef boost::shared_array<double> BstShrDArray; typedef boost::shared_array<int> BstShrIArray; inline BstShrDArray GetDoubleTmpSpace(const int size) { return MemoryManager::AllocateSharedArray<double>(size); } inline BstShrIArray GetIntTmpSpace(const int size) { return MemoryManager::AllocateSharedArray<int>(size); } } #endif //NEKTAR_LIB_UTILITIES_NEK_MEMORY_MANAGER_H /** $Log: NekMemoryManager.hpp,v $ Revision 1.4 2006/05/15 04:13:36 bnelson no message Revision 1.3 2006/05/14 21:31:49 bnelson Modified the upper bound on static shared array allocation. Revision 1.2 2006/05/06 20:36:16 sherwin Modifications to get LocalRegions/Project1D working Revision 1.1 2006/05/04 18:57:43 kirby *** empty log message *** Revision 1.5 2006/04/25 20:17:39 jfrazier Fixed a .Net issue with the deallocator function passed to shared_array. Revision 1.4 2006/04/01 22:00:11 sherwin Changed definition of ASSERT Revision 1.3 2006/03/21 09:21:31 sherwin Introduced NekMemoryManager Revision 1.2 2006/02/26 21:11:40 bnelson Added a variable sized array allocator. Revision 1.1 2006/02/23 07:53:23 bnelson *** empty log message *** **/ <|endoftext|>
<commit_before>#include "editorView.h" #include <QtCore/QTimeLine> using namespace qReal; int const zoomAnimationInterval = 20; int const zoomAnimationTimes = 4; EditorView::EditorView(QWidget *parent) : QGraphicsView(parent) , mMouseOldPosition() , mWheelPressed(false) , mTouchManager(this) { setRenderHint(QPainter::Antialiasing, true); mScene = new EditorViewScene(this); connect(mScene, SIGNAL(zoomIn()), this, SLOT(zoomIn())); connect(mScene, SIGNAL(zoomOut()), this, SLOT(zoomOut())); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setResizeAnchor(QGraphicsView::AnchorUnderMouse); mMVIface = new EditorViewMViface(this, mScene); setScene(mScene); setAcceptDrops(true); setDragMode(RubberBandDrag); setEnabled(false); setMouseTracking(true); setAlignment(Qt::AlignCenter); connect(&mTouchManager, SIGNAL(gestureStarted()), mScene, SLOT(deleteGesture())); } EditorView::~EditorView() { delete mMVIface; delete mScene; } EditorViewMViface *EditorView::mvIface() const { return mMVIface; } EditorViewScene *EditorView::editorViewScene() const { return mScene; } void EditorView::toggleAntialiasing(bool checked) { setRenderHint(QPainter::Antialiasing, checked); setRenderHint(QPainter::SmoothPixmapTransform, checked); } void EditorView::zoomIn() { if (!mWheelPressed) { startAnimation(SLOT(zoomInTime())); } } void EditorView::zoomOut() { if (!mWheelPressed) { startAnimation(SLOT(zoomOutTime())); } } void EditorView::checkGrid() { if (SettingsManager::value("ShowGrid").toBool()) { mScene->setNeedDrawGrid(mScene->realIndexGrid() >= 2 && mScene->realIndexGrid() <= 380); } } void EditorView::startAnimation(char const *slot) { QTimeLine *anim = new QTimeLine(zoomAnimationTimes * zoomAnimationInterval, this); anim->setUpdateInterval(zoomAnimationInterval); connect(anim, SIGNAL(valueChanged(qreal)), this, slot); connect(anim, SIGNAL(finished()), this, SLOT(animFinished())); anim->start(); } void EditorView::setMainWindow(qReal::MainWindow *mainWindow) { mMVIface->scene()->setMainWindow(mainWindow); } void EditorView::setDrawSceneGrid(bool show) { mScene->setNeedDrawGrid(show); mScene->invalidate(); } void EditorView::mouseMoveEvent(QMouseEvent *event) { if (mWheelPressed) { if (mMouseOldPosition != QPointF()) { qreal const scaleFactor = transform().m11(); qreal const dx = (event->localPos().x() - mMouseOldPosition.x()) / scaleFactor; qreal const dy = (event->localPos().y() - mMouseOldPosition.y()) / scaleFactor; viewport()->scroll(dx, dy); } mMouseOldPosition = event->localPos(); } QGraphicsView::mouseMoveEvent(event); if (event->buttons() & Qt::RightButton) { setDragMode(NoDrag); } else { if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ControlModifier)) { setDragMode(RubberBandDrag); mScene->itemSelectUpdate(); /*} else if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ShiftModifier)) { setDragMode(ScrollHandDrag); // (see #615) mScene->itemSelectUpdate();*/ } else if (event->buttons() & Qt::LeftButton ) { EdgeElement *newEdgeEl = dynamic_cast<EdgeElement *>(itemAt(event->pos())); if (newEdgeEl && newEdgeEl->isBreakPointPressed()) { newEdgeEl->breakPointUnpressed(); setDragMode(NoDrag); } } } if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::mouseReleaseEvent(QMouseEvent *event) { if (!(event->buttons() & Qt::MidButton)) { mWheelPressed = false; mMouseOldPosition = QPointF(); } QGraphicsView::mouseReleaseEvent(event); if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::mousePressEvent(QMouseEvent *event) { mWheelPressed = (event->buttons() & Qt::MidButton); mMouseOldPosition = QPointF(); if (!mWheelPressed) { QGraphicsView::mousePressEvent(event); } if (event->buttons() & Qt::LeftButton) { if (!(event->buttons() & Qt::RightButton) && !mTouchManager.isGestureRunning() && !itemAt(event->pos())) { setDragMode(RubberBandDrag); } if (event->modifiers() & Qt::ControlModifier) { mScene->itemSelectUpdate(); } } } void EditorView::scrollContentsBy(int dx, int dy) { QGraphicsView::scrollContentsBy(dx, dy); if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::keyPressEvent(QKeyEvent *event) { QGraphicsView::keyPressEvent(event); if (event->key() == Qt::Key_Space) { setDragMode(QGraphicsView::ScrollHandDrag); event->accept(); } } void EditorView::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Space) { setDragMode(QGraphicsView::RubberBandDrag); } else { QGraphicsView::keyPressEvent(event); } } bool EditorView::viewportEvent(QEvent *event) { switch (event->type()) { case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: // For some reason touch viewport events can`t be processed in manual event // filters, so catching them here return mTouchManager.processTouchEvent(static_cast<QTouchEvent *>(event)); default: break; } return QGraphicsView::viewportEvent(event); } void EditorView::invalidateScene() { scene()->invalidate(); } void EditorView::ensureElementVisible(Element const * const element) { if (element) { qreal const widgetWidth = size().width(); qreal const widgetHeight = size().height(); qreal const elementWidth = element->boundingRect().width(); qreal const elementHeight = element->boundingRect().height(); ensureVisible(element, (widgetWidth - elementWidth) / 2, (widgetHeight - elementHeight) / 2); } } void EditorView::ensureElementVisible(Element const * const element , int xMargin, int yMargin) { if (element) { ensureVisible(element, xMargin, yMargin); } } void EditorView::setTitlesVisible(bool visible) { mScene->setTitlesVisible(visible); } void EditorView::zoomInTime() { qreal const zoomFactor = SettingsManager::value("zoomFactor").toReal(); zoom(zoomFactor); } void EditorView::zoomOutTime() { qreal const zoomFactor = 1 / SettingsManager::value("zoomFactor").toReal(); zoom(zoomFactor); } void EditorView::animFinished() { delete sender(); } void EditorView::zoom(qreal const zoomFactor) { qreal const oldScale = transform().m11(); setSceneRect(mScene->sceneRect()); scale(zoomFactor, zoomFactor); qreal const currentScale = transform().m11(); qreal const maxScale = SettingsManager::value("maxZoom").toReal(); qreal const minScale = SettingsManager::value("minZoom").toReal(); if (currentScale > maxScale) { qreal const scaleNormalizer = maxScale / currentScale; scale(scaleNormalizer, scaleNormalizer); } if (currentScale < minScale) { qreal const scaleNormalizer = minScale / currentScale; scale(scaleNormalizer, scaleNormalizer); } if (SettingsManager::value("ShowGrid").toBool()) { mScene->setRealIndexGrid(mScene->realIndexGrid() * transform().m11() / oldScale); } checkGrid(); } <commit_msg>Corrected scaling behaviour after maximum or minimum is reached<commit_after>#include "editorView.h" #include <QtCore/QTimeLine> #include <qrutils/mathUtils/math.h> using namespace qReal; int const zoomAnimationInterval = 20; int const zoomAnimationTimes = 4; EditorView::EditorView(QWidget *parent) : QGraphicsView(parent) , mMouseOldPosition() , mWheelPressed(false) , mTouchManager(this) { setRenderHint(QPainter::Antialiasing, true); mScene = new EditorViewScene(this); connect(mScene, SIGNAL(zoomIn()), this, SLOT(zoomIn())); connect(mScene, SIGNAL(zoomOut()), this, SLOT(zoomOut())); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setResizeAnchor(QGraphicsView::AnchorUnderMouse); mMVIface = new EditorViewMViface(this, mScene); setScene(mScene); setAcceptDrops(true); setDragMode(RubberBandDrag); setEnabled(false); setMouseTracking(true); setAlignment(Qt::AlignCenter); connect(&mTouchManager, SIGNAL(gestureStarted()), mScene, SLOT(deleteGesture())); } EditorView::~EditorView() { delete mMVIface; delete mScene; } EditorViewMViface *EditorView::mvIface() const { return mMVIface; } EditorViewScene *EditorView::editorViewScene() const { return mScene; } void EditorView::toggleAntialiasing(bool checked) { setRenderHint(QPainter::Antialiasing, checked); setRenderHint(QPainter::SmoothPixmapTransform, checked); } void EditorView::zoomIn() { if (!mWheelPressed) { startAnimation(SLOT(zoomInTime())); } } void EditorView::zoomOut() { if (!mWheelPressed) { startAnimation(SLOT(zoomOutTime())); } } void EditorView::checkGrid() { if (SettingsManager::value("ShowGrid").toBool()) { mScene->setNeedDrawGrid(mScene->realIndexGrid() >= 2 && mScene->realIndexGrid() <= 380); } } void EditorView::startAnimation(char const *slot) { QTimeLine *anim = new QTimeLine(zoomAnimationTimes * zoomAnimationInterval, this); anim->setUpdateInterval(zoomAnimationInterval); connect(anim, SIGNAL(valueChanged(qreal)), this, slot); connect(anim, SIGNAL(finished()), this, SLOT(animFinished())); anim->start(); } void EditorView::setMainWindow(qReal::MainWindow *mainWindow) { mMVIface->scene()->setMainWindow(mainWindow); } void EditorView::setDrawSceneGrid(bool show) { mScene->setNeedDrawGrid(show); mScene->invalidate(); } void EditorView::mouseMoveEvent(QMouseEvent *event) { if (mWheelPressed) { if (mMouseOldPosition != QPointF()) { qreal const scaleFactor = transform().m11(); qreal const dx = (event->localPos().x() - mMouseOldPosition.x()) / scaleFactor; qreal const dy = (event->localPos().y() - mMouseOldPosition.y()) / scaleFactor; viewport()->scroll(dx, dy); } mMouseOldPosition = event->localPos(); } QGraphicsView::mouseMoveEvent(event); if (event->buttons() & Qt::RightButton) { setDragMode(NoDrag); } else { if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ControlModifier)) { setDragMode(RubberBandDrag); mScene->itemSelectUpdate(); /*} else if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ShiftModifier)) { setDragMode(ScrollHandDrag); // (see #615) mScene->itemSelectUpdate();*/ } else if (event->buttons() & Qt::LeftButton ) { EdgeElement *newEdgeEl = dynamic_cast<EdgeElement *>(itemAt(event->pos())); if (newEdgeEl && newEdgeEl->isBreakPointPressed()) { newEdgeEl->breakPointUnpressed(); setDragMode(NoDrag); } } } if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::mouseReleaseEvent(QMouseEvent *event) { if (!(event->buttons() & Qt::MidButton)) { mWheelPressed = false; mMouseOldPosition = QPointF(); } QGraphicsView::mouseReleaseEvent(event); if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::mousePressEvent(QMouseEvent *event) { mWheelPressed = (event->buttons() & Qt::MidButton); mMouseOldPosition = QPointF(); if (!mWheelPressed) { QGraphicsView::mousePressEvent(event); } if (event->buttons() & Qt::LeftButton) { if (!(event->buttons() & Qt::RightButton) && !mTouchManager.isGestureRunning() && !itemAt(event->pos())) { setDragMode(RubberBandDrag); } if (event->modifiers() & Qt::ControlModifier) { mScene->itemSelectUpdate(); } } } void EditorView::scrollContentsBy(int dx, int dy) { QGraphicsView::scrollContentsBy(dx, dy); if (mScene->getNeedDrawGrid()) { mScene->invalidate(); } } void EditorView::keyPressEvent(QKeyEvent *event) { QGraphicsView::keyPressEvent(event); if (event->key() == Qt::Key_Space) { setDragMode(QGraphicsView::ScrollHandDrag); event->accept(); } } void EditorView::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Space) { setDragMode(QGraphicsView::RubberBandDrag); } else { QGraphicsView::keyPressEvent(event); } } bool EditorView::viewportEvent(QEvent *event) { switch (event->type()) { case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: // For some reason touch viewport events can`t be processed in manual event // filters, so catching them here return mTouchManager.processTouchEvent(static_cast<QTouchEvent *>(event)); default: break; } return QGraphicsView::viewportEvent(event); } void EditorView::invalidateScene() { scene()->invalidate(); } void EditorView::ensureElementVisible(Element const * const element) { if (element) { qreal const widgetWidth = size().width(); qreal const widgetHeight = size().height(); qreal const elementWidth = element->boundingRect().width(); qreal const elementHeight = element->boundingRect().height(); ensureVisible(element, (widgetWidth - elementWidth) / 2, (widgetHeight - elementHeight) / 2); } } void EditorView::ensureElementVisible(Element const * const element , int xMargin, int yMargin) { if (element) { ensureVisible(element, xMargin, yMargin); } } void EditorView::setTitlesVisible(bool visible) { mScene->setTitlesVisible(visible); } void EditorView::zoomInTime() { qreal const zoomFactor = SettingsManager::value("zoomFactor").toReal(); zoom(zoomFactor); } void EditorView::zoomOutTime() { qreal const zoomFactor = 1 / SettingsManager::value("zoomFactor").toReal(); zoom(zoomFactor); } void EditorView::animFinished() { delete sender(); } void EditorView::zoom(qreal const zoomFactor) { qreal const oldScale = transform().m11(); qreal const maxScale = SettingsManager::value("maxZoom").toReal(); qreal const minScale = SettingsManager::value("minZoom").toReal(); if ((zoomFactor > 1 && mathUtils::Math::geq(oldScale, maxScale)) || (zoomFactor < 1 && mathUtils::Math::leq(oldScale, minScale))) { return; } setSceneRect(mScene->sceneRect()); scale(zoomFactor, zoomFactor); if (SettingsManager::value("ShowGrid").toBool()) { mScene->setRealIndexGrid(mScene->realIndexGrid() * zoomFactor); } checkGrid(); } <|endoftext|>
<commit_before>#include "File.hpp" #include "CompressedFile.hpp" #include "utils.hpp" #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sstream> #include <utility> #include <iostream> #include <cerrno> #include <system_error> extern "C" { # include <solv/solv_xfopen.h> }; namespace libdnf { std::unique_ptr<File> File::newFile(const std::string &filePath) { if (solv_xfopen_iscompressed(filePath.c_str()) == 1) { return std::unique_ptr<CompressedFile>(new CompressedFile(filePath)); } else { return std::unique_ptr<File>(new File(filePath)); } } File::File(const std::string &filePath) : filePath(filePath) , file(nullptr) {} File::~File() { try { close(); } catch (IOError &) {} } void File::open(const char *mode) { file = fopen(filePath.c_str(), mode); if (!file) { throw OpenError(filePath, std::system_category().message(errno)); } } void File::close() { if (file == nullptr) return; if (fclose(file) != 0) { throw CloseError(filePath); } file = nullptr; } size_t File::read(char *buffer, size_t count) { size_t ret = fread(buffer, sizeof(char), count, file); if (ret != count && ferror(file) != 0) { throw ReadError("Error while reading file \"" + filePath + "\"."); } return ret; } bool File::readLine(std::string &line) { char *buffer = nullptr; size_t size = 0; if (getline(&buffer, &size, file) == -1) { free(buffer); return false; } line = buffer; free(buffer); return true; } std::string File::getContent() { if (!file) { throw NotOpenedException(filePath); } fseek(file, 0, SEEK_END); auto fileSize = ftell(file); if (fileSize == -1) throw IOError(filePath); rewind(file); std::string content(fileSize, '\0'); read(&content.front(), fileSize); return content; } } <commit_msg>utils/File: Set FILE* to nullptr on close error<commit_after>#include "File.hpp" #include "CompressedFile.hpp" #include "utils.hpp" #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sstream> #include <utility> #include <iostream> #include <cerrno> #include <system_error> extern "C" { # include <solv/solv_xfopen.h> }; namespace libdnf { std::unique_ptr<File> File::newFile(const std::string &filePath) { if (solv_xfopen_iscompressed(filePath.c_str()) == 1) { return std::unique_ptr<CompressedFile>(new CompressedFile(filePath)); } else { return std::unique_ptr<File>(new File(filePath)); } } File::File(const std::string &filePath) : filePath(filePath) , file(nullptr) {} File::~File() { try { close(); } catch (IOError &) {} } void File::open(const char *mode) { file = fopen(filePath.c_str(), mode); if (!file) { throw OpenError(filePath, std::system_category().message(errno)); } } void File::close() { if (file == nullptr) return; if (fclose(file) != 0) { file = nullptr; throw CloseError(filePath); } file = nullptr; } size_t File::read(char *buffer, size_t count) { size_t ret = fread(buffer, sizeof(char), count, file); if (ret != count && ferror(file) != 0) { throw ReadError("Error while reading file \"" + filePath + "\"."); } return ret; } bool File::readLine(std::string &line) { char *buffer = nullptr; size_t size = 0; if (getline(&buffer, &size, file) == -1) { free(buffer); return false; } line = buffer; free(buffer); return true; } std::string File::getContent() { if (!file) { throw NotOpenedException(filePath); } fseek(file, 0, SEEK_END); auto fileSize = ftell(file); if (fileSize == -1) throw IOError(filePath); rewind(file); std::string content(fileSize, '\0'); read(&content.front(), fileSize); return content; } } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file ExtVM.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "ExtVM.h" #include "Executive.h" using namespace std; using namespace dev; using namespace dev::eth; bool ExtVM::call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp, Address _myAddressOverride, Address _codeAddressOverride) { Executive e(m_s, lastHashes, depth + 1); if (!e.call(_receiveAddress, _codeAddressOverride ? _codeAddressOverride : _receiveAddress, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, io_gas, origin)) { e.go(_onOp); e.accrueSubState(sub); } io_gas = e.endGas(); e.out().copyTo(_out); return !e.excepted(); } h160 ExtVM::create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp) { // Increment associated nonce for sender. m_s.noteSending(myAddress); Executive e(m_s, lastHashes, depth + 1); if (!e.create(myAddress, _endowment, gasPrice, io_gas, _code, origin)) { e.go(_onOp); e.accrueSubState(sub); } io_gas = e.endGas(); return e.newAddress(); } <commit_msg>fix CallCode to address 0<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file ExtVM.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "ExtVM.h" #include "Executive.h" using namespace std; using namespace dev; using namespace dev::eth; bool ExtVM::call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp, Address _myAddressOverride, Address _codeAddressOverride) { Executive e(m_s, lastHashes, depth + 1); if (!e.call(_receiveAddress, _codeAddressOverride, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, io_gas, origin)) { e.go(_onOp); e.accrueSubState(sub); } io_gas = e.endGas(); e.out().copyTo(_out); return !e.excepted(); } h160 ExtVM::create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp) { // Increment associated nonce for sender. m_s.noteSending(myAddress); Executive e(m_s, lastHashes, depth + 1); if (!e.create(myAddress, _endowment, gasPrice, io_gas, _code, origin)) { e.go(_onOp); e.accrueSubState(sub); } io_gas = e.endGas(); return e.newAddress(); } <|endoftext|>
<commit_before>/* SPI.cpp - SPI library for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. 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 "SPI.h" #include "HardwareSerial.h" typedef union { uint32_t regValue; struct { unsigned regL :6; unsigned regH :6; unsigned regN :6; unsigned regPre :13; unsigned regEQU :1; }; } spiClk_t; SPIClass SPI; SPIClass::SPIClass() { useHwCs = false; } void SPIClass::begin() { pinMode(SCK, SPECIAL); ///< GPIO14 pinMode(MISO, SPECIAL); ///< GPIO12 pinMode(MOSI, SPECIAL); ///< GPIO13 SPI1C = 0; setFrequency(1000000); ///< 1MHz SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE; SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO); SPI1C1 = 0; } void SPIClass::end() { pinMode(SCK, INPUT); pinMode(MISO, INPUT); pinMode(MOSI, INPUT); if(useHwCs) { pinMode(SS, INPUT); } } void SPIClass::setHwCs(bool use) { if(use) { pinMode(SS, SPECIAL); ///< GPIO15 SPI1U |= (SPIUCSSETUP | SPIUCSHOLD); } else { if(useHwCs) { pinMode(SS, INPUT); SPI1U &= ~(SPIUCSSETUP | SPIUCSHOLD); } } useHwCs = use; } void SPIClass::beginTransaction(SPISettings settings) { while(SPI1CMD & SPIBUSY) {} setFrequency(settings._clock); setBitOrder(settings._bitOrder); setDataMode(settings._dataMode); } void SPIClass::endTransaction() { } void SPIClass::setDataMode(uint8_t dataMode) { /** SPI_MODE0 0x00 - CPOL: 0 CPHA: 0 SPI_MODE1 0x01 - CPOL: 0 CPHA: 1 SPI_MODE2 0x10 - CPOL: 1 CPHA: 0 SPI_MODE3 0x11 - CPOL: 1 CPHA: 1 */ bool CPOL = (dataMode & 0x10); ///< CPOL (Clock Polarity) bool CPHA = (dataMode & 0x01); ///< CPHA (Clock Phase) if(CPHA) { SPI1U |= (SPIUSME); } else { SPI1U &= ~(SPIUSME); } if(CPOL) { //todo How set CPOL??? } } void SPIClass::setBitOrder(uint8_t bitOrder) { if(bitOrder == MSBFIRST) { SPI1C &= ~(SPICWBO | SPICRBO); } else { SPI1C |= (SPICWBO | SPICRBO); } } /** * calculate the Frequency based on the register value * @param reg * @return */ static uint32_t ClkRegToFreq(spiClk_t * reg) { return (ESP8266_CLOCK / ((reg->regPre + 1) * (reg->regN + 1))); } void SPIClass::setFrequency(uint32_t freq) { static uint32_t lastSetFrequency = 0; static uint32_t lastSetRegister = 0; if(freq >= ESP8266_CLOCK) { setClockDivider(0x80000000); return; } if(lastSetFrequency == freq && lastSetRegister == SPI1CLK) { // do nothing (speed optimization) return; } const spiClk_t minFreqReg = { 0x7FFFF000 }; uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg); if(freq < minFreq) { // use minimum possible clock setClockDivider(minFreqReg.regValue); lastSetRegister = SPI1CLK; lastSetFrequency = freq; return; } uint8_t calN = 1; spiClk_t bestReg = { 0 }; int32_t bestFreq = 0; // find the best match while(calN <= 0x3F) { // 0x3F max for N spiClk_t reg = { 0 }; int32_t calFreq; int32_t calPre; int8_t calPreVari = -2; reg.regN = calN; while(calPreVari++ <= 1) { // test different variants for Pre (we calculate in int so we miss the decimals, testing is the easyest and fastest way) calPre = (((ESP8266_CLOCK / (reg.regN + 1)) / freq) - 1) + calPreVari; if(calPre > 0x1FFF) { reg.regPre = 0x1FFF; // 8191 } else if(calPre <= 0) { reg.regPre = 0; } else { reg.regPre = calPre; } reg.regL = ((reg.regN + 1) / 2); // reg.regH = (reg.regN - reg.regL); // test calculation calFreq = ClkRegToFreq(&reg); //os_printf("-----[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d = %d\n", reg.regValue, freq, reg.regEQU, reg.regPre, reg.regN, reg.regH, reg.regL, calFreq); if(calFreq == (int32_t) freq) { // accurate match use it! memcpy(&bestReg, &reg, sizeof(bestReg)); break; } else if(calFreq < (int32_t) freq) { // never go over the requested frequency if(abs(freq - calFreq) < abs(freq - bestFreq)) { bestFreq = calFreq; memcpy(&bestReg, &reg, sizeof(bestReg)); } } } if(calFreq == (int32_t) freq) { // accurate match use it! break; } calN++; } // os_printf("[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d\t - Real Frequency: %d\n", bestReg.regValue, freq, bestReg.regEQU, bestReg.regPre, bestReg.regN, bestReg.regH, bestReg.regL, ClkRegToFreq(&bestReg)); setClockDivider(bestReg.regValue); lastSetRegister = SPI1CLK; lastSetFrequency = freq; } void SPIClass::setClockDivider(uint32_t clockDiv) { if(clockDiv == 0x80000000) { GPMUX |= (1 << 9); // Set bit 9 if sysclock required } else { GPMUX &= ~(1 << 9); } SPI1CLK = clockDiv; } inline void SPIClass::setDataBits(uint16_t bits) { const uint32_t mask = ~((SPIMMOSI << SPILMOSI) | (SPIMMISO << SPILMISO)); bits--; SPI1U1 = ((SPI1U1 & mask) | ((bits << SPILMOSI) | (bits << SPILMISO))); } uint8_t SPIClass::transfer(uint8_t data) { while(SPI1CMD & SPIBUSY) {} // reset to 8Bit mode setDataBits(8); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} return (uint8_t) (SPI1W0 & 0xff); } uint16_t SPIClass::transfer16(uint16_t data) { union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; in.val = data; if((SPI1C & (SPICWBO | SPICRBO))) { //MSBFIRST out.msb = transfer(in.msb); out.lsb = transfer(in.lsb); } else { //LSBFIRST out.lsb = transfer(in.lsb); out.msb = transfer(in.msb); } return out.val; } void SPIClass::write(uint8_t data) { while(SPI1CMD & SPIBUSY) {} // reset to 8Bit mode setDataBits(8); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} } void SPIClass::write16(uint16_t data) { write16(data, !(SPI1C & (SPICWBO | SPICRBO))); } void SPIClass::write16(uint16_t data, bool msb) { while(SPI1CMD & SPIBUSY) {} // Set to 16Bits transfer setDataBits(16); if(msb) { // MSBFIRST Byte first SPI1W0 = (data >> 8) | (data << 8); SPI1CMD |= SPIBUSY; } else { // LSBFIRST Byte first SPI1W0 = data; SPI1CMD |= SPIBUSY; } while(SPI1CMD & SPIBUSY) {} } void SPIClass::write32(uint32_t data) { write32(data, !(SPI1C & (SPICWBO | SPICRBO))); } void SPIClass::write32(uint32_t data, bool msb) { while(SPI1CMD & SPIBUSY) {} // Set to 32Bits transfer setDataBits(32); if(msb) { union { uint32_t l; uint8_t b[4]; } data_; data_.l = data; // MSBFIRST Byte first SPI1W0 = (data_.b[3] | (data_.b[2] << 8) | (data_.b[1] << 16) | (data_.b[0] << 24)); SPI1CMD |= SPIBUSY; } else { // LSBFIRST Byte first SPI1W0 = data; SPI1CMD |= SPIBUSY; } while(SPI1CMD & SPIBUSY) {} } /** * Note: * data need to be aligned to 32Bit * or you get an Fatal exception (9) * @param data uint8_t * * @param size uint32_t */ void SPIClass::writeBytes(uint8_t * data, uint32_t size) { while(size) { if(size > 64) { writeBytes_(data, 64); size -= 64; data += 64; } else { writeBytes_(data, size); size = 0; } } } void SPIClass::writeBytes_(uint8_t * data, uint8_t size) { while(SPI1CMD & SPIBUSY) {} // Set Bits to transfer setDataBits(size * 8); volatile uint32_t * fifoPtr = &SPI1W0; uint32_t * dataPtr = (uint32_t*) data; uint8_t dataSize = ((size + 3) / 4); while(dataSize--) { *fifoPtr = *dataPtr; dataPtr++; fifoPtr++; } SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} } /** * Note: * data need to be aligned to 32Bit * or you get an Fatal exception (9) * @param data uint8_t * * @param size uint8_t max for size is 64Byte * @param repeat uint32_t */ void SPIClass::writePattern(uint8_t * data, uint8_t size, uint32_t repeat) { if(size > 64) return; //max Hardware FIFO uint32_t byte = (size * repeat); uint8_t r = (64 / size); while(byte) { if(byte > 64) { writePattern_(data, size, r); byte -= 64; } else { writePattern_(data, size, (byte / size)); byte = 0; } } } void SPIClass::writePattern_(uint8_t * data, uint8_t size, uint8_t repeat) { uint8_t bytes = (size * repeat); uint8_t buffer[64]; uint8_t * bufferPtr = &buffer[0]; uint8_t * dataPtr; uint8_t dataSize = bytes; for(uint8_t i = 0; i < repeat; i++) { dataSize = size; dataPtr = data; while(dataSize--) { *bufferPtr = *dataPtr; dataPtr++; bufferPtr++; } } writeBytes(&buffer[0], bytes); } /** * Note: * in and out need to be aligned to 32Bit * or you get an Fatal exception (9) * @param out uint8_t * * @param in uint8_t * * @param size uint32_t */ void SPIClass::transferBytes(uint8_t * out, uint8_t * in, uint32_t size) { while(size) { if(size > 64) { transferBytes_(out, in, 64); size -= 64; if(out) out += 64; if(in) in += 64; } else { transferBytes_(out, in, size); size = 0; } } } void SPIClass::transferBytes_(uint8_t * out, uint8_t * in, uint8_t size) { while(SPI1CMD & SPIBUSY) {} // Set in/out Bits to transfer setDataBits(size * 8); volatile uint32_t * fifoPtr = &SPI1W0; uint8_t dataSize = ((size + 3) / 4); if(out) { uint32_t * dataPtr = (uint32_t*) out; while(dataSize--) { *fifoPtr = *dataPtr; dataPtr++; fifoPtr++; } } else { // no out data only read fill with dummy data! while(dataSize--) { *fifoPtr = 0xFFFFFFFF; fifoPtr++; } } SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} if(in) { volatile uint8_t * fifoPtr8 = (volatile uint8_t *) &SPI1W0; dataSize = size; while(dataSize--) { *in = *fifoPtr8; in++; fifoPtr8++; } } } <commit_msg>add CPOL setting<commit_after>/* SPI.cpp - SPI library for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. 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 "SPI.h" #include "HardwareSerial.h" typedef union { uint32_t regValue; struct { unsigned regL :6; unsigned regH :6; unsigned regN :6; unsigned regPre :13; unsigned regEQU :1; }; } spiClk_t; SPIClass SPI; SPIClass::SPIClass() { useHwCs = false; } void SPIClass::begin() { pinMode(SCK, SPECIAL); ///< GPIO14 pinMode(MISO, SPECIAL); ///< GPIO12 pinMode(MOSI, SPECIAL); ///< GPIO13 SPI1C = 0; setFrequency(1000000); ///< 1MHz SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE; SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO); SPI1C1 = 0; } void SPIClass::end() { pinMode(SCK, INPUT); pinMode(MISO, INPUT); pinMode(MOSI, INPUT); if(useHwCs) { pinMode(SS, INPUT); } } void SPIClass::setHwCs(bool use) { if(use) { pinMode(SS, SPECIAL); ///< GPIO15 SPI1U |= (SPIUCSSETUP | SPIUCSHOLD); } else { if(useHwCs) { pinMode(SS, INPUT); SPI1U &= ~(SPIUCSSETUP | SPIUCSHOLD); } } useHwCs = use; } void SPIClass::beginTransaction(SPISettings settings) { while(SPI1CMD & SPIBUSY) {} setFrequency(settings._clock); setBitOrder(settings._bitOrder); setDataMode(settings._dataMode); } void SPIClass::endTransaction() { } void SPIClass::setDataMode(uint8_t dataMode) { /** SPI_MODE0 0x00 - CPOL: 0 CPHA: 0 SPI_MODE1 0x01 - CPOL: 0 CPHA: 1 SPI_MODE2 0x10 - CPOL: 1 CPHA: 0 SPI_MODE3 0x11 - CPOL: 1 CPHA: 1 */ bool CPOL = (dataMode & 0x10); ///< CPOL (Clock Polarity) bool CPHA = (dataMode & 0x01); ///< CPHA (Clock Phase) if(CPHA) { SPI1U |= (SPIUSME); } else { SPI1U &= ~(SPIUSME); } if(CPOL) { SPI1P |= 1<<29; } else { SPI1P &= ~(1<<29); //todo test whether it is correct to set CPOL like this. } } void SPIClass::setBitOrder(uint8_t bitOrder) { if(bitOrder == MSBFIRST) { SPI1C &= ~(SPICWBO | SPICRBO); } else { SPI1C |= (SPICWBO | SPICRBO); } } /** * calculate the Frequency based on the register value * @param reg * @return */ static uint32_t ClkRegToFreq(spiClk_t * reg) { return (ESP8266_CLOCK / ((reg->regPre + 1) * (reg->regN + 1))); } void SPIClass::setFrequency(uint32_t freq) { static uint32_t lastSetFrequency = 0; static uint32_t lastSetRegister = 0; if(freq >= ESP8266_CLOCK) { setClockDivider(0x80000000); return; } if(lastSetFrequency == freq && lastSetRegister == SPI1CLK) { // do nothing (speed optimization) return; } const spiClk_t minFreqReg = { 0x7FFFF000 }; uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg); if(freq < minFreq) { // use minimum possible clock setClockDivider(minFreqReg.regValue); lastSetRegister = SPI1CLK; lastSetFrequency = freq; return; } uint8_t calN = 1; spiClk_t bestReg = { 0 }; int32_t bestFreq = 0; // find the best match while(calN <= 0x3F) { // 0x3F max for N spiClk_t reg = { 0 }; int32_t calFreq; int32_t calPre; int8_t calPreVari = -2; reg.regN = calN; while(calPreVari++ <= 1) { // test different variants for Pre (we calculate in int so we miss the decimals, testing is the easyest and fastest way) calPre = (((ESP8266_CLOCK / (reg.regN + 1)) / freq) - 1) + calPreVari; if(calPre > 0x1FFF) { reg.regPre = 0x1FFF; // 8191 } else if(calPre <= 0) { reg.regPre = 0; } else { reg.regPre = calPre; } reg.regL = ((reg.regN + 1) / 2); // reg.regH = (reg.regN - reg.regL); // test calculation calFreq = ClkRegToFreq(&reg); //os_printf("-----[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d = %d\n", reg.regValue, freq, reg.regEQU, reg.regPre, reg.regN, reg.regH, reg.regL, calFreq); if(calFreq == (int32_t) freq) { // accurate match use it! memcpy(&bestReg, &reg, sizeof(bestReg)); break; } else if(calFreq < (int32_t) freq) { // never go over the requested frequency if(abs(freq - calFreq) < abs(freq - bestFreq)) { bestFreq = calFreq; memcpy(&bestReg, &reg, sizeof(bestReg)); } } } if(calFreq == (int32_t) freq) { // accurate match use it! break; } calN++; } // os_printf("[0x%08X][%d]\t EQU: %d\t Pre: %d\t N: %d\t H: %d\t L: %d\t - Real Frequency: %d\n", bestReg.regValue, freq, bestReg.regEQU, bestReg.regPre, bestReg.regN, bestReg.regH, bestReg.regL, ClkRegToFreq(&bestReg)); setClockDivider(bestReg.regValue); lastSetRegister = SPI1CLK; lastSetFrequency = freq; } void SPIClass::setClockDivider(uint32_t clockDiv) { if(clockDiv == 0x80000000) { GPMUX |= (1 << 9); // Set bit 9 if sysclock required } else { GPMUX &= ~(1 << 9); } SPI1CLK = clockDiv; } inline void SPIClass::setDataBits(uint16_t bits) { const uint32_t mask = ~((SPIMMOSI << SPILMOSI) | (SPIMMISO << SPILMISO)); bits--; SPI1U1 = ((SPI1U1 & mask) | ((bits << SPILMOSI) | (bits << SPILMISO))); } uint8_t SPIClass::transfer(uint8_t data) { while(SPI1CMD & SPIBUSY) {} // reset to 8Bit mode setDataBits(8); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} return (uint8_t) (SPI1W0 & 0xff); } uint16_t SPIClass::transfer16(uint16_t data) { union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; in.val = data; if((SPI1C & (SPICWBO | SPICRBO))) { //MSBFIRST out.msb = transfer(in.msb); out.lsb = transfer(in.lsb); } else { //LSBFIRST out.lsb = transfer(in.lsb); out.msb = transfer(in.msb); } return out.val; } void SPIClass::write(uint8_t data) { while(SPI1CMD & SPIBUSY) {} // reset to 8Bit mode setDataBits(8); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} } void SPIClass::write16(uint16_t data) { write16(data, !(SPI1C & (SPICWBO | SPICRBO))); } void SPIClass::write16(uint16_t data, bool msb) { while(SPI1CMD & SPIBUSY) {} // Set to 16Bits transfer setDataBits(16); if(msb) { // MSBFIRST Byte first SPI1W0 = (data >> 8) | (data << 8); SPI1CMD |= SPIBUSY; } else { // LSBFIRST Byte first SPI1W0 = data; SPI1CMD |= SPIBUSY; } while(SPI1CMD & SPIBUSY) {} } void SPIClass::write32(uint32_t data) { write32(data, !(SPI1C & (SPICWBO | SPICRBO))); } void SPIClass::write32(uint32_t data, bool msb) { while(SPI1CMD & SPIBUSY) {} // Set to 32Bits transfer setDataBits(32); if(msb) { union { uint32_t l; uint8_t b[4]; } data_; data_.l = data; // MSBFIRST Byte first SPI1W0 = (data_.b[3] | (data_.b[2] << 8) | (data_.b[1] << 16) | (data_.b[0] << 24)); SPI1CMD |= SPIBUSY; } else { // LSBFIRST Byte first SPI1W0 = data; SPI1CMD |= SPIBUSY; } while(SPI1CMD & SPIBUSY) {} } /** * Note: * data need to be aligned to 32Bit * or you get an Fatal exception (9) * @param data uint8_t * * @param size uint32_t */ void SPIClass::writeBytes(uint8_t * data, uint32_t size) { while(size) { if(size > 64) { writeBytes_(data, 64); size -= 64; data += 64; } else { writeBytes_(data, size); size = 0; } } } void SPIClass::writeBytes_(uint8_t * data, uint8_t size) { while(SPI1CMD & SPIBUSY) {} // Set Bits to transfer setDataBits(size * 8); volatile uint32_t * fifoPtr = &SPI1W0; uint32_t * dataPtr = (uint32_t*) data; uint8_t dataSize = ((size + 3) / 4); while(dataSize--) { *fifoPtr = *dataPtr; dataPtr++; fifoPtr++; } SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} } /** * Note: * data need to be aligned to 32Bit * or you get an Fatal exception (9) * @param data uint8_t * * @param size uint8_t max for size is 64Byte * @param repeat uint32_t */ void SPIClass::writePattern(uint8_t * data, uint8_t size, uint32_t repeat) { if(size > 64) return; //max Hardware FIFO uint32_t byte = (size * repeat); uint8_t r = (64 / size); while(byte) { if(byte > 64) { writePattern_(data, size, r); byte -= 64; } else { writePattern_(data, size, (byte / size)); byte = 0; } } } void SPIClass::writePattern_(uint8_t * data, uint8_t size, uint8_t repeat) { uint8_t bytes = (size * repeat); uint8_t buffer[64]; uint8_t * bufferPtr = &buffer[0]; uint8_t * dataPtr; uint8_t dataSize = bytes; for(uint8_t i = 0; i < repeat; i++) { dataSize = size; dataPtr = data; while(dataSize--) { *bufferPtr = *dataPtr; dataPtr++; bufferPtr++; } } writeBytes(&buffer[0], bytes); } /** * Note: * in and out need to be aligned to 32Bit * or you get an Fatal exception (9) * @param out uint8_t * * @param in uint8_t * * @param size uint32_t */ void SPIClass::transferBytes(uint8_t * out, uint8_t * in, uint32_t size) { while(size) { if(size > 64) { transferBytes_(out, in, 64); size -= 64; if(out) out += 64; if(in) in += 64; } else { transferBytes_(out, in, size); size = 0; } } } void SPIClass::transferBytes_(uint8_t * out, uint8_t * in, uint8_t size) { while(SPI1CMD & SPIBUSY) {} // Set in/out Bits to transfer setDataBits(size * 8); volatile uint32_t * fifoPtr = &SPI1W0; uint8_t dataSize = ((size + 3) / 4); if(out) { uint32_t * dataPtr = (uint32_t*) out; while(dataSize--) { *fifoPtr = *dataPtr; dataPtr++; fifoPtr++; } } else { // no out data only read fill with dummy data! while(dataSize--) { *fifoPtr = 0xFFFFFFFF; fifoPtr++; } } SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY) {} if(in) { volatile uint8_t * fifoPtr8 = (volatile uint8_t *) &SPI1W0; dataSize = size; while(dataSize--) { *in = *fifoPtr8; in++; fifoPtr8++; } } } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * Copyright 2008-2010 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, 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 <assert.h> #include <string.h> #include <stdint.h> #include <stdio.h> #include <fstream> #include "image.hpp" namespace image { /** * http://en.wikipedia.org/wiki/Netpbm_format * http://netpbm.sourceforge.net/doc/ppm.html * http://netpbm.sourceforge.net/doc/pfm.html */ void Image::writePNM(std::ostream &os, const char *comment) const { const char *identifier; unsigned outChannels; switch (channelType) { case TYPE_UNORM8: if (channels == 1) { identifier = "P5"; outChannels = 1; } else { identifier = "P6"; outChannels = 3; } break; case TYPE_FLOAT: if (channels == 1) { identifier = "Pf"; outChannels = 1; } else { identifier = "PF"; outChannels = 3; } break; default: assert(0); } os << identifier << "\n"; if (comment) { os << "#" << comment << "\n"; } os << width << " " << height << "\n"; if (channelType == TYPE_UNORM8) { os << "255" << "\n"; } const unsigned char *row; if (channels == outChannels) { /* * Write whole pixel spans straight from the image buffer. */ for (row = start(); row != end(); row += stride()) { os.write((const char *)row, width*bytesPerPixel); } } else { /* * Need to add/remove channels, one pixel at a time. */ unsigned char *tmp = new unsigned char[width*bytesPerPixel]; if (channelType == TYPE_UNORM8) { /* * Optimized path for 8bit unorms. */ if (channels == 4) { for (row = start(); row != end(); row += stride()) { const uint32_t *src = (const uint32_t *)row; uint32_t *dst = (uint32_t *)tmp; unsigned x; for (x = 0; x + 4 <= width; x += 4) { /* * It's much faster to access dwords than bytes. * * FIXME: Big-endian version. */ uint32_t rgba0 = *src++ & 0xffffff; uint32_t rgba1 = *src++ & 0xffffff; uint32_t rgba2 = *src++ & 0xffffff; uint32_t rgba3 = *src++ & 0xffffff; uint32_t rgb0 = rgba0 | (rgba1 << 24); uint32_t rgb1 = (rgba1 >> 8) | (rgba2 << 16); uint32_t rgb2 = (rgba2 >> 16) | (rgba3 << 8); *dst++ = rgb0; *dst++ = rgb1; *dst++ = rgb2; } for (; x < width; ++x) { tmp[x*3 + 0] = row[x*4 + 0]; tmp[x*3 + 1] = row[x*4 + 1]; tmp[x*3 + 2] = row[x*4 + 2]; } os.write((const char *)tmp, width*3); } } else if (channels == 2) { for (row = start(); row != end(); row += stride()) { const unsigned char *src = row; unsigned char *dst = tmp; for (unsigned x = 0; x < width; ++x) { *dst++ = *src++; *dst++ = *src++; *dst++ = 0; } os.write((const char *)tmp, width*3); } } else { assert(0); } } else { /* * General path for float images. */ assert(channelType == TYPE_FLOAT); for (row = start(); row != end(); row += stride()) { const float *src = (const float *)row; float *dst = (float *)tmp; for (unsigned x = 0; x < width; ++x) { unsigned channel = 0; for (; channel < channels; ++channel) { *dst++ = *src++; } for (; channel < channels; ++channel) { *dst++ = 0; } } os.write((const char *)tmp, width*bytesPerPixel); } } delete [] tmp; } } bool Image::writePNM(const char *filename, const char *comment) const { std::ofstream os(filename, std::ofstream::binary); if (!os) { return false; } writePNM(os, comment); return true; } /** * Parse PNM header. * * Returns pointer to data start, or NULL on failure. */ const char * readPNMHeader(const char *buffer, size_t bufferSize, PNMInfo &info) { info.channels = 0; info.width = 0; info.height = 0; const char *currentBuffer = buffer; const char *nextBuffer; // parse number of channels char c; int scannedChannels = sscanf(currentBuffer, "P%c\n", &c); if (scannedChannels != 1) { // validate scanning of channels // invalid channel line return NULL; } // convert channel token to number of channels switch (c) { case '5': info.channels = 1; info.channelType = TYPE_UNORM8; break; case '6': info.channels = 3; info.channelType = TYPE_UNORM8; break; case 'f': info.channels = 1; info.channelType = TYPE_FLOAT; break; case 'F': info.channels = 3; info.channelType = TYPE_FLOAT; break; default: return NULL; } // advance past channel line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; // skip over optional comment if (*currentBuffer == '#') { // advance past comment line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; } // parse dimensions of image int scannedDimensions = sscanf(currentBuffer, "%u %u\n", &info.width, &info.height); if (scannedDimensions != 2) { // validate scanning of dimensions // invalid dimension line return NULL; } // advance past dimension line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; if (info.channelType == TYPE_UNORM8) { // skip over "255\n" at end of header nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; } // return start of image data return nextBuffer; } Image * readPNM(const char *buffer, size_t bufferSize) { PNMInfo info; const char *headerEnd = readPNMHeader(buffer, bufferSize, info); // if invalid PNM header was encountered, ... if (headerEnd == NULL) { std::cerr << "error: invalid PNM header"; return NULL; } Image *image = new Image(info.width, info.height, info.channels, false, info.channelType); size_t rowBytes = info.width * image->bytesPerPixel; for (unsigned char *row = image->start(); row != image->end(); row += image->stride()) { memcpy(row, headerEnd, rowBytes); headerEnd += rowBytes; } return image; } } /* namespace image */ <commit_msg>image: Fix PNM dumping for 2/4 channels.<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * Copyright 2008-2010 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, 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 <assert.h> #include <string.h> #include <stdint.h> #include <stdio.h> #include <fstream> #include "image.hpp" namespace image { /** * http://en.wikipedia.org/wiki/Netpbm_format * http://netpbm.sourceforge.net/doc/ppm.html * http://netpbm.sourceforge.net/doc/pfm.html */ void Image::writePNM(std::ostream &os, const char *comment) const { const char *identifier; unsigned outChannels; switch (channelType) { case TYPE_UNORM8: if (channels == 1) { identifier = "P5"; outChannels = 1; } else { identifier = "P6"; outChannels = 3; } break; case TYPE_FLOAT: if (channels == 1) { identifier = "Pf"; outChannels = 1; } else { identifier = "PF"; outChannels = 3; } break; default: assert(0); } os << identifier << "\n"; if (comment) { os << "#" << comment << "\n"; } os << width << " " << height << "\n"; if (channelType == TYPE_UNORM8) { os << "255" << "\n"; } const unsigned char *row; if (channels == outChannels) { /* * Write whole pixel spans straight from the image buffer. */ for (row = start(); row != end(); row += stride()) { os.write((const char *)row, width*bytesPerPixel); } } else { /* * Need to add/remove channels, one pixel at a time. */ unsigned char *tmp = new unsigned char[width*bytesPerPixel]; if (channelType == TYPE_UNORM8) { /* * Optimized path for 8bit unorms. */ if (channels == 4) { for (row = start(); row != end(); row += stride()) { const uint32_t *src = (const uint32_t *)row; uint32_t *dst = (uint32_t *)tmp; unsigned x; for (x = 0; x + 4 <= width; x += 4) { /* * It's much faster to access dwords than bytes. * * FIXME: Big-endian version. */ uint32_t rgba0 = *src++ & 0xffffff; uint32_t rgba1 = *src++ & 0xffffff; uint32_t rgba2 = *src++ & 0xffffff; uint32_t rgba3 = *src++ & 0xffffff; uint32_t rgb0 = rgba0 | (rgba1 << 24); uint32_t rgb1 = (rgba1 >> 8) | (rgba2 << 16); uint32_t rgb2 = (rgba2 >> 16) | (rgba3 << 8); *dst++ = rgb0; *dst++ = rgb1; *dst++ = rgb2; } for (; x < width; ++x) { tmp[x*3 + 0] = row[x*4 + 0]; tmp[x*3 + 1] = row[x*4 + 1]; tmp[x*3 + 2] = row[x*4 + 2]; } os.write((const char *)tmp, width*3); } } else if (channels == 2) { for (row = start(); row != end(); row += stride()) { const unsigned char *src = row; unsigned char *dst = tmp; for (unsigned x = 0; x < width; ++x) { *dst++ = *src++; *dst++ = *src++; *dst++ = 0; } os.write((const char *)tmp, width*3); } } else { assert(0); } } else { /* * General path for float images. */ unsigned copyChannels = std::min(channels, outChannels); assert(channelType == TYPE_FLOAT); for (row = start(); row != end(); row += stride()) { const float *src = (const float *)row; float *dst = (float *)tmp; for (unsigned x = 0; x < width; ++x) { unsigned channel = 0; for (; channel < copyChannels; ++channel) { *dst++ = *src++; } for (; channel < outChannels; ++channel) { *dst++ = 0; } } os.write((const char *)tmp, width*bytesPerPixel); } } delete [] tmp; } } bool Image::writePNM(const char *filename, const char *comment) const { std::ofstream os(filename, std::ofstream::binary); if (!os) { return false; } writePNM(os, comment); return true; } /** * Parse PNM header. * * Returns pointer to data start, or NULL on failure. */ const char * readPNMHeader(const char *buffer, size_t bufferSize, PNMInfo &info) { info.channels = 0; info.width = 0; info.height = 0; const char *currentBuffer = buffer; const char *nextBuffer; // parse number of channels char c; int scannedChannels = sscanf(currentBuffer, "P%c\n", &c); if (scannedChannels != 1) { // validate scanning of channels // invalid channel line return NULL; } // convert channel token to number of channels switch (c) { case '5': info.channels = 1; info.channelType = TYPE_UNORM8; break; case '6': info.channels = 3; info.channelType = TYPE_UNORM8; break; case 'f': info.channels = 1; info.channelType = TYPE_FLOAT; break; case 'F': info.channels = 3; info.channelType = TYPE_FLOAT; break; default: return NULL; } // advance past channel line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; // skip over optional comment if (*currentBuffer == '#') { // advance past comment line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; } // parse dimensions of image int scannedDimensions = sscanf(currentBuffer, "%u %u\n", &info.width, &info.height); if (scannedDimensions != 2) { // validate scanning of dimensions // invalid dimension line return NULL; } // advance past dimension line nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; bufferSize -= nextBuffer - currentBuffer; currentBuffer = nextBuffer; if (info.channelType == TYPE_UNORM8) { // skip over "255\n" at end of header nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; } // return start of image data return nextBuffer; } Image * readPNM(const char *buffer, size_t bufferSize) { PNMInfo info; const char *headerEnd = readPNMHeader(buffer, bufferSize, info); // if invalid PNM header was encountered, ... if (headerEnd == NULL) { std::cerr << "error: invalid PNM header"; return NULL; } Image *image = new Image(info.width, info.height, info.channels, false, info.channelType); size_t rowBytes = info.width * image->bytesPerPixel; for (unsigned char *row = image->start(); row != image->end(); row += image->stride()) { memcpy(row, headerEnd, rowBytes); headerEnd += rowBytes; } return image; } } /* namespace image */ <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // Lowest Common Ancestor (LCA) // O(lgn) per query // Link: http://www.spoj.com/status/LCA/ /////////////////////////////////////////////////////////////////////// #include <iostream> #include <algorithm> #include <vector> #include <stack> using namespace std; #define SZ(x) ((int)((x).size())) class LCA { public: typedef vector<int> VI; typedef vector<VI> VVI; VI depths; VVI parents; int N, root, max_lvl; // Vertices are 0-based indexed. LCA (int root_, VVI graph) { root = root_; N = graph.size(); depths.resize(N); max_lvl = 1; while ((1<<max_lvl) < N) max_lvl++; parents.resize(max_lvl, VI(N)); build_lca(root, -1, graph, 0); for (int i = 1; i < max_lvl; i++) for (int j = 0; j < N; j++) if (parents[i - 1][j] != -1) parents[i][j] = parents[i - 1][parents[i - 1][j]]; } int lca(int u, int v) { if (depths[u] < depths[v]) swap(u, v); int diff_dep = depths[u] - depths[v]; for (int i = 0; i < max_lvl; i++) if ((1<<i) & diff_dep) u = parents[i][u]; if (u == v) return u; for (int i = max_lvl - 1; i >= 0; i--) { if (parents[i][u] != parents[i][v]) { u = parents[i][u]; v = parents[i][v]; } } return parents[0][u]; } int get_depth(int u) { return depths[u]; } private: void build_lca(int at, int par, VVI &adj, int dep) { stack<int> S; parents[0][at] = par; depths[at] = dep; S.push(at); vector<int> cnt(N, 0); while (!S.empty()) { int u = S.top(); S.pop(); while (cnt[u] < SZ(adj[u])) { int v = adj[u][cnt[u]++]; if (v != parents[0][u]) { parents[0][v] = u; depths[v] = depths[u] + 1; S.push(v); if (cnt[u] < SZ(adj[u])) S.push(u); break; } } } } }; typedef vector<int> VI; typedef vector<VI> VVI; #define MAXN 1005 int main() { int test; scanf("%d", &test); for (int tt = 0; tt < test; tt++) { printf("Case %d:\n", tt + 1); int N; scanf("%d", &N); VI parents (N, -1); VVI graph (N); for (int i = 0; i < N; i++) { int sz; scanf("%d", &sz); int v; for (int j = 0; j < sz; j++) { scanf("%d", &v); v--; parents[v] = i; graph[i].push_back(v); graph[v].push_back(i); } } int root = 0; while (parents[root] != -1) root = parents[root]; LCA solver(root, graph); int Q; scanf("%d", &Q); int u, v; for (int i = 0; i < Q; i++) { scanf("%d %d", &u, &v); u--, v--; printf("%d\n", solver.lca(u, v) + 1); } } return 0; } <commit_msg>Modified LCA.cpp<commit_after>/////////////////////////////////////////////////////////////////////// // Lowest Common Ancestor (LCA) // O(lgn) per query // Link: http://www.spoj.com/status/LCA/ /////////////////////////////////////////////////////////////////////// #include <iostream> #include <algorithm> #include <vector> #include <stack> using namespace std; #define SZ(x) ((int)((x).size())) class LCA { public: typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<VVI> VVVI; VI depths; VVI parents; VVVI V; int N, root, max_lvl; // Vertices are 0-based indexed. LCA (int root_, VVI graph) { root = root_; N = graph.size(); depths.resize(N); max_lvl = 1; while ((1<<max_lvl) < N) max_lvl++; V.resize(max_lvl, vector<vector<int>>(N)); parents.resize(max_lvl, VI(N)); build_lca(root, -1, graph, 0); for (int i = 1; i < max_lvl; i++) for (int j = 0; j < N; j++) if (parents[i - 1][j] != -1) { parents[i][j] = parents[i - 1][parents[i - 1][j]]; } } vector<int> res; int lca(int u, int v) { if (depths[u] < depths[v]) swap(u, v); int diff_dep = depths[u] - depths[v]; for (int i = 0; i < max_lvl; i++) if ((1<<i) & diff_dep) { u = parents[i][u]; } if (u == v) { return u; } for (int i = max_lvl - 1; i >= 0; i--) { if (parents[i][u] != parents[i][v]) { u = parents[i][u]; v = parents[i][v]; } } return parents[0][u]; } int get_depth(int u) { return depths[u]; } private: void build_lca(int at, int par, VVI &adj, int dep) { parents[0][at] = par; depths[at] = dep; for (auto v : adj[at]) { if (v != par) { build_lca(v, at, adj, dep + 1); } } } }; // Using a stack to build a tree (might be necessary) // void build_lca(int at, int par, VVI &adj, int dep) { // stack<int> S; // parents[0][at] = par; // depths[at] = dep; // S.push(at); // vector<int> cnt(N, 0); // while (!S.empty()) { // int u = S.top(); S.pop(); // while (cnt[u] < SZ(adj[u])) { // int v = adj[u][cnt[u]++]; // if (v != parents[0][u]) { // parents[0][v] = u; // depths[v] = depths[u] + 1; // S.push(v); // if (cnt[u] < SZ(adj[u])) S.push(u); // break; // } // } // } // } typedef vector<int> VI; typedef vector<VI> VVI; #define MAXN 1005 int main() { int test; scanf("%d", &test); for (int tt = 0; tt < test; tt++) { printf("Case %d:\n", tt + 1); int N; scanf("%d", &N); VI parents (N, -1); VVI graph (N); for (int i = 0; i < N; i++) { int sz; scanf("%d", &sz); int v; for (int j = 0; j < sz; j++) { scanf("%d", &v); v--; parents[v] = i; graph[i].push_back(v); graph[v].push_back(i); } } int root = 0; while (parents[root] != -1) root = parents[root]; LCA solver(root, graph); int Q; scanf("%d", &Q); int u, v; for (int i = 0; i < Q; i++) { scanf("%d %d", &u, &v); u--, v--; printf("%d\n", solver.lca(u, v) + 1); } } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen 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. */ #ifdef RENDERER_NULL #include "RendererInternal.h" #include "utils/Utils.h" namespace renderer { RendererImpl::RendererImpl(const RendererDesc &desc) : RendererBase(desc) { SDL_Init(SDL_INIT_EVENTS); swapchainFormat = Format::sRGBA8; currentRefreshRate = 60; maxRefreshRate = 60; recreateRingBuffer(desc.ephemeralRingBufSize); frames.resize(desc.swapchain.numFrames); } void RendererImpl::recreateRingBuffer(unsigned int newSize) { assert(newSize > 0); ringBufPtr = 0; ringBufSize = newSize; ringBuffer.resize(newSize, 0); LOG_TODO("use valgrind to make sure we only write to intended parts of ring buffer"); } RendererImpl::~RendererImpl() { waitForDeviceIdle(); for (unsigned int i = 0; i < frames.size(); i++) { auto &f = frames.at(i); assert(!f.outstanding); deleteFrameInternal(f); } frames.clear(); SDL_Quit(); } bool Renderer::isRenderTargetFormatSupported(Format /* format */) const { LOG_TODO("actually check it..."); return true; } BufferHandle Renderer::createBuffer(BufferType /* type */, uint32_t size, const void *contents) { assert(size != 0); assert(contents != nullptr); Buffer buffer; buffer.ringBufferAlloc = false; buffer.beginOffs = 0; buffer.size = size; LOG_TODO("store contents into buffer"); return impl->buffers.add(std::move(buffer)); } BufferHandle Renderer::createEphemeralBuffer(BufferType /* type */, uint32_t size, const void *contents) { assert(size != 0); assert(contents != nullptr); unsigned int beginPtr = impl->ringBufferAllocate(size, 256); LOG_TODO("use valgrind to enforce we only write to intended parts of ring buffer"); memcpy(&impl->ringBuffer[beginPtr], contents, size); auto result = impl->buffers.add(); Buffer &buffer = result.first; buffer.ringBufferAlloc = true; buffer.beginOffs = beginPtr; buffer.size = size; impl->frames.at(impl->currentFrameIdx).ephemeralBuffers.push_back(result.second); return result.second; } FramebufferHandle Renderer::createFramebuffer(const FramebufferDesc &desc) { Framebuffer fb; fb.renderPass = desc.renderPass_; return impl->framebuffers.add(std::move(fb)); } RenderPassHandle Renderer::createRenderPass(const RenderPassDesc &desc) { RenderPass rp; rp.desc = desc; return impl->renderpasses.add(std::move(rp)); } PipelineHandle Renderer::createPipeline(const PipelineDesc &desc) { auto result = impl->pipelines.add(); auto &pipeline = result.first; pipeline.desc = desc; return result.second; } RenderTargetHandle Renderer::createRenderTarget(const RenderTargetDesc &desc) { assert(desc.width_ > 0); assert(desc.height_ > 0); assert(desc.format_ != +Format::Invalid); RenderTarget rendertarget; rendertarget.desc = desc; return impl->rendertargets.add(std::move(rendertarget)); } SamplerHandle Renderer::createSampler(const SamplerDesc &desc) { Sampler sampler; LOG_TODO("check desc"); sampler.desc = desc; return impl->samplers.add(std::move(sampler)); } VertexShaderHandle RendererImpl::createVertexShader(const std::string &name, const ShaderMacros & /* macros */) { std::string vertexShaderName = name + ".vert"; auto result_ = vertexShaders.add(); auto &v = result_.first; v.name = vertexShaderName; return result_.second; } FragmentShaderHandle RendererImpl::createFragmentShader(const std::string &name, const ShaderMacros & /* macros */) { std::string fragmentShaderName = name + ".frag"; auto result_ = fragmentShaders.add(); auto &f = result_.first; f.name = fragmentShaderName; return result_.second; } TextureHandle Renderer::createTexture(const TextureDesc &desc) { assert(desc.width_ > 0); assert(desc.height_ > 0); assert(desc.numMips_ > 0); LOG_TODO("check data"); Texture texture; LOG_TODO("check desc"); texture.desc = desc; return impl->textures.add(std::move(texture)); } DSLayoutHandle Renderer::createDescriptorSetLayout(const DescriptorLayout *layout) { DescriptorSetLayout dsLayout; while (layout->type != +DescriptorType::End) { dsLayout.layout.push_back(*layout); layout++; } assert(layout->offset == 0); return impl->dsLayouts.add(std::move(dsLayout)); } TextureHandle Renderer::getRenderTargetView(RenderTargetHandle /* handle */, Format /* f */) { TextureHandle handle; return handle; } void Renderer::deleteBuffer(BufferHandle & /* handle */) { } void Renderer::deleteFramebuffer(FramebufferHandle & /* */) { } void Renderer::deletePipeline(PipelineHandle & /* handle */) { } void Renderer::deleteRenderPass(RenderPassHandle & /* handle */) { } void Renderer::deleteRenderTarget(RenderTargetHandle & /* handle */) { } void Renderer::deleteSampler(SamplerHandle & /* handle */) { } void Renderer::deleteTexture(TextureHandle & /* handle */) { } void Renderer::deleteBuffer(BufferHandle && /* handle */) { } void Renderer::deleteFramebuffer(FramebufferHandle && /* */) { } void Renderer::deletePipeline(PipelineHandle && /* handle */) { } void Renderer::deleteRenderPass(RenderPassHandle && /* handle */) { } void Renderer::deleteRenderTarget(RenderTargetHandle && /* handle */) { } void Renderer::deleteSampler(SamplerHandle && /* handle */) { } void Renderer::deleteTexture(TextureHandle && /* handle */) { } void Renderer::setSwapchainDesc(const SwapchainDesc &desc) { impl->swapchainDesc = desc; } glm::uvec2 Renderer::getDrawableSize() const { return glm::uvec2(impl->swapchainDesc.width, impl->swapchainDesc.height); } MemoryStats Renderer::getMemStats() const { MemoryStats stats; return stats; } void RendererImpl::waitForDeviceIdle() { for (unsigned int i = 0; i < frames.size(); i++) { auto &f = frames.at(i); if (f.outstanding) { // try to wait waitForFrame(i); assert(!f.outstanding); } } } void Renderer::beginFrame() { assert(!impl->inFrame); impl->inFrame = true; impl->inRenderPass = false; impl->validPipeline = false; impl->pipelineDrawn = true; impl->currentFrameIdx = impl->frameNum % impl->frames.size(); assert(impl->currentFrameIdx < impl->frames.size()); auto &frame = impl->frames.at(impl->currentFrameIdx); // frames are a ringbuffer // if the frame we want to reuse is still pending on the GPU, wait for it if (frame.outstanding) { impl->waitForFrame(impl->currentFrameIdx); } assert(!frame.outstanding); } void Renderer::beginRenderPassSwapchain(RenderPassHandle rpHandle) { assert(rpHandle); assert(!impl->inFrame); impl->inFrame = true; impl->inRenderPass = false; impl->validPipeline = false; impl->pipelineDrawn = true; assert(!impl->renderingToSwapchain); impl->renderingToSwapchain = true; impl->currentFrameIdx = impl->frameNum % impl->frames.size(); assert(impl->currentFrameIdx < impl->frames.size()); auto &frame = impl->frames.at(impl->currentFrameIdx); // frames are a ringbuffer // if the frame we want to reuse is still pending on the GPU, wait for it if (frame.outstanding) { impl->waitForFrame(impl->currentFrameIdx); } assert(!frame.outstanding); } void Renderer::presentFrame() { assert(impl->inFrame); impl->inFrame = false; auto &frame = impl->frames.at(impl->currentFrameIdx); frame.usedRingBufPtr = impl->ringBufPtr; frame.outstanding = true; frame.lastFrameNum = impl->frameNum; impl->frameNum++; } void RendererImpl::waitForFrame(unsigned int frameIdx) { assert(frameIdx < frames.size()); Frame &frame = frames.at(frameIdx); assert(frame.outstanding); for (auto handle : frame.ephemeralBuffers) { Buffer &buffer = buffers.get(handle); if (buffer.ringBufferAlloc) { buffer.ringBufferAlloc = false; } assert(buffer.size > 0); buffer.size = 0; buffer.beginOffs = 0; buffers.remove(handle); } frame.ephemeralBuffers.clear(); frame.outstanding = false; lastSyncedFrame = std::max(lastSyncedFrame, frame.lastFrameNum); lastSyncedRingBufPtr = std::max(lastSyncedRingBufPtr, frame.usedRingBufPtr); } void RendererImpl::deleteFrameInternal(Frame &f) { assert(!f.outstanding); } void Renderer::beginRenderPass(RenderPassHandle rpHandle, FramebufferHandle fbHandle) { assert(impl->inFrame); assert(!impl->inRenderPass); assert(!impl->renderingToSwapchain); impl->inRenderPass = true; impl->validPipeline = false; assert(fbHandle); const auto &fb = impl->framebuffers.get(fbHandle); // make sure renderpass and framebuffer match assert(fb.renderPass == rpHandle); } void Renderer::endRenderPass() { assert(impl->inFrame); assert(impl->inRenderPass); impl->inRenderPass = false; impl->renderingToSwapchain = false; } void Renderer::layoutTransition(RenderTargetHandle image, Layout src, Layout dest) { assert(image); assert(dest != +Layout::Undefined); assert(src != dest); } void Renderer::bindPipeline(PipelineHandle pipeline) { assert(impl->inFrame); assert(pipeline); assert(impl->inRenderPass); assert(impl->pipelineDrawn); impl->pipelineDrawn = false; impl->validPipeline = true; impl->scissorSet = false; impl->currentPipeline = impl->pipelines.get(pipeline).desc; } void Renderer::bindIndexBuffer(BufferHandle /* buffer */, bool /* bit16 */ ) { assert(impl->inFrame); assert(impl->validPipeline); } void Renderer::bindVertexBuffer(unsigned int /* binding */, BufferHandle /* buffer */) { assert(impl->inFrame); assert(impl->validPipeline); } void Renderer::bindDescriptorSet(unsigned int /* index */, DSLayoutHandle /* layout */, const void * /* data_ */) { assert(impl->validPipeline); } void Renderer::setViewport(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) { assert(impl->inFrame); } void Renderer::setScissorRect(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) { assert(impl->validPipeline); assert(impl->currentPipeline.scissorTest_); impl->scissorSet = true; } void Renderer::blit(RenderTargetHandle source, RenderTargetHandle target) { assert(source); assert(target); assert(!impl->inRenderPass); } void Renderer::resolveMSAA(RenderTargetHandle source, RenderTargetHandle target) { assert(source); assert(target); assert(!impl->inRenderPass); } void Renderer::resolveMSAAToSwapchain(RenderTargetHandle source, Layout finalLayout) { assert(source); assert(finalLayout != +Layout::Undefined); assert(impl->inFrame); assert(!impl->inRenderPass); assert(!impl->renderingToSwapchain); } void Renderer::draw(unsigned int /* firstVertex */, unsigned int vertexCount) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } void Renderer::drawIndexedInstanced(unsigned int vertexCount, unsigned int instanceCount) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(instanceCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } void Renderer::drawIndexedOffset(unsigned int vertexCount, unsigned int /* firstIndex */, unsigned int /* minIndex */, unsigned int /* maxIndex */) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } } // namespace renderer #endif // RENDERER_NULL <commit_msg>Refactor null Renderer::createPipeline<commit_after>/* Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen 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. */ #ifdef RENDERER_NULL #include "RendererInternal.h" #include "utils/Utils.h" namespace renderer { RendererImpl::RendererImpl(const RendererDesc &desc) : RendererBase(desc) { SDL_Init(SDL_INIT_EVENTS); swapchainFormat = Format::sRGBA8; currentRefreshRate = 60; maxRefreshRate = 60; recreateRingBuffer(desc.ephemeralRingBufSize); frames.resize(desc.swapchain.numFrames); } void RendererImpl::recreateRingBuffer(unsigned int newSize) { assert(newSize > 0); ringBufPtr = 0; ringBufSize = newSize; ringBuffer.resize(newSize, 0); LOG_TODO("use valgrind to make sure we only write to intended parts of ring buffer"); } RendererImpl::~RendererImpl() { waitForDeviceIdle(); for (unsigned int i = 0; i < frames.size(); i++) { auto &f = frames.at(i); assert(!f.outstanding); deleteFrameInternal(f); } frames.clear(); SDL_Quit(); } bool Renderer::isRenderTargetFormatSupported(Format /* format */) const { LOG_TODO("actually check it..."); return true; } BufferHandle Renderer::createBuffer(BufferType /* type */, uint32_t size, const void *contents) { assert(size != 0); assert(contents != nullptr); Buffer buffer; buffer.ringBufferAlloc = false; buffer.beginOffs = 0; buffer.size = size; LOG_TODO("store contents into buffer"); return impl->buffers.add(std::move(buffer)); } BufferHandle Renderer::createEphemeralBuffer(BufferType /* type */, uint32_t size, const void *contents) { assert(size != 0); assert(contents != nullptr); unsigned int beginPtr = impl->ringBufferAllocate(size, 256); LOG_TODO("use valgrind to enforce we only write to intended parts of ring buffer"); memcpy(&impl->ringBuffer[beginPtr], contents, size); auto result = impl->buffers.add(); Buffer &buffer = result.first; buffer.ringBufferAlloc = true; buffer.beginOffs = beginPtr; buffer.size = size; impl->frames.at(impl->currentFrameIdx).ephemeralBuffers.push_back(result.second); return result.second; } FramebufferHandle Renderer::createFramebuffer(const FramebufferDesc &desc) { Framebuffer fb; fb.renderPass = desc.renderPass_; return impl->framebuffers.add(std::move(fb)); } RenderPassHandle Renderer::createRenderPass(const RenderPassDesc &desc) { RenderPass rp; rp.desc = desc; return impl->renderpasses.add(std::move(rp)); } PipelineHandle Renderer::createPipeline(const PipelineDesc &desc) { Pipeline pipeline; pipeline.desc = desc; return impl->pipelines.add(std::move(pipeline)); } RenderTargetHandle Renderer::createRenderTarget(const RenderTargetDesc &desc) { assert(desc.width_ > 0); assert(desc.height_ > 0); assert(desc.format_ != +Format::Invalid); RenderTarget rendertarget; rendertarget.desc = desc; return impl->rendertargets.add(std::move(rendertarget)); } SamplerHandle Renderer::createSampler(const SamplerDesc &desc) { Sampler sampler; LOG_TODO("check desc"); sampler.desc = desc; return impl->samplers.add(std::move(sampler)); } VertexShaderHandle RendererImpl::createVertexShader(const std::string &name, const ShaderMacros & /* macros */) { std::string vertexShaderName = name + ".vert"; auto result_ = vertexShaders.add(); auto &v = result_.first; v.name = vertexShaderName; return result_.second; } FragmentShaderHandle RendererImpl::createFragmentShader(const std::string &name, const ShaderMacros & /* macros */) { std::string fragmentShaderName = name + ".frag"; auto result_ = fragmentShaders.add(); auto &f = result_.first; f.name = fragmentShaderName; return result_.second; } TextureHandle Renderer::createTexture(const TextureDesc &desc) { assert(desc.width_ > 0); assert(desc.height_ > 0); assert(desc.numMips_ > 0); LOG_TODO("check data"); Texture texture; LOG_TODO("check desc"); texture.desc = desc; return impl->textures.add(std::move(texture)); } DSLayoutHandle Renderer::createDescriptorSetLayout(const DescriptorLayout *layout) { DescriptorSetLayout dsLayout; while (layout->type != +DescriptorType::End) { dsLayout.layout.push_back(*layout); layout++; } assert(layout->offset == 0); return impl->dsLayouts.add(std::move(dsLayout)); } TextureHandle Renderer::getRenderTargetView(RenderTargetHandle /* handle */, Format /* f */) { TextureHandle handle; return handle; } void Renderer::deleteBuffer(BufferHandle & /* handle */) { } void Renderer::deleteFramebuffer(FramebufferHandle & /* */) { } void Renderer::deletePipeline(PipelineHandle & /* handle */) { } void Renderer::deleteRenderPass(RenderPassHandle & /* handle */) { } void Renderer::deleteRenderTarget(RenderTargetHandle & /* handle */) { } void Renderer::deleteSampler(SamplerHandle & /* handle */) { } void Renderer::deleteTexture(TextureHandle & /* handle */) { } void Renderer::deleteBuffer(BufferHandle && /* handle */) { } void Renderer::deleteFramebuffer(FramebufferHandle && /* */) { } void Renderer::deletePipeline(PipelineHandle && /* handle */) { } void Renderer::deleteRenderPass(RenderPassHandle && /* handle */) { } void Renderer::deleteRenderTarget(RenderTargetHandle && /* handle */) { } void Renderer::deleteSampler(SamplerHandle && /* handle */) { } void Renderer::deleteTexture(TextureHandle && /* handle */) { } void Renderer::setSwapchainDesc(const SwapchainDesc &desc) { impl->swapchainDesc = desc; } glm::uvec2 Renderer::getDrawableSize() const { return glm::uvec2(impl->swapchainDesc.width, impl->swapchainDesc.height); } MemoryStats Renderer::getMemStats() const { MemoryStats stats; return stats; } void RendererImpl::waitForDeviceIdle() { for (unsigned int i = 0; i < frames.size(); i++) { auto &f = frames.at(i); if (f.outstanding) { // try to wait waitForFrame(i); assert(!f.outstanding); } } } void Renderer::beginFrame() { assert(!impl->inFrame); impl->inFrame = true; impl->inRenderPass = false; impl->validPipeline = false; impl->pipelineDrawn = true; impl->currentFrameIdx = impl->frameNum % impl->frames.size(); assert(impl->currentFrameIdx < impl->frames.size()); auto &frame = impl->frames.at(impl->currentFrameIdx); // frames are a ringbuffer // if the frame we want to reuse is still pending on the GPU, wait for it if (frame.outstanding) { impl->waitForFrame(impl->currentFrameIdx); } assert(!frame.outstanding); } void Renderer::beginRenderPassSwapchain(RenderPassHandle rpHandle) { assert(rpHandle); assert(!impl->inFrame); impl->inFrame = true; impl->inRenderPass = false; impl->validPipeline = false; impl->pipelineDrawn = true; assert(!impl->renderingToSwapchain); impl->renderingToSwapchain = true; impl->currentFrameIdx = impl->frameNum % impl->frames.size(); assert(impl->currentFrameIdx < impl->frames.size()); auto &frame = impl->frames.at(impl->currentFrameIdx); // frames are a ringbuffer // if the frame we want to reuse is still pending on the GPU, wait for it if (frame.outstanding) { impl->waitForFrame(impl->currentFrameIdx); } assert(!frame.outstanding); } void Renderer::presentFrame() { assert(impl->inFrame); impl->inFrame = false; auto &frame = impl->frames.at(impl->currentFrameIdx); frame.usedRingBufPtr = impl->ringBufPtr; frame.outstanding = true; frame.lastFrameNum = impl->frameNum; impl->frameNum++; } void RendererImpl::waitForFrame(unsigned int frameIdx) { assert(frameIdx < frames.size()); Frame &frame = frames.at(frameIdx); assert(frame.outstanding); for (auto handle : frame.ephemeralBuffers) { Buffer &buffer = buffers.get(handle); if (buffer.ringBufferAlloc) { buffer.ringBufferAlloc = false; } assert(buffer.size > 0); buffer.size = 0; buffer.beginOffs = 0; buffers.remove(handle); } frame.ephemeralBuffers.clear(); frame.outstanding = false; lastSyncedFrame = std::max(lastSyncedFrame, frame.lastFrameNum); lastSyncedRingBufPtr = std::max(lastSyncedRingBufPtr, frame.usedRingBufPtr); } void RendererImpl::deleteFrameInternal(Frame &f) { assert(!f.outstanding); } void Renderer::beginRenderPass(RenderPassHandle rpHandle, FramebufferHandle fbHandle) { assert(impl->inFrame); assert(!impl->inRenderPass); assert(!impl->renderingToSwapchain); impl->inRenderPass = true; impl->validPipeline = false; assert(fbHandle); const auto &fb = impl->framebuffers.get(fbHandle); // make sure renderpass and framebuffer match assert(fb.renderPass == rpHandle); } void Renderer::endRenderPass() { assert(impl->inFrame); assert(impl->inRenderPass); impl->inRenderPass = false; impl->renderingToSwapchain = false; } void Renderer::layoutTransition(RenderTargetHandle image, Layout src, Layout dest) { assert(image); assert(dest != +Layout::Undefined); assert(src != dest); } void Renderer::bindPipeline(PipelineHandle pipeline) { assert(impl->inFrame); assert(pipeline); assert(impl->inRenderPass); assert(impl->pipelineDrawn); impl->pipelineDrawn = false; impl->validPipeline = true; impl->scissorSet = false; impl->currentPipeline = impl->pipelines.get(pipeline).desc; } void Renderer::bindIndexBuffer(BufferHandle /* buffer */, bool /* bit16 */ ) { assert(impl->inFrame); assert(impl->validPipeline); } void Renderer::bindVertexBuffer(unsigned int /* binding */, BufferHandle /* buffer */) { assert(impl->inFrame); assert(impl->validPipeline); } void Renderer::bindDescriptorSet(unsigned int /* index */, DSLayoutHandle /* layout */, const void * /* data_ */) { assert(impl->validPipeline); } void Renderer::setViewport(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) { assert(impl->inFrame); } void Renderer::setScissorRect(unsigned int /* x */, unsigned int /* y */, unsigned int /* width */, unsigned int /* height */) { assert(impl->validPipeline); assert(impl->currentPipeline.scissorTest_); impl->scissorSet = true; } void Renderer::blit(RenderTargetHandle source, RenderTargetHandle target) { assert(source); assert(target); assert(!impl->inRenderPass); } void Renderer::resolveMSAA(RenderTargetHandle source, RenderTargetHandle target) { assert(source); assert(target); assert(!impl->inRenderPass); } void Renderer::resolveMSAAToSwapchain(RenderTargetHandle source, Layout finalLayout) { assert(source); assert(finalLayout != +Layout::Undefined); assert(impl->inFrame); assert(!impl->inRenderPass); assert(!impl->renderingToSwapchain); } void Renderer::draw(unsigned int /* firstVertex */, unsigned int vertexCount) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } void Renderer::drawIndexedInstanced(unsigned int vertexCount, unsigned int instanceCount) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(instanceCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } void Renderer::drawIndexedOffset(unsigned int vertexCount, unsigned int /* firstIndex */, unsigned int /* minIndex */, unsigned int /* maxIndex */) { assert(impl->inRenderPass); assert(impl->validPipeline); assert(vertexCount > 0); assert(!impl->currentPipeline.scissorTest_ || impl->scissorSet); impl->pipelineDrawn = true; } } // namespace renderer #endif // RENDERER_NULL <|endoftext|>
<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "render_queue.hpp" #include "render_context.hpp" #include <cstring> #include <iterator> #include <algorithm> #include <assert.h> using namespace std; using namespace Vulkan; using namespace Util; namespace Granite { void RenderQueue::sort() { for (auto &queue : queues) { stable_sort(begin(queue), end(queue), [](const RenderQueueData &a, const RenderQueueData &b) { return a.sorting_key < b.sorting_key; }); } } void RenderQueue::combine_render_info(const RenderQueue &queue) { for (unsigned i = 0; i < ecast(Queue::Count); i++) { auto e = static_cast<Queue>(i); queues[i].insert(end(queues[i]), begin(queue.get_queue_data(e)), end(queue.get_queue_data(e))); } } void RenderQueue::dispatch(Queue queue_type, CommandBuffer &cmd, const CommandBufferSavedState *state, size_t begin, size_t end) { auto *queue = queues[ecast(queue_type)].data(); while (begin < end) { if (state) cmd.restore_state(*state); unsigned instances = 1; for (size_t i = begin + 1; i < end && queue[i].render_info == queue[begin].render_info; i++) { assert(queue[i].render == queue[begin].render); instances++; } queue[begin].render(cmd, &queue[begin], instances); begin += instances; } } void RenderQueue::dispatch(Queue queue, CommandBuffer &cmd, const CommandBufferSavedState *state) { dispatch(queue, cmd, state, 0, queues[ecast(queue)].size()); } void RenderQueue::enqueue_queue_data(Queue queue_type, const RenderQueueData &render_info) { queues[ecast(queue_type)].push_back(render_info); } RenderQueue::Chain::iterator RenderQueue::insert_block() { return blocks.insert(end(blocks), Block(BlockSize)); } RenderQueue::Chain::iterator RenderQueue::insert_large_block(size_t size, size_t alignment) { size_t padded_size = alignment > alignof(uintmax_t) ? (size + alignment) : size; return large_blocks.insert(end(large_blocks), Block(padded_size)); } void *RenderQueue::allocate_from_block(Block &block, size_t size, size_t alignment) { block.ptr = (block.ptr + alignment - 1) & ~(alignment - 1); uintptr_t end = block.ptr + size; if (end <= block.end) { void *ret = reinterpret_cast<void *>(block.ptr); block.ptr = end; return ret; } else return nullptr; } void RenderQueue::reset() { current = begin(blocks); if (current != end(blocks)) current->reset(); for (auto &queue : queues) queue.clear(); large_blocks.clear(); render_infos.clear(); } void RenderQueue::reset_and_reclaim() { blocks.clear(); large_blocks.clear(); render_infos.clear(); current = end(blocks); for (auto &queue : queues) queue.clear(); } void *RenderQueue::allocate(size_t size, size_t alignment) { if (size + alignment > BlockSize) { auto itr = insert_large_block(size, alignment); return allocate_from_block(*itr, size, alignment); } // First allocation. if (current == end(blocks)) current = insert_block(); void *data = allocate_from_block(*current, size, alignment); if (data) return data; ++current; if (current == end(blocks)) current = insert_block(); else current->reset(); data = allocate_from_block(*current, size, alignment); return data; } uint64_t RenderInfo::get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash) { pipeline_hash &= 0xffff0000u; pipeline_hash |= draw_hash & 0xffffu; if (queue_type == Queue::Transparent) return pipeline_hash & 0xffffffffu; else return (UINT64_MAX << 32) | (pipeline_hash & 0xffffffffu); } uint64_t RenderInfo::get_sprite_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash, float z, StaticLayer layer) { static_assert(ecast(StaticLayer::Count) == 4, "Number of static layers is not 4."); // Monotonically increasing floating point will be monotonic in uint32_t as well when z is non-negative. z = muglm::max(z, 0.0f); uint32_t depth_key = floatBitsToUint(z); pipeline_hash &= 0xffff0000u; pipeline_hash |= draw_hash & 0xffffu; if (queue_type == Queue::Transparent) { depth_key ^= 0xffffffffu; // Back-to-front instead. // Prioritize correct back-to-front rendering over pipeline. return (uint64_t(depth_key) << 32) | pipeline_hash; } else { #if 0 // Prioritize state changes over depth. depth_key >>= 2; return (uint64_t(ecast(layer)) << 62) | (uint64_t(pipeline_hash) << 30) | depth_key; #else // Prioritize front-back sorting over state changes. pipeline_hash >>= 2; return (uint64_t(ecast(layer)) << 62) | (uint64_t(depth_key) << 30) | pipeline_hash; #endif } } uint64_t RenderInfo::get_sort_key(const RenderContext &context, Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash, const vec3 &center, StaticLayer layer) { float z = dot(context.get_render_parameters().camera_front, center - context.get_render_parameters().camera_position); return get_sprite_sort_key(queue_type, pipeline_hash, draw_hash, z, layer); } } <commit_msg>Sort by state changes.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "render_queue.hpp" #include "render_context.hpp" #include <cstring> #include <iterator> #include <algorithm> #include <assert.h> using namespace std; using namespace Vulkan; using namespace Util; namespace Granite { void RenderQueue::sort() { for (auto &queue : queues) { stable_sort(begin(queue), end(queue), [](const RenderQueueData &a, const RenderQueueData &b) { return a.sorting_key < b.sorting_key; }); } } void RenderQueue::combine_render_info(const RenderQueue &queue) { for (unsigned i = 0; i < ecast(Queue::Count); i++) { auto e = static_cast<Queue>(i); queues[i].insert(end(queues[i]), begin(queue.get_queue_data(e)), end(queue.get_queue_data(e))); } } void RenderQueue::dispatch(Queue queue_type, CommandBuffer &cmd, const CommandBufferSavedState *state, size_t begin, size_t end) { auto *queue = queues[ecast(queue_type)].data(); while (begin < end) { if (state) cmd.restore_state(*state); unsigned instances = 1; for (size_t i = begin + 1; i < end && queue[i].render_info == queue[begin].render_info; i++) { assert(queue[i].render == queue[begin].render); instances++; } queue[begin].render(cmd, &queue[begin], instances); begin += instances; } } void RenderQueue::dispatch(Queue queue, CommandBuffer &cmd, const CommandBufferSavedState *state) { dispatch(queue, cmd, state, 0, queues[ecast(queue)].size()); } void RenderQueue::enqueue_queue_data(Queue queue_type, const RenderQueueData &render_info) { queues[ecast(queue_type)].push_back(render_info); } RenderQueue::Chain::iterator RenderQueue::insert_block() { return blocks.insert(end(blocks), Block(BlockSize)); } RenderQueue::Chain::iterator RenderQueue::insert_large_block(size_t size, size_t alignment) { size_t padded_size = alignment > alignof(uintmax_t) ? (size + alignment) : size; return large_blocks.insert(end(large_blocks), Block(padded_size)); } void *RenderQueue::allocate_from_block(Block &block, size_t size, size_t alignment) { block.ptr = (block.ptr + alignment - 1) & ~(alignment - 1); uintptr_t end = block.ptr + size; if (end <= block.end) { void *ret = reinterpret_cast<void *>(block.ptr); block.ptr = end; return ret; } else return nullptr; } void RenderQueue::reset() { current = begin(blocks); if (current != end(blocks)) current->reset(); for (auto &queue : queues) queue.clear(); large_blocks.clear(); render_infos.clear(); } void RenderQueue::reset_and_reclaim() { blocks.clear(); large_blocks.clear(); render_infos.clear(); current = end(blocks); for (auto &queue : queues) queue.clear(); } void *RenderQueue::allocate(size_t size, size_t alignment) { if (size + alignment > BlockSize) { auto itr = insert_large_block(size, alignment); return allocate_from_block(*itr, size, alignment); } // First allocation. if (current == end(blocks)) current = insert_block(); void *data = allocate_from_block(*current, size, alignment); if (data) return data; ++current; if (current == end(blocks)) current = insert_block(); else current->reset(); data = allocate_from_block(*current, size, alignment); return data; } uint64_t RenderInfo::get_background_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash) { pipeline_hash &= 0xffff0000u; pipeline_hash |= draw_hash & 0xffffu; if (queue_type == Queue::Transparent) return pipeline_hash & 0xffffffffu; else return (UINT64_MAX << 32) | (pipeline_hash & 0xffffffffu); } uint64_t RenderInfo::get_sprite_sort_key(Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash, float z, StaticLayer layer) { static_assert(ecast(StaticLayer::Count) == 4, "Number of static layers is not 4."); // Monotonically increasing floating point will be monotonic in uint32_t as well when z is non-negative. z = muglm::max(z, 0.0f); uint32_t depth_key = floatBitsToUint(z); pipeline_hash &= 0xffff0000u; pipeline_hash |= draw_hash & 0xffffu; if (queue_type == Queue::Transparent) { depth_key ^= 0xffffffffu; // Back-to-front instead. // Prioritize correct back-to-front rendering over pipeline. return (uint64_t(depth_key) << 32) | pipeline_hash; } else { #if 1 // Prioritize state changes over depth. depth_key >>= 2; return (uint64_t(ecast(layer)) << 62) | (uint64_t(pipeline_hash) << 30) | depth_key; #else // Prioritize front-back sorting over state changes. pipeline_hash >>= 2; return (uint64_t(ecast(layer)) << 62) | (uint64_t(depth_key) << 30) | pipeline_hash; #endif } } uint64_t RenderInfo::get_sort_key(const RenderContext &context, Queue queue_type, Util::Hash pipeline_hash, Util::Hash draw_hash, const vec3 &center, StaticLayer layer) { float z = dot(context.get_render_parameters().camera_front, center - context.get_render_parameters().camera_position); return get_sprite_sort_key(queue_type, pipeline_hash, draw_hash, z, layer); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Cylinder.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlCylinder - implicit function for a cylinder // .SECTION Description // vlCylinder computes the implicit function and function gradient for // a cylinder. vlCylinder is a concrete implementation of vlImplicitFunction. // Cylinder is centered at origin and axes of rotation is along z-axis. (Use a // transform filter if necessary to reposition). #ifndef __vlCylinder_h #define __vlCylinder_h #include "ImpFunc.hh" class vlCylinder : public vlImplicitFunction { public: vlCylinder(); char *GetClassName() {return "vlCylinder";}; void PrintSelf(ostream& os, vlIndent indent); // ImplicitFunction interface float EvaluateFunction(float x[3]); void EvaluateGradient(float x[3], float g[3]); // Description: // Set/Get cylinder radius. vlSetMacro(Radius,float); vlGetMacro(Radius,float); // Description: // Set/Get cylinder height. vlSetMacro(Height,float); vlGetMacro(Height,float); protected: float Radius; float Height; }; #endif <commit_msg>ENH: Final definition.<commit_after>/*========================================================================= Program: Visualization Library Module: Cylinder.hh Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ // .NAME vlCylinder - implicit function for a cylinder // .SECTION Description // vlCylinder computes the implicit function and function gradient for // a cylinder. vlCylinder is a concrete implementation of vlImplicitFunction. // Cylinder is centered at origin and axes of rotation is along z-axis. (Use a // transform filter if necessary to reposition). // .SECTION Caveats // The cylinder is infinite in extent. To truncate the cylinder use the // vlImplicitBoolean in combination with clipping planes. #ifndef __vlCylinder_h #define __vlCylinder_h #include "ImpFunc.hh" class vlCylinder : public vlImplicitFunction { public: vlCylinder(); char *GetClassName() {return "vlCylinder";}; void PrintSelf(ostream& os, vlIndent indent); // ImplicitFunction interface float EvaluateFunction(float x[3]); void EvaluateGradient(float x[3], float g[3]); // Description: // Set/Get cylinder radius. vlSetMacro(Radius,float); vlGetMacro(Radius,float); protected: float Radius; }; #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef CPM_CPM_HPP #define CPM_CPM_HPP #include <iostream> #include <chrono> #include <random> #include <utility> #include <functional> #define STRINGIFY(x) #x #define TO_STRING(x) STRINGIFY(x) #if defined(__clang__) #define COMPILER "clang" #define COMPILER_FULL "clang-" TO_STRING(__clang_major__) "." TO_STRING(__clang_minor__) "." TO_STRING(__clang_patchlevel__) #elif defined(__ICC) || defined(__INTEL_COMPILER) #define COMPILER "icc" #define COMPILER_FULL "icc-" TO_STRING(__INTEL_COMPILER) #elif defined(__GNUC__) || defined(__GNUG__) #define COMPILER "gcc" #define COMPILER_FULL "gcc-" TO_STRING(__GNUC__) "." TO_STRING(__GNUC_MINOR__) "." TO_STRING(__GNUC_PATCHLEVEL__) #else #define COMPILER "unknown" #define COMPILER_FULL "unknown" #endif namespace cpm { typedef std::chrono::steady_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; inline std::string us_duration_str(std::size_t duration_us){ double duration = duration_us; if(duration > 1000 * 1000){ return std::to_string(duration / 1000.0 / 1000.0) + "s"; } else if(duration > 1000){ return std::to_string(duration / 1000.0) + "ms"; } else { return std::to_string(duration_us) + "us"; } } template<typename T> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } void randomize(){} template<typename T1, typename std::enable_if_t<std::is_convertible<double, typename T1::value_type>::value, int> = 42 > void randomize(T1& container){ randomize_double(container); } template<typename T1, typename... TT, typename std::enable_if_t<std::is_convertible<double, typename T1::value_type>::value, int> = 42 > void randomize(T1& container, TT&... containers){ randomize_double(container); randomize(containers...); } template<typename Tuple, typename Functor, std::size_t... I, typename... Args> inline void call_with_data(Tuple& data, Functor functor, std::index_sequence<I...> /*indices*/, Args... args){ functor(args..., std::get<I>(data)...); } template<typename Tuple, std::size_t... I> inline void randomize_each(Tuple& data, std::index_sequence<I...> /*indices*/){ using cpm::randomize; randomize(std::get<I>(data)...); } enum class stop_policy { TIMEOUT, GLOBAL_TIMEOUT, STOP }; template<std::size_t S, std::size_t E, std::size_t A, std::size_t M, stop_policy SP> struct cmp_policy { static constexpr const std::size_t start = S; static constexpr const std::size_t end = E; static constexpr const std::size_t add = A; static constexpr const std::size_t mul = M; static constexpr const stop_policy stop = SP; }; using std_stop_policy = cmp_policy<10, 1000000, 0, 10, stop_policy::STOP>; using std_timeout_policy = cmp_policy<10, 1000, 0, 10, stop_policy::TIMEOUT>; using std_global_timeout_policy = cmp_policy<10, 5000, 0, 10, stop_policy::GLOBAL_TIMEOUT>; struct benchmark; template<typename Policy> struct section { std::string name; benchmark& bench; section(std::string name, benchmark& bench) : name(std::move(name)), bench(bench) {} ~section(){ //TODO Report } }; struct benchmark { private: std::size_t tests = 0; std::size_t measures = 0; std::size_t runs = 0; public: std::size_t warmup = 10; std::size_t repeat = 50; bool standard_report = true; void start(){ if(standard_report){ std::cout << "Start CPM benchmarks" << std::endl; std::cout << " Each test is warmed-up " << warmup << " times" << std::endl; std::cout << " Each test is repeated " << repeat << " times" << std::endl; std::cout << " Compiler " << COMPILER_FULL << std::endl; std::cout << std::endl; } } ~benchmark(){ if(standard_report){ std::cout << std::endl; std::cout << "End of CPM benchmarks" << std::endl; std::cout << " " << tests << " tests have been run" << std::endl; std::cout << " " << measures << " measures have been taken" << std::endl; std::cout << " " << runs << " functors calls" << std::endl; std::cout << std::endl; } } template<typename Policy = std_stop_policy> section<Policy> multi(std::string name){ return {std::move(name), *this}; } //Measure simple functor (no randomization) template<typename Policy = std_stop_policy, typename Functor> void measure_simple(const std::string& title, Functor functor){ policy_run<Policy>( [&title, &functor, this](std::size_t d){ auto duration = measure_only_simple(functor, d); report(title, d, duration); return duration; } ); } //Measure with two-pass functors (init and functor) template<typename Policy = std_stop_policy, typename Init, typename Functor> void measure_two_pass(const std::string& title, Init init, Functor functor){ policy_run<Policy>( [&title, &functor, &init, this](std::size_t d){ auto duration = measure_only_two_pass(init, functor, d); report(title, d, duration); return duration; } ); } //measure a function with global references template<typename Policy = std_stop_policy, typename Functor, typename... T> void measure_global(const std::string& title, Functor functor, T&... references){ policy_run<Policy>( [&title, &functor, &references..., this](std::size_t d){ auto duration = measure_only_global(functor, references...); report(title, d, duration); return duration; } ); } //Measure and return the duration of a simple functor template<typename Functor> std::size_t measure_once(Functor functor){ auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); return duration.count(); } private: template<typename Policy, typename M> void policy_run(M measure){ ++tests; if(Policy::stop == stop_policy::STOP){ std::size_t d = Policy::start; while(d <= Policy::end){ auto duration = measure(d); d = d * Policy::mul + Policy::add; } } else if(Policy::stop == stop_policy::TIMEOUT || Policy::stop == stop_policy::GLOBAL_TIMEOUT){ std::size_t d = Policy::start; std::size_t mul = 1; if(Policy::stop == stop_policy::GLOBAL_TIMEOUT){ mul = repeat; } while(true){ auto duration = measure(d); if(((duration * repeat) / 1000) > Policy::end){ break; } d = d * Policy::mul + Policy::add; } } } template<typename Functor, typename... Args> std::size_t measure_only_simple(Functor& functor, Args... args){ ++measures; for(std::size_t i = 0; i < warmup; ++i){ functor(args...); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ auto start_time = timer_clock::now(); functor(args...); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } template<typename Init, typename Functor, typename... Args> std::size_t measure_only_two_pass(Init& init, Functor& functor, Args... args){ ++measures; auto data = init(args...); static constexpr const std::size_t tuple_s = std::tuple_size<decltype(data)>::value; std::make_index_sequence<tuple_s> sequence; for(std::size_t i = 0; i < warmup; ++i){ randomize_each(data, sequence); call_with_data(data, functor, sequence, args...); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ randomize_each(data, sequence); auto start_time = timer_clock::now(); call_with_data(data, functor, sequence, args...); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } template<typename Functor, typename... T> std::size_t measure_only_global(Functor& functor, T&... references){ ++measures; for(std::size_t i = 0; i < warmup; ++i){ using cpm::randomize; randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ using cpm::randomize; randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } void report(const std::string& title, std::size_t d, std::size_t duration){ if(standard_report){ std::cout << title << "(" << d << ") took " << us_duration_str(duration) << "\n"; } } }; } //end of namespace cpm #endif //CPM_CPM_HPP <commit_msg>Start section support<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef CPM_CPM_HPP #define CPM_CPM_HPP #include <iostream> #include <chrono> #include <random> #include <utility> #include <functional> #define STRINGIFY(x) #x #define TO_STRING(x) STRINGIFY(x) #if defined(__clang__) #define COMPILER "clang" #define COMPILER_FULL "clang-" TO_STRING(__clang_major__) "." TO_STRING(__clang_minor__) "." TO_STRING(__clang_patchlevel__) #elif defined(__ICC) || defined(__INTEL_COMPILER) #define COMPILER "icc" #define COMPILER_FULL "icc-" TO_STRING(__INTEL_COMPILER) #elif defined(__GNUC__) || defined(__GNUG__) #define COMPILER "gcc" #define COMPILER_FULL "gcc-" TO_STRING(__GNUC__) "." TO_STRING(__GNUC_MINOR__) "." TO_STRING(__GNUC_PATCHLEVEL__) #else #define COMPILER "unknown" #define COMPILER_FULL "unknown" #endif namespace cpm { typedef std::chrono::steady_clock timer_clock; typedef std::chrono::milliseconds milliseconds; typedef std::chrono::microseconds microseconds; inline std::string us_duration_str(std::size_t duration_us){ double duration = duration_us; if(duration > 1000 * 1000){ return std::to_string(duration / 1000.0 / 1000.0) + "s"; } else if(duration > 1000){ return std::to_string(duration / 1000.0) + "ms"; } else { return std::to_string(duration_us) + "us"; } } template<typename T> void randomize_double(T& container){ static std::default_random_engine rand_engine(std::time(nullptr)); static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0); static auto generator = std::bind(real_distribution, rand_engine); for(auto& v : container){ v = generator(); } } void randomize(){} template<typename T1, typename std::enable_if_t<std::is_convertible<double, typename T1::value_type>::value, int> = 42 > void randomize(T1& container){ randomize_double(container); } template<typename T1, typename... TT, typename std::enable_if_t<std::is_convertible<double, typename T1::value_type>::value, int> = 42 > void randomize(T1& container, TT&... containers){ randomize_double(container); randomize(containers...); } template<typename Tuple, typename Functor, std::size_t... I, typename... Args> inline void call_with_data(Tuple& data, Functor functor, std::index_sequence<I...> /*indices*/, Args... args){ functor(args..., std::get<I>(data)...); } template<typename Tuple, std::size_t... I> inline void randomize_each(Tuple& data, std::index_sequence<I...> /*indices*/){ using cpm::randomize; randomize(std::get<I>(data)...); } enum class stop_policy { TIMEOUT, GLOBAL_TIMEOUT, STOP }; template<std::size_t S, std::size_t E, std::size_t A, std::size_t M, stop_policy SP> struct cmp_policy { static constexpr const std::size_t start = S; static constexpr const std::size_t end = E; static constexpr const std::size_t add = A; static constexpr const std::size_t mul = M; static constexpr const stop_policy stop = SP; }; using std_stop_policy = cmp_policy<10, 1000000, 0, 10, stop_policy::STOP>; using std_timeout_policy = cmp_policy<10, 1000, 0, 10, stop_policy::TIMEOUT>; using std_global_timeout_policy = cmp_policy<10, 5000, 0, 10, stop_policy::GLOBAL_TIMEOUT>; template<typename DefaultPolicy = std_stop_policy> struct benchmark; template<typename Bench, typename Policy> struct section { private: std::string name; Bench& bench; public: section(std::string name, Bench& bench) : name(std::move(name)), bench(bench) {} //Measure simple functor (no randomization) template<typename Functor> void measure_simple(const std::string& title, Functor functor){ bench.template policy_run<Policy>( [&title, &functor, this](std::size_t d){ auto duration = bench.measure_only_simple(functor, d); report(title, d, duration); return duration; } ); } //Measure with two-pass functors (init and functor) template<typename Init, typename Functor> void measure_two_pass(const std::string& title, Init init, Functor functor){ bench.template policy_run<Policy>( [&title, &functor, &init, this](std::size_t d){ auto duration = bench.measure_only_two_pass(init, functor, d); report(title, d, duration); return duration; } ); } //measure a function with global references template<typename Functor, typename... T> void measure_global(const std::string& title, Functor functor, T&... references){ bench.template policy_run<Policy>( [&title, &functor, &references..., this](std::size_t d){ auto duration = bench.measure_only_global(functor, references...); report(title, d, duration); return duration; } ); } ~section(){ //TODO Report } private: void report(const std::string& title, std::size_t d, std::size_t duration){ std::cout << "SUB: " << title << "(" << d << ") took " << us_duration_str(duration) << "\n"; } }; template<typename DefaultPolicy> struct benchmark { private: template<typename Bench, typename Policy> friend class section; std::size_t tests = 0; std::size_t measures = 0; std::size_t runs = 0; public: std::size_t warmup = 10; std::size_t repeat = 50; bool standard_report = true; void start(){ if(standard_report){ std::cout << "Start CPM benchmarks" << std::endl; std::cout << " Each test is warmed-up " << warmup << " times" << std::endl; std::cout << " Each test is repeated " << repeat << " times" << std::endl; std::cout << " Compiler " << COMPILER_FULL << std::endl; std::cout << std::endl; } } ~benchmark(){ if(standard_report){ std::cout << std::endl; std::cout << "End of CPM benchmarks" << std::endl; std::cout << " " << tests << " tests have been run" << std::endl; std::cout << " " << measures << " measures have been taken" << std::endl; std::cout << " " << runs << " functors calls" << std::endl; std::cout << std::endl; } } template<typename Policy = DefaultPolicy> section<benchmark<DefaultPolicy>, Policy> multi(std::string name){ return {std::move(name), *this}; } //Measure simple functor (no randomization) template<typename Policy = DefaultPolicy, typename Functor> void measure_simple(const std::string& title, Functor functor){ policy_run<Policy>( [&title, &functor, this](std::size_t d){ auto duration = measure_only_simple(functor, d); report(title, d, duration); return duration; } ); } //Measure with two-pass functors (init and functor) template<typename Policy = DefaultPolicy, typename Init, typename Functor> void measure_two_pass(const std::string& title, Init init, Functor functor){ policy_run<Policy>( [&title, &functor, &init, this](std::size_t d){ auto duration = measure_only_two_pass(init, functor, d); report(title, d, duration); return duration; } ); } //measure a function with global references template<typename Policy = DefaultPolicy, typename Functor, typename... T> void measure_global(const std::string& title, Functor functor, T&... references){ policy_run<Policy>( [&title, &functor, &references..., this](std::size_t d){ auto duration = measure_only_global(functor, references...); report(title, d, duration); return duration; } ); } //Measure and return the duration of a simple functor template<typename Functor> std::size_t measure_once(Functor functor){ auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); return duration.count(); } private: template<typename Policy, typename M> void policy_run(M measure){ ++tests; if(Policy::stop == stop_policy::STOP){ std::size_t d = Policy::start; while(d <= Policy::end){ auto duration = measure(d); d = d * Policy::mul + Policy::add; } } else if(Policy::stop == stop_policy::TIMEOUT || Policy::stop == stop_policy::GLOBAL_TIMEOUT){ std::size_t d = Policy::start; std::size_t mul = 1; if(Policy::stop == stop_policy::GLOBAL_TIMEOUT){ mul = repeat; } while(true){ auto duration = measure(d); if(((duration * repeat) / 1000) > Policy::end){ break; } d = d * Policy::mul + Policy::add; } } } template<typename Functor, typename... Args> std::size_t measure_only_simple(Functor& functor, Args... args){ ++measures; for(std::size_t i = 0; i < warmup; ++i){ functor(args...); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ auto start_time = timer_clock::now(); functor(args...); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } template<typename Init, typename Functor, typename... Args> std::size_t measure_only_two_pass(Init& init, Functor& functor, Args... args){ ++measures; auto data = init(args...); static constexpr const std::size_t tuple_s = std::tuple_size<decltype(data)>::value; std::make_index_sequence<tuple_s> sequence; for(std::size_t i = 0; i < warmup; ++i){ randomize_each(data, sequence); call_with_data(data, functor, sequence, args...); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ randomize_each(data, sequence); auto start_time = timer_clock::now(); call_with_data(data, functor, sequence, args...); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } template<typename Functor, typename... T> std::size_t measure_only_global(Functor& functor, T&... references){ ++measures; for(std::size_t i = 0; i < warmup; ++i){ using cpm::randomize; randomize(references...); functor(); } std::size_t duration_acc = 0; for(std::size_t i = 0; i < repeat; ++i){ using cpm::randomize; randomize(references...); auto start_time = timer_clock::now(); functor(); auto end_time = timer_clock::now(); auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time); duration_acc += duration.count(); } runs += warmup + repeat; return duration_acc / repeat; } void report(const std::string& title, std::size_t d, std::size_t duration){ if(standard_report){ std::cout << title << "(" << d << ") took " << us_duration_str(duration) << "\n"; } } }; } //end of namespace cpm #endif //CPM_CPM_HPP <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_ETL_HPP #define ETL_ETL_HPP // The operators #include "generators.hpp" #include "transformers.hpp" #include "views.hpp" #include "virtual_views.hpp" #include "unary_op.hpp" #include "binary_op.hpp" // The expressions #include "binary_expr.hpp" #include "unary_expr.hpp" #include "stable_transform_expr.hpp" #include "generator_expr.hpp" // The value classes #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" #include "etl/fast_dyn_matrix.hpp" #include "etl/fast_dyn_vector.hpp" // The traits #include "traits.hpp" // The expressions building #include "fast_expr.hpp" #endif <commit_msg>Always include print support<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_ETL_HPP #define ETL_ETL_HPP // The operators #include "generators.hpp" #include "transformers.hpp" #include "views.hpp" #include "virtual_views.hpp" #include "unary_op.hpp" #include "binary_op.hpp" // The expressions #include "binary_expr.hpp" #include "unary_expr.hpp" #include "stable_transform_expr.hpp" #include "generator_expr.hpp" // The value classes #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" #include "etl/fast_dyn_matrix.hpp" #include "etl/fast_dyn_vector.hpp" // The traits #include "traits.hpp" // The expressions building #include "fast_expr.hpp" // to_string support #include "print.hpp" #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include "modules/desktop_capture/mouse_cursor_monitor.h" #include <X11/extensions/Xfixes.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/x11/x_error_trap.h" #include "rtc_base/logging.h" namespace { // WindowCapturer returns window IDs of X11 windows with WM_STATE attribute. // These windows may not be immediate children of the root window, because // window managers may re-parent them to add decorations. However, // XQueryPointer() expects to be passed children of the root. This function // searches up the list of the windows to find the root child that corresponds // to |window|. Window GetTopLevelWindow(Display* display, Window window) { while (true) { // If the window is in WithdrawnState then look at all of its children. ::Window root, parent; ::Window *children; unsigned int num_children; if (!XQueryTree(display, window, &root, &parent, &children, &num_children)) { LOG(LS_ERROR) << "Failed to query for child windows although window" << "does not have a valid WM_STATE."; return None; } if (children) XFree(children); if (parent == root) break; window = parent; } return window; } } // namespace namespace webrtc { class MouseCursorMonitorX11 : public MouseCursorMonitor, public SharedXDisplay::XEventHandler { public: MouseCursorMonitorX11(const DesktopCaptureOptions& options, Window window); ~MouseCursorMonitorX11() override; void Init(Callback* callback, Mode mode) override; void Capture() override; private: // SharedXDisplay::XEventHandler interface. bool HandleXEvent(const XEvent& event) override; Display* display() { return x_display_->display(); } // Captures current cursor shape and stores it in |cursor_shape_|. void CaptureCursor(); rtc::scoped_refptr<SharedXDisplay> x_display_; Callback* callback_; Mode mode_; Window window_; bool have_xfixes_; int xfixes_event_base_; int xfixes_error_base_; std::unique_ptr<MouseCursor> cursor_shape_; }; MouseCursorMonitorX11::MouseCursorMonitorX11( const DesktopCaptureOptions& options, Window window) : x_display_(options.x_display()), callback_(NULL), mode_(SHAPE_AND_POSITION), window_(window), have_xfixes_(false), xfixes_event_base_(-1), xfixes_error_base_(-1) { // Set a default initial cursor shape in case XFixes is not present. const int kSize = 5; std::unique_ptr<DesktopFrame> default_cursor( new BasicDesktopFrame(DesktopSize(kSize, kSize))); const uint8_t pixels[kSize * kSize] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t* ptr = default_cursor->data(); for (int y = 0; y < kSize; ++y) { for (int x = 0; x < kSize; ++x) { *ptr++ = pixels[kSize * y + x]; *ptr++ = pixels[kSize * y + x]; *ptr++ = pixels[kSize * y + x]; *ptr++ = 0xff; } } DesktopVector hotspot(2, 2); cursor_shape_.reset(new MouseCursor(default_cursor.release(), hotspot)); } MouseCursorMonitorX11::~MouseCursorMonitorX11() { if (have_xfixes_) { x_display_->RemoveEventHandler(xfixes_event_base_ + XFixesCursorNotify, this); } } void MouseCursorMonitorX11::Init(Callback* callback, Mode mode) { // Init can be called only once per instance of MouseCursorMonitor. RTC_DCHECK(!callback_); RTC_DCHECK(callback); callback_ = callback; mode_ = mode; have_xfixes_ = XFixesQueryExtension(display(), &xfixes_event_base_, &xfixes_error_base_); if (have_xfixes_) { // Register for changes to the cursor shape. XFixesSelectCursorInput(display(), window_, XFixesDisplayCursorNotifyMask); x_display_->AddEventHandler(xfixes_event_base_ + XFixesCursorNotify, this); CaptureCursor(); } else { LOG(LS_INFO) << "X server does not support XFixes."; } } void MouseCursorMonitorX11::Capture() { RTC_DCHECK(callback_); // Process X11 events in case XFixes has sent cursor notification. x_display_->ProcessPendingXEvents(); // cursor_shape_| is set only if we were notified of a cursor shape change. if (cursor_shape_.get()) callback_->OnMouseCursor(cursor_shape_.release()); // Get cursor position if necessary. if (mode_ == SHAPE_AND_POSITION) { int root_x; int root_y; int win_x; int win_y; Window root_window; Window child_window; unsigned int mask; XErrorTrap error_trap(display()); Bool result = XQueryPointer(display(), window_, &root_window, &child_window, &root_x, &root_y, &win_x, &win_y, &mask); CursorState state; if (!result || error_trap.GetLastErrorAndDisable() != 0) { state = OUTSIDE; } else { // In screen mode (window_ == root_window) the mouse is always inside. // XQueryPointer() sets |child_window| to None if the cursor is outside // |window_|. state = (window_ == root_window || child_window != None) ? INSIDE : OUTSIDE; } // As the comments to GetTopLevelWindow() above indicate, in window capture, // the cursor position capture happens in |window_|, while the frame catpure // happens in |child_window|. These two windows are not alwyas same, as // window manager may add some decorations to the |window_|. So translate // the coordinate in |window_| to the coordinate space of |child_window|. if (window_ != root_window && state == INSIDE) { int translated_x, translated_y; Window unused; if (XTranslateCoordinates(display(), window_, child_window, win_x, win_y, &translated_x, &translated_y, &unused)) { win_x = translated_x; win_y = translated_y; } } const DesktopVector position(win_x, win_y); // TODO(zijiehe): Remove this overload. callback_->OnMouseCursorPosition(state, position); // X11 always starts the coordinate from (0, 0), so we do not need to // translate here. callback_->OnMouseCursorPosition(position); } } bool MouseCursorMonitorX11::HandleXEvent(const XEvent& event) { if (have_xfixes_ && event.type == xfixes_event_base_ + XFixesCursorNotify) { const XFixesCursorNotifyEvent* cursor_event = reinterpret_cast<const XFixesCursorNotifyEvent*>(&event); if (cursor_event->subtype == XFixesDisplayCursorNotify) { CaptureCursor(); } // Return false, even if the event has been handled, because there might be // other listeners for cursor notifications. } return false; } void MouseCursorMonitorX11::CaptureCursor() { RTC_DCHECK(have_xfixes_); XFixesCursorImage* img; { XErrorTrap error_trap(display()); img = XFixesGetCursorImage(display()); if (!img || error_trap.GetLastErrorAndDisable() != 0) return; } std::unique_ptr<DesktopFrame> image( new BasicDesktopFrame(DesktopSize(img->width, img->height))); // Xlib stores 32-bit data in longs, even if longs are 64-bits long. unsigned long* src = img->pixels; uint32_t* dst = reinterpret_cast<uint32_t*>(image->data()); uint32_t* dst_end = dst + (img->width * img->height); while (dst < dst_end) { *dst++ = static_cast<uint32_t>(*src++); } DesktopVector hotspot(std::min(img->width, img->xhot), std::min(img->height, img->yhot)); XFree(img); cursor_shape_.reset(new MouseCursor(image.release(), hotspot)); } // static MouseCursorMonitor* MouseCursorMonitor::CreateForWindow( const DesktopCaptureOptions& options, WindowId window) { if (!options.x_display()) return NULL; window = GetTopLevelWindow(options.x_display()->display(), window); if (window == None) return NULL; return new MouseCursorMonitorX11(options, window); } MouseCursorMonitor* MouseCursorMonitor::CreateForScreen( const DesktopCaptureOptions& options, ScreenId screen) { if (!options.x_display()) return NULL; return new MouseCursorMonitorX11( options, DefaultRootWindow(options.x_display()->display())); } std::unique_ptr<MouseCursorMonitor> MouseCursorMonitor::Create( const DesktopCaptureOptions& options) { return std::unique_ptr<MouseCursorMonitor>( CreateForScreen(options, kFullDesktopScreenId)); } } // namespace webrtc <commit_msg>[Window Capture] Inaccurate cursor position during window sharing on X11<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include "modules/desktop_capture/mouse_cursor_monitor.h" #include <X11/extensions/Xfixes.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "modules/desktop_capture/desktop_capture_options.h" #include "modules/desktop_capture/desktop_capture_types.h" #include "modules/desktop_capture/desktop_frame.h" #include "modules/desktop_capture/mouse_cursor.h" #include "modules/desktop_capture/x11/x_error_trap.h" #include "rtc_base/logging.h" namespace { // WindowCapturer returns window IDs of X11 windows with WM_STATE attribute. // These windows may not be immediate children of the root window, because // window managers may re-parent them to add decorations. However, // XQueryPointer() expects to be passed children of the root. This function // searches up the list of the windows to find the root child that corresponds // to |window|. Window GetTopLevelWindow(Display* display, Window window) { while (true) { // If the window is in WithdrawnState then look at all of its children. ::Window root, parent; ::Window *children; unsigned int num_children; if (!XQueryTree(display, window, &root, &parent, &children, &num_children)) { LOG(LS_ERROR) << "Failed to query for child windows although window" << "does not have a valid WM_STATE."; return None; } if (children) XFree(children); if (parent == root) break; window = parent; } return window; } } // namespace namespace webrtc { class MouseCursorMonitorX11 : public MouseCursorMonitor, public SharedXDisplay::XEventHandler { public: MouseCursorMonitorX11(const DesktopCaptureOptions& options, Window window); ~MouseCursorMonitorX11() override; void Init(Callback* callback, Mode mode) override; void Capture() override; private: // SharedXDisplay::XEventHandler interface. bool HandleXEvent(const XEvent& event) override; Display* display() { return x_display_->display(); } // Captures current cursor shape and stores it in |cursor_shape_|. void CaptureCursor(); rtc::scoped_refptr<SharedXDisplay> x_display_; Callback* callback_; Mode mode_; Window window_; bool have_xfixes_; int xfixes_event_base_; int xfixes_error_base_; std::unique_ptr<MouseCursor> cursor_shape_; }; MouseCursorMonitorX11::MouseCursorMonitorX11( const DesktopCaptureOptions& options, Window window) : x_display_(options.x_display()), callback_(NULL), mode_(SHAPE_AND_POSITION), window_(window), have_xfixes_(false), xfixes_event_base_(-1), xfixes_error_base_(-1) { // Set a default initial cursor shape in case XFixes is not present. const int kSize = 5; std::unique_ptr<DesktopFrame> default_cursor( new BasicDesktopFrame(DesktopSize(kSize, kSize))); const uint8_t pixels[kSize * kSize] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t* ptr = default_cursor->data(); for (int y = 0; y < kSize; ++y) { for (int x = 0; x < kSize; ++x) { *ptr++ = pixels[kSize * y + x]; *ptr++ = pixels[kSize * y + x]; *ptr++ = pixels[kSize * y + x]; *ptr++ = 0xff; } } DesktopVector hotspot(2, 2); cursor_shape_.reset(new MouseCursor(default_cursor.release(), hotspot)); } MouseCursorMonitorX11::~MouseCursorMonitorX11() { if (have_xfixes_) { x_display_->RemoveEventHandler(xfixes_event_base_ + XFixesCursorNotify, this); } } void MouseCursorMonitorX11::Init(Callback* callback, Mode mode) { // Init can be called only once per instance of MouseCursorMonitor. RTC_DCHECK(!callback_); RTC_DCHECK(callback); callback_ = callback; mode_ = mode; have_xfixes_ = XFixesQueryExtension(display(), &xfixes_event_base_, &xfixes_error_base_); if (have_xfixes_) { // Register for changes to the cursor shape. XFixesSelectCursorInput(display(), window_, XFixesDisplayCursorNotifyMask); x_display_->AddEventHandler(xfixes_event_base_ + XFixesCursorNotify, this); CaptureCursor(); } else { LOG(LS_INFO) << "X server does not support XFixes."; } } void MouseCursorMonitorX11::Capture() { RTC_DCHECK(callback_); // Process X11 events in case XFixes has sent cursor notification. x_display_->ProcessPendingXEvents(); // cursor_shape_| is set only if we were notified of a cursor shape change. if (cursor_shape_.get()) callback_->OnMouseCursor(cursor_shape_.release()); // Get cursor position if necessary. if (mode_ == SHAPE_AND_POSITION) { int root_x; int root_y; int win_x; int win_y; Window root_window; Window child_window; unsigned int mask; XErrorTrap error_trap(display()); Bool result = XQueryPointer(display(), window_, &root_window, &child_window, &root_x, &root_y, &win_x, &win_y, &mask); CursorState state; if (!result || error_trap.GetLastErrorAndDisable() != 0) { state = OUTSIDE; } else { // In screen mode (window_ == root_window) the mouse is always inside. // XQueryPointer() sets |child_window| to None if the cursor is outside // |window_|. state = (window_ == root_window || child_window != None) ? INSIDE : OUTSIDE; } // As the comments to GetTopLevelWindow() above indicate, in window capture, // the cursor position capture happens in |window_|, while the frame catpure // happens in |child_window|. These two windows are not alwyas same, as // window manager may add some decorations to the |window_|. So translate // the coordinate in |window_| to the coordinate space of |child_window|. if (window_ != root_window && state == INSIDE) { int translated_x, translated_y; Window unused; if (XTranslateCoordinates(display(), window_, child_window, win_x, win_y, &translated_x, &translated_y, &unused)) { win_x = translated_x; win_y = translated_y; } } // TODO(zijiehe): Remove this overload. callback_->OnMouseCursorPosition(state, DesktopVector(win_x, win_y)); // X11 always starts the coordinate from (0, 0), so we do not need to // translate here. callback_->OnMouseCursorPosition(DesktopVector(root_x, root_y)); } } bool MouseCursorMonitorX11::HandleXEvent(const XEvent& event) { if (have_xfixes_ && event.type == xfixes_event_base_ + XFixesCursorNotify) { const XFixesCursorNotifyEvent* cursor_event = reinterpret_cast<const XFixesCursorNotifyEvent*>(&event); if (cursor_event->subtype == XFixesDisplayCursorNotify) { CaptureCursor(); } // Return false, even if the event has been handled, because there might be // other listeners for cursor notifications. } return false; } void MouseCursorMonitorX11::CaptureCursor() { RTC_DCHECK(have_xfixes_); XFixesCursorImage* img; { XErrorTrap error_trap(display()); img = XFixesGetCursorImage(display()); if (!img || error_trap.GetLastErrorAndDisable() != 0) return; } std::unique_ptr<DesktopFrame> image( new BasicDesktopFrame(DesktopSize(img->width, img->height))); // Xlib stores 32-bit data in longs, even if longs are 64-bits long. unsigned long* src = img->pixels; uint32_t* dst = reinterpret_cast<uint32_t*>(image->data()); uint32_t* dst_end = dst + (img->width * img->height); while (dst < dst_end) { *dst++ = static_cast<uint32_t>(*src++); } DesktopVector hotspot(std::min(img->width, img->xhot), std::min(img->height, img->yhot)); XFree(img); cursor_shape_.reset(new MouseCursor(image.release(), hotspot)); } // static MouseCursorMonitor* MouseCursorMonitor::CreateForWindow( const DesktopCaptureOptions& options, WindowId window) { if (!options.x_display()) return NULL; window = GetTopLevelWindow(options.x_display()->display(), window); if (window == None) return NULL; return new MouseCursorMonitorX11(options, window); } MouseCursorMonitor* MouseCursorMonitor::CreateForScreen( const DesktopCaptureOptions& options, ScreenId screen) { if (!options.x_display()) return NULL; return new MouseCursorMonitorX11( options, DefaultRootWindow(options.x_display()->display())); } std::unique_ptr<MouseCursorMonitor> MouseCursorMonitor::Create( const DesktopCaptureOptions& options) { return std::unique_ptr<MouseCursorMonitor>( CreateForScreen(options, kFullDesktopScreenId)); } } // namespace webrtc <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, Elm Library Project // 3-clause BSD License // //M*/ #include "elm/layers/triangulation.h" #ifdef __WITH_PCL // test normally #include <boost/filesystem.hpp> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/features/normal_3d.h> #include <pcl/surface/gp3.h> #include <pcl/io/vtk_io.h> #include "elm/core/exception.h" #include "elm/core/layerconfig.h" #include "elm/core/pcl/vertices.h" #include "elm/core/signal.h" #include "elm/layers/layerfactory.h" #include "elm/ts/ts.h" #include "elm/ts/layer_assertions.h" using namespace std; namespace bfs=boost::filesystem; using namespace cv; using namespace pcl; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(Triangulation); const bfs::path TEST_DIR("testdata"); const bfs::path TEST_PATH_PCD = TEST_DIR/"bun0.pcd"; // Names for I/O const string NAME_INPUT_POINT_CLOUD = "in"; ///< name of input point cloud const string NAME_OUTPUT_VERTICES = "v"; ///< name of output vertices class TriangulationInitTest : public ::testing::Test { protected: virtual void SetUp() { cfg_ = LayerConfig(); cfg_.Params(params_); io_names_ = LayerIONames(); io_names_.Input(Triangulation::KEY_INPUT_POINT_CLOUD, NAME_INPUT_POINT_CLOUD); io_names_.Output(Triangulation::KEY_OUTPUT_VERTICES, NAME_OUTPUT_VERTICES); } virtual void TearDown() { params_.clear(); } // members PTree params_; LayerConfig cfg_; LayerIONames io_names_; }; TEST_F(TriangulationInitTest, Constructor) { EXPECT_NO_THROW(Triangulation to(cfg_)); } TEST_F(TriangulationInitTest, MissingParams) { cfg_.Params(PTree()); EXPECT_NO_THROW(Triangulation to(cfg_)); Triangulation to; EXPECT_NO_THROW(to.Reset(cfg_)); EXPECT_NO_THROW(to.Reconfigure(cfg_)); } TEST_F(TriangulationInitTest, CreateWithFactory) { shared_ptr<base_Layer> to_ptr = LayerFactory::CreateShared("Triangulation", cfg_, io_names_); EXPECT_TRUE(bool(to_ptr)); } /** * @brief Test the live methods assuming a sucessful initialization */ class TriangulationTest : public TriangulationInitTest { protected: virtual void SetUp() { TriangulationInitTest::SetUp(); // Load input file into a PointCloudXYZ cloud_in_.reset(new CloudXYZ); PCLPointCloud2 cloud_blob; pcl::io::loadPCDFile(TEST_PATH_PCD.string(), cloud_blob); fromPCLPointCloud2 (cloud_blob, *cloud_in_); to_ = LayerFactory::CreateShared("Triangulation", cfg_, io_names_); sig_.Append(NAME_INPUT_POINT_CLOUD, PointCloud2Mat_<PointXYZ>(cloud_in_)); } virtual void TearDown() { TriangulationInitTest::TearDown(); sig_.Clear(); } shared_ptr<base_Layer> to_; ///< pointer to test object Signal sig_; CloudXYZPtr cloud_in_; }; TEST_F(TriangulationTest, ActivateEmptyInput) { sig_.Append(NAME_INPUT_POINT_CLOUD, Mat1f()); EXPECT_THROW(to_->Activate(sig_), ExceptionBadDims); } TEST_F(TriangulationTest, ActivateAndResponse) { // Normal estimation* NormalEstimation<PointXYZ, Normal> n; PointCloud<Normal>::Ptr normals(new PointCloud<Normal>); search::KdTree<PointXYZ>::Ptr tree(new search::KdTree<PointXYZ>); tree->setInputCloud(cloud_in_); n.setInputCloud(cloud_in_); n.setSearchMethod(tree); n.setKSearch(20); n.compute(*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* PointCloud<PointNormal>::Ptr cloud_with_normals(new PointCloud<PointNormal>); concatenateFields(*cloud_in_, *normals, *cloud_with_normals); //* cloud_with_normals = cloud + normals // Create search tree* search::KdTree<PointNormal>::Ptr tree2(new search::KdTree<PointNormal>); tree2->setInputCloud(cloud_with_normals); // Initialize objects GreedyProjectionTriangulation<PointNormal> gp3; // Set the maximum distance between connected points (maximum edge length) gp3.setSearchRadius(Triangulation::DEFAULT_SEARCH_RADIUS); // Set typical values for the parameters gp3.setMu( Triangulation::DEFAULT_MU); gp3.setMaximumNearestNeighbors( Triangulation::DEFAULT_MAX_NN); gp3.setMaximumSurfaceAngle( Triangulation::DEFAULT_MAX_SURFACE_ANGLE); gp3.setMinimumAngle( Triangulation::DEFAULT_MIN_ANGLE); gp3.setMaximumAngle( Triangulation::DEFAULT_MAX_ANGLE); gp3.setNormalConsistency( Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY); // Get result gp3.setInputCloud(cloud_with_normals); gp3.setSearchMethod(tree2); //PolygonMesh triangles; //gp3.reconstruct(triangles); vector<Vertices > vertices_vec; gp3.reconstruct(vertices_vec); // Additional vertex information // vector<int> parts = gp3.getPartIDs(); // vector<int> states = gp3.getPointStates(); // cout<<triangles<<endl; // Finish //pcl::io::saveVTKFile ("mesh.vtk", triangles); to_->Activate(sig_); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_VERTICES)) << "Output feature already exists, better clear signal first."; to_->Response(sig_); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_VERTICES)) << "Output feature is missing."; Mat1f vertices_mat = sig_.MostRecent(NAME_OUTPUT_VERTICES); int nb_vertices = static_cast<int>(vertices_vec.size()); int sz_vertex = static_cast<int>(vertices_vec[0].vertices.size()); EXPECT_MAT_DIMS_EQ(vertices_mat, Size2i(nb_vertices*sz_vertex, 1)) << "Dimensions do not match."; int k=0; for(int i=0; i<nb_vertices; i++) { vector<uint32_t> tmp = vertices_vec[i].vertices; for(int j=0; j<sz_vertex; j++) { EXPECT_FLOAT_EQ(static_cast<float>(tmp[j]), vertices_mat(k++)) << "Vertex mismatch."; } } } } // annonymous namespace for test fixtures #else // __WITH_PCL #warning "Skipping building Triangulation layer unit tests" #endif // __WITH_PCL <commit_msg>triangulation layer: update assertion to no longer expect a flattened row matrix of triangulated mesh<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, Elm Library Project // 3-clause BSD License // //M*/ #include "elm/layers/triangulation.h" #ifdef __WITH_PCL // test normally #include <boost/filesystem.hpp> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/features/normal_3d.h> #include <pcl/surface/gp3.h> #include <pcl/io/vtk_io.h> #include "elm/core/exception.h" #include "elm/core/layerconfig.h" #include "elm/core/pcl/vertices.h" #include "elm/core/signal.h" #include "elm/layers/layerfactory.h" #include "elm/ts/ts.h" #include "elm/ts/layer_assertions.h" using namespace std; namespace bfs=boost::filesystem; using namespace cv; using namespace pcl; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(Triangulation); const bfs::path TEST_DIR("testdata"); const bfs::path TEST_PATH_PCD = TEST_DIR/"bun0.pcd"; // Names for I/O const string NAME_INPUT_POINT_CLOUD = "in"; ///< name of input point cloud const string NAME_OUTPUT_VERTICES = "v"; ///< name of output vertices class TriangulationInitTest : public ::testing::Test { protected: virtual void SetUp() { cfg_ = LayerConfig(); cfg_.Params(params_); io_names_ = LayerIONames(); io_names_.Input(Triangulation::KEY_INPUT_POINT_CLOUD, NAME_INPUT_POINT_CLOUD); io_names_.Output(Triangulation::KEY_OUTPUT_VERTICES, NAME_OUTPUT_VERTICES); } virtual void TearDown() { params_.clear(); } // members PTree params_; LayerConfig cfg_; LayerIONames io_names_; }; TEST_F(TriangulationInitTest, Constructor) { EXPECT_NO_THROW(Triangulation to(cfg_)); } TEST_F(TriangulationInitTest, MissingParams) { cfg_.Params(PTree()); EXPECT_NO_THROW(Triangulation to(cfg_)); Triangulation to; EXPECT_NO_THROW(to.Reset(cfg_)); EXPECT_NO_THROW(to.Reconfigure(cfg_)); } TEST_F(TriangulationInitTest, CreateWithFactory) { shared_ptr<base_Layer> to_ptr = LayerFactory::CreateShared("Triangulation", cfg_, io_names_); EXPECT_TRUE(bool(to_ptr)); } /** * @brief Test the live methods assuming a sucessful initialization */ class TriangulationTest : public TriangulationInitTest { protected: virtual void SetUp() { TriangulationInitTest::SetUp(); // Load input file into a PointCloudXYZ cloud_in_.reset(new CloudXYZ); PCLPointCloud2 cloud_blob; pcl::io::loadPCDFile(TEST_PATH_PCD.string(), cloud_blob); fromPCLPointCloud2 (cloud_blob, *cloud_in_); to_ = LayerFactory::CreateShared("Triangulation", cfg_, io_names_); sig_.Append(NAME_INPUT_POINT_CLOUD, PointCloud2Mat_<PointXYZ>(cloud_in_)); } virtual void TearDown() { TriangulationInitTest::TearDown(); sig_.Clear(); } shared_ptr<base_Layer> to_; ///< pointer to test object Signal sig_; CloudXYZPtr cloud_in_; }; TEST_F(TriangulationTest, ActivateEmptyInput) { sig_.Append(NAME_INPUT_POINT_CLOUD, Mat1f()); EXPECT_THROW(to_->Activate(sig_), ExceptionBadDims); } TEST_F(TriangulationTest, ActivateAndResponse) { // Normal estimation* NormalEstimation<PointXYZ, Normal> n; PointCloud<Normal>::Ptr normals(new PointCloud<Normal>); search::KdTree<PointXYZ>::Ptr tree(new search::KdTree<PointXYZ>); tree->setInputCloud(cloud_in_); n.setInputCloud(cloud_in_); n.setSearchMethod(tree); n.setKSearch(20); n.compute(*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* PointCloud<PointNormal>::Ptr cloud_with_normals(new PointCloud<PointNormal>); concatenateFields(*cloud_in_, *normals, *cloud_with_normals); //* cloud_with_normals = cloud + normals // Create search tree* search::KdTree<PointNormal>::Ptr tree2(new search::KdTree<PointNormal>); tree2->setInputCloud(cloud_with_normals); // Initialize objects GreedyProjectionTriangulation<PointNormal> gp3; // Set the maximum distance between connected points (maximum edge length) gp3.setSearchRadius(Triangulation::DEFAULT_SEARCH_RADIUS); // Set typical values for the parameters gp3.setMu( Triangulation::DEFAULT_MU); gp3.setMaximumNearestNeighbors( Triangulation::DEFAULT_MAX_NN); gp3.setMaximumSurfaceAngle( Triangulation::DEFAULT_MAX_SURFACE_ANGLE); gp3.setMinimumAngle( Triangulation::DEFAULT_MIN_ANGLE); gp3.setMaximumAngle( Triangulation::DEFAULT_MAX_ANGLE); gp3.setNormalConsistency( Triangulation::DEFAULT_IS_NORMAL_CONSISTENCY); // Get result gp3.setInputCloud(cloud_with_normals); gp3.setSearchMethod(tree2); //PolygonMesh triangles; //gp3.reconstruct(triangles); vector<Vertices > vertices_vec; gp3.reconstruct(vertices_vec); // Additional vertex information // vector<int> parts = gp3.getPartIDs(); // vector<int> states = gp3.getPointStates(); // cout<<triangles<<endl; // Finish //pcl::io::saveVTKFile ("mesh.vtk", triangles); to_->Activate(sig_); EXPECT_FALSE(sig_.Exists(NAME_OUTPUT_VERTICES)) << "Output feature already exists, better clear signal first."; to_->Response(sig_); EXPECT_TRUE(sig_.Exists(NAME_OUTPUT_VERTICES)) << "Output feature is missing."; Mat1f vertices_mat = sig_.MostRecent(NAME_OUTPUT_VERTICES); int nb_vertices = static_cast<int>(vertices_vec.size()); int sz_vertex = static_cast<int>(vertices_vec[0].vertices.size()); EXPECT_MAT_DIMS_EQ(vertices_mat, Size2i(sz_vertex, nb_vertices)) << "Dimensions do not match."; int k=0; for(int i=0; i<nb_vertices; i++) { vector<uint32_t> tmp = vertices_vec[i].vertices; for(int j=0; j<sz_vertex; j++) { EXPECT_FLOAT_EQ(static_cast<float>(tmp[j]), vertices_mat(k++)) << "Vertex mismatch."; } } } } // annonymous namespace for test fixtures #else // __WITH_PCL #warning "Skipping building Triangulation layer unit tests" #endif // __WITH_PCL <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <algorithm> #include <cmath> #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *frame, ReferenceLineInfo *reference_line_info) { Task::Execute(frame, reference_line_info); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); const auto &frenet_path = path_data.frenet_frame_path(); const auto &frenet_points = frenet_path.points(); if (frenet_points.empty()) { AERROR << "Path is empty."; return false; } const double half_width = common::VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; const double lateral_radius = half_width + FLAGS_lateral_ignore_buffer; const double lateral_stop_radius = half_width + FLAGS_static_decision_nudge_l_buffer; for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto &obstacle = *path_obstacle->obstacle(); bool is_bycycle_or_pedestrain = (obstacle.Perception().type() == perception::PerceptionObstacle::BICYCLE || obstacle.Perception().type() == perception::PerceptionObstacle::PEDESTRIAN); if (!is_bycycle_or_pedestrain && !obstacle.IsStatic()) { continue; } if (path_obstacle->HasLongitudinalDecision() && path_obstacle->LongitudinalDecision().has_ignore() && path_obstacle->HasLateralDecision() && path_obstacle->LateralDecision().has_ignore()) { continue; } if (path_obstacle->HasLongitudinalDecision() && path_obstacle->LongitudinalDecision().has_stop()) { continue; } if (path_obstacle->reference_line_st_boundary().boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->PerceptionSLBoundary(); if (sl_boundary.end_s() < frenet_points.front().s() || sl_boundary.start_s() > frenet_points.back().s()) { path_decision->AddLongitudinalDecision("PathDecider/not-in-s", obstacle.Id(), object_decision); path_decision->AddLateralDecision("PathDecider/not-in-s", obstacle.Id(), object_decision); continue; } const auto frenet_point = frenet_path.GetNearestPoint(sl_boundary); const double curr_l = frenet_point.l(); if (curr_l - lateral_radius > sl_boundary.end_l() || curr_l + lateral_radius < sl_boundary.start_l()) { // ignore path_decision->AddLateralDecision("PathDecider/not-in-l", obstacle.Id(), object_decision); } else if (curr_l - lateral_stop_radius < sl_boundary.end_l() && curr_l + lateral_stop_radius > sl_boundary.start_l()) { // stop *object_decision.mutable_stop() = GenerateObjectStopDecision(*path_obstacle); if (path_decision->MergeWithMainStop( object_decision.stop(), obstacle.Id(), reference_line_info_->reference_line(), reference_line_info_->AdcSlBoundary())) { path_decision->AddLongitudinalDecision("PathDecider/nearest-stop", obstacle.Id(), object_decision); } else { ObjectDecisionType object_decision; object_decision.mutable_ignore(); path_decision->AddLongitudinalDecision("PathDecider/not-nearest-stop", obstacle.Id(), object_decision); } } else if (FLAGS_enable_nudge_decision) { // nudge if (curr_l - lateral_stop_radius > sl_boundary.end_l()) { // LEFT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); path_decision->AddLateralDecision("PathDecider/left-nudge", obstacle.Id(), object_decision); } else { // RIGHT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); path_decision->AddLateralDecision("PathDecider/right-nudge", obstacle.Id(), object_decision); } } } return true; } ObjectStop PathDecider::GenerateObjectStopDecision( const PathObstacle &path_obstacle) const { ObjectStop object_stop; double stop_distance = path_obstacle.MinRadiusStopDistance( VehicleConfigHelper::GetConfig().vehicle_param()); object_stop.set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); object_stop.set_distance_s(-stop_distance); const double stop_ref_s = path_obstacle.PerceptionSLBoundary().start_s() - stop_distance; const auto stop_ref_point = reference_line_info_->reference_line().GetReferencePoint(stop_ref_s); object_stop.mutable_stop_point()->set_x(stop_ref_point.x()); object_stop.mutable_stop_point()->set_y(stop_ref_point.y()); object_stop.set_stop_heading(stop_ref_point.heading()); return object_stop; } } // namespace planning } // namespace apollo <commit_msg>planning: fix SIDEPASS stuck issue<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <algorithm> #include <cmath> #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *frame, ReferenceLineInfo *reference_line_info) { Task::Execute(frame, reference_line_info); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); const auto &frenet_path = path_data.frenet_frame_path(); const auto &frenet_points = frenet_path.points(); if (frenet_points.empty()) { AERROR << "Path is empty."; return false; } const double half_width = common::VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; const double lateral_radius = half_width + FLAGS_lateral_ignore_buffer; const double lateral_stop_radius = half_width + FLAGS_static_decision_nudge_l_buffer; for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto &obstacle = *path_obstacle->obstacle(); bool is_bycycle_or_pedestrain = (obstacle.Perception().type() == perception::PerceptionObstacle::BICYCLE || obstacle.Perception().type() == perception::PerceptionObstacle::PEDESTRIAN); if (!is_bycycle_or_pedestrain && !obstacle.IsStatic()) { continue; } if (path_obstacle->HasLongitudinalDecision() && path_obstacle->LongitudinalDecision().has_ignore() && path_obstacle->HasLateralDecision() && path_obstacle->LateralDecision().has_ignore()) { continue; } if (path_obstacle->HasLongitudinalDecision() && path_obstacle->LongitudinalDecision().has_stop()) { // STOP decision continue; } if (path_obstacle->HasLateralDecision() && path_obstacle->LateralDecision().has_sidepass()) { // SIDE_PASS decision continue; } if (path_obstacle->reference_line_st_boundary().boundary_type() == StBoundary::BoundaryType::KEEP_CLEAR) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->PerceptionSLBoundary(); if (sl_boundary.end_s() < frenet_points.front().s() || sl_boundary.start_s() > frenet_points.back().s()) { path_decision->AddLongitudinalDecision("PathDecider/not-in-s", obstacle.Id(), object_decision); path_decision->AddLateralDecision("PathDecider/not-in-s", obstacle.Id(), object_decision); continue; } const auto frenet_point = frenet_path.GetNearestPoint(sl_boundary); const double curr_l = frenet_point.l(); if (curr_l - lateral_radius > sl_boundary.end_l() || curr_l + lateral_radius < sl_boundary.start_l()) { // ignore path_decision->AddLateralDecision("PathDecider/not-in-l", obstacle.Id(), object_decision); } else if (curr_l - lateral_stop_radius < sl_boundary.end_l() && curr_l + lateral_stop_radius > sl_boundary.start_l()) { // stop *object_decision.mutable_stop() = GenerateObjectStopDecision(*path_obstacle); if (path_decision->MergeWithMainStop( object_decision.stop(), obstacle.Id(), reference_line_info_->reference_line(), reference_line_info_->AdcSlBoundary())) { path_decision->AddLongitudinalDecision("PathDecider/nearest-stop", obstacle.Id(), object_decision); } else { ObjectDecisionType object_decision; object_decision.mutable_ignore(); path_decision->AddLongitudinalDecision("PathDecider/not-nearest-stop", obstacle.Id(), object_decision); } } else if (FLAGS_enable_nudge_decision) { // nudge if (curr_l - lateral_stop_radius > sl_boundary.end_l()) { // LEFT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); path_decision->AddLateralDecision("PathDecider/left-nudge", obstacle.Id(), object_decision); } else { // RIGHT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); path_decision->AddLateralDecision("PathDecider/right-nudge", obstacle.Id(), object_decision); } } } return true; } ObjectStop PathDecider::GenerateObjectStopDecision( const PathObstacle &path_obstacle) const { ObjectStop object_stop; double stop_distance = path_obstacle.MinRadiusStopDistance( VehicleConfigHelper::GetConfig().vehicle_param()); object_stop.set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); object_stop.set_distance_s(-stop_distance); const double stop_ref_s = path_obstacle.PerceptionSLBoundary().start_s() - stop_distance; const auto stop_ref_point = reference_line_info_->reference_line().GetReferencePoint(stop_ref_s); object_stop.mutable_stop_point()->set_x(stop_ref_point.x()); object_stop.mutable_stop_point()->set_y(stop_ref_point.y()); object_stop.set_stop_heading(stop_ref_point.heading()); return object_stop; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include "translator.h" #include "analyzer.h" #include "exception.h" #include "printer.h" #include "yaml.h" #include <QtCore/QDir> using namespace std; enum { _Base = GeneralCodes, CannotCreateOutputDir, CannotWriteToFile }; Translator::Translator(const QString& configFilePath, QString outputDirPath) : _outputDirPath(outputDirPath.endsWith('/') ? std::move(outputDirPath) : outputDirPath + '/') , _printer( [&]() { using namespace kainjow::mustache; Printer::context_type env; const auto configY = YamlMap::loadFromFile(configFilePath.toStdString()); for (const auto p: configY["env"].asMap()) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) env.set(pName, p.second.as<string>()); else { const auto pDefinition = *p.second.asMap().begin(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } } vector<string> outputFiles; for (const auto f: configY["templates"].asSequence()) outputFiles.emplace_back(f.as<string>()); QString configDir = QFileInfo(configFilePath).dir().path(); if (!configDir.isEmpty()) configDir += '/'; return Printer { std::move(env), outputFiles, configDir.toStdString(), _outputDirPath.toStdString(), configY["outFilesList"].as<string>("") }; }()) { // TODO: Load types translation table } TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, bool constRef) const { TypeUsage tu = swaggerType == "boolean" ? TypeUsage("bool") : swaggerType == "integer" ? swaggerFormat == "int64" ? TypeUsage("std::int64_t", "<cstdint>") : swaggerFormat == "int32" ? TypeUsage("std::int32_t", "<cstdint>") : TypeUsage("int") : swaggerType == "number" ? TypeUsage(swaggerFormat == "float" ? "float" : "double") : swaggerType == "string" ? (swaggerFormat == "byte" || swaggerFormat == "binary" ? TypeUsage("QByteArray", "<QtCore/QByteArray>") : swaggerFormat == "date" ? TypeUsage("QDate", "<QtCore/QDate>") : swaggerFormat == "date-time" ? TypeUsage("QDateTime", "<QtCore/QDateTime>") : TypeUsage("QString", "<QtCore/QString>")) : swaggerType == "array" ? TypeUsage("QJsonArray", "<QtCore/QJsonArray>") : swaggerType == "object" ? TypeUsage("QJsonObject", "<QtCore/QJsonObject>") : TypeUsage(""); if (tu.name.front() == 'Q' && constRef) tu.name = "const " + tu.name + '&'; return tu; } TypeUsage Translator::mapArrayType(const TypeUsage& innerType, bool constRef) const { TypeUsage tu = innerType.name == "QString" ? TypeUsage("QStringList", "<QtCore/QStringList>") : TypeUsage("QVector<" + innerType.name + ">", innerType.imports, "<QtCore/QVector>"); if (tu.name.front() == 'Q' && constRef) tu.name = "const " + tu.name + '&'; return tu; } Model Translator::processFile(string filePath, string baseDirPath) const { Model m = Analyzer(filePath, baseDirPath, *this).loadModel(); if (!m.callClasses.empty() || !m.types.empty()) { if (!m.fileDir.empty()) { QDir d { _outputDirPath + m.fileDir.c_str() }; if (!d.exists() && !d.mkpath(".")) fail(CannotCreateOutputDir, "Cannot create output directory"); } _printer.print(m); } return m; } <commit_msg>Check output directory more aggressively<commit_after>#include "translator.h" #include "analyzer.h" #include "exception.h" #include "printer.h" #include "yaml.h" #include <QtCore/QDir> using namespace std; enum { _Base = GeneralCodes, CannotCreateOutputDir, CannotWriteToFile }; Translator::Translator(const QString& configFilePath, QString outputDirPath) : _outputDirPath(outputDirPath.endsWith('/') ? std::move(outputDirPath) : outputDirPath + '/') , _printer( [&]() { using namespace kainjow::mustache; Printer::context_type env; const auto configY = YamlMap::loadFromFile(configFilePath.toStdString()); for (const auto p: configY["env"].asMap()) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) env.set(pName, p.second.as<string>()); else { const auto pDefinition = *p.second.asMap().begin(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } } vector<string> outputFiles; for (const auto f: configY["templates"].asSequence()) outputFiles.emplace_back(f.as<string>()); QString configDir = QFileInfo(configFilePath).dir().path(); if (!configDir.isEmpty()) configDir += '/'; return Printer { std::move(env), outputFiles, configDir.toStdString(), _outputDirPath.toStdString(), configY["outFilesList"].as<string>("") }; }()) { // TODO: Load types translation table } TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, bool constRef) const { TypeUsage tu = swaggerType == "boolean" ? TypeUsage("bool") : swaggerType == "integer" ? swaggerFormat == "int64" ? TypeUsage("std::int64_t", "<cstdint>") : swaggerFormat == "int32" ? TypeUsage("std::int32_t", "<cstdint>") : TypeUsage("int") : swaggerType == "number" ? TypeUsage(swaggerFormat == "float" ? "float" : "double") : swaggerType == "string" ? (swaggerFormat == "byte" || swaggerFormat == "binary" ? TypeUsage("QByteArray", "<QtCore/QByteArray>") : swaggerFormat == "date" ? TypeUsage("QDate", "<QtCore/QDate>") : swaggerFormat == "date-time" ? TypeUsage("QDateTime", "<QtCore/QDateTime>") : TypeUsage("QString", "<QtCore/QString>")) : swaggerType == "array" ? TypeUsage("QJsonArray", "<QtCore/QJsonArray>") : swaggerType == "object" ? TypeUsage("QJsonObject", "<QtCore/QJsonObject>") : TypeUsage(""); if (tu.name.front() == 'Q' && constRef) tu.name = "const " + tu.name + '&'; return tu; } TypeUsage Translator::mapArrayType(const TypeUsage& innerType, bool constRef) const { TypeUsage tu = innerType.name == "QString" ? TypeUsage("QStringList", "<QtCore/QStringList>") : TypeUsage("QVector<" + innerType.name + ">", innerType.imports, "<QtCore/QVector>"); if (tu.name.front() == 'Q' && constRef) tu.name = "const " + tu.name + '&'; return tu; } Model Translator::processFile(string filePath, string baseDirPath) const { Model m = Analyzer(filePath, baseDirPath, *this).loadModel(); if (!m.callClasses.empty() || !m.types.empty()) { QDir d { _outputDirPath + m.fileDir.c_str() }; if (!d.exists() && !d.mkpath(".")) fail(CannotCreateOutputDir, "Cannot create output directory"); _printer.print(m); } return m; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll_test.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/neural/recurrent_layer.hpp" #include "dll/neural/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" // Simple RNN TEST_CASE("unit/rnn/1", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 75; using network_t = dll::dyn_network_desc< dll::network_layers< dll::recurrent_layer<time_steps, sequence_length, hidden_units, dll::last_only>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 30) < 0.15); REQUIRE(net->evaluate_error(dataset.test()) < 0.25); } // Simple RNN with truncation TEST_CASE("unit/rnn/2", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 75; using network_t = dll::dyn_network_desc< dll::network_layers< dll::recurrent_layer<time_steps, sequence_length, hidden_units, dll::last_only, dll::truncate<20>>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 30) < 0.15); REQUIRE(net->evaluate_error(dataset.test()) < 0.25); } // Deep RNN TEST_CASE("unit/rnn/3", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 30; using network_t = dll::dyn_network_desc< dll::network_layers< dll::recurrent_layer<time_steps, sequence_length, hidden_units, dll::last_only>, dll::recurrent_layer<time_steps, hidden_units, hidden_units, dll::last_only>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 50) < 0.5); REQUIRE(net->evaluate_error(dataset.test()) < 0.5); } <commit_msg>Fix RNN test case<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll_test.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/neural/rnn_layer.hpp" #include "dll/neural/recurrent_last_layer.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" // Simple RNN TEST_CASE("unit/rnn/1", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 75; using network_t = dll::dyn_network_desc< dll::network_layers< dll::rnn_layer<time_steps, sequence_length, hidden_units, dll::last_only>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 30) < 0.15); REQUIRE(net->evaluate_error(dataset.test()) < 0.25); } // Simple RNN with truncation TEST_CASE("unit/rnn/2", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 75; using network_t = dll::dyn_network_desc< dll::network_layers< dll::rnn_layer<time_steps, sequence_length, hidden_units, dll::last_only, dll::truncate<20>>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 30) < 0.15); REQUIRE(net->evaluate_error(dataset.test()) < 0.25); } // Deep RNN TEST_CASE("unit/rnn/3", "[unit][rnn]") { auto dataset = dll::make_mnist_dataset_nc_sub(0, 2000, dll::batch_size<100>{}, dll::scale_pre<255>{}); constexpr size_t time_steps = 28; constexpr size_t sequence_length = 28; constexpr size_t hidden_units = 30; using network_t = dll::dyn_network_desc< dll::network_layers< dll::rnn_layer<time_steps, sequence_length, hidden_units, dll::last_only>, dll::rnn_layer<time_steps, hidden_units, hidden_units, dll::last_only>, dll::recurrent_last_layer<time_steps, hidden_units>, dll::dense_layer<hidden_units, 10, dll::softmax> > , dll::updater<dll::updater_type::ADAM> // Adam , dll::batch_size<100> // The mini-batch size >::network_t; auto net = std::make_unique<network_t>(); REQUIRE(net->fine_tune(dataset.train(), 50) < 0.5); REQUIRE(net->evaluate_error(dataset.test()) < 0.5); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <paddle/framework/net.h> #include <paddle/framework/op_registry.h> #include <paddle/framework/operator.h> namespace paddle { namespace framework { static int infer_shape_cnt = 0; static int run_cnt = 0; class TestOp : public OperatorBase { public: void InferShape(const ScopePtr& scope) const override { ++infer_shape_cnt; } void Run(const ScopePtr& scope, const platform::DeviceContext& dev_ctx) const override { ++run_cnt; } }; template <typename T> void AssertSameVectorWithoutOrder(const std::vector<T>& expected, const std::vector<T>& actual) { ASSERT_EQ(expected.size(), actual.size()); std::unordered_set<T> expected_set; for (auto& tmp : expected) { expected_set.insert(tmp); } for (auto& act : actual) { ASSERT_NE(expected_set.end(), expected_set.find(act)); } } class PlainNetTest : public testing::Test { virtual void SetUp() { net_ = std::make_shared<PlainNet>(); ASSERT_NE(net_, nullptr); auto op1 = std::make_shared<TestOp>(); op1->inputs_ = {"x", "w1", "b1"}; op1->outputs_ = {"y"}; net_->AddOp(op1); auto op2 = std::make_shared<TestOp>(); op2->inputs_ = {"y", "w2", "b2"}; op2->outputs_ = {"z"}; net_->AddOp(op2); net_->CompleteAddOp(); } virtual void TearDown() {} void TestOpKernel() { AssertSameVectorWithoutOrder({"x", "w1", "b1", "w2", "b2"}, net_->inputs_); AssertSameVectorWithoutOrder({"y", "z"}, net_->outputs_); auto tmp_idx_iter = net_->attrs_.find("temporary_index"); ASSERT_NE(net_->attrs_.end(), tmp_idx_iter); auto& tmp_idx = boost::get<std::vector<int>>(tmp_idx_iter->second); ASSERT_EQ(1UL, tmp_idx.size()); ASSERT_EQ("y", net_->outputs_[tmp_idx[0]]); auto scope = std::make_shared<Scope>(); platform::CPUDeviceContext dev_ctx; net_->InferShape(scope); net_->Run(scope, dev_ctx); ASSERT_EQ(2, infer_shape_cnt); ASSERT_EQ(2, run_cnt); ASSERT_THROW(net_->AddOp(op2), EnforceNotMet); } void TestAddBackwardOp() { auto grad_ops = AddBackwardOp(net_); for (auto& op : grad_ops->ops_) { op->DebugString(); } } private: std::shared_ptr<PlainNet> net_; }; TEST(OpKernel, all) { PlainNetTest net; net->TestOpKernel(); } TEST(AddBackwardOp, TestAddBackwardOp) { PlainNetTest net; net->TestAddBackwardOp(); } } // namespace framework } // namespace paddle <commit_msg>"add net op testing"<commit_after>#include <gtest/gtest.h> #include <paddle/framework/net.h> #include <paddle/framework/op_registry.h> #include <paddle/framework/operator.h> namespace paddle { namespace framework { static int infer_shape_cnt = 0; static int run_cnt = 0; class TestOp : public OperatorBase { public: void InferShape(const ScopePtr& scope) const override { ++infer_shape_cnt; } void Run(const ScopePtr& scope, const platform::DeviceContext& dev_ctx) const override { ++run_cnt; } }; template <typename T> void AssertSameVectorWithoutOrder(const std::vector<T>& expected, const std::vector<T>& actual) { ASSERT_EQ(expected.size(), actual.size()); std::unordered_set<T> expected_set; for (auto& tmp : expected) { expected_set.insert(tmp); } for (auto& act : actual) { ASSERT_NE(expected_set.end(), expected_set.find(act)); } } class PlainNetTest : public testing::Test { public: virtual void SetUp() { net_ = std::make_shared<PlainNet>(); ASSERT_NE(net_, nullptr); auto op1 = std::make_shared<TestOp>(); op1->inputs_ = {"x", "w1", "b1"}; op1->outputs_ = {"y"}; net_->AddOp(op1); auto op2 = std::make_shared<TestOp>(); op2->inputs_ = {"y", "w2", "b2"}; op2->outputs_ = {"z"}; net_->AddOp(op2); net_->CompleteAddOp(); } virtual void TearDown() {} virtual void TestBody() {} void TestOpKernel() { AssertSameVectorWithoutOrder({"x", "w1", "b1", "w2", "b2"}, net_->inputs_); AssertSameVectorWithoutOrder({"y", "z"}, net_->outputs_); auto tmp_idx_iter = net_->attrs_.find("temporary_index"); ASSERT_NE(net_->attrs_.end(), tmp_idx_iter); auto& tmp_idx = boost::get<std::vector<int>>(tmp_idx_iter->second); ASSERT_EQ(1UL, tmp_idx.size()); ASSERT_EQ("y", net_->outputs_[tmp_idx[0]]); auto scope = std::make_shared<Scope>(); platform::CPUDeviceContext dev_ctx; net_->InferShape(scope); net_->Run(scope, dev_ctx); ASSERT_EQ(2, infer_shape_cnt); ASSERT_EQ(2, run_cnt); auto op2 = std::make_shared<TestOp>(); ASSERT_THROW(net_->AddOp(op2), EnforceNotMet); } void TestAddBackwardOp() { auto grad_ops = AddBackwardOp(net_); for (auto& op : grad_ops->ops_) { op->DebugString(); } } private: std::shared_ptr<PlainNet> net_; }; TEST(OpKernel, all) { PlainNetTest net; net.TestOpKernel(); } TEST(AddBackwardOp, TestAddBackwardOp) { PlainNetTest net; net.TestAddBackwardOp(); } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/math/im2col.h" namespace paddle { namespace operators { namespace math { /* * im = [input_channels, input_height, input_width] * col = * [input_channels, filter_height, filter_width, output_height, output_width] */ template <class T> class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& im, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* col) { PADDLE_ENFORCE(im.dims().size() == 3); PADDLE_ENFORCE(col->dims().size() == 5); int im_channels = im.dims()[0]; int im_height = im.dims()[1]; int im_width = im.dims()[2]; int filter_height = col->dims()[1]; int filter_width = col->dims()[2]; int col_height = col->dims()[3]; int col_width = col->dims()[4]; PADDLE_ENFORCE_EQ((im_height + padding[0] + padding[2] - ((dilation[0] * (filter_height - 1) + 1))) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ((im_width + padding[1] + padding[3] - ((dilation[1] * (filter_width - 1) + 1))) / stride[1] + 1, col_width, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); int channels_col = im_channels * filter_height * filter_width; const T* im_data = im.data<T>(); T* col_data = col->data<T>(); int w_offset = -1; int h_offset = 0; int c_im = 0; for (int c = 0; c < channels_col; ++c) { ++w_offset; if (w_offset == filter_width) { w_offset = 0; ++h_offset; if (h_offset == filter_height) { h_offset = 0; ++c_im; } } for (int h = 0; h < col_height; ++h) { int im_row_idx = h * stride[0] - padding[0] + h_offset * dilation[0]; for (int w = 0; w < col_width; ++w) { int im_col_idx = w * stride[1] - padding[1] + w_offset * dilation[1]; int col_idx = (c * col_height + h) * col_width + w; int im_idx = (im_row_idx + c_im * im_height) * im_width + im_col_idx; col_data[col_idx] = (im_row_idx < 0 || im_row_idx >= im_height || im_col_idx < 0 || im_col_idx >= im_width) ? static_cast<T>(0) : im_data[im_idx]; } } } } }; /* * im = [input_channels, input_height, input_width] * col = * [input_channels, filter_height, filter_width, output_height, output_width] */ template <class T> class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& col, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* im) { PADDLE_ENFORCE(im->dims().size() == 3); PADDLE_ENFORCE(col.dims().size() == 5); int im_channels = im->dims()[0]; int im_height = im->dims()[1]; int im_width = im->dims()[2]; int filter_height = col.dims()[1]; int filter_width = col.dims()[2]; int col_height = col.dims()[3]; int col_width = col.dims()[4]; PADDLE_ENFORCE_EQ((im_height + padding[0] + padding[2] - ((dilation[0] * (filter_height - 1) + 1))) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ((im_width + padding[1] + padding[3] - ((dilation[1] * (filter_width - 1) + 1))) / stride[1] + 1, col_width, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); int channels_col = im_channels * filter_height * filter_width; T* im_data = im->data<T>(); const T* col_data = col.data<T>(); int w_offset = -1; int h_offset = 0; int c_im = 0; for (int c = 0; c < channels_col; ++c) { ++w_offset; if (w_offset == filter_width) { w_offset = 0; ++h_offset; if (h_offset == filter_height) { h_offset = 0; ++c_im; } } for (int h = 0; h < col_height; ++h) { int im_row_idx = h * stride[0] - padding[0] + h_offset * dilation[0]; for (int w = 0; w < col_width; ++w) { int im_col_idx = w * stride[1] - padding[1] + w_offset * dilation[1]; if ((im_row_idx) >= 0 && (im_row_idx) < im_height && (im_col_idx) >= 0 && (im_col_idx) < im_width) { im_data[(im_row_idx + c_im * im_height) * im_width + im_col_idx] += col_data[(c * col_height + h) * col_width + w]; } } } } } }; template class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, float>; template class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, double>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, float>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, double>; /* * im = [input_channels, input_height, input_width] * col = * [output_height, output_width, input_channels, filter_height, filter_width] */ template <class T> class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& im, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* col) { PADDLE_ENFORCE(im.dims().size() == 3); PADDLE_ENFORCE(col->dims().size() == 5); int im_channels = im.dims()[0]; int im_height = im.dims()[1]; int im_width = im.dims()[2]; int filter_height = col->dims()[3]; int filter_width = col->dims()[4]; int col_height = col->dims()[0]; int col_width = col->dims()[1]; PADDLE_ENFORCE_EQ( (im_height + padding[0] + padding[2] - filter_height) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ( (im_width + padding[1] + padding[3] - filter_width) / stride[1] + 1, col_width, "col_width and padding(padding_left, padding_right) are " "inconsistent."); const T* im_data = im.data<T>(); T* col_data = col->data<T>(); for (int col_row_idx = 0; col_row_idx < col_height; ++col_row_idx) { for (int col_col_idx = 0; col_col_idx < col_width; ++col_col_idx) { for (int channel = 0; channel < im_channels; ++channel) { for (int filter_row_idx = 0; filter_row_idx < filter_height; ++filter_row_idx) { int im_row_offset = col_row_idx * stride[0] + filter_row_idx - padding[0]; for (int filter_col_idx = 0; filter_col_idx < filter_width; ++filter_col_idx) { int im_col_offset = col_col_idx * stride[1] + filter_col_idx - padding[1]; int col_offset = ((((col_row_idx)*col_width + col_col_idx) * im_channels + channel) * filter_height + filter_row_idx) * filter_width + filter_col_idx; int im_offset = (channel * im_height + im_row_offset) * im_width + im_col_offset; col_data[col_offset] = (im_row_offset < 0 || im_row_offset >= im_height || im_col_offset < 0 || im_col_offset >= im_width) ? static_cast<T>(0) : im_data[im_offset]; } } } } } } }; /* * im = [input_channels, input_height, input_width] * col = * [output_height, output_width, input_channels, filter_height, filter_width] */ template <class T> class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& col, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* im) { PADDLE_ENFORCE(im->dims().size() == 3); PADDLE_ENFORCE(col.dims().size() == 5); int im_channels = im->dims()[0]; int im_height = im->dims()[1]; int im_width = im->dims()[2]; int filter_height = col.dims()[3]; int filter_width = col.dims()[4]; int col_height = col.dims()[0]; int col_width = col.dims()[1]; PADDLE_ENFORCE_EQ( (im_height + padding[0] + padding[2] - filter_height) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ( (im_width + padding[1] + padding[3] - filter_width) / stride[1] + 1, col_width, "col_width and padding(padding_left, padding_right) are " "inconsistent."); T* im_data = im->data<T>(); const T* col_data = col.data<T>(); for (int col_row_idx = 0; col_row_idx < col_height; ++col_row_idx) { for (int col_col_idx = 0; col_col_idx < col_width; ++col_col_idx) { for (int channel = 0; channel < im_channels; ++channel) { for (int filter_row_idx = 0; filter_row_idx < filter_height; ++filter_row_idx) { int im_row_offset = col_row_idx * stride[0] + filter_row_idx - padding[0]; for (int filter_col_idx = 0; filter_col_idx < filter_width; ++filter_col_idx) { int im_col_offset = col_col_idx * stride[1] + filter_col_idx - padding[1]; int col_offset = (((col_row_idx * col_width + col_col_idx) * im_channels + channel) * filter_height + filter_row_idx) * filter_width + filter_col_idx; if (im_row_offset >= 0 && im_row_offset < im_height && im_col_offset >= 0 && im_col_offset < im_width) { int im_offset = (channel * im_height + im_row_offset) * im_width + im_col_offset; im_data[im_offset] += col_data[col_offset]; } } } } } } } }; template class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, float>; template class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, double>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, float>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, double>; } // namespace math } // namespace operators } // namespace paddle <commit_msg>refine im2col<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/operators/math/im2col.h" namespace paddle { namespace operators { namespace math { /* * im = [input_channels, input_height, input_width] * col = * [input_channels, filter_height, filter_width, output_height, output_width] */ template <class T> class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& im, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* col) { PADDLE_ENFORCE(im.dims().size() == 3); PADDLE_ENFORCE(col->dims().size() == 5); int im_channels = im.dims()[0]; int im_height = im.dims()[1]; int im_width = im.dims()[2]; int filter_height = col->dims()[1]; int filter_width = col->dims()[2]; int col_height = col->dims()[3]; int col_width = col->dims()[4]; PADDLE_ENFORCE_EQ((im_height + padding[0] + padding[2] - ((dilation[0] * (filter_height - 1) + 1))) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ((im_width + padding[1] + padding[3] - ((dilation[1] * (filter_width - 1) + 1))) / stride[1] + 1, col_width, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); int channels_col = im_channels * filter_height * filter_width; const T* im_data = im.data<T>(); T* col_data = col->data<T>(); for (int c = 0; c < channels_col; ++c) { int w_offset = c % filter_width; int h_offset = (c / filter_width) % filter_height; int c_im = c / (filter_width * filter_height); for (int h = 0; h < col_height; ++h) { int im_row_idx = h * stride[0] - padding[0] + h_offset * dilation[0]; for (int w = 0; w < col_width; ++w) { int im_col_idx = w * stride[1] - padding[1] + w_offset * dilation[1]; int col_idx = (c * col_height + h) * col_width + w; int im_idx = (im_row_idx + c_im * im_height) * im_width + im_col_idx; col_data[col_idx] = (im_row_idx < 0 || im_row_idx >= im_height || im_col_idx < 0 || im_col_idx >= im_width) ? static_cast<T>(0) : im_data[im_idx]; } } } } }; /* * im = [input_channels, input_height, input_width] * col = * [input_channels, filter_height, filter_width, output_height, output_width] */ template <class T> class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& col, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* im) { PADDLE_ENFORCE(im->dims().size() == 3); PADDLE_ENFORCE(col.dims().size() == 5); int im_channels = im->dims()[0]; int im_height = im->dims()[1]; int im_width = im->dims()[2]; int filter_height = col.dims()[1]; int filter_width = col.dims()[2]; int col_height = col.dims()[3]; int col_width = col.dims()[4]; PADDLE_ENFORCE_EQ((im_height + padding[0] + padding[2] - ((dilation[0] * (filter_height - 1) + 1))) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ((im_width + padding[1] + padding[3] - ((dilation[1] * (filter_width - 1) + 1))) / stride[1] + 1, col_width, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); int channels_col = im_channels * filter_height * filter_width; T* im_data = im->data<T>(); const T* col_data = col.data<T>(); int w_offset = -1; int h_offset = 0; int c_im = 0; for (int c = 0; c < channels_col; ++c) { ++w_offset; if (w_offset == filter_width) { w_offset = 0; ++h_offset; if (h_offset == filter_height) { h_offset = 0; ++c_im; } } for (int h = 0; h < col_height; ++h) { int im_row_idx = h * stride[0] - padding[0] + h_offset * dilation[0]; for (int w = 0; w < col_width; ++w) { int im_col_idx = w * stride[1] - padding[1] + w_offset * dilation[1]; if ((im_row_idx) >= 0 && (im_row_idx) < im_height && (im_col_idx) >= 0 && (im_col_idx) < im_width) { im_data[(im_row_idx + c_im * im_height) * im_width + im_col_idx] += col_data[(c * col_height + h) * col_width + w]; } } } } } }; template class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, float>; template class Im2ColFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, double>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, float>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kCFO, platform::CPUDeviceContext, double>; /* * im = [input_channels, input_height, input_width] * col = * [output_height, output_width, input_channels, filter_height, filter_width] */ template <class T> class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& im, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* col) { PADDLE_ENFORCE(im.dims().size() == 3); PADDLE_ENFORCE(col->dims().size() == 5); int im_channels = im.dims()[0]; int im_height = im.dims()[1]; int im_width = im.dims()[2]; int filter_height = col->dims()[3]; int filter_width = col->dims()[4]; int col_height = col->dims()[0]; int col_width = col->dims()[1]; PADDLE_ENFORCE_EQ( (im_height + padding[0] + padding[2] - filter_height) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ( (im_width + padding[1] + padding[3] - filter_width) / stride[1] + 1, col_width, "col_width and padding(padding_left, padding_right) are " "inconsistent."); const T* im_data = im.data<T>(); T* col_data = col->data<T>(); for (int col_row_idx = 0; col_row_idx < col_height; ++col_row_idx) { for (int col_col_idx = 0; col_col_idx < col_width; ++col_col_idx) { for (int channel = 0; channel < im_channels; ++channel) { for (int filter_row_idx = 0; filter_row_idx < filter_height; ++filter_row_idx) { int im_row_offset = col_row_idx * stride[0] + filter_row_idx - padding[0]; for (int filter_col_idx = 0; filter_col_idx < filter_width; ++filter_col_idx) { int im_col_offset = col_col_idx * stride[1] + filter_col_idx - padding[1]; int col_offset = ((((col_row_idx)*col_width + col_col_idx) * im_channels + channel) * filter_height + filter_row_idx) * filter_width + filter_col_idx; int im_offset = (channel * im_height + im_row_offset) * im_width + im_col_offset; col_data[col_offset] = (im_row_offset < 0 || im_row_offset >= im_height || im_col_offset < 0 || im_col_offset >= im_width) ? static_cast<T>(0) : im_data[im_offset]; } } } } } } }; /* * im = [input_channels, input_height, input_width] * col = * [output_height, output_width, input_channels, filter_height, filter_width] */ template <class T> class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, T> { public: void operator()(const platform::CPUDeviceContext& context, const framework::Tensor& col, const std::vector<int>& dilation, const std::vector<int>& stride, const std::vector<int>& padding, framework::Tensor* im) { PADDLE_ENFORCE(im->dims().size() == 3); PADDLE_ENFORCE(col.dims().size() == 5); int im_channels = im->dims()[0]; int im_height = im->dims()[1]; int im_width = im->dims()[2]; int filter_height = col.dims()[3]; int filter_width = col.dims()[4]; int col_height = col.dims()[0]; int col_width = col.dims()[1]; PADDLE_ENFORCE_EQ( (im_height + padding[0] + padding[2] - filter_height) / stride[0] + 1, col_height, "Output_height and padding(padding_up, padding_down) are " "inconsistent."); PADDLE_ENFORCE_EQ( (im_width + padding[1] + padding[3] - filter_width) / stride[1] + 1, col_width, "col_width and padding(padding_left, padding_right) are " "inconsistent."); T* im_data = im->data<T>(); const T* col_data = col.data<T>(); for (int col_row_idx = 0; col_row_idx < col_height; ++col_row_idx) { for (int col_col_idx = 0; col_col_idx < col_width; ++col_col_idx) { for (int channel = 0; channel < im_channels; ++channel) { for (int filter_row_idx = 0; filter_row_idx < filter_height; ++filter_row_idx) { int im_row_offset = col_row_idx * stride[0] + filter_row_idx - padding[0]; for (int filter_col_idx = 0; filter_col_idx < filter_width; ++filter_col_idx) { int im_col_offset = col_col_idx * stride[1] + filter_col_idx - padding[1]; int col_offset = (((col_row_idx * col_width + col_col_idx) * im_channels + channel) * filter_height + filter_row_idx) * filter_width + filter_col_idx; if (im_row_offset >= 0 && im_row_offset < im_height && im_col_offset >= 0 && im_col_offset < im_width) { int im_offset = (channel * im_height + im_row_offset) * im_width + im_col_offset; im_data[im_offset] += col_data[col_offset]; } } } } } } } }; template class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, float>; template class Im2ColFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, double>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, float>; template class Col2ImFunctor<paddle::operators::math::ColFormat::kOCF, platform::CPUDeviceContext, double>; } // namespace math } // namespace operators } // namespace paddle <|endoftext|>
<commit_before> #include "cmdline/cmdline.h" #include "mhap/overlap.h" #include "mhap/parser.h" #include "ra/include/ra/ra.hpp" #include <algorithm> #include <ctime> #include <fstream> #include <iostream> #include <vector> #include <sys/stat.h> // trimming params int READ_LEN_THRESHOLD = 100000; uint32_t MAX_READS_IN_TIP = 2; uint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5; // BFS params in bubble popping size_t MAX_NODES = 2000; int MAX_DISTANCE = MAX_NODES * 10000; double MAX_DIFFERENCE = 0.25; // contig extraction params size_t MAX_BRANCHES = 18; size_t MAX_START_NODES = 100; double LENGTH_THRESHOLD = 0.2; double QUALITY_THRESHOLD = 0.2; using std::cerr; using std::cin; using std::cout; using std::endl; using std::fstream; using std::max; using std::string; using std::vector; // map reads so we can access reads with mapped[read_id] void map_reads(vector<Read*>* mapped, vector<Read*>& reads) { int max_id = -1; for (auto r: reads) { max_id = max(max_id, r->getId()); } mapped->resize(max_id + 1, nullptr); for (auto r: reads) { (*mapped)[r->getId()] = r; } } string output_dir_name() { time_t rawtime; struct tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo); return string(buffer); } void must_mkdir(const string& path) { if (mkdir(path.c_str(), 0755) == -1) { fprintf(stderr, "Can't create directory %s\n", path.c_str()); exit(1); } } void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) { for (uint32_t i = 0; i < contigs.size(); ++i) { const auto& contig = contigs[i]; const auto& parts = contig->getParts(); const auto& last_part = contig->getParts().back(); fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n", i, last_part.offset + reads[last_part.src]->getLength(), parts.size() ); for (const auto& p: parts) { fprintf(stdout, "%d ", p.src); } fprintf(stdout, "\n"); } } int main(int argc, char **argv) { cmdline::parser args; // input params args.add<string>("reads", 'r', "reads file", true); args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta"); args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0); args.add<string>("overlaps", 'x', "overlaps file", true); args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg"); args.add<bool>("verbose", 'v', "verbose output", false); // bubble popping params args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750); args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25); args.parse_check(argc, argv); const int thread_num = std::max(std::thread::hardware_concurrency(), 1U); const string reads_filename = args.get<string>("reads"); const string reads_format = args.get<string>("reads_format"); const string overlaps_filename = args.get<string>("overlaps"); const string overlaps_format = args.get<string>("overlaps_format"); const bool verbose_output = args.get<bool>("verbose"); const int reads_id_offset = args.get<int>("reads_id_offset"); const string output_dir = output_dir_name(); MAX_NODES = args.get<int>("bp_max_nodes"); MAX_DISTANCE = MAX_NODES * 10000; MAX_DIFFERENCE = args.get<double>("bp_max_diff"); vector<Overlap*> overlaps, filtered; vector<Read*> reads; vector<Read*> reads_mapped; must_mkdir(output_dir); std::cerr << "Output dir: " << output_dir << std::endl; if (reads_format == "fasta") { readFastaReads(reads, reads_filename.c_str()); } else if (reads_format == "fastq") { readFastqReads(reads, reads_filename.c_str()); } else if (reads_format == "afg") { readAfgReads(reads, reads_filename.c_str()); } else { assert(false); } // map reads so we have reads_mapped[read_id] -> read map_reads(&reads_mapped, reads); std::cerr << "Read " << reads.size() << " reads" << std::endl; if (overlaps_format == "afg") { readAfgOverlaps(overlaps, overlaps_filename.c_str()); } else if (overlaps_format == "mhap") { fstream overlaps_file(overlaps_filename); MHAP::read_overlaps(overlaps_file, &overlaps); overlaps_file.close(); } else { assert(false); } // fix overlap read ids for (auto o: overlaps) { o->setA(o->getA() - reads_id_offset); o->setB(o->getB() - reads_id_offset); } for (auto o: overlaps) { const auto a = o->getA(); const auto b = o->getB(); if (reads_mapped[a] == nullptr) { cerr << "Read " << a << " not found" << endl; exit(1); } if (reads_mapped[b] == nullptr) { cerr << "Read " << b << " not found" << endl; exit(1); } o->setReadA(reads_mapped[a]); o->setReadB(reads_mapped[b]); } cerr << overlaps.size() << " overlaps read" << endl; int skipped = 0; for (uint32_t i = 0; i < overlaps.size(); ++i) { const auto o = overlaps[i]; if (o->getReadA()->getLength() < 3000 || o->getReadB()->getLength() < 3000) { skipped++; continue; } overlaps[i - skipped] = overlaps[i]; } overlaps.resize(overlaps.size() - skipped); vector<Overlap*> nocontainments; filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true); if (verbose_output) { writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str()); } vector<Overlap*> notransitives; filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true); if (verbose_output) { writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str()); } createReverseComplements(reads, thread_num); StringGraph* graph = new StringGraph(reads, notransitives); graph->simplify(); if (verbose_output) { vector<Overlap*> simplified_overlaps; graph->extractOverlaps(simplified_overlaps); writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str()); } std::vector<StringGraphComponent*> components; graph->extractComponents(components); std::vector<Contig*> contigs; auto contigs_fast = fopen((output_dir + "/contigs_fast.fasta").c_str(), "w"); int idx = 0; for (const auto& component : components) { string seq; component->extractSequence(seq); fprintf(contigs_fast, ">seq%d\n", idx); fprintf(contigs_fast, "%s\n", seq.c_str()); idx++; ContigExtractor* extractor = new ContigExtractor(component); const auto& contig = extractor->extractContig(); if (contig == nullptr) { continue; } contigs.emplace_back(contig); } fclose(contigs_fast); std::cerr << "number of contigs " << contigs.size() << std::endl; print_contigs_info(contigs, reads_mapped); writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str()); for (auto r: reads) delete r; for (auto o: overlaps) delete o; for (auto c: components) delete c; for (auto c: contigs) delete c; delete graph; return 0; } <commit_msg>introduce READ_MIN_LENGTH constant<commit_after> #include "cmdline/cmdline.h" #include "mhap/overlap.h" #include "mhap/parser.h" #include "ra/include/ra/ra.hpp" #include <algorithm> #include <ctime> #include <fstream> #include <iostream> #include <vector> #include <sys/stat.h> // trimming params int READ_LEN_THRESHOLD = 100000; uint32_t MAX_READS_IN_TIP = 2; uint32_t MAX_DEPTH_WITHOUT_EXTRA_FORK = 5; // BFS params in bubble popping size_t MAX_NODES = 2000; int MAX_DISTANCE = MAX_NODES * 10000; double MAX_DIFFERENCE = 0.25; // contig extraction params size_t MAX_BRANCHES = 18; size_t MAX_START_NODES = 100; double LENGTH_THRESHOLD = 0.2; double QUALITY_THRESHOLD = 0.2; // filter reads param size_t READS_MIN_LEN = 3000; using std::cerr; using std::cin; using std::cout; using std::endl; using std::fstream; using std::max; using std::string; using std::vector; // map reads so we can access reads with mapped[read_id] void map_reads(vector<Read*>* mapped, vector<Read*>& reads) { int max_id = -1; for (auto r: reads) { max_id = max(max_id, r->getId()); } mapped->resize(max_id + 1, nullptr); for (auto r: reads) { (*mapped)[r->getId()] = r; } } string output_dir_name() { time_t rawtime; struct tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "layout_%Y%m%d_%H%M%S", timeinfo); return string(buffer); } void must_mkdir(const string& path) { if (mkdir(path.c_str(), 0755) == -1) { fprintf(stderr, "Can't create directory %s\n", path.c_str()); exit(1); } } void print_contigs_info(const vector<Contig *>& contigs, const vector<Read*>& reads) { for (uint32_t i = 0; i < contigs.size(); ++i) { const auto& contig = contigs[i]; const auto& parts = contig->getParts(); const auto& last_part = contig->getParts().back(); fprintf(stdout, "contig %u; length: ≈%lu, reads: %lu\n", i, last_part.offset + reads[last_part.src]->getLength(), parts.size() ); for (const auto& p: parts) { fprintf(stdout, "%d ", p.src); } fprintf(stdout, "\n"); } } int main(int argc, char **argv) { cmdline::parser args; // input params args.add<string>("reads", 'r', "reads file", true); args.add<string>("reads_format", 's', "reads format; supported: fasta, fastq, afg", false, "fasta"); args.add<int>("reads_id_offset", 'a', "reads id offset (first read id)", false, 0); args.add<string>("overlaps", 'x', "overlaps file", true); args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg"); args.add<bool>("verbose", 'v', "verbose output", false); // bubble popping params args.add<int>("bp_max_nodes", 'm', "max nodes in bubble branch", false, 750); args.add<double>("bp_max_diff", 'n', "max difference between bubble branches", false, 0.25); args.parse_check(argc, argv); const int thread_num = std::max(std::thread::hardware_concurrency(), 1U); const string reads_filename = args.get<string>("reads"); const string reads_format = args.get<string>("reads_format"); const string overlaps_filename = args.get<string>("overlaps"); const string overlaps_format = args.get<string>("overlaps_format"); const bool verbose_output = args.get<bool>("verbose"); const int reads_id_offset = args.get<int>("reads_id_offset"); const string output_dir = output_dir_name(); MAX_NODES = args.get<int>("bp_max_nodes"); MAX_DISTANCE = MAX_NODES * 10000; MAX_DIFFERENCE = args.get<double>("bp_max_diff"); vector<Overlap*> overlaps, filtered; vector<Read*> reads; vector<Read*> reads_mapped; must_mkdir(output_dir); std::cerr << "Output dir: " << output_dir << std::endl; if (reads_format == "fasta") { readFastaReads(reads, reads_filename.c_str()); } else if (reads_format == "fastq") { readFastqReads(reads, reads_filename.c_str()); } else if (reads_format == "afg") { readAfgReads(reads, reads_filename.c_str()); } else { assert(false); } // map reads so we have reads_mapped[read_id] -> read map_reads(&reads_mapped, reads); std::cerr << "Read " << reads.size() << " reads" << std::endl; if (overlaps_format == "afg") { readAfgOverlaps(overlaps, overlaps_filename.c_str()); } else if (overlaps_format == "mhap") { fstream overlaps_file(overlaps_filename); MHAP::read_overlaps(overlaps_file, &overlaps); overlaps_file.close(); } else { assert(false); } // fix overlap read ids for (auto o: overlaps) { o->setA(o->getA() - reads_id_offset); o->setB(o->getB() - reads_id_offset); } for (auto o: overlaps) { const auto a = o->getA(); const auto b = o->getB(); if (reads_mapped[a] == nullptr) { cerr << "Read " << a << " not found" << endl; exit(1); } if (reads_mapped[b] == nullptr) { cerr << "Read " << b << " not found" << endl; exit(1); } o->setReadA(reads_mapped[a]); o->setReadB(reads_mapped[b]); } cerr << overlaps.size() << " overlaps read" << endl; int skipped = 0; for (uint32_t i = 0; i < overlaps.size(); ++i) { const auto o = overlaps[i]; if (o->getReadA()->getLength() < READS_MIN_LEN || o->getReadB()->getLength() < READS_MIN_LEN) { skipped++; continue; } overlaps[i - skipped] = overlaps[i]; } overlaps.resize(overlaps.size() - skipped); vector<Overlap*> nocontainments; filterContainedOverlaps(nocontainments, overlaps, reads_mapped, true); if (verbose_output) { writeOverlaps(nocontainments, (output_dir + "/nocont.afg").c_str()); } vector<Overlap*> notransitives; filterTransitiveOverlaps(notransitives, nocontainments, thread_num, true); if (verbose_output) { writeOverlaps(notransitives, (output_dir + "/nocont.notran.afg").c_str()); } createReverseComplements(reads, thread_num); StringGraph* graph = new StringGraph(reads, notransitives); graph->simplify(); if (verbose_output) { vector<Overlap*> simplified_overlaps; graph->extractOverlaps(simplified_overlaps); writeOverlaps(simplified_overlaps, (output_dir + "/simplified.afg").c_str()); } std::vector<StringGraphComponent*> components; graph->extractComponents(components); std::vector<Contig*> contigs; auto contigs_fast = fopen((output_dir + "/contigs_fast.fasta").c_str(), "w"); int idx = 0; for (const auto& component : components) { string seq; component->extractSequence(seq); fprintf(contigs_fast, ">seq%d\n", idx); fprintf(contigs_fast, "%s\n", seq.c_str()); idx++; ContigExtractor* extractor = new ContigExtractor(component); const auto& contig = extractor->extractContig(); if (contig == nullptr) { continue; } contigs.emplace_back(contig); } fclose(contigs_fast); std::cerr << "number of contigs " << contigs.size() << std::endl; print_contigs_info(contigs, reads_mapped); writeAfgContigs(contigs, (output_dir + "/contigs.afg").c_str()); for (auto r: reads) delete r; for (auto o: overlaps) delete o; for (auto c: components) delete c; for (auto c: contigs) delete c; delete graph; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: anydata.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: jb $ $Date: 2002-02-11 14:29:07 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef INCLUDED_SHARABLE_ANYDATA_HXX #define INCLUDED_SHARABLE_ANYDATA_HXX #ifndef INCLUDED_SHARABLE_BASETYPES_HXX #include "types.hxx" #endif //----------------------------------------------------------------------------- namespace com { namespace sun { namespace star { namespace uno { class Any; class Type; } } } } //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace memory { class Allocator; class Accessor; } //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- //typedef Address AnyData; // data that fits is stored inline union AnyData { typedef Byte TypeCode; Address data; sal_Bool boolValue; sal_Int16 shortValue; sal_Int32 intValue; Address longValue; // points to sal_Int64 Address doubleValue; // points to double (IEEE 8-bit) ... // float floatValue; // ... or should we use float (IEEE 4-bit) ? Vector binaryValue; // points to counted sal_(u)Int8 [] String stringValue; // points to counted sal_Unicode [] Vector sequenceValue; // points to counted AnyData [] (or SomeType [] ?) }; //----------------------------------------------------------------------------- AnyData::TypeCode getTypeCode(::com::sun::star::uno::Type const & _aType); ::com::sun::star::uno::Type getUnoType( AnyData::TypeCode _aType); AnyData allocData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, ::com::sun::star::uno::Any const & _aAny); // AnyData copyData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, AnyData _aData); void freeData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, AnyData _aData); ::com::sun::star::uno::Any readData(memory::Accessor const& _anAccessor, AnyData::TypeCode _aType, AnyData _aData); //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_SHARABLE_ANYDATA_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.224); FILE MERGED 2005/09/05 17:04:18 rt 1.1.224.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: anydata.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:41:13 $ * * 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 INCLUDED_SHARABLE_ANYDATA_HXX #define INCLUDED_SHARABLE_ANYDATA_HXX #ifndef INCLUDED_SHARABLE_BASETYPES_HXX #include "types.hxx" #endif //----------------------------------------------------------------------------- namespace com { namespace sun { namespace star { namespace uno { class Any; class Type; } } } } //----------------------------------------------------------------------------- namespace configmgr { //----------------------------------------------------------------------------- namespace memory { class Allocator; class Accessor; } //----------------------------------------------------------------------------- namespace sharable { //----------------------------------------------------------------------------- //typedef Address AnyData; // data that fits is stored inline union AnyData { typedef Byte TypeCode; Address data; sal_Bool boolValue; sal_Int16 shortValue; sal_Int32 intValue; Address longValue; // points to sal_Int64 Address doubleValue; // points to double (IEEE 8-bit) ... // float floatValue; // ... or should we use float (IEEE 4-bit) ? Vector binaryValue; // points to counted sal_(u)Int8 [] String stringValue; // points to counted sal_Unicode [] Vector sequenceValue; // points to counted AnyData [] (or SomeType [] ?) }; //----------------------------------------------------------------------------- AnyData::TypeCode getTypeCode(::com::sun::star::uno::Type const & _aType); ::com::sun::star::uno::Type getUnoType( AnyData::TypeCode _aType); AnyData allocData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, ::com::sun::star::uno::Any const & _aAny); // AnyData copyData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, AnyData _aData); void freeData(memory::Allocator const& _anAllocator, AnyData::TypeCode _aType, AnyData _aData); ::com::sun::star::uno::Any readData(memory::Accessor const& _anAccessor, AnyData::TypeCode _aType, AnyData _aData); //----------------------------------------------------------------------------- } //----------------------------------------------------------------------------- } #endif // INCLUDED_SHARABLE_ANYDATA_HXX <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; } } for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); } return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; } } for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } return 0; } <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" #include "StarControl.h" #include "RayControl.h" #include "CameraBase.h" #include "ActorBase.h" #include "sys/SysControl.h" #include "FileSystem.h" #include "RenderManager.h" #include "Texture.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); vec3 x = m_pCameraBase->GetModelview().getRow3(0); vec3 y = m_pCameraBase->GetModelview().getRow3(1); vec3 z = m_pCameraBase->GetModelview().getRow3(2); mat4 r = mat4_identity; r.setColumn3(0, -x); // r.setColumn3(1, z); // r.setColumn3(2, y); // m_pRole->UpdateTransform(r); m_pRole->Update(ifps); m_pSkillSystem->Update(ifps); m_pStarControl->Update(m_pCameraBase->GetPosition(), m_pCameraBase->GetDirection()); return 1; } int CGameProcess::Render() { ////test //m_pTestHero->Render(); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(10.0f,0.0f,1.0f), vec4(1.0f,0.0f,0.0f,1.0f)); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,10.0f,1.0f), vec4(0.0f,1.0f,0.0f,1.0f)); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,0.0f,11.0f), vec4(0.0f,0.0f,1.0f,1.0f)); ////~test return 1; } int CGameProcess::KeyPress(unsigned int nKey) { if (nKey == 'w') { //g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_FORWARD, 1); } else if (nKey == 's') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 1); } else if (nKey == 'a') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 1); } else if (nKey == 'd') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_MOVE_RIGHT, 1); } else if (nKey == 'q') { g_Engine.pControls->SetState(CControls::STATE_JUMP, 1); } else if (nKey == 'e') { g_Engine.pControls->SetState(CControls::STATE_CROUCH, 1); } else if (nKey == CApp::KEY_SHIFT) { g_Engine.pControls->SetState(CControls::STATE_RUN, 1); } return 1; } int CGameProcess::KeyRelease(unsigned int nKey) { if (nKey == 'w') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_FORWARD, 0); } else if (nKey == 's') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 0); } else if (nKey == 'a') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 0); } return 0; }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" #include "StarControl.h" #include "RayControl.h" #include "CameraBase.h" #include "ActorBase.h" #include "sys/SysControl.h" #include "FileSystem.h" #include "RenderManager.h" #include "Texture.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); vec3 x = m_pCameraBase->GetModelview().getRow3(0); vec3 y = m_pCameraBase->GetModelview().getRow3(1); vec3 z = m_pCameraBase->GetModelview().getRow3(2); mat4 r = mat4_identity; r.setColumn3(0, -x); // r.setColumn3(1, z); // r.setColumn3(2, y); // m_pRole->UpdateTransform(r); m_pRole->Update(ifps); m_pSkillSystem->Update(ifps); m_pStarControl->Update(m_pCameraBase->GetPosition(), m_pCameraBase->GetDirection()); return 1; } int CGameProcess::Render() { ////test //m_pTestHero->Render(); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(10.0f,0.0f,1.0f), vec4(1.0f,0.0f,0.0f,1.0f)); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,10.0f,1.0f), vec4(0.0f,1.0f,0.0f,1.0f)); //g_Engine.pVisualizer->RenderLine3D(vec3(0.0f,0.0f,1.0f), vec3(0.0f,0.0f,11.0f), vec4(0.0f,0.0f,1.0f,1.0f)); ////~test return 1; } int CGameProcess::KeyPress(unsigned int nKey) { if (nKey == 'w') { //g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_FORWARD, 1); } else if (nKey == 's') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 1); } else if (nKey == 'a') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 1); } else if (nKey == 'd') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 1); g_Engine.pControls->SetState(CControls::STATE_MOVE_RIGHT, 1); } else if (nKey == 'q') { g_Engine.pControls->SetState(CControls::STATE_JUMP, 1); } else if (nKey == 'e') { g_Engine.pControls->SetState(CControls::STATE_CROUCH, 1); } else if (nKey == CApp::KEY_SHIFT) { g_Engine.pControls->SetState(CControls::STATE_RUN, 1); } return 1; } int CGameProcess::KeyRelease(unsigned int nKey) { if (nKey == 'w') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_FORWARD, 0); } else if (nKey == 's') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_BACKWARD, 0); } else if (nKey == 'a') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_MOVE_LEFT, 0); } else if (nKey == 'd') { g_Engine.pControls->SetState(CControls::STATE_RESTORE, 0); g_Engine.pControls->SetState(CControls::STATE_MOVE_RIGHT, 0); } return 0; }<|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "dht/i_partitioner.hh" #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <boost/any.hpp> #include <cstdint> #include <boost/variant.hpp> #include <unordered_map> #include <map> #include <set> #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "tuple.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" #include "timestamp.hh" #include "tombstone.hh" #include "atomic_cell.hh" #include "bytes.hh" using partition_key_type = tuple_type<>; using clustering_key_type = tuple_type<>; using clustering_prefix_type = tuple_prefix; using partition_key = bytes; using clustering_key = bytes; using clustering_prefix = clustering_prefix_type::value_type; using row = std::map<column_id, atomic_cell_or_collection>; struct deletable_row final { tombstone t; row cells; }; using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>; class mutation_partition final { private: tombstone _tombstone; row _static_row; std::map<clustering_key, deletable_row, key_compare> _rows; row_tombstone_set _row_tombstones; public: mutation_partition(schema_ptr s) : _rows(key_compare(s->clustering_key_type)) , _row_tombstones(serialized_compare(s->clustering_key_prefix_type)) { } void apply(tombstone t) { _tombstone.apply(t); } void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t); void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) { apply_row_tombstone(schema, {std::move(prefix), std::move(t)}); } void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone); void apply(schema_ptr schema, const mutation_partition& p); const row_tombstone_set& row_tombstones() const { return _row_tombstones; } row& static_row() { return _static_row; } row& clustered_row(const clustering_key& key) { return _rows[key].cells; } row& clustered_row(clustering_key&& key) { return _rows[std::move(key)].cells; } row* find_row(const clustering_key& key); tombstone tombstone_for_row(schema_ptr schema, const clustering_key& key); friend std::ostream& operator<<(std::ostream& os, const mutation_partition& mp); }; class mutation final { public: schema_ptr schema; partition_key key; mutation_partition p; public: mutation(partition_key key_, schema_ptr schema_) : schema(std::move(schema_)) , key(std::move(key_)) , p(schema) { } mutation(mutation&&) = default; mutation(const mutation&) = default; void set_static_cell(const column_definition& def, atomic_cell::one value) { emplace_or_insert(p.static_row(), def.id, std::move(value)); } void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, atomic_cell::one value) { auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix)); emplace_or_insert(row, def.id, std::move(value)); } void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell::one value) { auto& row = p.clustered_row(key); emplace_or_insert(row, def.id, std::move(value)); } private: static void emplace_or_insert(row& row, column_id id, atomic_cell::one&& value) { // our mutations are not yet immutable auto i = row.lower_bound(id); if (i == row.end() || i->first != id) { row.emplace_hint(i, id, atomic_cell_or_collection::from_atomic_cell(std::move(value))); } else { i->second = atomic_cell_or_collection::from_atomic_cell(std::move(value)); } } friend std::ostream& operator<<(std::ostream& os, const mutation& m); }; struct column_family { column_family(schema_ptr schema); mutation_partition& find_or_create_partition(const bytes& key); row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key); mutation_partition* find_partition(const bytes& key); row* find_row(const bytes& partition_key, const bytes& clustering_key); schema_ptr _schema; // partition key -> partition std::map<bytes, mutation_partition, key_compare> partitions; void apply(const mutation& m); }; class keyspace { public: std::unordered_map<sstring, column_family> column_families; static future<keyspace> populate(sstring datadir); schema_ptr find_schema(const sstring& cf_name); column_family* find_column_family(const sstring& cf_name); }; // Policy for distributed<database>: // broadcast metadata writes // local metadata reads // use shard_of() for data class database { public: std::unordered_map<sstring, keyspace> keyspaces; future<> init_from_data_directory(sstring datadir); static future<database> populate(sstring datadir); keyspace* find_keyspace(const sstring& name); future<> stop() { return make_ready_future<>(); } void assign(database&& db) { *this = std::move(db); } unsigned shard_of(const dht::token& t); }; #endif /* DATABASE_HH_ */ <commit_msg>mutation: support for collections<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DATABASE_HH_ #define DATABASE_HH_ #include "dht/i_partitioner.hh" #include "core/sstring.hh" #include "core/shared_ptr.hh" #include "net/byteorder.hh" #include "utils/UUID.hh" #include "db_clock.hh" #include "gc_clock.hh" #include <functional> #include <boost/any.hpp> #include <cstdint> #include <boost/variant.hpp> #include <unordered_map> #include <map> #include <set> #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <experimental/optional> #include <string.h> #include "types.hh" #include "tuple.hh" #include "core/future.hh" #include "cql3/column_specification.hh" #include <limits> #include <cstddef> #include "schema.hh" #include "timestamp.hh" #include "tombstone.hh" #include "atomic_cell.hh" #include "bytes.hh" using partition_key_type = tuple_type<>; using clustering_key_type = tuple_type<>; using clustering_prefix_type = tuple_prefix; using partition_key = bytes; using clustering_key = bytes; using clustering_prefix = clustering_prefix_type::value_type; using row = std::map<column_id, atomic_cell_or_collection>; struct deletable_row final { tombstone t; row cells; }; using row_tombstone_set = std::map<bytes, tombstone, serialized_compare>; class mutation_partition final { private: tombstone _tombstone; row _static_row; std::map<clustering_key, deletable_row, key_compare> _rows; row_tombstone_set _row_tombstones; public: mutation_partition(schema_ptr s) : _rows(key_compare(s->clustering_key_type)) , _row_tombstones(serialized_compare(s->clustering_key_prefix_type)) { } void apply(tombstone t) { _tombstone.apply(t); } void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t); void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) { apply_row_tombstone(schema, {std::move(prefix), std::move(t)}); } void apply_row_tombstone(schema_ptr schema, std::pair<bytes, tombstone> row_tombstone); void apply(schema_ptr schema, const mutation_partition& p); const row_tombstone_set& row_tombstones() const { return _row_tombstones; } row& static_row() { return _static_row; } row& clustered_row(const clustering_key& key) { return _rows[key].cells; } row& clustered_row(clustering_key&& key) { return _rows[std::move(key)].cells; } row* find_row(const clustering_key& key); tombstone tombstone_for_row(schema_ptr schema, const clustering_key& key); friend std::ostream& operator<<(std::ostream& os, const mutation_partition& mp); }; class mutation final { public: schema_ptr schema; partition_key key; mutation_partition p; public: mutation(partition_key key_, schema_ptr schema_) : schema(std::move(schema_)) , key(std::move(key_)) , p(schema) { } mutation(mutation&&) = default; mutation(const mutation&) = default; void set_static_cell(const column_definition& def, atomic_cell_or_collection value) { emplace_or_insert(p.static_row(), def.id, std::move(value)); } void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection value) { auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix)); emplace_or_insert(row, def.id, std::move(value)); } void set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection value) { auto& row = p.clustered_row(key); emplace_or_insert(row, def.id, std::move(value)); } private: static void emplace_or_insert(row& row, column_id id, atomic_cell_or_collection&& value) { // our mutations are not yet immutable auto i = row.lower_bound(id); if (i == row.end() || i->first != id) { row.emplace_hint(i, id, std::move(value)); } else { i->second = std::move(value); } } friend std::ostream& operator<<(std::ostream& os, const mutation& m); }; struct column_family { column_family(schema_ptr schema); mutation_partition& find_or_create_partition(const bytes& key); row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key); mutation_partition* find_partition(const bytes& key); row* find_row(const bytes& partition_key, const bytes& clustering_key); schema_ptr _schema; // partition key -> partition std::map<bytes, mutation_partition, key_compare> partitions; void apply(const mutation& m); }; class keyspace { public: std::unordered_map<sstring, column_family> column_families; static future<keyspace> populate(sstring datadir); schema_ptr find_schema(const sstring& cf_name); column_family* find_column_family(const sstring& cf_name); }; // Policy for distributed<database>: // broadcast metadata writes // local metadata reads // use shard_of() for data class database { public: std::unordered_map<sstring, keyspace> keyspaces; future<> init_from_data_directory(sstring datadir); static future<database> populate(sstring datadir); keyspace* find_keyspace(const sstring& name); future<> stop() { return make_ready_future<>(); } void assign(database&& db) { *this = std::move(db); } unsigned shard_of(const dht::token& t); }; #endif /* DATABASE_HH_ */ <|endoftext|>
<commit_before>// Copyright 2018 Intel Corporation. #include <gtest/gtest.h> #include "testing/matchers.h" #include "tile/codegen/schedule/deps.h" #include "tile/stripe/stripe.h" #include "tile/stripe/stripe.pb.h" namespace gp = google::protobuf; using ::testing::EqualsProto; namespace vertexai { namespace tile { namespace codegen { namespace schedule { TEST(DepsTest, SmallDepMix) { stripe::proto::Block input_proto; gp::TextFormat::ParseFromString(R"( location { unit { } } refs { location { unit { } } into: "b1" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } refs { location { unit { } } into: "b2" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } stmts { load { from:"b1" into:"$1" } } stmts { store { from:"$1" into:"b2" } } stmts { load { from:"b2" into:"$2" } deps: 0} stmts { constant { name:"$3" iconst: 0 } } stmts { intrinsic { name:"ADD" inputs:"$2" inputs:"$3" outputs:"$4"} } stmts { special { name:"COPY" inputs:"b1" outputs:"b2"} } stmts { store { from:"$4" into:"b2"} } )", &input_proto); std::shared_ptr<stripe::Block> block{stripe::FromProto(input_proto)}; ComputeDepsForTree(block.get()); stripe::proto::Block output_proto{IntoProto(*block)}; EXPECT_THAT(output_proto, EqualsProto(R"( location { unit { } } refs { location { unit { } } into: "b1" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } refs { location { unit { } } into: "b2" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } stmts { load { from:"b1" into:"$1" } } stmts { store { from:"$1" into:"b2" } deps: 0 } stmts { load { from:"b2" into:"$2" } deps: 1} stmts { constant { name:"$3" iconst: 0 } } stmts { intrinsic { name:"ADD" inputs:"$2" inputs:"$3" outputs:"$4"} deps: 2 deps: 3} stmts { special { name:"COPY" inputs:"b1" outputs:"b2"} deps: 2} stmts { store { from:"$4" into:"b2"} deps: 4 deps: 5} )")); } } // namespace schedule } // namespace codegen } // namespace tile } // namespace vertexai <commit_msg>Explicit raw string delim<commit_after>// Copyright 2018 Intel Corporation. #include <gtest/gtest.h> #include "testing/matchers.h" #include "tile/codegen/schedule/deps.h" #include "tile/stripe/stripe.h" #include "tile/stripe/stripe.pb.h" namespace gp = google::protobuf; using ::testing::EqualsProto; namespace vertexai { namespace tile { namespace codegen { namespace schedule { TEST(DepsTest, SmallDepMix) { stripe::proto::Block input_proto; gp::TextFormat::ParseFromString(R"( location { unit { } } refs { location { unit { } } into: "b1" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } refs { location { unit { } } into: "b2" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } stmts { load { from:"b1" into:"$1" } } stmts { store { from:"$1" into:"b2" } } stmts { load { from:"b2" into:"$2" } deps: 0} stmts { constant { name:"$3" iconst: 0 } } stmts { intrinsic { name:"ADD" inputs:"$2" inputs:"$3" outputs:"$4"} } stmts { special { name:"COPY" inputs:"b1" outputs:"b2"} } stmts { store { from:"$4" into:"b2"} } )", &input_proto); std::shared_ptr<stripe::Block> block{stripe::FromProto(input_proto)}; ComputeDepsForTree(block.get()); stripe::proto::Block output_proto{IntoProto(*block)}; EXPECT_THAT(output_proto, EqualsProto(R"proto( location { unit { } } refs { location { unit { } } into: "b1" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } refs { location { unit { } } into: "b2" shape { type: FLOAT32 dimensions: {size:1 stride:1} } } stmts { load { from:"b1" into:"$1" } } stmts { store { from:"$1" into:"b2" } deps: 0 } stmts { load { from:"b2" into:"$2" } deps: 1} stmts { constant { name:"$3" iconst: 0 } } stmts { intrinsic { name:"ADD" inputs:"$2" inputs:"$3" outputs:"$4"} deps: 2 deps: 3} stmts { special { name:"COPY" inputs:"b1" outputs:"b2"} deps: 2} stmts { store { from:"$4" into:"b2"} deps: 4 deps: 5} )proto")); } } // namespace schedule } // namespace codegen } // namespace tile } // namespace vertexai <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Sk4px.h" #include "SkNx.h" #include "SkRandom.h" #include "Test.h" template <int N, typename T> static void test_Nf(skiatest::Reporter* r) { auto assert_nearly_eq = [&](double eps, const SkNf<N,T>& v, T a, T b, T c, T d) { auto close = [=](T a, T b) { return fabs(a-b) <= eps; }; T vals[4]; v.store(vals); bool ok = close(vals[0], a) && close(vals[1], b) && close(v.template kth<0>(), a) && close(v.template kth<1>(), b); REPORTER_ASSERT(r, ok); if (N == 4) { ok = close(vals[2], c) && close(vals[3], d) && close(v.template kth<2>(), c) && close(v.template kth<3>(), d); REPORTER_ASSERT(r, ok); } }; auto assert_eq = [&](const SkNf<N,T>& v, T a, T b, T c, T d) { return assert_nearly_eq(0, v, a,b,c,d); }; T vals[] = {3, 4, 5, 6}; SkNf<N,T> a = SkNf<N,T>::Load(vals), b(a), c = a; SkNf<N,T> d; d = a; assert_eq(a, 3, 4, 5, 6); assert_eq(b, 3, 4, 5, 6); assert_eq(c, 3, 4, 5, 6); assert_eq(d, 3, 4, 5, 6); assert_eq(a+b, 6, 8, 10, 12); assert_eq(a*b, 9, 16, 25, 36); assert_eq(a*b-b, 6, 12, 20, 30); assert_eq((a*b).sqrt(), 3, 4, 5, 6); assert_eq(a/b, 1, 1, 1, 1); assert_eq(SkNf<N,T>(0)-a, -3, -4, -5, -6); SkNf<N,T> fours(4); assert_eq(fours.sqrt(), 2,2,2,2); assert_nearly_eq(0.001, fours.rsqrt0(), 0.5, 0.5, 0.5, 0.5); assert_nearly_eq(0.001, fours.rsqrt1(), 0.5, 0.5, 0.5, 0.5); assert_nearly_eq(0.001, fours.rsqrt2(), 0.5, 0.5, 0.5, 0.5); assert_eq( fours. invert(), 0.25, 0.25, 0.25, 0.25); assert_nearly_eq(0.001, fours.approxInvert(), 0.25, 0.25, 0.25, 0.25); assert_eq(SkNf<N,T>::Min(a, fours), 3, 4, 4, 4); assert_eq(SkNf<N,T>::Max(a, fours), 4, 4, 5, 6); // Test some comparisons. This is not exhaustive. REPORTER_ASSERT(r, (a == b).allTrue()); REPORTER_ASSERT(r, (a+b == a*b-b).anyTrue()); REPORTER_ASSERT(r, !(a+b == a*b-b).allTrue()); REPORTER_ASSERT(r, !(a+b == a*b).anyTrue()); REPORTER_ASSERT(r, !(a != b).anyTrue()); REPORTER_ASSERT(r, (a < fours).anyTrue()); REPORTER_ASSERT(r, (a <= fours).anyTrue()); REPORTER_ASSERT(r, !(a > fours).allTrue()); REPORTER_ASSERT(r, !(a >= fours).allTrue()); } DEF_TEST(SkNf, r) { test_Nf<2, float>(r); test_Nf<2, double>(r); test_Nf<4, float>(r); test_Nf<4, double>(r); } template <int N, typename T> void test_Ni(skiatest::Reporter* r) { auto assert_eq = [&](const SkNi<N,T>& v, T a, T b, T c, T d, T e, T f, T g, T h) { T vals[8]; v.store(vals); switch (N) { case 8: REPORTER_ASSERT(r, vals[4] == e && vals[5] == f && vals[6] == g && vals[7] == h); case 4: REPORTER_ASSERT(r, vals[2] == c && vals[3] == d); case 2: REPORTER_ASSERT(r, vals[0] == a && vals[1] == b); } switch (N) { case 8: REPORTER_ASSERT(r, v.template kth<4>() == e && v.template kth<5>() == f && v.template kth<6>() == g && v.template kth<7>() == h); case 4: REPORTER_ASSERT(r, v.template kth<2>() == c && v.template kth<3>() == d); case 2: REPORTER_ASSERT(r, v.template kth<0>() == a && v.template kth<1>() == b); } }; T vals[] = { 1,2,3,4,5,6,7,8 }; SkNi<N,T> a = SkNi<N,T>::Load(vals), b(a), c = a; SkNi<N,T> d; d = a; assert_eq(a, 1,2,3,4,5,6,7,8); assert_eq(b, 1,2,3,4,5,6,7,8); assert_eq(c, 1,2,3,4,5,6,7,8); assert_eq(d, 1,2,3,4,5,6,7,8); assert_eq(a+a, 2,4,6,8,10,12,14,16); assert_eq(a*a, 1,4,9,16,25,36,49,64); assert_eq(a*a-a, 0,2,6,12,20,30,42,56); assert_eq(a >> 2, 0,0,0,1,1,1,1,2); assert_eq(a << 1, 2,4,6,8,10,12,14,16); REPORTER_ASSERT(r, a.template kth<1>() == 2); } DEF_TEST(SkNi, r) { test_Ni<2, uint16_t>(r); test_Ni<4, uint16_t>(r); test_Ni<8, uint16_t>(r); test_Ni<2, int>(r); test_Ni<4, int>(r); test_Ni<8, int>(r); } DEF_TEST(SkNi_min, r) { // Exhaustively check the 8x8 bit space. for (int a = 0; a < (1<<8); a++) { for (int b = 0; b < (1<<8); b++) { REPORTER_ASSERT(r, Sk16b::Min(Sk16b(a), Sk16b(b)).kth<0>() == SkTMin(a, b)); }} // Exhausting the 16x16 bit space is kind of slow, so only do that in release builds. #ifdef SK_DEBUG SkRandom rand; for (int i = 0; i < (1<<16); i++) { uint16_t a = rand.nextU() >> 16, b = rand.nextU() >> 16; REPORTER_ASSERT(r, Sk8h::Min(Sk8h(a), Sk8h(b)).kth<0>() == SkTMin(a, b)); } #else for (int a = 0; a < (1<<16); a++) { for (int b = 0; b < (1<<16); b++) { REPORTER_ASSERT(r, Sk8h::Min(Sk8h(a), Sk8h(b)).kth<0>() == SkTMin(a, b)); }} #endif } DEF_TEST(SkNi_saturatedAdd, r) { for (int a = 0; a < (1<<8); a++) { for (int b = 0; b < (1<<8); b++) { int exact = a+b; if (exact > 255) { exact = 255; } if (exact < 0) { exact = 0; } REPORTER_ASSERT(r, Sk16b(a).saturatedAdd(Sk16b(b)).kth<0>() == exact); } } } DEF_TEST(Sk4px_muldiv255round, r) { for (int a = 0; a < (1<<8); a++) { for (int b = 0; b < (1<<8); b++) { int exact = (a*b+127)/255; // Duplicate a and b 16x each. Sk4px av((SkAlpha)a), bv((SkAlpha)b); // This way should always be exactly correct. int correct = av.mulWiden(bv).div255RoundNarrow().kth<0>(); REPORTER_ASSERT(r, correct == exact); // We're a bit more flexible on this method: correct for 0 or 255, otherwise off by <=1. int fast = av.fastMulDiv255Round(bv).kth<0>(); REPORTER_ASSERT(r, fast-exact >= -1 && fast-exact <= 1); if (a == 0 || a == 255 || b == 0 || b == 255) { REPORTER_ASSERT(r, fast == exact); } } } } <commit_msg>Revert of Thorough tests for saturatedAdd and mulDiv255Round. (patchset #1 id:1 of https://codereview.chromium.org/1184113003/)<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkNx.h" #include "SkRandom.h" #include "Test.h" template <int N, typename T> static void test_Nf(skiatest::Reporter* r) { auto assert_nearly_eq = [&](double eps, const SkNf<N,T>& v, T a, T b, T c, T d) { auto close = [=](T a, T b) { return fabs(a-b) <= eps; }; T vals[4]; v.store(vals); bool ok = close(vals[0], a) && close(vals[1], b) && close(v.template kth<0>(), a) && close(v.template kth<1>(), b); REPORTER_ASSERT(r, ok); if (N == 4) { ok = close(vals[2], c) && close(vals[3], d) && close(v.template kth<2>(), c) && close(v.template kth<3>(), d); REPORTER_ASSERT(r, ok); } }; auto assert_eq = [&](const SkNf<N,T>& v, T a, T b, T c, T d) { return assert_nearly_eq(0, v, a,b,c,d); }; T vals[] = {3, 4, 5, 6}; SkNf<N,T> a = SkNf<N,T>::Load(vals), b(a), c = a; SkNf<N,T> d; d = a; assert_eq(a, 3, 4, 5, 6); assert_eq(b, 3, 4, 5, 6); assert_eq(c, 3, 4, 5, 6); assert_eq(d, 3, 4, 5, 6); assert_eq(a+b, 6, 8, 10, 12); assert_eq(a*b, 9, 16, 25, 36); assert_eq(a*b-b, 6, 12, 20, 30); assert_eq((a*b).sqrt(), 3, 4, 5, 6); assert_eq(a/b, 1, 1, 1, 1); assert_eq(SkNf<N,T>(0)-a, -3, -4, -5, -6); SkNf<N,T> fours(4); assert_eq(fours.sqrt(), 2,2,2,2); assert_nearly_eq(0.001, fours.rsqrt0(), 0.5, 0.5, 0.5, 0.5); assert_nearly_eq(0.001, fours.rsqrt1(), 0.5, 0.5, 0.5, 0.5); assert_nearly_eq(0.001, fours.rsqrt2(), 0.5, 0.5, 0.5, 0.5); assert_eq( fours. invert(), 0.25, 0.25, 0.25, 0.25); assert_nearly_eq(0.001, fours.approxInvert(), 0.25, 0.25, 0.25, 0.25); assert_eq(SkNf<N,T>::Min(a, fours), 3, 4, 4, 4); assert_eq(SkNf<N,T>::Max(a, fours), 4, 4, 5, 6); // Test some comparisons. This is not exhaustive. REPORTER_ASSERT(r, (a == b).allTrue()); REPORTER_ASSERT(r, (a+b == a*b-b).anyTrue()); REPORTER_ASSERT(r, !(a+b == a*b-b).allTrue()); REPORTER_ASSERT(r, !(a+b == a*b).anyTrue()); REPORTER_ASSERT(r, !(a != b).anyTrue()); REPORTER_ASSERT(r, (a < fours).anyTrue()); REPORTER_ASSERT(r, (a <= fours).anyTrue()); REPORTER_ASSERT(r, !(a > fours).allTrue()); REPORTER_ASSERT(r, !(a >= fours).allTrue()); } DEF_TEST(SkNf, r) { test_Nf<2, float>(r); test_Nf<2, double>(r); test_Nf<4, float>(r); test_Nf<4, double>(r); } template <int N, typename T> void test_Ni(skiatest::Reporter* r) { auto assert_eq = [&](const SkNi<N,T>& v, T a, T b, T c, T d, T e, T f, T g, T h) { T vals[8]; v.store(vals); switch (N) { case 8: REPORTER_ASSERT(r, vals[4] == e && vals[5] == f && vals[6] == g && vals[7] == h); case 4: REPORTER_ASSERT(r, vals[2] == c && vals[3] == d); case 2: REPORTER_ASSERT(r, vals[0] == a && vals[1] == b); } switch (N) { case 8: REPORTER_ASSERT(r, v.template kth<4>() == e && v.template kth<5>() == f && v.template kth<6>() == g && v.template kth<7>() == h); case 4: REPORTER_ASSERT(r, v.template kth<2>() == c && v.template kth<3>() == d); case 2: REPORTER_ASSERT(r, v.template kth<0>() == a && v.template kth<1>() == b); } }; T vals[] = { 1,2,3,4,5,6,7,8 }; SkNi<N,T> a = SkNi<N,T>::Load(vals), b(a), c = a; SkNi<N,T> d; d = a; assert_eq(a, 1,2,3,4,5,6,7,8); assert_eq(b, 1,2,3,4,5,6,7,8); assert_eq(c, 1,2,3,4,5,6,7,8); assert_eq(d, 1,2,3,4,5,6,7,8); assert_eq(a+a, 2,4,6,8,10,12,14,16); assert_eq(a*a, 1,4,9,16,25,36,49,64); assert_eq(a*a-a, 0,2,6,12,20,30,42,56); assert_eq(a >> 2, 0,0,0,1,1,1,1,2); assert_eq(a << 1, 2,4,6,8,10,12,14,16); REPORTER_ASSERT(r, a.template kth<1>() == 2); } DEF_TEST(SkNi, r) { test_Ni<2, uint16_t>(r); test_Ni<4, uint16_t>(r); test_Ni<8, uint16_t>(r); test_Ni<2, int>(r); test_Ni<4, int>(r); test_Ni<8, int>(r); } DEF_TEST(SkNi_min, r) { // Exhaustively check the 8x8 bit space. for (int a = 0; a < (1<<8); a++) { for (int b = 0; b < (1<<8); b++) { REPORTER_ASSERT(r, Sk16b::Min(Sk16b(a), Sk16b(b)).kth<0>() == SkTMin(a, b)); }} // Exhausting the 16x16 bit space is kind of slow, so only do that in release builds. #ifdef SK_DEBUG SkRandom rand; for (int i = 0; i < (1<<16); i++) { uint16_t a = rand.nextU() >> 16, b = rand.nextU() >> 16; REPORTER_ASSERT(r, Sk8h::Min(Sk8h(a), Sk8h(b)).kth<0>() == SkTMin(a, b)); } #else for (int a = 0; a < (1<<16); a++) { for (int b = 0; b < (1<<16); b++) { REPORTER_ASSERT(r, Sk8h::Min(Sk8h(a), Sk8h(b)).kth<0>() == SkTMin(a, b)); }} #endif } <|endoftext|>
<commit_before>/* * pv.cpp * */ #include <columns/buildandrun.hpp> int customexit(HyPerCol * hc, int argc, char * argv[]); int main(int argc, char * argv[]) { char * param_file = NULL; int paramfilestatus = pv_getopt_str(argc, argv, "-p", &param_file); int cl_argc = argc + (paramfilestatus!=0 ? 2 : 0); char ** cl_argv = (char **) malloc((size_t) cl_argc * sizeof(char *)); assert(cl_argv!=NULL); for (int a=0; a<argc; a++) { cl_argv[a] = strdup(argv[a]); assert(cl_argv[a]); } if (paramfilestatus!=0) { cl_argv[argc] = strdup("-p"); assert(cl_argv[argc]); cl_argv[argc+1] = strdup("input/CloneVLayerTest.params"); assert(cl_argv[argc+1]); } int status; status = buildandrun(cl_argc, cl_argv, NULL, &customexit, NULL); free(cl_argv); cl_argv = NULL; return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE; } int customexit(HyPerCol * hc, int argc, char * argv[]) { int check_clone_id = -1; int check_sigmoid_id = -1; for (int k=0; k<hc->numberOfLayers(); k++) { if (!strcmp(hc->getLayer(k)->getName(), "check_clone")) { assert(check_clone_id<0); check_clone_id = k; } if (!strcmp(hc->getLayer(k)->getName(), "check_sigmoid")) { assert(check_sigmoid_id<0); check_sigmoid_id = k; } } int N; HyPerLayer * check_clone_layer = hc->getLayer(check_clone_id); assert(check_clone_layer!=NULL); const pvdata_t * check_clone_layer_data = check_clone_layer->getLayerData(); N = check_clone_layer->getNumExtended(); for (int k=0; k<N; k++) { assert(fabsf(check_clone_layer_data[k])<1e-6); } HyPerLayer * check_sigmoid_layer = hc->getLayer(check_sigmoid_id); assert(check_sigmoid_layer!=NULL); const pvdata_t * check_sigmoid_layer_data = check_sigmoid_layer->getLayerData(); N = check_sigmoid_layer->getNumExtended(); for (int k=0; k<N; k++) { assert(fabsf(check_sigmoid_layer_data[k])<1e-6); } if (hc->columnId()==0) { printf("%s passed.\n", argv[0]); } return PV_SUCCESS; } <commit_msg>CloneVLayerTest bug fix<commit_after>/* * pv.cpp * */ #include <columns/buildandrun.hpp> int customexit(HyPerCol * hc, int argc, char * argv[]); int main(int argc, char * argv[]) { char * param_file = NULL; int paramfilestatus = pv_getopt_str(argc, argv, "-p", &param_file); int cl_argc = argc + (paramfilestatus!=0 ? 2 : 0); char ** cl_argv = (char **) malloc((size_t) (cl_argc+1) * sizeof(char *)); assert(cl_argv!=NULL); for (int a=0; a<argc; a++) { cl_argv[a] = strdup(argv[a]); assert(cl_argv[a]); } if (paramfilestatus!=0) { cl_argv[argc] = strdup("-p"); assert(cl_argv[argc]); cl_argv[argc+1] = strdup("input/CloneVLayerTest.params"); assert(cl_argv[argc+1]); } cl_argv[cl_argc] = NULL; int status; status = buildandrun(cl_argc, cl_argv, NULL, &customexit, NULL); free(cl_argv); cl_argv = NULL; return status==PV_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE; } int customexit(HyPerCol * hc, int argc, char * argv[]) { int check_clone_id = -1; int check_sigmoid_id = -1; for (int k=0; k<hc->numberOfLayers(); k++) { if (!strcmp(hc->getLayer(k)->getName(), "check_clone")) { assert(check_clone_id<0); check_clone_id = k; } if (!strcmp(hc->getLayer(k)->getName(), "check_sigmoid")) { assert(check_sigmoid_id<0); check_sigmoid_id = k; } } int N; HyPerLayer * check_clone_layer = hc->getLayer(check_clone_id); assert(check_clone_layer!=NULL); const pvdata_t * check_clone_layer_data = check_clone_layer->getLayerData(); N = check_clone_layer->getNumExtended(); for (int k=0; k<N; k++) { assert(fabsf(check_clone_layer_data[k])<1e-6); } HyPerLayer * check_sigmoid_layer = hc->getLayer(check_sigmoid_id); assert(check_sigmoid_layer!=NULL); const pvdata_t * check_sigmoid_layer_data = check_sigmoid_layer->getLayerData(); N = check_sigmoid_layer->getNumExtended(); for (int k=0; k<N; k++) { assert(fabsf(check_sigmoid_layer_data[k])<1e-6); } if (hc->columnId()==0) { printf("%s passed.\n", argv[0]); } return PV_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include "libs/catch/catch.hpp" #include "src/dopt_node.h" TEST_CASE("entangle|dopt_node-enc") { auto n = entangle::OTNode(8888, 100); entangle::upd_t u = { entangle::del, 100, 'c' }; REQUIRE(n.enc_upd_t(u).compare("1:100:c") == 0); REQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'c' }) == true); REQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'd' }) == false); REQUIRE(n.cmp_upd_t(n.dec_upd_t("1:100:c"), { entangle::del, 100, 'c' }) == true); } TEST_CASE("entangle|dopt_node-convergence") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 2); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE(x.join("localhost", 8000) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("11") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '2') == true); sleep(1); CHECK(s.get_context().compare("211") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.del(1) == true); sleep(1); CHECK(s.get_context().compare("21") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(s.del(0) == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(s.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(s.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); sleep(1); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); } TEST_CASE("entangle|dopt_node-daemon") { auto n = entangle::OTNode(8888, 100); auto m = entangle::OTNode(8889, 100); REQUIRE(m.join("localhost", 8888) == false); REQUIRE_NOTHROW(n.up()); REQUIRE_NOTHROW(n.dn()); REQUIRE_NOTHROW(n.up()); REQUIRE_NOTHROW(m.up()); REQUIRE(m.join("localhost", 8888) == true); sleep(1); REQUIRE(m.size() == 1); REQUIRE(n.size() == 1); REQUIRE(m.join("localhost", 8888) == false); REQUIRE(n.join("localhost", 8889) == false); REQUIRE(m.size() == 1); REQUIRE(n.size() == 1); REQUIRE(m.drop("localhost", 8888) == true); sleep(1); REQUIRE(m.size() == 0); REQUIRE(n.size() == 0); REQUIRE_NOTHROW(m.dn()); REQUIRE_NOTHROW(n.dn()); // auto-call OTNode::dn on stack unwind REQUIRE_NOTHROW(n.up()); sleep(1); } TEST_CASE("entangle|dopt_node-topography") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 2); auto y = entangle::OTNode(8051, 1); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 1); /** * single node, single server topology */ REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 2); /** * multi node, single server topology */ REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); /** * multi-layer tree topology */ REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8050) == true); REQUIRE(s.size() == 1); REQUIRE(x.size() == 2); REQUIRE(x.ins(0, '1') == true); sleep(1); REQUIRE(s.get_context().compare("1") == 0); REQUIRE(x.get_context().compare(s.get_context()) == 0); REQUIRE(y.get_context().compare(s.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8050) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE(x.size() == 0); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); } TEST_CASE("entangle|dopt_node-concurrent") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 1); auto y = entangle::OTNode(8051, 1); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 2); /** * concurrent update checking */ REQUIRE(x.ins(0, '1') == true); REQUIRE(y.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); REQUIRE(y.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("11") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(x.ins(0, '1') == true); sleep(1); REQUIRE(y.ins(0, '1') == true); CHECK(s.get_context().compare("11") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); } <commit_msg>bug fix in test suite<commit_after>#include <iostream> #include <unistd.h> #include "libs/catch/catch.hpp" #include "src/dopt_node.h" TEST_CASE("entangle|dopt_node-enc") { auto n = entangle::OTNode(8888, 100); entangle::upd_t u = { entangle::del, 100, 'c' }; REQUIRE(n.enc_upd_t(u).compare("1:100:c") == 0); REQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'c' }) == true); REQUIRE(n.cmp_upd_t({ entangle::del, 100, 'c'}, { entangle::del, 100, 'd' }) == false); REQUIRE(n.cmp_upd_t(n.dec_upd_t("1:100:c"), { entangle::del, 100, 'c' }) == true); } TEST_CASE("entangle|dopt_node-convergence") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 2); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE(x.join("localhost", 8000) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("11") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.ins(0, '2') == true); sleep(1); CHECK(s.get_context().compare("211") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(x.del(1) == true); sleep(1); CHECK(s.get_context().compare("21") == 0); CHECK(x.get_context().compare(s.get_context()) == 0); REQUIRE(s.del(0) == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(s.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(s.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); sleep(1); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); } TEST_CASE("entangle|dopt_node-daemon") { auto n = entangle::OTNode(8888, 100); auto m = entangle::OTNode(8889, 100); REQUIRE(m.join("localhost", 8888) == false); REQUIRE_NOTHROW(n.up()); REQUIRE_NOTHROW(n.dn()); REQUIRE_NOTHROW(n.up()); REQUIRE_NOTHROW(m.up()); REQUIRE(m.join("localhost", 8888) == true); sleep(1); REQUIRE(m.size() == 1); REQUIRE(n.size() == 1); REQUIRE(m.join("localhost", 8888) == false); REQUIRE(n.join("localhost", 8889) == false); REQUIRE(m.size() == 1); REQUIRE(n.size() == 1); REQUIRE(m.drop("localhost", 8888) == true); sleep(1); REQUIRE(m.size() == 0); REQUIRE(n.size() == 0); REQUIRE_NOTHROW(m.dn()); REQUIRE_NOTHROW(n.dn()); // auto-call OTNode::dn on stack unwind REQUIRE_NOTHROW(n.up()); sleep(1); } TEST_CASE("entangle|dopt_node-topography") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 2); auto y = entangle::OTNode(8051, 1); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 1); /** * single node, single server topology */ REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 2); /** * multi node, single server topology */ REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); /** * multi-layer tree topology */ REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8050) == true); REQUIRE(s.size() == 1); REQUIRE(x.size() == 2); REQUIRE(x.ins(0, '1') == true); sleep(1); REQUIRE(s.get_context().compare("1") == 0); REQUIRE(x.get_context().compare(s.get_context()) == 0); REQUIRE(y.get_context().compare(s.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8050) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE(x.size() == 0); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); } TEST_CASE("entangle|dopt_node-concurrent") { auto s = entangle::OTNode(8000, 100); auto x = entangle::OTNode(8050, 1); auto y = entangle::OTNode(8051, 1); REQUIRE_NOTHROW(s.up()); REQUIRE_NOTHROW(x.up()); REQUIRE_NOTHROW(y.up()); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 2); /** * concurrent update checking */ REQUIRE(x.ins(0, '1') == true); REQUIRE(y.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); REQUIRE(y.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(s.size() == 0); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("1") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("11") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.del(0) == true); REQUIRE(x.del(0) == true); sleep(1); CHECK(s.get_context().compare("") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE(x.join("localhost", 8000) == true); REQUIRE(y.join("localhost", 8000) == true); sleep(1); REQUIRE(x.ins(0, '1') == true); sleep(1); REQUIRE(y.ins(0, '1') == true); sleep(1); CHECK(s.get_context().compare("11") == 0); CHECK(s.get_context().compare(x.get_context()) == 0); CHECK(s.get_context().compare(y.get_context()) == 0); REQUIRE(x.drop("localhost", 8000) == true); REQUIRE(y.drop("localhost", 8000) == true); sleep(1); REQUIRE_NOTHROW(s.dn()); REQUIRE_NOTHROW(x.dn()); REQUIRE_NOTHROW(y.dn()); } <|endoftext|>
<commit_before>#ifndef __UTIL_H #define __UTIL_H #include "types.hh" #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <signal.h> #include <iostream> namespace nix { #define foreach(it_type, it, collection) \ for (it_type it = collection.begin(); it != collection.end(); ++it) /* Return an environment variable. */ string getEnv(const string & key, const string & def = ""); /* Return an absolutized path, resolving paths relative to the specified directory, or the current directory otherwise. The path is also canonicalised. */ Path absPath(Path path, Path dir = ""); /* Canonicalise a path by removing all `.' or `..' components and double or trailing slashes. Optionally resolves all symlink components such that each component of the resulting path is *not* a symbolic link. */ Path canonPath(const Path & path, bool resolveSymlinks = false); /* Return the directory part of the given canonical path, i.e., everything before the final `/'. If the path is the root or an immediate child thereof (e.g., `/foo'), this means an empty string is returned. */ Path dirOf(const Path & path); /* Return the base name of the given canonical path, i.e., everything following the final `/'. */ string baseNameOf(const Path & path); /* Return true iff the given path exists. */ bool pathExists(const Path & path); /* Read the contents (target) of a symbolic link. The result is not in any way canonicalised. */ Path readLink(const Path & path); bool isLink(const Path & path); /* Read the contents of a directory. The entries `.' and `..' are removed. */ Strings readDirectory(const Path & path); /* Read the contents of a file into a string. */ string readFile(int fd); string readFile(const Path & path); /* Write a string to a file. */ void writeFile(const Path & path, const string & s); /* Read a line from a file descriptor. */ string readLine(int fd); /* Write a line to a file descriptor. */ void writeLine(int fd, string s); /* Compute the sum of the sizes of all files in `path'. */ void computePathSize(const Path & path, unsigned long long & bytes, unsigned long long & blocks); /* Delete a path; i.e., in the case of a directory, it is deleted recursively. Don't use this at home, kids. The second variant returns the number of bytes and blocks freed. */ void deletePath(const Path & path); void deletePath(const Path & path, unsigned long long & bytesFreed, unsigned long long & blocksFreed); /* Make a path read-only recursively. */ void makePathReadOnly(const Path & path); /* Create a temporary directory. */ Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix", bool includePid = true, bool useGlobalCounter = true); /* Create a directory and all its parents, if necessary. Returns the list of created directories, in order of creation. */ Paths createDirs(const Path & path); /* Create a file and write the given text to it. The file is written in binary mode (i.e., no end-of-line conversions). The path should not already exist. */ void writeStringToFile(const Path & path, const string & s); template<class T, class A> T singleton(const A & a) { T t; t.insert(a); return t; } /* Messages. */ typedef enum { ltPretty, /* nice, nested output */ ltEscapes, /* nesting indicated using escape codes (for log2xml) */ ltFlat /* no nesting */ } LogType; extern LogType logType; extern Verbosity verbosity; /* suppress msgs > this */ class Nest { private: bool nest; public: Nest(); ~Nest(); void open(Verbosity level, const format & f); void close(); }; void printMsg_(Verbosity level, const format & f); #define startNest(varName, level, f) \ Nest varName; \ if (level <= verbosity) { \ varName.open(level, (f)); \ } #define printMsg(level, f) \ do { \ if (level <= verbosity) { \ printMsg_(level, (f)); \ } \ } while (0) #define debug(f) printMsg(lvlDebug, f) void warnOnce(bool & haveWarned, const format & f); extern void (*writeToStderr) (const unsigned char * buf, size_t count); /* Wrappers arount read()/write() that read/write exactly the requested number of bytes. */ void readFull(int fd, unsigned char * buf, size_t count); void writeFull(int fd, const unsigned char * buf, size_t count); MakeError(EndOfFile, Error) /* Read a file descriptor until EOF occurs. */ string drainFD(int fd); /* Automatic cleanup of resources. */ template <class T> struct AutoDeleteArray { T * p; AutoDeleteArray(T * p) : p(p) { } ~AutoDeleteArray() { delete [] p; } }; class AutoDelete { Path path; bool del; bool recursive; public: AutoDelete(const Path & p, bool recursive = true); ~AutoDelete(); void cancel(); }; class AutoCloseFD { int fd; public: AutoCloseFD(); AutoCloseFD(int fd); AutoCloseFD(const AutoCloseFD & fd); ~AutoCloseFD(); void operator =(int fd); operator int() const; void close(); bool isOpen(); int borrow(); }; class Pipe { public: AutoCloseFD readSide, writeSide; void create(); }; class AutoCloseDir { DIR * dir; public: AutoCloseDir(); AutoCloseDir(DIR * dir); ~AutoCloseDir(); void operator =(DIR * dir); operator DIR *(); }; class Pid { pid_t pid; bool separatePG; int killSignal; public: Pid(); ~Pid(); void operator =(pid_t pid); operator pid_t(); void kill(); int wait(bool block); void setSeparatePG(bool separatePG); void setKillSignal(int signal); }; /* Kill all processes running under the specified uid by sending them a SIGKILL. */ void killUser(uid_t uid); /* Run a program and return its stdout in a string (i.e., like the shell backtick operator). */ string runProgram(Path program, bool searchPath = false, const Strings & args = Strings()); /* Close all file descriptors except stdin, stdout, stderr, and those listed in the given set. Good practice in child processes. */ void closeMostFDs(const set<int> & exceptions); /* Wrapper around _exit() on Unix and ExitProcess() on Windows. (On Cygwin, _exit() doesn't seem to do the right thing.) */ void quickExit(int status); /* Common initialisation for setuid programs: clear the environment, sanitize file handles 0, 1 and 2. */ void setuidCleanup(); /* User interruption. */ extern volatile sig_atomic_t _isInterrupted; void _interrupted(); void inline checkInterrupt() { if (_isInterrupted) _interrupted(); } MakeError(Interrupted, BaseError) /* String packing / unpacking. */ string packStrings(const Strings & strings); Strings unpackStrings(const string & s); /* String tokenizer. */ Strings tokenizeString(const string & s, const string & separators = " \t\n\r"); /* Convert the exit status of a child as returned by wait() into an error string. */ string statusToString(int status); bool statusOk(int status); /* Parse a string into an integer. */ template<class N> bool string2Int(const string & s, N & n) { std::istringstream str(s); str >> n; return str && str.get() == EOF; } string int2String(int n); /* Return true iff `s' ends in `suffix'. */ bool hasSuffix(const string & s, const string & suffix); /* Exception handling in destructors: print an error message, then ignore the exception. */ void ignoreException(); /* STL functions such as sort() pass a binary function object around by value, so it gets cloned a lot. This is bad if the function object has state or is simply large. This adapter wraps the function object to simulate passing by reference. */ template<class F> struct binary_function_ref_adapter { F * p; binary_function_ref_adapter(F * _p) { p = _p; } typename F::result_type operator () ( const typename F::first_argument_type & x, const typename F::second_argument_type & y) { return (*p)(x, y); } }; } #endif /* !__UTIL_H */ <commit_msg>* Grrr.<commit_after>#ifndef __UTIL_H #define __UTIL_H #include "types.hh" #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <signal.h> #include <cstdio> namespace nix { #define foreach(it_type, it, collection) \ for (it_type it = collection.begin(); it != collection.end(); ++it) /* Return an environment variable. */ string getEnv(const string & key, const string & def = ""); /* Return an absolutized path, resolving paths relative to the specified directory, or the current directory otherwise. The path is also canonicalised. */ Path absPath(Path path, Path dir = ""); /* Canonicalise a path by removing all `.' or `..' components and double or trailing slashes. Optionally resolves all symlink components such that each component of the resulting path is *not* a symbolic link. */ Path canonPath(const Path & path, bool resolveSymlinks = false); /* Return the directory part of the given canonical path, i.e., everything before the final `/'. If the path is the root or an immediate child thereof (e.g., `/foo'), this means an empty string is returned. */ Path dirOf(const Path & path); /* Return the base name of the given canonical path, i.e., everything following the final `/'. */ string baseNameOf(const Path & path); /* Return true iff the given path exists. */ bool pathExists(const Path & path); /* Read the contents (target) of a symbolic link. The result is not in any way canonicalised. */ Path readLink(const Path & path); bool isLink(const Path & path); /* Read the contents of a directory. The entries `.' and `..' are removed. */ Strings readDirectory(const Path & path); /* Read the contents of a file into a string. */ string readFile(int fd); string readFile(const Path & path); /* Write a string to a file. */ void writeFile(const Path & path, const string & s); /* Read a line from a file descriptor. */ string readLine(int fd); /* Write a line to a file descriptor. */ void writeLine(int fd, string s); /* Compute the sum of the sizes of all files in `path'. */ void computePathSize(const Path & path, unsigned long long & bytes, unsigned long long & blocks); /* Delete a path; i.e., in the case of a directory, it is deleted recursively. Don't use this at home, kids. The second variant returns the number of bytes and blocks freed. */ void deletePath(const Path & path); void deletePath(const Path & path, unsigned long long & bytesFreed, unsigned long long & blocksFreed); /* Make a path read-only recursively. */ void makePathReadOnly(const Path & path); /* Create a temporary directory. */ Path createTempDir(const Path & tmpRoot = "", const Path & prefix = "nix", bool includePid = true, bool useGlobalCounter = true); /* Create a directory and all its parents, if necessary. Returns the list of created directories, in order of creation. */ Paths createDirs(const Path & path); /* Create a file and write the given text to it. The file is written in binary mode (i.e., no end-of-line conversions). The path should not already exist. */ void writeStringToFile(const Path & path, const string & s); template<class T, class A> T singleton(const A & a) { T t; t.insert(a); return t; } /* Messages. */ typedef enum { ltPretty, /* nice, nested output */ ltEscapes, /* nesting indicated using escape codes (for log2xml) */ ltFlat /* no nesting */ } LogType; extern LogType logType; extern Verbosity verbosity; /* suppress msgs > this */ class Nest { private: bool nest; public: Nest(); ~Nest(); void open(Verbosity level, const format & f); void close(); }; void printMsg_(Verbosity level, const format & f); #define startNest(varName, level, f) \ Nest varName; \ if (level <= verbosity) { \ varName.open(level, (f)); \ } #define printMsg(level, f) \ do { \ if (level <= verbosity) { \ printMsg_(level, (f)); \ } \ } while (0) #define debug(f) printMsg(lvlDebug, f) void warnOnce(bool & haveWarned, const format & f); extern void (*writeToStderr) (const unsigned char * buf, size_t count); /* Wrappers arount read()/write() that read/write exactly the requested number of bytes. */ void readFull(int fd, unsigned char * buf, size_t count); void writeFull(int fd, const unsigned char * buf, size_t count); MakeError(EndOfFile, Error) /* Read a file descriptor until EOF occurs. */ string drainFD(int fd); /* Automatic cleanup of resources. */ template <class T> struct AutoDeleteArray { T * p; AutoDeleteArray(T * p) : p(p) { } ~AutoDeleteArray() { delete [] p; } }; class AutoDelete { Path path; bool del; bool recursive; public: AutoDelete(const Path & p, bool recursive = true); ~AutoDelete(); void cancel(); }; class AutoCloseFD { int fd; public: AutoCloseFD(); AutoCloseFD(int fd); AutoCloseFD(const AutoCloseFD & fd); ~AutoCloseFD(); void operator =(int fd); operator int() const; void close(); bool isOpen(); int borrow(); }; class Pipe { public: AutoCloseFD readSide, writeSide; void create(); }; class AutoCloseDir { DIR * dir; public: AutoCloseDir(); AutoCloseDir(DIR * dir); ~AutoCloseDir(); void operator =(DIR * dir); operator DIR *(); }; class Pid { pid_t pid; bool separatePG; int killSignal; public: Pid(); ~Pid(); void operator =(pid_t pid); operator pid_t(); void kill(); int wait(bool block); void setSeparatePG(bool separatePG); void setKillSignal(int signal); }; /* Kill all processes running under the specified uid by sending them a SIGKILL. */ void killUser(uid_t uid); /* Run a program and return its stdout in a string (i.e., like the shell backtick operator). */ string runProgram(Path program, bool searchPath = false, const Strings & args = Strings()); /* Close all file descriptors except stdin, stdout, stderr, and those listed in the given set. Good practice in child processes. */ void closeMostFDs(const set<int> & exceptions); /* Wrapper around _exit() on Unix and ExitProcess() on Windows. (On Cygwin, _exit() doesn't seem to do the right thing.) */ void quickExit(int status); /* Common initialisation for setuid programs: clear the environment, sanitize file handles 0, 1 and 2. */ void setuidCleanup(); /* User interruption. */ extern volatile sig_atomic_t _isInterrupted; void _interrupted(); void inline checkInterrupt() { if (_isInterrupted) _interrupted(); } MakeError(Interrupted, BaseError) /* String packing / unpacking. */ string packStrings(const Strings & strings); Strings unpackStrings(const string & s); /* String tokenizer. */ Strings tokenizeString(const string & s, const string & separators = " \t\n\r"); /* Convert the exit status of a child as returned by wait() into an error string. */ string statusToString(int status); bool statusOk(int status); /* Parse a string into an integer. */ template<class N> bool string2Int(const string & s, N & n) { std::istringstream str(s); str >> n; return str && str.get() == EOF; } string int2String(int n); /* Return true iff `s' ends in `suffix'. */ bool hasSuffix(const string & s, const string & suffix); /* Exception handling in destructors: print an error message, then ignore the exception. */ void ignoreException(); /* STL functions such as sort() pass a binary function object around by value, so it gets cloned a lot. This is bad if the function object has state or is simply large. This adapter wraps the function object to simulate passing by reference. */ template<class F> struct binary_function_ref_adapter { F * p; binary_function_ref_adapter(F * _p) { p = _p; } typename F::result_type operator () ( const typename F::first_argument_type & x, const typename F::second_argument_type & y) { return (*p)(x, y); } }; } #endif /* !__UTIL_H */ <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <numeric> #include "glt/load_models.h" glt::ModelInfo::ModelInfo(size_t index_offset, size_t indices, size_t vert_offset) : index_offset(index_offset), indices(indices), vert_offset(vert_offset) {} bool glt::load_models(const std::vector<std::string> &model_files, SubBuffer &vert_buf, SubBuffer &elem_buf, BufferAllocator &allocator, std::unordered_map<std::string, ModelInfo> &elem_offsets) { using namespace glt; std::vector<tinyobj::shape_t> loaded_models; for (const auto &file : model_files){ std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err = tinyobj::LoadObj(shapes, materials, file.c_str()); if (!err.empty()){ std::cout << "Failed to load model " << file << " error: " << err << std::endl; return false; } std::cout << "loaded " << shapes.size() << " model(s) from " << file << ", name(s):\n"; for (const auto &s : shapes){ std::cout << "\t" << s.name << "\n"; } std::copy(shapes.begin(), shapes.end(), std::back_inserter(loaded_models)); } size_t total_elems = std::accumulate(loaded_models.begin(), loaded_models.end(), 0, [](const size_t &cur, const tinyobj::shape_t &s){ return cur + s.mesh.indices.size(); }); elem_buf = allocator.alloc(total_elems * sizeof(GLuint), sizeof(GLuint)); { unsigned int *elems = static_cast<unsigned int*>(elem_buf.map(GL_ELEMENT_ARRAY_BUFFER, GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT)); // Track our offset in the element count size_t prev_offset = 0; for (const auto &s : loaded_models){ elem_offsets[s.name] = ModelInfo{prev_offset, s.mesh.indices.size()}; std::copy(s.mesh.indices.begin(), s.mesh.indices.end(), elems + prev_offset); prev_offset += s.mesh.indices.size(); } elem_buf.unmap(GL_ELEMENT_ARRAY_BUFFER); } // We store 6 floats per element at the moment // Format is vec3 (pos), vec3 (normal), vec2 (texcoord) vert_buf = allocator.alloc(total_elems * 8 * sizeof(float)); { float *verts = static_cast<float*>(vert_buf.map(GL_ARRAY_BUFFER, GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT)); // Track our offset in the vertex buffer size_t i = 0; for (const auto &s : loaded_models){ elem_offsets[s.name].vert_offset = i / 8; for (auto p = s.mesh.positions.begin(), n = s.mesh.normals.begin(), t = s.mesh.texcoords.begin(); p != s.mesh.positions.end() && n != s.mesh.normals.end(); i += 8) { for (int k = 0; k < 3; ++k, ++p){ verts[i + k] = *p; } for (int k = 3; k < 6; ++k, ++n){ verts[i + k] = *n; } // Some models may not have/need texcoords if (t != s.mesh.texcoords.end()){ for (int k = 6; k < 8; ++k, ++t){ verts[i + k] = *t; } } } } vert_buf.unmap(GL_ARRAY_BUFFER); } return true; } std::ostream& operator<<(std::ostream &os, const glt::ModelInfo &m){ os << "glt::ModelInfo:" << "\n\tindex_offset: " << m.index_offset << "\n\tindices: " << m.indices << "\n\tvert_offset: " << m.vert_offset << "\n--------\n"; return os; } <commit_msg>Now also handle missing normals<commit_after>#include <iostream> #include <algorithm> #include <numeric> #include "glt/load_models.h" glt::ModelInfo::ModelInfo(size_t index_offset, size_t indices, size_t vert_offset) : index_offset(index_offset), indices(indices), vert_offset(vert_offset) {} bool glt::load_models(const std::vector<std::string> &model_files, SubBuffer &vert_buf, SubBuffer &elem_buf, BufferAllocator &allocator, std::unordered_map<std::string, ModelInfo> &elem_offsets) { using namespace glt; std::vector<tinyobj::shape_t> loaded_models; for (const auto &file : model_files){ std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err = tinyobj::LoadObj(shapes, materials, file.c_str()); if (!err.empty()){ std::cout << "Failed to load model " << file << " error: " << err << std::endl; return false; } std::cout << "loaded " << shapes.size() << " model(s) from " << file << ", name(s):\n"; for (const auto &s : shapes){ std::cout << "\t" << s.name << "\n"; } std::copy(shapes.begin(), shapes.end(), std::back_inserter(loaded_models)); } size_t total_elems = std::accumulate(loaded_models.begin(), loaded_models.end(), 0, [](const size_t &cur, const tinyobj::shape_t &s){ return cur + s.mesh.indices.size(); }); elem_buf = allocator.alloc(total_elems * sizeof(GLuint), sizeof(GLuint)); { unsigned int *elems = static_cast<unsigned int*>(elem_buf.map(GL_ELEMENT_ARRAY_BUFFER, GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT)); // Track our offset in the element count size_t prev_offset = 0; for (const auto &s : loaded_models){ elem_offsets[s.name] = ModelInfo{prev_offset, s.mesh.indices.size()}; std::copy(s.mesh.indices.begin(), s.mesh.indices.end(), elems + prev_offset); prev_offset += s.mesh.indices.size(); } elem_buf.unmap(GL_ELEMENT_ARRAY_BUFFER); } // We store 6 floats per element at the moment // Format is vec3 (pos), vec3 (normal), vec2 (texcoord) vert_buf = allocator.alloc(total_elems * 8 * sizeof(float)); { float *verts = static_cast<float*>(vert_buf.map(GL_ARRAY_BUFFER, GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT)); // Track our offset in the vertex buffer size_t i = 0; for (const auto &s : loaded_models){ elem_offsets[s.name].vert_offset = i / 8; for (auto p = s.mesh.positions.begin(), n = s.mesh.normals.begin(), t = s.mesh.texcoords.begin(); p != s.mesh.positions.end(); i += 8) { for (int k = 0; k < 3; ++k, ++p){ verts[i + k] = *p; } if (n != s.mesh.normals.end()){ for (int k = 3; k < 6; ++k, ++n){ verts[i + k] = *n; } } // Some models may not have/need texcoords if (t != s.mesh.texcoords.end()){ for (int k = 6; k < 8; ++k, ++t){ verts[i + k] = *t; } } } } vert_buf.unmap(GL_ARRAY_BUFFER); } return true; } std::ostream& operator<<(std::ostream &os, const glt::ModelInfo &m){ os << "glt::ModelInfo:" << "\n\tindex_offset: " << m.index_offset << "\n\tindices: " << m.indices << "\n\tvert_offset: " << m.vert_offset << "\n--------\n"; return os; } <|endoftext|>
<commit_before> #include <legato.h> #include <thread> #include <string> #include <list> #include <iostream> #ifndef MUST_BE_DEFINED #error MUST_BE_DEFINED was not defined. #endif COMPONENT_INIT { LE_INFO("Hello world, from thread 1."); std::thread newThread([]() { le_thread_InitLegatoThreadData("thread 2"); // This will crash if the Legato thread-specific data has not been initialized. le_thread_GetCurrent(); LE_INFO("Hello world, from %s.", le_thread_GetMyName()); le_thread_CleanupLegatoThreadData(); }); LE_INFO("Thead 2 stared, and waiting for it to complete."); newThread.join(); LE_INFO("Thead 2 ended, all done with init."); std::list<std::string> stuff; // C++ 11 for (auto s : stuff) { std::cout << "stuff: " << s << std::endl; } exit(EXIT_SUCCESS); } <commit_msg>Fix klocwork issues with uninitialized variables in the "apps" module.<commit_after> #include <legato.h> #include <thread> #include <string> #include <list> #include <iostream> #ifndef MUST_BE_DEFINED #error MUST_BE_DEFINED was not defined. #endif COMPONENT_INIT { LE_INFO("Hello world, from thread 1."); std::thread newThread([]() { le_thread_InitLegatoThreadData("thread 2"); // This will crash if the Legato thread-specific data has not been initialized. le_thread_GetCurrent(); LE_INFO("Hello world, from %s.", le_thread_GetMyName()); le_thread_CleanupLegatoThreadData(); }); LE_INFO("Thead 2 stared, and waiting for it to complete."); newThread.join(); LE_INFO("Thead 2 ended, all done with init."); std::list<std::string> stuff; // C++ 11 for (auto const &s : stuff) { std::cout << "stuff: " << s << std::endl; } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#pragma once #include "lubee/tests/test.hpp" #include "../random/convex2d.hpp" #include "../random/point2d.hpp" #include "../random/segment2d.hpp" #include "../random/circle2d.hpp" #include "../random/aabb2d.hpp" #include "../random/capsule2d.hpp" #include "../random/line2d.hpp" #include "../random/ray2d.hpp" #include "../random/triangle2d.hpp" namespace beat { namespace g2 { using lubee::RangeI; using lubee::RangeF; class Generator : public lubee::test::Random { private: using RInt = decltype(std::declval<lubee::test::Random>().mt().getUniformF<int>()); RInt _ri; using RFloat = decltype(std::declval<lubee::test::Random>().mt().getUniformF<float>()); RFloat _rf, _rp, _rcirr, _rcapr; public: void setPointRange(const RangeF& r) { _rp = mt().getUniformF<float>(r); } void setCircleRadius(const RangeF& r) { _rcirr = mt().getUniformF<float>(r); } void setCapsuleRadius(const RangeF& r) { _rcapr = mt().getUniformF<float>(r); } Generator(): _ri(mt().getUniformF<int>()), _rf(mt().getUniformF<float>()), _rp(mt().getUniformF<float>(RangeF{1e2f})), _rcirr(mt().getUniformF<float>(RangeF{0, 1e1f})), _rcapr(mt().getUniformF<float>(RangeF{0, 1e1f})) {} void genShape(Point& dst) { dst = genPoint(); } void genShape(Segment& dst) { dst = genSegment(); } void genShape(Line& dst) { dst = genLine(); } void genShape(Ray& dst) { dst = genRay(); } void genShape(AABB& dst) { dst = genAABB(); } void genShape(Triangle& dst) { dst = genTriangleArea(); } void genShape(Capsule& dst) { dst = genCapsule(); } void genShape(Circle& dst) { dst = genCircle(); } void genShape(Convex& dst) { dst = genConvex(); } Point genPoint() { return random::GenPoint(_rp); } Line genLine() { return random::GenLine(_rp); } Ray genRay() { return random::GenRay(_rp); } Segment genSegment() { return random::GenSegment(_rp); } Circle genCircle() { return random::GenCircle(_rp, _rcirr); } AABB genAABB() { return random::GenAABBArea(_rp, 1e-1f); } Capsule genCapsule() { return random::GenCapsule(_rp, _rcapr); } Vec2 genDir() { return frea::random::GenVecUnit<Vec2>(mt().getUniformF<float>()); } Triangle genTriangleArea() { return random::GenTriangleArea(_rp, 1e-1f); } Triangle genTriangle() { return random::GenTriangle(_rp); } Convex genConvex(int n=-1) { auto& mt = this->mt(); if(n < 0) { n = mt.getUniform<int>({3, 32+1}); } return random::GenConvexArea(_rp, n, 1e-1f); } int genInt(const RangeI& r) { return _ri(r); } float genFloat(const RangeF& r) { return _rf(r); } }; } } <commit_msg>Generate: Poseのランダム生成<commit_after>#pragma once #include "lubee/tests/test.hpp" #include "../random/convex2d.hpp" #include "../random/point2d.hpp" #include "../random/segment2d.hpp" #include "../random/circle2d.hpp" #include "../random/aabb2d.hpp" #include "../random/capsule2d.hpp" #include "../random/line2d.hpp" #include "../random/ray2d.hpp" #include "../random/triangle2d.hpp" #include "../random/pose2d.hpp" namespace beat { namespace g2 { using lubee::RangeI; using lubee::RangeF; class Generator : public lubee::test::Random { private: using RInt = decltype(std::declval<lubee::test::Random>().mt().getUniformF<int>()); RInt _ri; using RFloat = decltype(std::declval<lubee::test::Random>().mt().getUniformF<float>()); RFloat _rf, _rp, _rcirr, _rcapr, _rscale; public: void setPointRange(const RangeF& r) { _rp = mt().getUniformF<float>(r); } void setCircleRadius(const RangeF& r) { _rcirr = mt().getUniformF<float>(r); } void setCapsuleRadius(const RangeF& r) { _rcapr = mt().getUniformF<float>(r); } void setScalingRange(const RangeF& r) { _rscale = mt().getUniformF<float>(r); } Generator(): _ri(mt().getUniformF<int>()), _rf(mt().getUniformF<float>()), _rp(mt().getUniformF<float>(RangeF{1e2f})), _rcirr(mt().getUniformF<float>(RangeF{0, 1e1f})), _rcapr(mt().getUniformF<float>(RangeF{0, 1e1f})), _rscale(mt().getUniformF<float>(RangeF{1e-2f, 1e1f})) {} void genShape(Point& dst) { dst = genPoint(); } void genShape(Segment& dst) { dst = genSegment(); } void genShape(Line& dst) { dst = genLine(); } void genShape(Ray& dst) { dst = genRay(); } void genShape(AABB& dst) { dst = genAABB(); } void genShape(Triangle& dst) { dst = genTriangleArea(); } void genShape(Capsule& dst) { dst = genCapsule(); } void genShape(Circle& dst) { dst = genCircle(); } void genShape(Convex& dst) { dst = genConvex(); } void genShape(Pose& dst) { dst = genPose(); } Pose genPose() { return g2::random::GenPose(_rp, _rscale); } Point genPoint() { return random::GenPoint(_rp); } Line genLine() { return random::GenLine(_rp); } Ray genRay() { return random::GenRay(_rp); } Segment genSegment() { return random::GenSegment(_rp); } Circle genCircle() { return random::GenCircle(_rp, _rcirr); } AABB genAABB() { return random::GenAABBArea(_rp, 1e-1f); } Capsule genCapsule() { return random::GenCapsule(_rp, _rcapr); } Vec2 genDir() { return frea::random::GenVecUnit<Vec2>(mt().getUniformF<float>()); } Triangle genTriangleArea() { return random::GenTriangleArea(_rp, 1e-1f); } Triangle genTriangle() { return random::GenTriangle(_rp); } Convex genConvex(int n=-1) { auto& mt = this->mt(); if(n < 0) { n = mt.getUniform<int>({3, 32+1}); } return random::GenConvexArea(_rp, n, 1e-1f); } int genInt(const RangeI& r) { return _ri(r); } float genFloat(const RangeF& r) { return _rf(r); } }; } } <|endoftext|>
<commit_before>#pragma once #include "physics/inertia_tensor.hpp" #include "geometry/barycentre_calculator.hpp" #include "geometry/identity.hpp" #include "geometry/point.hpp" namespace principia { namespace physics { namespace internal_inertia_tensor { using geometry::Barycentre; using geometry::Identity; using geometry::SymmetricProduct; template<typename Frame> InertiaTensor<Frame>::InertiaTensor( Mass const& mass, R3x3Matrix<MomentOfInertia> const& coordinates, Position<Frame> const& centre_of_mass) : InertiaTensor(mass, MakeSymmetricBilinearForm(coordinates), centre_of_mass) {} template<typename Frame> R3Element<MomentOfInertia> InertiaTensor<Frame>::MomentsOfInertia() const { return R3Element<MomentOfInertia>(); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Rotate( Rotation<Frame, ToFrame> const& rotation) const { return InertiaTensor<ToFrame>(); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Rotate( Rotation<ToFrame, Frame> const& rotation) const { return InertiaTensor<ToFrame>(); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Translate( Position<Frame> const& point) const { static Identity<Frame, ToFrame> const identity{}; auto const translation = point - Frame::origin; auto const translated_form = form_ + 2 * mass_ * SymmetricProduct(translation, translation); auto const translated_centre_of_mass_displacement = centre_of_mass_ - point; return InertiaTensor<ToFrame>( mass_, identity(translated_form), ToFrame::origin + identity(translated_centre_of_mass_displacement)); } template<typename Frame> template<typename PrincipalAxesFrame> typename InertiaTensor<Frame>::PrincipalAxes<PrincipalAxesFrame> InertiaTensor<Frame>::Diagonalize() const { auto const eigensystem = form_.Diagonalize(); //TODO(phl): What happens to the points? reference_point_: identity; // centre_of_mass_: rotation. return {InertiaTensor<PrincipalAxesFrame>( mass_, eigensystem.form, reference_point_, centre_of_mass_), eigensystem.rotation}; } template<typename Frame> InertiaTensor<Frame>::InertiaTensor( Mass const& mass, SymmetricBilinearForm<MomentOfInertia, Frame> const& form, Position<Frame> const& centre_of_mass) : mass_(mass), form_(form), centre_of_mass_(centre_of_mass) {} template<typename Frame> SymmetricBilinearForm<MomentOfInertia, Frame> InertiaTensor<Frame>::MakeSymmetricBilinearForm( R3x3Matrix<MomentOfInertia> const& tensor) { return SymmetricBilinearForm<MomentOfInertia, Frame>( R3x3Matrix<MomentOfInertia>( {0.5 * (tensor(1, 1) + tensor(2, 2) - tensor(0, 0)), -tensor(0, 1), -tensor(0, 2)}, {-tensor(1, 0), 0.5 * (tensor(2, 2) + tensor(0, 0) - tensor(1, 1)), -tensor(1, 2)}, {-tensor(2, 0), -tensor(2, 1), 0.5 * (tensor(0, 0) + tensor(1, 1) - tensor(2, 2)) / 2})); } template<typename Frame> InertiaTensor<Frame> operator+(InertiaTensor<Frame> const& left, InertiaTensor<Frame> const& right) { CHECK_EQ(left.reference_point_, right.reference_point_); return InertiaTensor<Frame>(left.mass_ + right.mass_, left.form_ + right.form_, left.reference_point_, Barycentre<Position<Frame>, Mass>( {left.centre_of_mass_, right.centre_of_mass_}, {left.mass_, right.mass_})); } } // namespace internal_inertia_tensor } // namespace physics } // namespace principia<commit_msg>Rotation and diagonalization of the tensor.<commit_after>#pragma once #include "physics/inertia_tensor.hpp" #include "geometry/barycentre_calculator.hpp" #include "geometry/identity.hpp" #include "geometry/point.hpp" namespace principia { namespace physics { namespace internal_inertia_tensor { using geometry::Barycentre; using geometry::Identity; using geometry::SymmetricProduct; template<typename Frame> InertiaTensor<Frame>::InertiaTensor( Mass const& mass, R3x3Matrix<MomentOfInertia> const& coordinates, Position<Frame> const& centre_of_mass) : InertiaTensor(mass, MakeSymmetricBilinearForm(coordinates), centre_of_mass) {} template<typename Frame> R3Element<MomentOfInertia> InertiaTensor<Frame>::MomentsOfInertia() const { return R3Element<MomentOfInertia>(); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Rotate( Rotation<Frame, ToFrame> const& rotation) const { auto const centre_of_mass_displacement = centre_of_mass_ - Frame::origin; auto const rotated_centre_of_mass_displacement = rotation(centre_of_mass_displacement); return InertiaTensor<ToFrame>( mass_, rotation(form_), ToFrame::origin + rotated_centre_of_mass_displacement); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Rotate( Rotation<ToFrame, Frame> const& rotation) const { return Rotate(rotation.Inverse()); } template<typename Frame> template<typename ToFrame> InertiaTensor<ToFrame> InertiaTensor<Frame>::Translate( Position<Frame> const& point) const { static Identity<Frame, ToFrame> const identity{}; auto const translation = point - Frame::origin; auto const translated_form = form_ + 2 * mass_ * SymmetricProduct(translation, translation); auto const translated_centre_of_mass_displacement = centre_of_mass_ - point; return InertiaTensor<ToFrame>( mass_, identity(translated_form), ToFrame::origin + identity(translated_centre_of_mass_displacement)); } template<typename Frame> template<typename PrincipalAxesFrame> typename InertiaTensor<Frame>::PrincipalAxes<PrincipalAxesFrame> InertiaTensor<Frame>::Diagonalize() const { // Diagonalizing is possible in any frame, but it's only sensible in a frame // centred at the centre of mass. CHECK_EQ(Frame::origin, centre_of_mass_); auto const eigensystem = form_.Diagonalize(); return InertiaTensor<PrincipalAxesFrame>( mass_, eigensystem.form, PrincipalAxes::origin); } template<typename Frame> InertiaTensor<Frame>::InertiaTensor( Mass const& mass, SymmetricBilinearForm<MomentOfInertia, Frame> const& form, Position<Frame> const& centre_of_mass) : mass_(mass), form_(form), centre_of_mass_(centre_of_mass) {} template<typename Frame> SymmetricBilinearForm<MomentOfInertia, Frame> InertiaTensor<Frame>::MakeSymmetricBilinearForm( R3x3Matrix<MomentOfInertia> const& tensor) { return SymmetricBilinearForm<MomentOfInertia, Frame>( R3x3Matrix<MomentOfInertia>( {0.5 * (tensor(1, 1) + tensor(2, 2) - tensor(0, 0)), -tensor(0, 1), -tensor(0, 2)}, {-tensor(1, 0), 0.5 * (tensor(2, 2) + tensor(0, 0) - tensor(1, 1)), -tensor(1, 2)}, {-tensor(2, 0), -tensor(2, 1), 0.5 * (tensor(0, 0) + tensor(1, 1) - tensor(2, 2)) / 2})); } template<typename Frame> InertiaTensor<Frame> operator+(InertiaTensor<Frame> const& left, InertiaTensor<Frame> const& right) { CHECK_EQ(left.reference_point_, right.reference_point_); return InertiaTensor<Frame>(left.mass_ + right.mass_, left.form_ + right.form_, left.reference_point_, Barycentre<Position<Frame>, Mass>( {left.centre_of_mass_, right.centre_of_mass_}, {left.mass_, right.mass_})); } } // namespace internal_inertia_tensor } // namespace physics } // namespace principia<|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential Utility library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not 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 "gear_config.h" #include <fcntl.h> #include <semaphore.h> #include <sys/stat.h> #include <unistd.h> #include <cassert> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <util/signal.hpp> namespace datadifferential { namespace util { #define MAGIC_MEMORY 123569 bool SignalThread::is_shutdown() { bool ret; pthread_mutex_lock(&shutdown_mutex); ret= bool(__shutdown != SHUTDOWN_RUNNING); pthread_mutex_unlock(&shutdown_mutex); return ret; } void SignalThread::set_shutdown(shutdown_t arg) { pthread_mutex_lock(&shutdown_mutex); __shutdown= arg; pthread_mutex_unlock(&shutdown_mutex); if (arg == SHUTDOWN_GRACEFUL) { if (pthread_kill(thread, SIGUSR2) == 0) { void *retval; pthread_join(thread, &retval); } } } shutdown_t SignalThread::get_shutdown() { shutdown_t local; pthread_mutex_lock(&shutdown_mutex); local= __shutdown; pthread_mutex_unlock(&shutdown_mutex); return local; } void SignalThread::post() { sem_post(lock); } void SignalThread::test() { (void)magic_memory; assert(magic_memory == MAGIC_MEMORY); assert(sigismember(&set, SIGABRT)); assert(sigismember(&set, SIGINT)); assert(sigismember(&set, SIGQUIT)); assert(sigismember(&set, SIGTERM)); assert(sigismember(&set, SIGUSR2)); } void SignalThread::sighup(signal_callback_fn* arg) { _sighup= arg; } std::string SignalThread::random_lock_name(std::string::size_type len = 10) { static auto& chrs = "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; thread_local static std::mt19937 rg{std::random_device{}()}; thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2); // convenient to named semaphore definition // http://man7.org/linux/man-pages/man7/sem_overview.7.html std::string s{"/"}; s.reserve(len--); while (len--) { s += chrs[pick(rg)]; } return s; } void SignalThread::sighup() { if (_sighup) { _sighup(); } } SignalThread::~SignalThread() { if (not is_shutdown()) { set_shutdown(SHUTDOWN_GRACEFUL); } #if 0 if (pthread_equal(thread, pthread_self()) != 0 and (pthread_kill(thread, 0) == ESRCH) == true) { void *retval; pthread_join(thread, &retval); } #endif sem_close(lock); } extern "C" { static void *sig_thread(void *arg) { SignalThread *context= (SignalThread*)arg; context->test(); context->post(); while (context->get_shutdown() == SHUTDOWN_RUNNING) { int sig; if (context->wait(sig) == -1) { std::cerr << "sigwait() returned errno:" << strerror(errno) << std::endl; continue; } switch (sig) { case SIGUSR2: break; case SIGHUP: context->sighup(); break; case SIGABRT: case SIGINT: case SIGQUIT: case SIGTERM: if (context->is_shutdown() == false) { context->set_shutdown(SHUTDOWN_FORCED); } if (context->exit_on_signal()) { exit(EXIT_SUCCESS); } break; default: std::cerr << "Signal handling thread got unexpected signal " << strsignal(sig) << std::endl; break; } } return NULL; } } SignalThread::SignalThread(bool exit_on_signal_arg) : _exit_on_signal(exit_on_signal_arg), magic_memory(MAGIC_MEMORY), __shutdown(SHUTDOWN_RUNNING), thread(pthread_self()), _sighup(NULL) { pthread_mutex_init(&shutdown_mutex, NULL); sigemptyset(&set); sigaddset(&set, SIGABRT); sigaddset(&set, SIGINT); sigaddset(&set, SIGQUIT); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR2); } bool SignalThread::setup() { set_shutdown(SHUTDOWN_RUNNING); int error; if ((error= pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0) { std::cerr << "pthread_sigmask() died during pthread_sigmask(" << strerror(error) << ")" << std::endl; return false; } if ((error= pthread_create(&thread, NULL, &sig_thread, this)) != 0) { std::cerr << "pthread_create() died during pthread_create(" << strerror(error) << ")" << std::endl; return false; } const char * lock_name = random_lock_name().c_str(); lock = sem_open(lock_name, O_CREAT, S_IRUSR|S_IWUSR, 0); if (lock == SEM_FAILED) { std::cerr << "WARNING: sem_open failed(" << strerror(errno) << ")" << " when opening lock '" << lock_name << "'." << std::endl; } else { sem_wait(lock); } return true; } } /* namespace util */ } /* namespace datadifferential */ <commit_msg>add O_EXCL to sem_open's flags<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential Utility library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not 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 "gear_config.h" #include <fcntl.h> #include <semaphore.h> #include <sys/stat.h> #include <unistd.h> #include <cassert> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <util/signal.hpp> namespace datadifferential { namespace util { #define MAGIC_MEMORY 123569 bool SignalThread::is_shutdown() { bool ret; pthread_mutex_lock(&shutdown_mutex); ret= bool(__shutdown != SHUTDOWN_RUNNING); pthread_mutex_unlock(&shutdown_mutex); return ret; } void SignalThread::set_shutdown(shutdown_t arg) { pthread_mutex_lock(&shutdown_mutex); __shutdown= arg; pthread_mutex_unlock(&shutdown_mutex); if (arg == SHUTDOWN_GRACEFUL) { if (pthread_kill(thread, SIGUSR2) == 0) { void *retval; pthread_join(thread, &retval); } } } shutdown_t SignalThread::get_shutdown() { shutdown_t local; pthread_mutex_lock(&shutdown_mutex); local= __shutdown; pthread_mutex_unlock(&shutdown_mutex); return local; } void SignalThread::post() { sem_post(lock); } void SignalThread::test() { (void)magic_memory; assert(magic_memory == MAGIC_MEMORY); assert(sigismember(&set, SIGABRT)); assert(sigismember(&set, SIGINT)); assert(sigismember(&set, SIGQUIT)); assert(sigismember(&set, SIGTERM)); assert(sigismember(&set, SIGUSR2)); } void SignalThread::sighup(signal_callback_fn* arg) { _sighup= arg; } std::string SignalThread::random_lock_name(std::string::size_type len = 10) { static auto& chrs = "0123456789" "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; thread_local static std::mt19937 rg{std::random_device{}()}; thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2); // convenient to named semaphore definition // http://man7.org/linux/man-pages/man7/sem_overview.7.html std::string s{"/"}; s.reserve(len--); while (len--) { s += chrs[pick(rg)]; } return s; } void SignalThread::sighup() { if (_sighup) { _sighup(); } } SignalThread::~SignalThread() { if (not is_shutdown()) { set_shutdown(SHUTDOWN_GRACEFUL); } #if 0 if (pthread_equal(thread, pthread_self()) != 0 and (pthread_kill(thread, 0) == ESRCH) == true) { void *retval; pthread_join(thread, &retval); } #endif sem_close(lock); } extern "C" { static void *sig_thread(void *arg) { SignalThread *context= (SignalThread*)arg; context->test(); context->post(); while (context->get_shutdown() == SHUTDOWN_RUNNING) { int sig; if (context->wait(sig) == -1) { std::cerr << "sigwait() returned errno:" << strerror(errno) << std::endl; continue; } switch (sig) { case SIGUSR2: break; case SIGHUP: context->sighup(); break; case SIGABRT: case SIGINT: case SIGQUIT: case SIGTERM: if (context->is_shutdown() == false) { context->set_shutdown(SHUTDOWN_FORCED); } if (context->exit_on_signal()) { exit(EXIT_SUCCESS); } break; default: std::cerr << "Signal handling thread got unexpected signal " << strsignal(sig) << std::endl; break; } } return NULL; } } SignalThread::SignalThread(bool exit_on_signal_arg) : _exit_on_signal(exit_on_signal_arg), magic_memory(MAGIC_MEMORY), __shutdown(SHUTDOWN_RUNNING), thread(pthread_self()), _sighup(NULL) { pthread_mutex_init(&shutdown_mutex, NULL); sigemptyset(&set); sigaddset(&set, SIGABRT); sigaddset(&set, SIGINT); sigaddset(&set, SIGQUIT); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR2); } bool SignalThread::setup() { set_shutdown(SHUTDOWN_RUNNING); int error; if ((error= pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0) { std::cerr << "pthread_sigmask() died during pthread_sigmask(" << strerror(error) << ")" << std::endl; return false; } if ((error= pthread_create(&thread, NULL, &sig_thread, this)) != 0) { std::cerr << "pthread_create() died during pthread_create(" << strerror(error) << ")" << std::endl; return false; } const char * lock_name = random_lock_name().c_str(); lock = sem_open(lock_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, 0); if (lock == SEM_FAILED) { std::cerr << "WARNING: sem_open failed(" << strerror(errno) << ")" << " when opening lock '" << lock_name << "'." << std::endl; } else { sem_wait(lock); } return true; } } /* namespace util */ } /* namespace datadifferential */ <|endoftext|>
<commit_before>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_tracker(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; create_directory("./tmp1_tracker", ec); std::ofstream file("./tmp1_tracker/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url); add_torrent_params addp; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp1_tracker"; torrent_handle h = s->add_torrent(addp); test_sleep(2000); // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1); delete s; // we should have announced the stopped event now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2); stop_tracker(); stop_web_server(); } <commit_msg>add unit test to make sure the next tier is tried in the tracker list when the one ahead of it fails<commit_after>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_tracker(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; create_directory("./tmp1_tracker", ec); std::ofstream file("./tmp1_tracker/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url); add_torrent_params addp; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp1_tracker"; torrent_handle h = s->add_torrent(addp); test_sleep(2000); // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1); delete s; // we should have announced the stopped event now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2); // ======================================== // test that we move on to try the next tier if the first one fails // ======================================== s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask); sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = false; sett.tracker_completion_timeout = 4; sett.tracker_receive_timeout = 2; s->set_settings(sett); create_directory("./tmp2_tracker", ec); file.open("./tmp2_tracker/temporary"); t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); // this should fail snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce"); t->add_tracker(tracker_url, 0); // and this should fail snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce"); t->add_tracker(tracker_url, 1); // this should be announced to // udp trackers are prioritized if they're on the same host as an http one // so this must be before the http one on 127.0.0.1 snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 2); // and this should not be announced to (since the one before it succeeded) snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 3); prev_udp_announces = g_udp_tracker_requests; prev_http_announces = g_http_tracker_requests; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp2_tracker"; h = s->add_torrent(addp); for (int i = 0; i < 10; ++i) { test_sleep(1000); print_alerts(*s, "s"); if (g_udp_tracker_requests == prev_udp_announces + 1) break; } test_sleep(1000); TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces); delete s; stop_tracker(); stop_web_server(); return 0; } <|endoftext|>
<commit_before>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_tracker(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; create_directory("./tmp1_tracker", ec); std::ofstream file("./tmp1_tracker/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url); add_torrent_params addp; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp1_tracker"; torrent_handle h = s->add_torrent(addp); test_sleep(2000); // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1); delete s; // we should have announced the stopped event now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2); // ======================================== // test that we move on to try the next tier if the first one fails // ======================================== s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask); sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = false; sett.tracker_completion_timeout = 2; sett.tracker_receive_timeout = 1; s->set_settings(sett); create_directory("./tmp2_tracker", ec); file.open("./tmp2_tracker/temporary"); t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); // this should fail snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce"); t->add_tracker(tracker_url, 0); // and this should fail snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce"); t->add_tracker(tracker_url, 1); // this should be announced to // udp trackers are prioritized if they're on the same host as an http one // so this must be before the http one on 127.0.0.1 snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 2); // and this should not be announced to (since the one before it succeeded) snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 3); prev_udp_announces = g_udp_tracker_requests; prev_http_announces = g_http_tracker_requests; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp2_tracker"; h = s->add_torrent(addp); for (int i = 0; i < 10; ++i) { print_alerts(*s, "s"); test_sleep(1000); if (g_udp_tracker_requests == prev_udp_announces + 1) break; } test_sleep(1000); TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces); delete s; stop_tracker(); stop_web_server(); return 0; } <commit_msg>added more diagnostics to test_tracker.cpp<commit_after>#include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/alert.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include <fstream> using namespace libtorrent; int test_main() { int http_port = start_web_server(); int udp_port = start_tracker(); int prev_udp_announces = g_udp_tracker_requests; int prev_http_announces = g_http_tracker_requests; int const alert_mask = alert::all_categories & ~alert::progress_notification & ~alert::stats_notification; session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask); session_settings sett; sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = true; s->set_settings(sett); error_code ec; create_directory("./tmp1_tracker", ec); std::ofstream file("./tmp1_tracker/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); char tracker_url[200]; snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 0); snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 1); add_torrent_params addp; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp1_tracker"; torrent_handle h = s->add_torrent(addp); for (int i = 0; i < 100; ++i) { print_alerts(*s, "s"); test_sleep(100); if (g_udp_tracker_requests == prev_udp_announces + 1 && g_http_tracker_requests == prev_http_announces + 1) break; } // we should have announced to the tracker by now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); // we should have announced the stopped event now TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2); TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2); // ======================================== // test that we move on to try the next tier if the first one fails // ======================================== s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask); sett.half_open_limit = 1; sett.announce_to_all_trackers = true; sett.announce_to_all_tiers = false; sett.tracker_completion_timeout = 2; sett.tracker_receive_timeout = 1; s->set_settings(sett); create_directory("./tmp2_tracker", ec); file.open("./tmp2_tracker/temporary"); t = ::create_torrent(&file, 16 * 1024, 13, false); file.close(); // this should fail snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce"); t->add_tracker(tracker_url, 0); // and this should fail snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce"); t->add_tracker(tracker_url, 1); // this should be announced to // udp trackers are prioritized if they're on the same host as an http one // so this must be before the http one on 127.0.0.1 snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port); t->add_tracker(tracker_url, 2); // and this should not be announced to (since the one before it succeeded) snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port); t->add_tracker(tracker_url, 3); prev_udp_announces = g_udp_tracker_requests; prev_http_announces = g_http_tracker_requests; addp.paused = false; addp.auto_managed = false; addp.ti = t; addp.save_path = "./tmp2_tracker"; h = s->add_torrent(addp); for (int i = 0; i < 10; ++i) { print_alerts(*s, "s"); test_sleep(1000); if (g_udp_tracker_requests == prev_udp_announces + 1) break; } test_sleep(1000); TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1); TEST_EQUAL(g_http_tracker_requests, prev_http_announces); fprintf(stderr, "destructing session\n"); delete s; fprintf(stderr, "done\n"); stop_tracker(); stop_web_server(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2009-2012 Red Hat, 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. */ //condor includes #include "condor_common.h" #include "condor_config.h" #include "condor_attributes.h" #include "condor_debug.h" #include "stl_string_utils.h" // C++ includes // enable for debugging classad to ostream // watch out for unistd clash //#include <sstream> //local includes #include "LocatorObject.h" #include "AviaryConversionMacros.h" #include "AviaryUtils.h" #include "EndpointPublisher.h" using namespace std; using namespace aviary::locator; using namespace aviary::util; namespace aviary { namespace locator { LocatorObject locator; }} LocatorObject::LocatorObject () { m_publishing = param_boolean("AVIARY_PUBLISH_LOCATION",FALSE); } LocatorObject::~LocatorObject() { } bool LocatorObject::isPublishing() { return m_publishing; } string LocatorObject::getPool() { return getPoolName(); } void LocatorObject::locate(const string& name, const string& major, const string& minor, bool partials, EndpointSetType& matches) { dprintf(D_FULLDEBUG,"LocatorObject::locate: %s/%s/%s\n",name.c_str(),major.c_str(),minor.c_str()); for (EndpointMapType::iterator it = m_endpoints.begin(); it != m_endpoints.end(); it++) { if (major == (*it).second.MajorType || major == "ANY") { if (minor == (*it).second.MinorType || minor.empty()) { if (!partials && name == (*it).second.Name) { matches.insert((*it).second); } else if (string::npos != (*it).second.Name.find(name)) { matches.insert((*it).second); } } } } } void LocatorObject::update (const ClassAd& ad) { Endpoint ep_new = createEndpoint(ad); EndpointMapType::iterator it = m_endpoints.find(ep_new.Name); if (it == m_endpoints.end()) { m_endpoints[ep_new.Name] = ep_new; dprintf(D_FULLDEBUG,"LocatorObject: added endpoint '%s'\n",ep_new.EndpointUri.c_str()); } else { Endpoint& ep_old = (*it).second; if (DebugFlags & D_FULLDEBUG) { stringstream sold,snew; sold << ep_old; snew << ep_new; dprintf(D_FULLDEBUG,"LocatorObject: comparing endpoint '%s' to '%s'\n",sold.str().c_str(),snew.str().c_str()); } if (ep_new == ep_old) { // found it so reset its heartbeat flag ep_old.missed_updates = 0; } else { // assume a new process has taken over this endpoint m_endpoints.erase(it); m_endpoints[ep_new.Name] = ep_new; dprintf(D_FULLDEBUG,"LocatorObject: replaced endpoint for '%s'\n",ep_new.Name.c_str()); } } // debug if (IsFulldebug(D_FULLDEBUG)) { const_cast<ClassAd*>(&ad)->dPrint(D_FULLDEBUG|D_NOHEADER); } } void LocatorObject::invalidate(const ClassAd& ad) { string name; if (!ad.LookupString(ATTR_NAME,name)){ dprintf(D_ALWAYS,"LocatorObject: invalidate ad doesn't contain %s attribute!\n",ATTR_NAME); return; } EndpointMapType::iterator it = m_endpoints.find(name); if (it != m_endpoints.end()) { dprintf(D_FULLDEBUG,"LocatorObject: removing endpoint '%s'\n",(*it).first.c_str()); m_endpoints.erase(it); } } void LocatorObject::invalidateAll() { m_endpoints.clear(); } Endpoint LocatorObject::createEndpoint(const compat_classad::ClassAd& ad) { Endpoint m_stats; MGMT_DECLARATIONS; STRING(MyAddress); STRING(Name); STRING(Machine); STRING(EndpointUri); STRING(MajorType); STRING(MinorType); m_stats.missed_updates = 0; return m_stats; } void LocatorObject::pruneMissingEndpoints(int max_misses) { // walk our collection of endpoints, marking & removing as needed for (EndpointMapType::iterator it = m_endpoints.begin(); m_endpoints.end() != it; it++) { (*it).second.missed_updates++; if ((*it).second.missed_updates > max_misses) { dprintf(D_FULLDEBUG,"LocatorObject: pruning endpoint '%s'\n",(*it).first.c_str()); m_endpoints.erase(it); } } }<commit_msg>Fix for debug changes in aviary locator.<commit_after>/* * Copyright 2009-2012 Red Hat, 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. */ //condor includes #include "condor_common.h" #include "condor_config.h" #include "condor_attributes.h" #include "condor_debug.h" #include "stl_string_utils.h" // C++ includes // enable for debugging classad to ostream // watch out for unistd clash //#include <sstream> //local includes #include "LocatorObject.h" #include "AviaryConversionMacros.h" #include "AviaryUtils.h" #include "EndpointPublisher.h" using namespace std; using namespace aviary::locator; using namespace aviary::util; namespace aviary { namespace locator { LocatorObject locator; }} LocatorObject::LocatorObject () { m_publishing = param_boolean("AVIARY_PUBLISH_LOCATION",FALSE); } LocatorObject::~LocatorObject() { } bool LocatorObject::isPublishing() { return m_publishing; } string LocatorObject::getPool() { return getPoolName(); } void LocatorObject::locate(const string& name, const string& major, const string& minor, bool partials, EndpointSetType& matches) { dprintf(D_FULLDEBUG,"LocatorObject::locate: %s/%s/%s\n",name.c_str(),major.c_str(),minor.c_str()); for (EndpointMapType::iterator it = m_endpoints.begin(); it != m_endpoints.end(); it++) { if (major == (*it).second.MajorType || major == "ANY") { if (minor == (*it).second.MinorType || minor.empty()) { if (!partials && name == (*it).second.Name) { matches.insert((*it).second); } else if (string::npos != (*it).second.Name.find(name)) { matches.insert((*it).second); } } } } } void LocatorObject::update (const ClassAd& ad) { Endpoint ep_new = createEndpoint(ad); EndpointMapType::iterator it = m_endpoints.find(ep_new.Name); if (it == m_endpoints.end()) { m_endpoints[ep_new.Name] = ep_new; dprintf(D_FULLDEBUG,"LocatorObject: added endpoint '%s'\n",ep_new.EndpointUri.c_str()); } else { Endpoint& ep_old = (*it).second; if (IsDebugLevel( D_FULLDEBUG)) { stringstream sold,snew; sold << ep_old; snew << ep_new; dprintf(D_FULLDEBUG,"LocatorObject: comparing endpoint '%s' to '%s'\n",sold.str().c_str(),snew.str().c_str()); } if (ep_new == ep_old) { // found it so reset its heartbeat flag ep_old.missed_updates = 0; } else { // assume a new process has taken over this endpoint m_endpoints.erase(it); m_endpoints[ep_new.Name] = ep_new; dprintf(D_FULLDEBUG,"LocatorObject: replaced endpoint for '%s'\n",ep_new.Name.c_str()); } } // debug if (IsFulldebug(D_FULLDEBUG)) { const_cast<ClassAd*>(&ad)->dPrint(D_FULLDEBUG|D_NOHEADER); } } void LocatorObject::invalidate(const ClassAd& ad) { string name; if (!ad.LookupString(ATTR_NAME,name)){ dprintf(D_ALWAYS,"LocatorObject: invalidate ad doesn't contain %s attribute!\n",ATTR_NAME); return; } EndpointMapType::iterator it = m_endpoints.find(name); if (it != m_endpoints.end()) { dprintf(D_FULLDEBUG,"LocatorObject: removing endpoint '%s'\n",(*it).first.c_str()); m_endpoints.erase(it); } } void LocatorObject::invalidateAll() { m_endpoints.clear(); } Endpoint LocatorObject::createEndpoint(const compat_classad::ClassAd& ad) { Endpoint m_stats; MGMT_DECLARATIONS; STRING(MyAddress); STRING(Name); STRING(Machine); STRING(EndpointUri); STRING(MajorType); STRING(MinorType); m_stats.missed_updates = 0; return m_stats; } void LocatorObject::pruneMissingEndpoints(int max_misses) { // walk our collection of endpoints, marking & removing as needed for (EndpointMapType::iterator it = m_endpoints.begin(); m_endpoints.end() != it; it++) { (*it).second.missed_updates++; if ((*it).second.missed_updates > max_misses) { dprintf(D_FULLDEBUG,"LocatorObject: pruning endpoint '%s'\n",(*it).first.c_str()); m_endpoints.erase(it); } } } <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0); tiramisu::var i("i", 0, N), j("j", 0, N); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j); S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i0); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0); S0.store_in(&buf0, {i ,j}); tiramisu::codegen({&buf0}, "build/generated_fct_test_118.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; } <commit_msg>Fix test<commit_after>#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0); tiramisu::var i("i", 0, N), j("j", 0, N); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1))); S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i0); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0); S0.store_in(&buf0, {i ,j}); tiramisu::codegen({&buf0}, "build/generated_fct_test_118.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <uvw.hpp> TEST(FsEvent, TODO) { auto loop = uvw::Loop::getDefault(); auto handle = uvw::FsEventHandle::create(loop); handle = nullptr; // TODO } <commit_msg>Test fs event (#89)<commit_after>#include <gtest/gtest.h> #include <uvw.hpp> TEST(FsEvent, Functionalities) { const std::string filename = std::string{TARGET_FS_EVENT_DIR} + std::string{"/test.file"}; auto loop = uvw::Loop::getDefault(); auto handle = loop->resource<uvw::FsEventHandle>(); auto request = loop->resource<uvw::FileReq>(); bool checkFsEventEvent = false; handle->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); request->on<uvw::ErrorEvent>([](const auto &, auto &) { FAIL(); }); handle->on<uvw::FsEventEvent>([&checkFsEventEvent](const auto &event, auto &hndl) { ASSERT_FALSE(checkFsEventEvent); ASSERT_EQ(std::string{event.filename}, std::string{"test.file"}); checkFsEventEvent = true; hndl.stop(); hndl.close(); ASSERT_TRUE(hndl.closing()); }); request->on<uvw::FsEvent<uvw::FileReq::Type::WRITE>>([](const auto &, auto &req) { req.close(); }); request->on<uvw::FsEvent<uvw::FileReq::Type::OPEN>>([](const auto &, auto &req) { req.write(std::unique_ptr<char[]>{new char[1]{ 42 }}, 1, 0); }); handle->start(std::string{TARGET_FS_EVENT_DIR}, uvw::FsEventHandle::Event::RECURSIVE); request->open(filename, O_CREAT | O_RDWR | O_TRUNC, 0644); ASSERT_EQ(handle->path(), std::string{TARGET_FS_EVENT_DIR}); ASSERT_TRUE(handle->active()); ASSERT_FALSE(handle->closing()); loop->run(); ASSERT_TRUE(checkFsEventEvent); } <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bip38.hpp" #include <algorithm> #include <string> #include <boost/test/unit_test.hpp> #include <bitcoin/bitcoin.hpp> using namespace bc; using namespace bc::wallet; // TODO: implement testnet tests. #ifndef ENABLE_TESTNET BOOST_AUTO_TEST_SUITE(bip38_tests) /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__create_token) static void test_create_token(/* const bip38_vector& vector */) { // TODO } // TODO: add test vectors for create_token. BOOST_AUTO_TEST_CASE(bip38__create_token__always__throws) { test_create_token(/* vector */); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__create_key_pair) // TODO: create compressed vector(s). static void test_create_key_pair(const bip38_vector& vector) { bip38::token token; BOOST_REQUIRE(decode_base58(token, vector.token)); bip38::seed seed; BOOST_REQUIRE(decode_base16(seed, vector.seed)); ec_point point; bip38::public_key public_key; bip38::private_key private_key; BOOST_REQUIRE(bip38::create_key_pair(private_key, public_key, point, token, seed, vector.version, vector.compressed)); BOOST_REQUIRE_EQUAL(encode_base58(public_key), vector.public_key); BOOST_REQUIRE_EQUAL(encode_base58(private_key), vector.private_key); } BOOST_AUTO_TEST_CASE(bip38__create_key_pair__vector_8__expected) { test_create_key_pair(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__create_key_pair__vector_9__expected) { test_create_key_pair(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() #ifdef WITH_ICU /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__encrypt) static void test_encrypt(const bip38_vector& vector) { ec_secret secret; BOOST_REQUIRE(decode_base16(secret, vector.ec_secret)); bip38::private_key private_key; bip38::encrypt(private_key, secret, vector.passphrase, vector.version, vector.compressed); BOOST_REQUIRE_EQUAL(encode_base58(private_key), vector.private_key); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_0__expected) { test_encrypt(bip38_test_vector0); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_1__expected) { test_encrypt(bip38_test_vector1); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_2_compressed__expected) { test_encrypt(bip38_test_vector2); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_3_compressed__expected) { test_encrypt(bip38_test_vector3); } // #3 from: github.com/bitcoin/bips/blob/master/bip-0038.mediawiki#no-compression-no-ec-multiply BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_unicode___expected) { // This vector encodes as the passphrase as base16. bip38_vector vector; vector.version = 0x00; vector.compressed = false; vector.passphrase = "cf92cc8100f0909080f09f92a9"; vector.ec_secret = "64eeab5f9be2a01a8365a579511eb3373c87c40da6d2a25f05bda68fe077b66e"; vector.private_key = "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"; ////vector.address = "16ktGzmfrurhbhi6JGqsMWf7TyqK9HNAeF"; data_chunk not_normalized; BOOST_REQUIRE(decode_base16(not_normalized, vector.passphrase)); std::string passphrase(not_normalized.begin(), not_normalized.end()); const auto normal = to_normal_nfc_form(passphrase); data_chunk normalized(normal.size()); std::copy(normal.begin(), normal.end(), normalized.begin()); BOOST_REQUIRE_EQUAL(encode_base16(normalized), "cf9300f0909080f09f92a9"); ec_secret secret; BOOST_REQUIRE(decode_base16(secret, vector.ec_secret)); bip38::private_key private_key; bip38::encrypt(private_key, secret, passphrase, vector.version, vector.compressed); BOOST_REQUIRE_EQUAL(encode_base58(private_key), vector.private_key); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__decrypt1) // TODO: create compressed + multiplied vector(s). static void test_decrypt1(const bip38_vector& vector) { bip38::private_key private_key; BOOST_REQUIRE(decode_base58(private_key, vector.private_key)); ec_secret secret; uint8_t version; bool compressed; BOOST_REQUIRE(bip38::decrypt(secret, version, compressed, private_key, vector.passphrase)); BOOST_REQUIRE_EQUAL(encode_base16(secret), vector.ec_secret); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_0__expected) { test_decrypt1(bip38_test_vector0); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_1__expected) { test_decrypt1(bip38_test_vector1); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_2_compressed__expected) { test_decrypt1(bip38_test_vector2); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_3_compressed__expected) { test_decrypt1(bip38_test_vector3); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_4_multiplied__expected) { test_decrypt1(bip38_test_vector4); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_5_multiplied__expected) { test_decrypt1(bip38_test_vector5); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_6_multiplied__expected) { test_decrypt1(bip38_test_vector6); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_7_multiplied__expected) { test_decrypt1(bip38_test_vector7); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_8_multiplied__expected) { test_decrypt1(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_9_multiplied__expected) { test_decrypt1(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__decrypt2) // TODO: create compressed vector(s). static void test_decrypt2(const bip38_vector& vector) { bip38::public_key public_key; BOOST_REQUIRE(decode_base58(public_key, vector.public_key)); ec_point point; uint8_t out_version; BOOST_REQUIRE(bip38::decrypt(point, out_version, public_key, vector.passphrase)); BOOST_REQUIRE_EQUAL(out_version, vector.version); static const auto version = 0x00; const auto expected = payment_address(version, point).to_string(); BOOST_REQUIRE_EQUAL(expected, vector.address); } BOOST_AUTO_TEST_CASE(bip38__decrypt2__vector_8__expected) { test_decrypt2(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__decrypt2__vector_9__expected) { test_decrypt2(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// #endif // WITH_ICU BOOST_AUTO_TEST_SUITE_END() #endif // !ENABLE_TESTNET <commit_msg>Implement parsers for each bip38 data type, fix create_key_pair.<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bip38.hpp" #include <algorithm> #include <string> #include <boost/test/unit_test.hpp> #include <bitcoin/bitcoin.hpp> using namespace bc; using namespace bc::wallet; // TODO: implement testnet tests. #ifndef ENABLE_TESTNET BOOST_AUTO_TEST_SUITE(bip38_tests) /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__create_token) static void test_create_token(/* const bip38_vector& vector */) { // TODO } // TODO: add test vectors for create_token. BOOST_AUTO_TEST_CASE(bip38__create_token__always__throws) { test_create_token(/* vector */); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__create_key_pair) // TODO: create compressed vector(s). static void test_create_key_pair(const bip38_vector& vector) { bip38::token token; BOOST_REQUIRE(decode_base58(token, vector.token)); bip38::seed seed; BOOST_REQUIRE(decode_base16(seed, vector.seed)); ec_point point; bip38::public_key public_key; bip38::private_key private_key; BOOST_REQUIRE(bip38::create_key_pair(private_key, public_key, point, token, seed, vector.version, vector.compressed)); BOOST_CHECK_EQUAL(encode_base58(private_key), vector.private_key); BOOST_CHECK_EQUAL(encode_base58(public_key), vector.public_key); } BOOST_AUTO_TEST_CASE(bip38__create_key_pair__vector_8__expected) { test_create_key_pair(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__create_key_pair__vector_9__expected) { test_create_key_pair(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() #ifdef WITH_ICU /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__encrypt) static void test_encrypt(const bip38_vector& vector) { ec_secret secret; BOOST_REQUIRE(decode_base16(secret, vector.ec_secret)); bip38::private_key private_key; bip38::encrypt(private_key, secret, vector.passphrase, vector.version, vector.compressed); BOOST_REQUIRE_EQUAL(encode_base58(private_key), vector.private_key); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_0__expected) { test_encrypt(bip38_test_vector0); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_1__expected) { test_encrypt(bip38_test_vector1); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_2_compressed__expected) { test_encrypt(bip38_test_vector2); } BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_3_compressed__expected) { test_encrypt(bip38_test_vector3); } // #3 from: github.com/bitcoin/bips/blob/master/bip-0038.mediawiki#no-compression-no-ec-multiply BOOST_AUTO_TEST_CASE(bip38__encrypt__vector_unicode___expected) { // This vector encodes as the passphrase as base16. bip38_vector vector; vector.version = 0x00; vector.compressed = false; vector.passphrase = "cf92cc8100f0909080f09f92a9"; vector.ec_secret = "64eeab5f9be2a01a8365a579511eb3373c87c40da6d2a25f05bda68fe077b66e"; vector.private_key = "6PRW5o9FLp4gJDDVqJQKJFTpMvdsSGJxMYHtHaQBF3ooa8mwD69bapcDQn"; ////vector.address = "16ktGzmfrurhbhi6JGqsMWf7TyqK9HNAeF"; data_chunk not_normalized; BOOST_REQUIRE(decode_base16(not_normalized, vector.passphrase)); std::string passphrase(not_normalized.begin(), not_normalized.end()); const auto normal = to_normal_nfc_form(passphrase); data_chunk normalized(normal.size()); std::copy(normal.begin(), normal.end(), normalized.begin()); BOOST_REQUIRE_EQUAL(encode_base16(normalized), "cf9300f0909080f09f92a9"); ec_secret secret; BOOST_REQUIRE(decode_base16(secret, vector.ec_secret)); bip38::private_key private_key; bip38::encrypt(private_key, secret, passphrase, vector.version, vector.compressed); BOOST_REQUIRE_EQUAL(encode_base58(private_key), vector.private_key); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__decrypt1) // TODO: create compressed + multiplied vector(s). static void test_decrypt1(const bip38_vector& vector) { bip38::private_key private_key; BOOST_REQUIRE(decode_base58(private_key, vector.private_key)); ec_secret secret; uint8_t version; bool compressed; BOOST_REQUIRE(bip38::decrypt(secret, version, compressed, private_key, vector.passphrase)); BOOST_REQUIRE_EQUAL(encode_base16(secret), vector.ec_secret); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_0__expected) { test_decrypt1(bip38_test_vector0); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_1__expected) { test_decrypt1(bip38_test_vector1); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_2_compressed__expected) { test_decrypt1(bip38_test_vector2); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_3_compressed__expected) { test_decrypt1(bip38_test_vector3); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_4_multiplied__expected) { test_decrypt1(bip38_test_vector4); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_5_multiplied__expected) { test_decrypt1(bip38_test_vector5); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_6_multiplied__expected) { test_decrypt1(bip38_test_vector6); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_7_multiplied__expected) { test_decrypt1(bip38_test_vector7); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_8_multiplied__expected) { test_decrypt1(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__decrypt1__vector_9_multiplied__expected) { test_decrypt1(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_SUITE(bip38__decrypt2) // TODO: create compressed vector(s). static void test_decrypt2(const bip38_vector& vector) { bip38::public_key public_key; BOOST_REQUIRE(decode_base58(public_key, vector.public_key)); ec_point point; uint8_t version; BOOST_REQUIRE(bip38::decrypt(point, version, public_key, vector.passphrase)); BOOST_REQUIRE_EQUAL(version, vector.version); const auto expected = payment_address(0x00, point).to_string(); BOOST_REQUIRE_EQUAL(expected, vector.address); } BOOST_AUTO_TEST_CASE(bip38__decrypt2__vector_8__expected) { test_decrypt2(bip38_test_vector8); } BOOST_AUTO_TEST_CASE(bip38__decrypt2__vector_9__expected) { test_decrypt2(bip38_test_vector9); } BOOST_AUTO_TEST_SUITE_END() /////////////////////////////////////////////////////////////////////////////// #endif // WITH_ICU BOOST_AUTO_TEST_SUITE_END() #endif // !ENABLE_TESTNET <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2015, Stuart W Baker * 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. * * \file TivaEEPROMEmulation.hxx * This file implements Tiva compatible EEPROM emulation in FLASH. * * @author Stuart W. Baker * @date 21 January 2015 */ #include "EEPROM.hxx" #include "driverlib/rom.h" #include "driverlib/rom_map.h" #include "driverlib/flash.h" /** Emulates EEPROM in FLASH for the Tiva platform. * @todo there is a known bug whereby the ADDRESS_SPACE cannot be larger than * (block size - 4). */ class TivaEEPROMEmulation : public EEPROM { public: /** Product family. We use this to determine details, such as sector size, * specific to a given family and relevant to the agorithm. */ enum Family { TM4C123 = 1024, /**< Tiva TM4C123 devices, 1K block size */ TM4C129 = 1024 * 16 /**< Tiva TM4C129 devices, 16K block Size */ }; /** Constructor. * @param name device name * @param file_size maximum file size that we can grow to. */ TivaEEPROMEmulation(const char *name, size_t file_size); /** Destructor. */ ~TivaEEPROMEmulation(); /** Write to the EEPROM. NOTE!!! This is not necessarily atomic across * byte boundaries in the case of power loss. The user should take this * into account as it relates to data integrity of a whole block. * @ref index index within EEPROM address space to start write * @ref buf data to write * @ref len length in bytes of data to write */ void write(unsigned int index, const void *buf, size_t len) OVERRIDE; /** Read from the EEPROM. * @ref index index within EEPROM address space to start read * @ref buf location to post read data * @ref len length in bytes of data to read */ void read(unsigned int index, void *buf, size_t len) OVERRIDE; private: /** Total FLASH memory size to use for EEPROM Emulation. Must be at least * 2 block large and at least 4x the total amount of EEPROM address space * that will be emulated. Larger sizes will result in greater endurance. */ static const size_t FLASH_SIZE; /** @ref Family that device belongs to */ static const Family FAMILY; /** Address space in terms of bytes to emulate, must be less than 2^16. */ static const size_t ADDRESS_SPACE; /** Shadow the EEPROM data in RAM. This will increase read performance at * the expense of additional RAM usage. */ static const bool SHADOW_IN_RAM; /** magic marker for an intact block */ static const uint32_t MAGIC_INTACT; /** magic marker for a block that we are transitioning to intact */ static const uint32_t MAGIC_DIRTY; /** magic marker for a used block */ static const uint32_t MAGIC_USED; /** magic marker for an erased block */ static const uint32_t MAGIC_ERASED; /** Raw FLASH for storing EEPROM emulated data. */ static const uint16_t* const raw; /** Write to the EEPROM on a native word boundary. * @ref index word within EEPROM address space to write * @ref data data to write */ void write_word(unsigned int index, const uint16_t data); /** Read from the EEPROM on a native word boundary. * @ref index word within EEPROM address space to read * @ref data location to place read data */ void read_word(unsigned int index, uint16_t *data); /** Get the next active block pointer. * @return a pointer to the beginning of the next active block */ uint32_t *next_active() { return ((activeIndex + 1) < block_count()) ? block(activeIndex + 1) : block(0); } /** Get the active block pointer. * @return a pointer to the beginning of the active block */ uint32_t *active() { return block(activeIndex); } /** Get the block index data pointer. * @param i index of block to get a data pointer to * @return a pointer to the beginning of the block index data */ uint32_t *block(int i) { return (uint32_t*)(raw + ((FAMILY >> 1) * i)); } /** Get the block index. * @param i index of block to get a pointer to * @return a pointer to the beginning of the block index */ int block_index(uint32_t *block_address) { return ((uintptr_t)block_address - (uintptr_t)raw) / FAMILY; } /** Total number of FLASH blocks being used for emulation. * @return number of FLASH blocks being used for emulation */ int block_count() { return FLASH_SIZE / FAMILY; } /** Total number of EEPROM slots in a FLASH block. * @return number of EEPROM slots in a FLASH block. */ int slot_count() { return (FAMILY / sizeof(uint32_t)) - 1; } /** Simple TivaWare abstraction for FlashErase() API. * @param address the start address of the flash block to be erased */ void flash_erase(void *address) { HASSERT(((uintptr_t)address % FAMILY) == 0); HASSERT((uintptr_t)address >= (uintptr_t)raw); HASSERT((uintptr_t)address < (uintptr_t)(raw + (FLASH_SIZE >> 1))); MAP_FlashErase((uint32_t)address); } /** Simple TivaWare abstraction for FlashProgram() API. * @param data a pointer to the data to be programmed * @param address the starting address in flash to be programmed. * Must be a multiple of four. * @param count the number of bytes to be programmed. * Must be a multiple of four */ void flash_program(uint32_t *data, void *address, uint32_t count) { HASSERT(((uintptr_t)address % 4) == 0); HASSERT((uintptr_t)address >= (uintptr_t)raw); HASSERT((uintptr_t)address < (uintptr_t)(raw + (FLASH_SIZE >> 1))); HASSERT((count % 4) == 0); MAP_FlashProgram(data, (uint32_t)address, count); } /** pointer to RAM for shadowing EEPROM. */ uint16_t *shadow; /** index of the active block */ int activeIndex; /** number of available slots for new data */ size_t available; /** Default constructor. */ TivaEEPROMEmulation(); DISALLOW_COPY_AND_ASSIGN(TivaEEPROMEmulation); }; <commit_msg>Add include guards<commit_after>/** \copyright * Copyright (c) 2015, Stuart W Baker * 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. * * \file TivaEEPROMEmulation.hxx * This file implements Tiva compatible EEPROM emulation in FLASH. * * @author Stuart W. Baker * @date 21 January 2015 */ #ifndef _FREERTOS_DRIVERS_TI_TIVAEEPROMEMULATION_HXX_ #define _FREERTOS_DRIVERS_TI_TIVAEEPROMEMULATION_HXX_ #include "EEPROM.hxx" #include "driverlib/rom.h" #include "driverlib/rom_map.h" #include "driverlib/flash.h" /** Emulates EEPROM in FLASH for the Tiva platform. * @todo there is a known bug whereby the ADDRESS_SPACE cannot be larger than * (block size - 4). */ class TivaEEPROMEmulation : public EEPROM { public: /** Product family. We use this to determine details, such as sector size, * specific to a given family and relevant to the agorithm. */ enum Family { TM4C123 = 1024, /**< Tiva TM4C123 devices, 1K block size */ TM4C129 = 1024 * 16 /**< Tiva TM4C129 devices, 16K block Size */ }; /** Constructor. * @param name device name * @param file_size maximum file size that we can grow to. */ TivaEEPROMEmulation(const char *name, size_t file_size); /** Destructor. */ ~TivaEEPROMEmulation(); /** Write to the EEPROM. NOTE!!! This is not necessarily atomic across * byte boundaries in the case of power loss. The user should take this * into account as it relates to data integrity of a whole block. * @ref index index within EEPROM address space to start write * @ref buf data to write * @ref len length in bytes of data to write */ void write(unsigned int index, const void *buf, size_t len) OVERRIDE; /** Read from the EEPROM. * @ref index index within EEPROM address space to start read * @ref buf location to post read data * @ref len length in bytes of data to read */ void read(unsigned int index, void *buf, size_t len) OVERRIDE; private: /** Total FLASH memory size to use for EEPROM Emulation. Must be at least * 2 block large and at least 4x the total amount of EEPROM address space * that will be emulated. Larger sizes will result in greater endurance. */ static const size_t FLASH_SIZE; /** @ref Family that device belongs to */ static const Family FAMILY; /** Address space in terms of bytes to emulate, must be less than 2^16. */ static const size_t ADDRESS_SPACE; /** Shadow the EEPROM data in RAM. This will increase read performance at * the expense of additional RAM usage. */ static const bool SHADOW_IN_RAM; /** magic marker for an intact block */ static const uint32_t MAGIC_INTACT; /** magic marker for a block that we are transitioning to intact */ static const uint32_t MAGIC_DIRTY; /** magic marker for a used block */ static const uint32_t MAGIC_USED; /** magic marker for an erased block */ static const uint32_t MAGIC_ERASED; /** Raw FLASH for storing EEPROM emulated data. */ static const uint16_t* const raw; /** Write to the EEPROM on a native word boundary. * @ref index word within EEPROM address space to write * @ref data data to write */ void write_word(unsigned int index, const uint16_t data); /** Read from the EEPROM on a native word boundary. * @ref index word within EEPROM address space to read * @ref data location to place read data */ void read_word(unsigned int index, uint16_t *data); /** Get the next active block pointer. * @return a pointer to the beginning of the next active block */ uint32_t *next_active() { return ((activeIndex + 1) < block_count()) ? block(activeIndex + 1) : block(0); } /** Get the active block pointer. * @return a pointer to the beginning of the active block */ uint32_t *active() { return block(activeIndex); } /** Get the block index data pointer. * @param i index of block to get a data pointer to * @return a pointer to the beginning of the block index data */ uint32_t *block(int i) { return (uint32_t*)(raw + ((FAMILY >> 1) * i)); } /** Get the block index. * @param i index of block to get a pointer to * @return a pointer to the beginning of the block index */ int block_index(uint32_t *block_address) { return ((uintptr_t)block_address - (uintptr_t)raw) / FAMILY; } /** Total number of FLASH blocks being used for emulation. * @return number of FLASH blocks being used for emulation */ int block_count() { return FLASH_SIZE / FAMILY; } /** Total number of EEPROM slots in a FLASH block. * @return number of EEPROM slots in a FLASH block. */ int slot_count() { return (FAMILY / sizeof(uint32_t)) - 1; } /** Simple TivaWare abstraction for FlashErase() API. * @param address the start address of the flash block to be erased */ void flash_erase(void *address) { HASSERT(((uintptr_t)address % FAMILY) == 0); HASSERT((uintptr_t)address >= (uintptr_t)raw); HASSERT((uintptr_t)address < (uintptr_t)(raw + (FLASH_SIZE >> 1))); MAP_FlashErase((uint32_t)address); } /** Simple TivaWare abstraction for FlashProgram() API. * @param data a pointer to the data to be programmed * @param address the starting address in flash to be programmed. * Must be a multiple of four. * @param count the number of bytes to be programmed. * Must be a multiple of four */ void flash_program(uint32_t *data, void *address, uint32_t count) { HASSERT(((uintptr_t)address % 4) == 0); HASSERT((uintptr_t)address >= (uintptr_t)raw); HASSERT((uintptr_t)address < (uintptr_t)(raw + (FLASH_SIZE >> 1))); HASSERT((count % 4) == 0); MAP_FlashProgram(data, (uint32_t)address, count); } /** pointer to RAM for shadowing EEPROM. */ uint16_t *shadow; /** index of the active block */ int activeIndex; /** number of available slots for new data */ size_t available; /** Default constructor. */ TivaEEPROMEmulation(); DISALLOW_COPY_AND_ASSIGN(TivaEEPROMEmulation); }; #endif /* _FREERTOS_DRIVERS_TI_TIVAEEPROMEMULATION_HXX_ */ <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /************************************************************************************************** *** This file was autogenerated from GrOverdrawFragmentProcessor.fp; do not modify. **************************************************************************************************/ #include "GrOverdrawFragmentProcessor.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramBuilder.h" #include "GrTexture.h" #include "SkSLCPP.h" #include "SkSLUtil.h" class GrGLSLOverdrawFragmentProcessor : public GrGLSLFragmentProcessor { public: GrGLSLOverdrawFragmentProcessor() {} void emitCode(EmitArgs& args) override { GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder; const GrOverdrawFragmentProcessor& _outer = args.fFp.cast<GrOverdrawFragmentProcessor>(); (void)_outer; auto color0 = _outer.color0(); (void)color0; auto color1 = _outer.color1(); (void)color1; auto color2 = _outer.color2(); (void)color2; auto color3 = _outer.color3(); (void)color3; auto color4 = _outer.color4(); (void)color4; auto color5 = _outer.color5(); (void)color5; fragBuilder->codeAppendf( "half alpha = half(255.0 * float(%s.w));\nif (float(alpha) < 0.5) {\n %s = " "half4(%f, %f, %f, %f);\n} else if (float(alpha) < 1.5) {\n %s = half4(%f, %f, " "%f, %f);\n} else if (float(alpha) < 2.5) {\n %s = half4(%f, %f, %f, %f);\n} " "else if (float(alpha) < 3.5) {\n %s = half4(%f, %f, %f, %f);\n} else if " "(float(alpha) < 4.5) {\n %s = half4(%f, %f, %f, %f);\n} else {\n %s = " "half4(%f, %f, %f, %f);\n}\n", args.fInputColor, args.fOutputColor, SkGetPackedR32(_outer.color0()) / 255.0, SkGetPackedG32(_outer.color0()) / 255.0, SkGetPackedB32(_outer.color0()) / 255.0, SkGetPackedA32(_outer.color0()) / 255.0, args.fOutputColor, SkGetPackedR32(_outer.color1()) / 255.0, SkGetPackedG32(_outer.color1()) / 255.0, SkGetPackedB32(_outer.color1()) / 255.0, SkGetPackedA32(_outer.color1()) / 255.0, args.fOutputColor, SkGetPackedR32(_outer.color2()) / 255.0, SkGetPackedG32(_outer.color2()) / 255.0, SkGetPackedB32(_outer.color2()) / 255.0, SkGetPackedA32(_outer.color2()) / 255.0, args.fOutputColor, SkGetPackedR32(_outer.color3()) / 255.0, SkGetPackedG32(_outer.color3()) / 255.0, SkGetPackedB32(_outer.color3()) / 255.0, SkGetPackedA32(_outer.color3()) / 255.0, args.fOutputColor, SkGetPackedR32(_outer.color4()) / 255.0, SkGetPackedG32(_outer.color4()) / 255.0, SkGetPackedB32(_outer.color4()) / 255.0, SkGetPackedA32(_outer.color4()) / 255.0, args.fOutputColor, SkGetPackedR32(_outer.color5()) / 255.0, SkGetPackedG32(_outer.color5()) / 255.0, SkGetPackedB32(_outer.color5()) / 255.0, SkGetPackedA32(_outer.color5()) / 255.0); } private: void onSetData(const GrGLSLProgramDataManager& pdman, const GrFragmentProcessor& _proc) override {} }; GrGLSLFragmentProcessor* GrOverdrawFragmentProcessor::onCreateGLSLInstance() const { return new GrGLSLOverdrawFragmentProcessor(); } void GrOverdrawFragmentProcessor::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {} bool GrOverdrawFragmentProcessor::onIsEqual(const GrFragmentProcessor& other) const { const GrOverdrawFragmentProcessor& that = other.cast<GrOverdrawFragmentProcessor>(); (void)that; if (fColor0 != that.fColor0) return false; if (fColor1 != that.fColor1) return false; if (fColor2 != that.fColor2) return false; if (fColor3 != that.fColor3) return false; if (fColor4 != that.fColor4) return false; if (fColor5 != that.fColor5) return false; return true; } GrOverdrawFragmentProcessor::GrOverdrawFragmentProcessor(const GrOverdrawFragmentProcessor& src) : INHERITED(kGrOverdrawFragmentProcessor_ClassID, src.optimizationFlags()) , fColor0(src.fColor0) , fColor1(src.fColor1) , fColor2(src.fColor2) , fColor3(src.fColor3) , fColor4(src.fColor4) , fColor5(src.fColor5) {} std::unique_ptr<GrFragmentProcessor> GrOverdrawFragmentProcessor::clone() const { return std::unique_ptr<GrFragmentProcessor>(new GrOverdrawFragmentProcessor(*this)); } <commit_msg>removed GrOverdrawFragmentProcessor.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd 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 */ /** * @file src/helpers/creds-socket/creds-socket-inner.cpp * @author Radoslaw Bartosiak <r.bartosiak@samsung.com> * @author Aleksander Zdyb <a.zdyb@samsung.com> * @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com> * @version 1.0 * @brief Implementation of internal libcynara-creds-socket functions */ #include <errno.h> #include <string> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <cynara-error.h> #include "creds-socket-inner.h" int getClientSmackLabel(int socketFd, char **client) { char dummy; int ret; socklen_t length = 1; char *result; ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERSEC, &dummy, &length); if ((ret < 0) && (errno != ERANGE)) return CYNARA_API_INVALID_PARAM; result = static_cast<char*>(calloc(length + 1, sizeof(char))); if (result == nullptr) return CYNARA_API_OUT_OF_MEMORY; ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERSEC, result, &length); if (ret < 0) { free(result); return CYNARA_API_INVALID_PARAM; } *client = result; return CYNARA_API_SUCCESS; } #define GET_CRED(SOCK, RESULT, CRED) \ struct ucred credentials; \ int ret = getCredentials(SOCK, &credentials); \ if (ret < 0) \ return ret; \ \ *RESULT = strdup(std::to_string(credentials.CRED).c_str()); \ if (*RESULT == nullptr) \ return CYNARA_API_OUT_OF_MEMORY; \ \ return CYNARA_API_SUCCESS; \ int getClientPid(int socketFd, char **client) { GET_CRED(socketFd, client, pid) } int getUserId(int socketFd, char **user) { GET_CRED(socketFd, user, uid) } int getUserGid(int socketFd, char **user) { GET_CRED(socketFd, user, gid) } int getCredentials(int socketFd, struct ucred *credentials) { if (credentials == nullptr) return CYNARA_API_UNKNOWN_ERROR; int ret; socklen_t length = sizeof(struct ucred); ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERCRED, credentials, &length); if (ret < 0) { switch (errno) { case EBADF: case ENOTSOCK: return CYNARA_API_INVALID_PARAM; default: return CYNARA_API_UNKNOWN_ERROR; } } return CYNARA_API_SUCCESS; } int getPid(int socketFd, pid_t *pid) { struct ucred credentials; int ret = getCredentials(socketFd, &credentials); if (ret < 0) return ret; *pid = credentials.pid; return CYNARA_API_SUCCESS; } <commit_msg>Fix catching exceptions in socket helper functions<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd 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 */ /** * @file src/helpers/creds-socket/creds-socket-inner.cpp * @author Radoslaw Bartosiak <r.bartosiak@samsung.com> * @author Aleksander Zdyb <a.zdyb@samsung.com> * @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com> * @version 1.0 * @brief Implementation of internal libcynara-creds-socket functions */ #include <cerrno> #include <cstring> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <exceptions/TryCatch.h> #include <cynara-error.h> #include "creds-socket-inner.h" int getClientSmackLabel(int socketFd, char **client) { char dummy; int ret; socklen_t length = 1; char *result; ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERSEC, &dummy, &length); if ((ret < 0) && (errno != ERANGE)) return CYNARA_API_INVALID_PARAM; result = static_cast<char*>(calloc(length + 1, sizeof(char))); if (result == nullptr) return CYNARA_API_OUT_OF_MEMORY; ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERSEC, result, &length); if (ret < 0) { free(result); return CYNARA_API_INVALID_PARAM; } *client = result; return CYNARA_API_SUCCESS; } #define GET_CRED(SOCK, RESULT, CRED) \ return Cynara::tryCatch([&]() { \ struct ucred credentials; \ int ret = getCredentials(SOCK, &credentials); \ if (ret < 0) \ return ret; \ \ *RESULT = strdup(std::to_string(credentials.CRED).c_str()); \ if (*RESULT == nullptr) \ return CYNARA_API_OUT_OF_MEMORY; \ \ return CYNARA_API_SUCCESS; \ }); int getClientPid(int socketFd, char **client) { GET_CRED(socketFd, client, pid) } int getUserId(int socketFd, char **user) { GET_CRED(socketFd, user, uid) } int getUserGid(int socketFd, char **user) { GET_CRED(socketFd, user, gid) } int getCredentials(int socketFd, struct ucred *credentials) { if (credentials == nullptr) return CYNARA_API_UNKNOWN_ERROR; int ret; socklen_t length = sizeof(struct ucred); ret = getsockopt(socketFd, SOL_SOCKET, SO_PEERCRED, credentials, &length); if (ret < 0) { switch (errno) { case EBADF: case ENOTSOCK: return CYNARA_API_INVALID_PARAM; default: return CYNARA_API_UNKNOWN_ERROR; } } return CYNARA_API_SUCCESS; } int getPid(int socketFd, pid_t *pid) { struct ucred credentials; int ret = getCredentials(socketFd, &credentials); if (ret < 0) return ret; *pid = credentials.pid; return CYNARA_API_SUCCESS; } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_dataframe /// \notebook -draw /// This tutorial illustrates how NanoAOD files can be processed with ROOT /// dataframes. The NanoAOD-like input file is filled with events from /// CMS OpenData containing muon candidates from 2011 data /// ([DOI: 10.7483/OPENDATA.CMS.RZ34.QR6N](http://opendata.cern.ch/record/17)). /// The script matches muon pairs /// and produces an histogram of the dimuon mass spectrum showing resonances /// up to the Z mass. /// /// \macro_image /// \macro_code /// /// \date August 2018 /// \author Stefan Wunsch (KIT, CERN) #include "ROOT/RDataFrame.hxx" #include "ROOT/RVec.hxx" #include "TCanvas.h" #include "TH1D.h" #include "TLatex.h" #include "TLorentzVector.h" #include "TStyle.h" using namespace ROOT::VecOps; void df102_NanoAODDimuonAnalysis() { // Enable multi-threading ROOT::EnableImplicitMT(); // Create dataframe from NanoAOD file ROOT::RDataFrame df("Events", "http://root.cern.ch/files/NanoAOD_DoubleMuon_CMS2011OpenData.root"); // Select events with more than two muons auto df_filtered = df.Filter("nMuon>=2", "More than two muons"); // Find muon pair with highest pt and opposite charge auto find_pair = [](const RVec<float> &pt, const RVec<int> &charge) { // Get indices that sort the muon pts in descending order const auto idx = Reverse(Argsort(pt)); // Find muon with second-highest pt and opposite charge const auto i1 = idx[0]; for (size_t i = 1; i < idx.size(); i++) { const auto i2 = idx[i]; if (charge[i1] != charge[i2]) { return RVec<size_t>({i1, i2}); } } // Return empty selection if no candidate matches return RVec<size_t>({}); }; auto df_pair = df_filtered.Define("Muon_pair", find_pair, {"Muon_pt", "Muon_charge"}) .Filter("Muon_pair.size() == 2", "Found valid pair"); // Compute invariant mass of the di-muon system auto compute_mass = [](RVec<float> &pt, RVec<float> &eta, RVec<float> &phi, RVec<float> &mass, RVec<size_t> &idx) { // Compose four-vectors of both muons TLorentzVector p1; const auto i1 = idx[0]; p1.SetPtEtaPhiM(pt[i1], eta[i1], phi[i1], mass[i1]); TLorentzVector p2; const auto i2 = idx[1]; p2.SetPtEtaPhiM(pt[i2], eta[i2], phi[i2], mass[i2]); // Add four-vectors to build di-muon system and return the invariant mass return (p1 + p2).M(); }; auto df_mass = df_pair.Define("Dimuon_mass", compute_mass, {"Muon_pt", "Muon_eta", "Muon_phi", "Muon_mass", "Muon_pair"}); // Produce histogram of di-muon mass spectrum auto h = df_mass.Histo1D({"Dimuon_mass", "Dimuon_mass", 20000, 0.25, 300}, "Dimuon_mass") .GetValue(); // Make plot gStyle->SetOptStat(0); gStyle->SetTextFont(42); auto c = new TCanvas("c", "c", 800, 600); c->SetLogx(); c->SetLogy(); h.SetTitle(""); h.GetXaxis()->SetTitle("Invariant di-muon mass (GeV)"); h.GetXaxis()->SetTitleSize(0.04); h.GetYaxis()->SetTitle("N_{Events}"); h.GetYaxis()->SetTitleSize(0.04); h.Draw(); TLatex label; label.SetNDC(true); label.DrawLatex(0.175, 0.740, "#eta"); label.DrawLatex(0.205, 0.785, "#rho,#omega"); label.DrawLatex(0.270, 0.750, "#phi"); label.DrawLatex(0.400, 0.800, "J/#psi"); label.DrawLatex(0.415, 0.680, "#psi'"); label.DrawLatex(0.485, 0.760, "Y(1,2,3S)"); label.DrawLatex(0.755, 0.620, "Z"); label.DrawLatex(0.170, 0.350, "#bf{CMS Open Data}"); label.DrawLatex(0.170, 0.275, "#bf{#sqrt{s} = 7 TeV}"); label.DrawLatex(0.170, 0.200, "#bf{L_{int} = 2.4 fb^{-1}}"); label.SetTextSize(0.032); label.DrawLatex(0.10, 0.920, "Run2011A Double Muon Dataset (DOI: 10.7483/OPENDATA.CMS.RZ34.QR6N)"); c->SaveAs("nanoaod_dimuon_spectrum.pdf"); } int main() { df102_NanoAODDimuonAnalysis(); } <commit_msg>Display the pdf file generated by the macro.<commit_after>/// \file /// \ingroup tutorial_dataframe /// \notebook -draw /// This tutorial illustrates how NanoAOD files can be processed with ROOT /// dataframes. The NanoAOD-like input file is filled with events from /// CMS OpenData containing muon candidates from 2011 data /// ([DOI: 10.7483/OPENDATA.CMS.RZ34.QR6N](http://opendata.cern.ch/record/17)). /// The script matches muon pairs /// and produces an histogram of the dimuon mass spectrum showing resonances /// up to the Z mass. /// /// \macro_image (nanoaod_dimuon_spectrum.pdf) /// \macro_code /// /// \date August 2018 /// \author Stefan Wunsch (KIT, CERN) #include "ROOT/RDataFrame.hxx" #include "ROOT/RVec.hxx" #include "TCanvas.h" #include "TH1D.h" #include "TLatex.h" #include "TLorentzVector.h" #include "TStyle.h" using namespace ROOT::VecOps; void df102_NanoAODDimuonAnalysis() { // Enable multi-threading ROOT::EnableImplicitMT(); // Create dataframe from NanoAOD file ROOT::RDataFrame df("Events", "http://root.cern.ch/files/NanoAOD_DoubleMuon_CMS2011OpenData.root"); // Select events with more than two muons auto df_filtered = df.Filter("nMuon>=2", "More than two muons"); // Find muon pair with highest pt and opposite charge auto find_pair = [](const RVec<float> &pt, const RVec<int> &charge) { // Get indices that sort the muon pts in descending order const auto idx = Reverse(Argsort(pt)); // Find muon with second-highest pt and opposite charge const auto i1 = idx[0]; for (size_t i = 1; i < idx.size(); i++) { const auto i2 = idx[i]; if (charge[i1] != charge[i2]) { return RVec<size_t>({i1, i2}); } } // Return empty selection if no candidate matches return RVec<size_t>({}); }; auto df_pair = df_filtered.Define("Muon_pair", find_pair, {"Muon_pt", "Muon_charge"}) .Filter("Muon_pair.size() == 2", "Found valid pair"); // Compute invariant mass of the di-muon system auto compute_mass = [](RVec<float> &pt, RVec<float> &eta, RVec<float> &phi, RVec<float> &mass, RVec<size_t> &idx) { // Compose four-vectors of both muons TLorentzVector p1; const auto i1 = idx[0]; p1.SetPtEtaPhiM(pt[i1], eta[i1], phi[i1], mass[i1]); TLorentzVector p2; const auto i2 = idx[1]; p2.SetPtEtaPhiM(pt[i2], eta[i2], phi[i2], mass[i2]); // Add four-vectors to build di-muon system and return the invariant mass return (p1 + p2).M(); }; auto df_mass = df_pair.Define("Dimuon_mass", compute_mass, {"Muon_pt", "Muon_eta", "Muon_phi", "Muon_mass", "Muon_pair"}); // Produce histogram of di-muon mass spectrum auto h = df_mass.Histo1D({"Dimuon_mass", "Dimuon_mass", 20000, 0.25, 300}, "Dimuon_mass") .GetValue(); // Make plot gStyle->SetOptStat(0); gStyle->SetTextFont(42); auto c = new TCanvas("c", "c", 800, 600); c->SetLogx(); c->SetLogy(); h.SetTitle(""); h.GetXaxis()->SetTitle("Invariant di-muon mass (GeV)"); h.GetXaxis()->SetTitleSize(0.04); h.GetYaxis()->SetTitle("N_{Events}"); h.GetYaxis()->SetTitleSize(0.04); h.Draw(); TLatex label; label.SetNDC(true); label.DrawLatex(0.175, 0.740, "#eta"); label.DrawLatex(0.205, 0.785, "#rho,#omega"); label.DrawLatex(0.270, 0.750, "#phi"); label.DrawLatex(0.400, 0.800, "J/#psi"); label.DrawLatex(0.415, 0.680, "#psi'"); label.DrawLatex(0.485, 0.760, "Y(1,2,3S)"); label.DrawLatex(0.755, 0.620, "Z"); label.DrawLatex(0.170, 0.350, "#bf{CMS Open Data}"); label.DrawLatex(0.170, 0.275, "#bf{#sqrt{s} = 7 TeV}"); label.DrawLatex(0.170, 0.200, "#bf{L_{int} = 2.4 fb^{-1}}"); label.SetTextSize(0.032); label.DrawLatex(0.10, 0.920, "Run2011A Double Muon Dataset (DOI: 10.7483/OPENDATA.CMS.RZ34.QR6N)"); c->SaveAs("nanoaod_dimuon_spectrum.pdf"); } int main() { df102_NanoAODDimuonAnalysis(); } <|endoftext|>
<commit_before>// Unit Test Framework Includes #include "UnitTest++.h" #include <cstdlib> // File To Test #include "sll.h" using namespace UnitTest; //----------------------------------------------------------------------------- // Begin Unit Tests //----------------------------------------------------------------------------- namespace { //------------------------------------------------------------------------- // Test sll_new function //------------------------------------------------------------------------- TEST(Verify_sll_new_returns_newly_allocated_empty_list) { sll_t* list = sll_new(); CHECK( NULL != list ); CHECK( NULL == list->head ); CHECK( NULL == list->tail ); free( list ); } //------------------------------------------------------------------------- // Test sll_new_node function //------------------------------------------------------------------------- TEST(Verify_sll_new_node_returns_newly_allocated_node_with_given_contents) { int stuff = 0; sll_node_t* node = sll_new_node( &stuff ); CHECK( NULL != node ); CHECK( &stuff == node->contents ); CHECK( NULL == node->next ); free( node ); } //------------------------------------------------------------------------- // Test sll_free function //------------------------------------------------------------------------- TEST(Verify_sll_free_does_nothing_on_null_pointer) { sll_free( NULL, 0 ); } TEST(Verify_sll_free_frees_the_given_empty_list) { sll_t* list = sll_new(); sll_free( list, 0 ); } TEST(Verify_sll_free_frees_the_given_list_including_nodes) { sll_t* list = sll_new(); list->head = sll_new_node(NULL); list->tail = list->head; sll_free( list, 0 ); } TEST(Verify_sll_free_frees_the_given_list_including_nodes_and_node_contents) { sll_t* list = sll_new(); int* foo = (int*)malloc( sizeof(int) ); list->head = sll_new_node( foo ); list->tail = list->head; sll_free( list, 1 ); } //------------------------------------------------------------------------- // Test sll_free_node function //------------------------------------------------------------------------- TEST(Verify_sll_free_node_does_nothing_on_null_pointer) { sll_free_node( NULL, 0 ); } TEST(Verify_sll_free_node_frees_the_given_node) { sll_node_t* node = sll_new_node( NULL ); sll_free_node( node, 0 ); } TEST(Verify_sll_free_node_frees_the_given_node_and_contents) { int* foo = (int*)malloc( sizeof(int) ); sll_node_t* node = sll_new_node( foo ); sll_free_node( node, 1 ); } //------------------------------------------------------------------------- // Test sll_front function //------------------------------------------------------------------------- TEST(Verify_sll_front_returns_NULL_if_list_is_NULL) { CHECK( NULL == sll_front( NULL ) ); } TEST(Verify_sll_front_returns_NULL_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_front( &list ) ); } TEST(Verify_sll_front_returns_the_head_of_the_list) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node1 == sll_front( &list ) ); } //------------------------------------------------------------------------- // Test sll_back function //------------------------------------------------------------------------- TEST(Verify_sll_back_returns_NULL_if_list_is_NULL) { CHECK( NULL == sll_back( NULL ) ); } TEST(Verify_sll_back_returns_NULL_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_back( &list ) ); } TEST(Verify_sll_back_returns_the_tail_of_the_list) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node2 == sll_back( &list ) ); } //------------------------------------------------------------------------- // Test sll_length function //------------------------------------------------------------------------- TEST(Verify_sll_length_returns_0_when_passed_null_pointer) { CHECK( 0 == sll_length(NULL) ); } TEST(Verify_sll_length_returns_0_when_list_is_empty) { sll_t* list = sll_new(); CHECK( 0 == sll_length( list ) ); free( list ); } TEST(Verify_sll_length_returns_1_when_list_is_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( 1 == sll_length( &list ) ); } TEST(Verify_sll_length_returns_2_when_list_is_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( 2 == sll_length( &list ) ); } //------------------------------------------------------------------------- // Test sll_index function //------------------------------------------------------------------------- TEST(Verify_sll_index_returns_NULL_on_null_pointer) { CHECK( NULL == sll_index( NULL, 0 ) ); } TEST(Verify_sll_index_returns_NULL_when_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_index( &list, 0 ) ); } TEST(Verify_sll_index_returns_NULL_when_index_out_of_range) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( NULL == sll_index( &list, 3 ) ); } TEST(Verify_sll_index_returns_node_at_index_0_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node1 == sll_index( &list, 0 ) ); } TEST(Verify_sll_index_returns_node_at_index_1_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node2 == sll_index( &list, 1 ) ); } TEST(Verify_sll_index_returns_node_at_index_2_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node3 == sll_index( &list, 2 ) ); } //------------------------------------------------------------------------- // Test sll_push_front function //------------------------------------------------------------------------- TEST(Verify_sll_push_front_returns_null_if_list_is_null) { CHECK( NULL == sll_push_front( NULL, NULL ) ); } TEST(Verify_sll_push_front_pushes_to_empty_list) { sll_t list = { NULL, NULL }; sll_node_t* node = sll_push_front( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL == node->next ); CHECK( node == list.head ); CHECK( node == list.tail ); } TEST(Verify_sll_push_front_pushes_to_front_of_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; sll_node_t* node = sll_push_front( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL != node->next ); CHECK( node == list.head ); CHECK( node != list.tail ); } //------------------------------------------------------------------------- // Test sll_push_back function //------------------------------------------------------------------------- TEST(Verify_sll_push_back_returns_null_if_list_is_null) { CHECK( NULL == sll_push_back( NULL, NULL ) ); } TEST(Verify_sll_push_back_pushes_to_empty_list) { sll_t list = { NULL, NULL }; sll_node_t* node = sll_push_back( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL == node->next ); CHECK( node == list.head ); CHECK( node == list.tail ); } TEST(Verify_sll_push_back_pushes_to_back_of_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; sll_node_t* node = sll_push_back( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( &node1 != node->next ); CHECK( node != list.head ); CHECK( node == list.tail ); } //------------------------------------------------------------------------- // Test sll_pop_front function //------------------------------------------------------------------------- TEST(Verify_pop_front_returns_null_if_list_is_null) { CHECK( NULL == sll_pop_front( NULL ) ); } TEST(Verify_pop_front_returns_null_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_pop_front( &list ) ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( NULL == list.head ); CHECK( NULL == list.tail ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( &node2 == list.head ); CHECK( &node2 == list.tail ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_3) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( &node2 == list.head ); CHECK( &node3 == list.tail ); } //------------------------------------------------------------------------- // Test sll_pop_back function //------------------------------------------------------------------------- TEST(Verify_pop_back_does_nothing_if_list_is_null) { CHECK( NULL == sll_pop_back( NULL ) ); } TEST(Verify_pop_back_does_nothing_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_pop_back( &list ) ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( &node1 == sll_pop_back( &list ) ); CHECK( NULL == list.head ); CHECK( NULL == list.tail ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node2 == sll_pop_back( &list ) ); CHECK( &node1 == list.head ); CHECK( &node1 == list.tail ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_3) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node3 == sll_pop_back( &list ) ); CHECK( &node1 == list.head ); CHECK( &node2 == list.tail ); } //------------------------------------------------------------------------- // Test sll_insert function //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Test sll_delete function //------------------------------------------------------------------------- } <commit_msg>Updated unit tests for singly linked list<commit_after>// Unit Test Framework Includes #include "UnitTest++.h" #include <cstdlib> // File To Test #include "sll.h" using namespace UnitTest; //----------------------------------------------------------------------------- // Begin Unit Tests //----------------------------------------------------------------------------- namespace { //------------------------------------------------------------------------- // Test sll_new function //------------------------------------------------------------------------- TEST(Verify_sll_new_returns_newly_allocated_empty_list) { sll_t* list = sll_new(); CHECK( NULL != list ); CHECK( NULL == list->head ); CHECK( NULL == list->tail ); free( list ); } //------------------------------------------------------------------------- // Test sll_new_node function //------------------------------------------------------------------------- TEST(Verify_sll_new_node_returns_newly_allocated_node_with_given_contents) { int stuff = 0; sll_node_t* node = sll_new_node( &stuff ); CHECK( NULL != node ); CHECK( &stuff == node->contents ); CHECK( NULL == node->next ); free( node ); } //------------------------------------------------------------------------- // Test sll_free function //------------------------------------------------------------------------- TEST(Verify_sll_free_does_nothing_on_null_pointer) { sll_free( NULL, 0 ); } TEST(Verify_sll_free_frees_the_given_empty_list) { sll_t* list = sll_new(); sll_free( list, 0 ); } TEST(Verify_sll_free_frees_the_given_list_including_nodes) { sll_t* list = sll_new(); list->head = sll_new_node(NULL); list->tail = list->head; sll_free( list, 0 ); } TEST(Verify_sll_free_frees_the_given_list_including_nodes_and_node_contents) { sll_t* list = sll_new(); int* foo = (int*)malloc( sizeof(int) ); list->head = sll_new_node( foo ); list->tail = list->head; sll_free( list, 1 ); } //------------------------------------------------------------------------- // Test sll_free_node function //------------------------------------------------------------------------- TEST(Verify_sll_free_node_does_nothing_on_null_pointer) { sll_free_node( NULL, 0 ); } TEST(Verify_sll_free_node_frees_the_given_node) { sll_node_t* node = sll_new_node( NULL ); sll_free_node( node, 0 ); } TEST(Verify_sll_free_node_frees_the_given_node_and_contents) { int* foo = (int*)malloc( sizeof(int) ); sll_node_t* node = sll_new_node( foo ); sll_free_node( node, 1 ); } //------------------------------------------------------------------------- // Test sll_front function //------------------------------------------------------------------------- TEST(Verify_sll_front_returns_NULL_if_list_is_NULL) { CHECK( NULL == sll_front( NULL ) ); } TEST(Verify_sll_front_returns_NULL_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_front( &list ) ); } TEST(Verify_sll_front_returns_the_head_of_the_list) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node1 == sll_front( &list ) ); } //------------------------------------------------------------------------- // Test sll_back function //------------------------------------------------------------------------- TEST(Verify_sll_back_returns_NULL_if_list_is_NULL) { CHECK( NULL == sll_back( NULL ) ); } TEST(Verify_sll_back_returns_NULL_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_back( &list ) ); } TEST(Verify_sll_back_returns_the_tail_of_the_list) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node2 == sll_back( &list ) ); } //------------------------------------------------------------------------- // Test sll_length function //------------------------------------------------------------------------- TEST(Verify_sll_length_returns_0_when_passed_null_pointer) { CHECK( 0 == sll_length(NULL) ); } TEST(Verify_sll_length_returns_0_when_list_is_empty) { sll_t* list = sll_new(); CHECK( 0 == sll_length( list ) ); free( list ); } TEST(Verify_sll_length_returns_1_when_list_is_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( 1 == sll_length( &list ) ); } TEST(Verify_sll_length_returns_2_when_list_is_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( 2 == sll_length( &list ) ); } //------------------------------------------------------------------------- // Test sll_index function //------------------------------------------------------------------------- TEST(Verify_sll_index_returns_NULL_on_null_pointer) { CHECK( NULL == sll_index( NULL, 0 ) ); } TEST(Verify_sll_index_returns_NULL_when_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_index( &list, 0 ) ); } TEST(Verify_sll_index_returns_NULL_when_index_out_of_range) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( NULL == sll_index( &list, 3 ) ); } TEST(Verify_sll_index_returns_node_at_index_0_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node1 == sll_index( &list, 0 ) ); } TEST(Verify_sll_index_returns_node_at_index_1_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node2 == sll_index( &list, 1 ) ); } TEST(Verify_sll_index_returns_node_at_index_2_of_3_element_list) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node3 == sll_index( &list, 2 ) ); } //------------------------------------------------------------------------- // Test sll_push_front function //------------------------------------------------------------------------- TEST(Verify_sll_push_front_returns_null_if_list_is_null) { CHECK( NULL == sll_push_front( NULL, NULL ) ); } TEST(Verify_sll_push_front_pushes_to_empty_list) { sll_t list = { NULL, NULL }; sll_node_t* node = sll_push_front( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL == node->next ); CHECK( node == list.head ); CHECK( node == list.tail ); } TEST(Verify_sll_push_front_pushes_to_front_of_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; sll_node_t* node = sll_push_front( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL != node->next ); CHECK( node == list.head ); CHECK( node != list.tail ); } //------------------------------------------------------------------------- // Test sll_push_back function //------------------------------------------------------------------------- TEST(Verify_sll_push_back_returns_null_if_list_is_null) { CHECK( NULL == sll_push_back( NULL, NULL ) ); } TEST(Verify_sll_push_back_pushes_to_empty_list) { sll_t list = { NULL, NULL }; sll_node_t* node = sll_push_back( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( NULL == node->next ); CHECK( node == list.head ); CHECK( node == list.tail ); } TEST(Verify_sll_push_back_pushes_to_back_of_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; sll_node_t* node = sll_push_back( &list, (void*)0x1234 ); CHECK( NULL != node ); CHECK( (void*)0x1234 == node->contents ); CHECK( &node1 != node->next ); CHECK( node != list.head ); CHECK( node == list.tail ); } //------------------------------------------------------------------------- // Test sll_pop_front function //------------------------------------------------------------------------- TEST(Verify_pop_front_returns_null_if_list_is_null) { CHECK( NULL == sll_pop_front( NULL ) ); } TEST(Verify_pop_front_returns_null_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_pop_front( &list ) ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( NULL == list.head ); CHECK( NULL == list.tail ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( &node2 == list.head ); CHECK( &node2 == list.tail ); } TEST(Verify_pop_front_removes_a_node_from_the_front_of_a_list_of_length_3) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node1 == sll_pop_front( &list ) ); CHECK( &node2 == list.head ); CHECK( &node3 == list.tail ); } //------------------------------------------------------------------------- // Test sll_pop_back function //------------------------------------------------------------------------- TEST(Verify_pop_back_does_nothing_if_list_is_null) { CHECK( NULL == sll_pop_back( NULL ) ); } TEST(Verify_pop_back_does_nothing_if_list_is_empty) { sll_t list = { NULL, NULL }; CHECK( NULL == sll_pop_back( &list ) ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_1) { sll_node_t node1 = { NULL, NULL }; sll_t list = { &node1, &node1 }; CHECK( &node1 == sll_pop_back( &list ) ); CHECK( NULL == list.head ); CHECK( NULL == list.tail ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_2) { sll_node_t node2 = { NULL, NULL }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node2 }; CHECK( &node2 == sll_pop_back( &list ) ); CHECK( &node1 == list.head ); CHECK( &node1 == list.tail ); } TEST(Verify_pop_back_removes_a_node_from_the_back_of_a_list_of_length_3) { sll_node_t node3 = { NULL, NULL }; sll_node_t node2 = { NULL, &node3 }; sll_node_t node1 = { NULL, &node2 }; sll_t list = { &node1, &node3 }; CHECK( &node3 == sll_pop_back( &list ) ); CHECK( &node1 == list.head ); CHECK( &node2 == list.tail ); } //------------------------------------------------------------------------- // Test sll_insert function //------------------------------------------------------------------------- TEST(Verify_insert_does_nothing_if_list_is_null) { CHECK( NULL == sll_insert( NULL, 0, (void*)0x1234 ) ); } //------------------------------------------------------------------------- // Test sll_delete function //------------------------------------------------------------------------- TEST(Verify_delete_does_nothing_if_list_is_null) { CHECK( NULL == sll_insert( NULL, 0, 0 ) ); } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File FilterBenchmark.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Outputs time when solution first exceeds a threshold value. // /////////////////////////////////////////////////////////////////////////////// #include <CardiacEPSolver/Filters/FilterBenchmark.h> namespace Nektar { namespace SolverUtils { std::string FilterBenchmark::className = GetFilterFactory().RegisterCreatorFunction("Benchmark", FilterBenchmark::create); FilterBenchmark::FilterBenchmark( const LibUtilities::SessionReaderSharedPtr &pSession, const std::map<std::string, std::string> &pParams) : Filter(pSession) { ASSERTL0(pParams.find("ThresholdValue") != pParams.end(), "Missing parameter 'ThresholdValue'."); m_thresholdValue = atof(pParams.find("ThresholdValue")->second.c_str()); ASSERTL0(pParams.find("InitialValue") != pParams.end(), "Missing parameter 'InitialValue'."); m_initialValue = atof(pParams.find("InitialValue")->second.c_str()); ASSERTL0(!(pParams.find("OutputFile")->second.empty()), "Missing parameter 'OutputFile'."); m_outputFile = pParams.find("OutputFile")->second; if (pParams.find("StartTime") != pParams.end()) { m_startTime = atof(pParams.find("StartTime")->second.c_str()); } m_fld = MemoryManager<LibUtilities::FieldIO>::AllocateSharedPtr(pSession->GetComm()); } FilterBenchmark::~FilterBenchmark() { } void FilterBenchmark::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_threshold.push_back(Array<OneD, NekDouble>( pFields[0]->GetNpoints(), m_initialValue)); m_idx = Array<OneD, int> (pFields[0]->GetNpoints(), 0); m_polarity = Array<OneD, int> (pFields[0]->GetNpoints(), -1); } void FilterBenchmark::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { if (time < m_startTime) { return; } int i; NekDouble timestep = pFields[0]->GetSession()->GetParameter("TimeStep"); for (i = 0; i < pFields[0]->GetNpoints(); ++i) { if ((m_polarity[i] == -1 && pFields[0]->GetPhys()[i] > m_thresholdValue) || (m_polarity[i] == 1 && pFields[0]->GetPhys()[i] < m_thresholdValue)) { m_threshold[m_idx[i]][i] = time; m_idx[i]++; m_polarity[i] *= -1; } } int max_idx = Vmath::Vmax(pFields[0]->GetNpoints(), m_idx, 1); pFields[0]->GetSession()->GetComm()->AllReduce(max_idx, LibUtilities::ReduceMax); if (m_threshold.size() == max_idx) { m_threshold.push_back(Array<OneD, NekDouble>( pFields[0]->GetNpoints(), m_initialValue)); } } void FilterBenchmark::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { for (int i = 0; i < m_threshold.size() - 1; ++i) { std::stringstream vOutputFilename; vOutputFilename << m_outputFile << "_" << i << ".fld"; std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef = pFields[0]->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); Array<OneD, NekDouble> vCoeffs(pFields[0]->GetNcoeffs()); pFields[0]->FwdTrans_IterPerExp(m_threshold[i], vCoeffs); // copy Data into FieldData and set variable for(int i = 0; i < FieldDef.size(); ++i) { // Could do a search here to find correct variable FieldDef[i]->m_fields.push_back("m"); pFields[0]->AppendFieldData(FieldDef[i], FieldData[i], vCoeffs); } m_fld->Write(vOutputFilename.str(),FieldDef,FieldData); } } bool FilterBenchmark::v_IsTimeDependent() { return true; } } } <commit_msg>Added check to enforce minimum APD in benchmark filter.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File FilterBenchmark.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Outputs time when solution first exceeds a threshold value. // /////////////////////////////////////////////////////////////////////////////// #include <CardiacEPSolver/Filters/FilterBenchmark.h> namespace Nektar { namespace SolverUtils { std::string FilterBenchmark::className = GetFilterFactory().RegisterCreatorFunction("Benchmark", FilterBenchmark::create); FilterBenchmark::FilterBenchmark( const LibUtilities::SessionReaderSharedPtr &pSession, const std::map<std::string, std::string> &pParams) : Filter(pSession) { ASSERTL0(pParams.find("ThresholdValue") != pParams.end(), "Missing parameter 'ThresholdValue'."); m_thresholdValue = atof(pParams.find("ThresholdValue")->second.c_str()); ASSERTL0(pParams.find("InitialValue") != pParams.end(), "Missing parameter 'InitialValue'."); m_initialValue = atof(pParams.find("InitialValue")->second.c_str()); ASSERTL0(!(pParams.find("OutputFile")->second.empty()), "Missing parameter 'OutputFile'."); m_outputFile = pParams.find("OutputFile")->second; if (pParams.find("StartTime") != pParams.end()) { m_startTime = atof(pParams.find("StartTime")->second.c_str()); } m_fld = MemoryManager<LibUtilities::FieldIO>::AllocateSharedPtr(pSession->GetComm()); } FilterBenchmark::~FilterBenchmark() { } void FilterBenchmark::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { m_threshold.push_back(Array<OneD, NekDouble>( pFields[0]->GetNpoints(), m_initialValue)); m_idx = Array<OneD, int> (pFields[0]->GetNpoints(), 0); m_polarity = Array<OneD, int> (pFields[0]->GetNpoints(), -1); } void FilterBenchmark::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { if (time < m_startTime) { return; } int i; NekDouble timestep = pFields[0]->GetSession()->GetParameter("TimeStep"); for (i = 0; i < pFields[0]->GetNpoints(); ++i) { if ((m_polarity[i] == -1 && pFields[0]->GetPhys()[i] > m_thresholdValue) || (m_polarity[i] == 1 && pFields[0]->GetPhys()[i] < m_thresholdValue)) { // If APD too short, reset if (m_polarity[i] == 1 && time - m_threshold[m_idx[i]][i] < 50) { m_idx[i]--; m_threshold[m_idx[i]][i] = m_initialValue; } else { m_threshold[m_idx[i]][i] = time; m_idx[i]++; } m_polarity[i] *= -1; } } int max_idx = Vmath::Vmax(pFields[0]->GetNpoints(), m_idx, 1); pFields[0]->GetSession()->GetComm()->AllReduce(max_idx, LibUtilities::ReduceMax); if (m_threshold.size() == max_idx) { m_threshold.push_back(Array<OneD, NekDouble>( pFields[0]->GetNpoints(), m_initialValue)); } } void FilterBenchmark::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time) { for (int i = 0; i < m_threshold.size() - 1; ++i) { std::stringstream vOutputFilename; vOutputFilename << m_outputFile << "_" << i << ".fld"; std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef = pFields[0]->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); Array<OneD, NekDouble> vCoeffs(pFields[0]->GetNcoeffs()); pFields[0]->FwdTrans_IterPerExp(m_threshold[i], vCoeffs); // copy Data into FieldData and set variable for(int i = 0; i < FieldDef.size(); ++i) { // Could do a search here to find correct variable FieldDef[i]->m_fields.push_back("m"); pFields[0]->AppendFieldData(FieldDef[i], FieldData[i], vCoeffs); } m_fld->Write(vOutputFilename.str(),FieldDef,FieldData); } } bool FilterBenchmark::v_IsTimeDependent() { return true; } } } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include "RdYarpRobotManager.hpp" namespace rd { RdYarpRobotManager::RdYarpRobotManager(const std::string& robotName): RdRobotManager(robotName) { connected = false; enabled = false; } bool RdYarpRobotManager::moveForward(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_MOVE_FORWARD,velocity); } bool RdYarpRobotManager::moveBackwards(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_MOVE_BACKWARDS,velocity); } bool RdYarpRobotManager::turnLeft(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TURN_LEFT,velocity); } bool RdYarpRobotManager::turnRight(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TURN_RIGHT,velocity); } bool RdYarpRobotManager::stopMovement() { RD_DEBUG("\n"); return send1vocab(VOCAB_STOP_MOVEMENT); } bool RdYarpRobotManager::tiltUp(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TILT_UP,velocity); } bool RdYarpRobotManager::tiltDown(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TILT_DOWN,velocity); } bool RdYarpRobotManager::panLeft(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_PAN_LEFT,velocity); } bool RdYarpRobotManager::panRight(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_PAN_RIGHT,velocity); } bool RdYarpRobotManager::stopCameraMovement() { RD_DEBUG("\n"); return send1vocab(VOCAB_STOP_CAMERA_MOVEMENT); } bool RdYarpRobotManager::connect() { if( connected ) { RD_WARNING("Already connected\n"); return true; } yarp::os::NetworkBase::initMinimum(); if ( ! yarp::os::NetworkBase::checkNetwork() ) { RD_ERROR("Found no yarp network (try running 'yarpserver &'', or '--mockupRobotManager' for Fake robot motors). Bye!\n"); return false; } std::string launchRobotOptionsStr("(on /"); launchRobotOptionsStr += robotName; launchRobotOptionsStr += ") (as roblauncher) (cmd \"sudo launchRaspiYarp --device RdRobotServer --subdevice RdOnePwmMotors --name /"; // RdOnePwmMotors or RdFakeMotors launchRobotOptionsStr += robotName; launchRobotOptionsStr += " --gpios 17 27\")"; yarp::os::Property launchRobotOptions; launchRobotOptions.fromString(launchRobotOptionsStr); //-- Default should look like "/rd1/rpc:s" RD_DEBUG("Attempting to start motors on robot side [parameters: %s]...\n",launchRobotOptionsStr.c_str()); RD_INFO("If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); int robotRet = yarp::os::Run::client(launchRobotOptions); if (robotRet == 0) { RD_SUCCESS("Started motors on robot side.\n"); } else { RD_WARNING("Could not start motors on robot side, but will atempt to connect anyway.\n"); } std::string launchCameraOptionsStr("(on /"); launchCameraOptionsStr += robotName; launchCameraOptionsStr += ") (as launcher) (cmd \"yarpdev --device opencv_grabber --name /"; launchCameraOptionsStr += robotName; launchCameraOptionsStr += "/img:o\")"; yarp::os::Property launchCameraOptions; launchCameraOptions.fromString(launchCameraOptionsStr); RD_DEBUG("Attempting to start camera on robot side [parameters: %s]...\n",launchCameraOptionsStr.c_str()); RD_INFO("If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); int cameraRet = yarp::os::Run::client(launchCameraOptions); //-- Default should look like "/rd1/img:o" if (cameraRet == 0) { RD_SUCCESS("Started camera on robot side.\n"); } else { RD_WARNING("Could not start camera on robot side, but will atempt to connect anyway.\n"); } std::string local_s("/robotDevastation/"); local_s += robotName; local_s += "/rpc:c"; rpcClient.open(local_s); //-- Default should look like "/robotDevastation/rd1/rpc:c" std::string remote_s("/"); remote_s += robotName; remote_s += "/rpc:s"; int tries = 0; while(tries++ < 10) { yarp::os::Network::connect(local_s,remote_s); if( rpcClient.getOutputCount() > 0) break; RD_DEBUG("Wait to connect to remote robot, try %d...\n",tries); yarp::os::Time::delay(0.5); } if (tries == 11) { RD_ERROR("Timeout on connect to remote robot! If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); return false; } RD_SUCCESS("Connected to remote robot.\n"); return true; } bool RdYarpRobotManager::disconnect() { rpcClient.close(); return true; } bool RdYarpRobotManager::test() { return true; } void RdYarpRobotManager::setEnabled(bool enabled) { } void RdYarpRobotManager::onDestroy(){ return; } bool RdYarpRobotManager::send1vocab1int(int vocab, int integer) { yarp::os::Bottle cmd, response; cmd.addVocab(vocab); cmd.addInt(integer); rpcClient.write(cmd,response); if( response.get(0).asVocab() == VOCAB_OK ) return true; else return false; } bool RdYarpRobotManager::send1vocab(int vocab) { yarp::os::Bottle cmd, response; cmd.addVocab(vocab); rpcClient.write(cmd,response); if( response.get(0).asVocab() == VOCAB_OK ) return true; else return false; } } //rd <commit_msg>only try remote robot and camera yarprun launch if yarprun port exists<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*- #include "RdYarpRobotManager.hpp" namespace rd { RdYarpRobotManager::RdYarpRobotManager(const std::string& robotName): RdRobotManager(robotName) { connected = false; enabled = false; } bool RdYarpRobotManager::moveForward(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_MOVE_FORWARD,velocity); } bool RdYarpRobotManager::moveBackwards(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_MOVE_BACKWARDS,velocity); } bool RdYarpRobotManager::turnLeft(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TURN_LEFT,velocity); } bool RdYarpRobotManager::turnRight(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TURN_RIGHT,velocity); } bool RdYarpRobotManager::stopMovement() { RD_DEBUG("\n"); return send1vocab(VOCAB_STOP_MOVEMENT); } bool RdYarpRobotManager::tiltUp(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TILT_UP,velocity); } bool RdYarpRobotManager::tiltDown(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_TILT_DOWN,velocity); } bool RdYarpRobotManager::panLeft(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_PAN_LEFT,velocity); } bool RdYarpRobotManager::panRight(int velocity) { RD_DEBUG("\n"); return send1vocab1int(VOCAB_PAN_RIGHT,velocity); } bool RdYarpRobotManager::stopCameraMovement() { RD_DEBUG("\n"); return send1vocab(VOCAB_STOP_CAMERA_MOVEMENT); } bool RdYarpRobotManager::connect() { if( connected ) { RD_WARNING("Already connected\n"); return true; } yarp::os::NetworkBase::initMinimum(); if ( ! yarp::os::NetworkBase::checkNetwork() ) { RD_ERROR("Found no yarp network (try running 'yarpserver &'', or '--mockupRobotManager' for Fake robot motors). Bye!\n"); return false; } std::string yarprunPortStr("/"); yarprunPortStr += robotName; if( yarp::os::NetworkBase::exists(yarprunPortStr) ) { std::string launchRobotOptionsStr("(on /"); launchRobotOptionsStr += robotName; launchRobotOptionsStr += ") (as roblauncher) (cmd \"sudo launchRaspiYarp --device RdRobotServer --subdevice RdOnePwmMotors --name /"; // RdOnePwmMotors or RdFakeMotors launchRobotOptionsStr += robotName; launchRobotOptionsStr += " --gpios 17 27\")"; yarp::os::Property launchRobotOptions; launchRobotOptions.fromString(launchRobotOptionsStr); //-- Default should look like "/rd1/rpc:s" RD_DEBUG("Attempting to start motors on robot side [parameters: %s]...\n",launchRobotOptionsStr.c_str()); RD_INFO("If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); int robotRet = yarp::os::Run::client(launchRobotOptions); if (robotRet == 0) { RD_SUCCESS("Started motors on robot side.\n"); } else { RD_WARNING("Could not start motors on robot side, but will atempt to connect anyway.\n"); } std::string launchCameraOptionsStr("(on /"); launchCameraOptionsStr += robotName; launchCameraOptionsStr += ") (as launcher) (cmd \"yarpdev --device opencv_grabber --name /"; launchCameraOptionsStr += robotName; launchCameraOptionsStr += "/img:o\")"; yarp::os::Property launchCameraOptions; launchCameraOptions.fromString(launchCameraOptionsStr); RD_DEBUG("Attempting to start camera on robot side [parameters: %s]...\n",launchCameraOptionsStr.c_str()); RD_INFO("If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); int cameraRet = yarp::os::Run::client(launchCameraOptions); //-- Default should look like "/rd1/img:o" if (cameraRet == 0) { RD_SUCCESS("Started camera on robot side.\n"); } else { RD_WARNING("Could not start camera on robot side, but will atempt to connect anyway.\n"); } } else { RD_WARNING("No %s yarprun port found. Will try to connect, but jump remote launching.\n", yarprunPortStr.c_str()); } std::string local_s("/robotDevastation/"); local_s += robotName; local_s += "/rpc:c"; rpcClient.open(local_s); //-- Default should look like "/robotDevastation/rd1/rpc:c" std::string remote_s("/"); remote_s += robotName; remote_s += "/rpc:s"; int tries = 0; while(tries++ < 10) { yarp::os::Network::connect(local_s,remote_s); if( rpcClient.getOutputCount() > 0) break; RD_DEBUG("Wait to connect to remote robot, try %d...\n",tries); yarp::os::Time::delay(0.5); } if (tries == 11) { RD_ERROR("Timeout on connect to remote robot! If you prefer a fake robot with a fake camera, launch 'robotDevastation --mockupRobotManager --mockupImageManager'\n"); return false; } RD_SUCCESS("Connected to remote robot.\n"); return true; } bool RdYarpRobotManager::disconnect() { rpcClient.close(); return true; } bool RdYarpRobotManager::test() { return true; } void RdYarpRobotManager::setEnabled(bool enabled) { } void RdYarpRobotManager::onDestroy(){ return; } bool RdYarpRobotManager::send1vocab1int(int vocab, int integer) { yarp::os::Bottle cmd, response; cmd.addVocab(vocab); cmd.addInt(integer); rpcClient.write(cmd,response); if( response.get(0).asVocab() == VOCAB_OK ) return true; else return false; } bool RdYarpRobotManager::send1vocab(int vocab) { yarp::os::Bottle cmd, response; cmd.addVocab(vocab); rpcClient.write(cmd,response); if( response.get(0).asVocab() == VOCAB_OK ) return true; else return false; } } //rd <|endoftext|>
<commit_before> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <boost/test/unit_test.hpp> #include <iostream> // Enable testing of private and protected methods, too // #define protected public // #define private public #include "storage/EtcFstab.h" #include "storage/Filesystems/FilesystemImpl.h" using namespace std; using namespace storage; BOOST_AUTO_TEST_CASE( parse_and_format ) { // This needs to be formatted exactly like the expected output string_vec input = { /** 00 **/ "LABEL=swap swap swap defaults 0 0", /** 01 **/ "LABEL=xfs-root / xfs defaults 0 0", /** 02 **/ "LABEL=btrfs-root /btrfs-root btrfs ro 1 2", /** 03 **/ "LABEL=space /space xfs noauto,user 1 2" }; EtcFstab fstab; fstab.parse( input ); // // Check formatting // string_vec output = fstab.format_lines(); BOOST_CHECK_EQUAL( fstab.get_entry_count(), input.size() ); for ( int i=0; i < fstab.get_entry_count(); ++i ) BOOST_CHECK_EQUAL( output[i], input[i] ); // // Check all fields // int i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=xfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=btrfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=space" ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "swap" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/btrfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); i=0; BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "swap" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "xfs" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "btrfs" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "xfs" ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), true ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), true ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), false ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), false ); // // Check mount options // const MountOpts & opts_ref = fstab.get_entry( 1 )->get_mount_opts(); // xfs-root BOOST_CHECK_EQUAL( opts_ref.contains( "defaults" ), false ); MountOpts opts = fstab.get_entry( 2 )->get_mount_opts(); // btrfs-root partition BOOST_CHECK_EQUAL( opts.size(), 1 ); BOOST_CHECK_EQUAL( opts.get_opt( 0 ), "ro" ); BOOST_CHECK_EQUAL( opts.contains( "ro" ), true ); BOOST_CHECK_EQUAL( opts.contains( "wrglbrmpf" ), false ); BOOST_CHECK_EQUAL( opts.contains( "defaults" ), false ); opts = fstab.get_entry( 3 )->get_mount_opts(); // space partition BOOST_CHECK_EQUAL( opts.size(), 2 ); BOOST_CHECK_EQUAL( opts.contains( "user" ), true ); BOOST_CHECK_EQUAL( opts.contains( "noauto" ), true ); BOOST_CHECK_EQUAL( opts.contains( "auto" ), false ); // // Check setting mount options // opts << "umask=007" << "gid=42"; fstab.get_entry( 3 )->set_mount_opts( opts ); opts.clear(); // just making sure there are no leftovers opts = fstab.get_entry( 3 )->get_mount_opts(); BOOST_CHECK_EQUAL( opts.size(), 4 ); BOOST_CHECK_EQUAL( opts.contains( "umask=007" ), true ); BOOST_CHECK_EQUAL( opts.contains( "umask" ), false ); BOOST_CHECK_EQUAL( opts.contains( "gid=42" ), true ); BOOST_CHECK_EQUAL( opts.format(), "noauto,user,umask=007,gid=42" ); // // Check (historic) dump pass and fsck pass // i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 1 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 1 ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 2 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 2 ); } BOOST_AUTO_TEST_CASE( mount_order ) { // Wrong mount order by intention string_vec input = { /** 00 **/ "LABEL=var-log /var/log ext4 defaults 1 2", /** 01 **/ "LABEL=var /var ext4 defaults 1 2", /** 02 **/ "LABEL=walk /space/walk xfs noauto,user 1 2", /** 03 **/ "LABEL=space /space xfs noauto,user 1 2", /** 04 **/ "LABEL=root / ext4 defaults 1 1" }; EtcFstab fstab; fstab.parse( input ); // // Check and fix mount order // BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); fstab.fix_mount_order(); BOOST_CHECK_EQUAL( fstab.check_mount_order(), true ); int i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var/log" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); // // Take out /var and re-insert it // FstabEntry * var_entry = fstab.find_mount_point( "/var" ); BOOST_CHECK_EQUAL( var_entry != 0, true ); BOOST_CHECK_EQUAL( var_entry->get_device(), "LABEL=var" ); int index = fstab.get_index_of( var_entry ); BOOST_CHECK_EQUAL( index, 1 ); CommentedConfigFile::Entry * entry = fstab.take( index ); BOOST_CHECK_EQUAL( entry == var_entry, true ); BOOST_CHECK_EQUAL( fstab.get_entry( 1 )->get_mount_point(), "/var/log" ); fstab.add( var_entry ); BOOST_CHECK_EQUAL( fstab.get_entry( 1 )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( 2 )->get_mount_point(), "/var/log" ); // // Take out /var and /var/log and reinsert them (they go to the end now) // var_entry = fstab.find_mount_point( "/var" ); FstabEntry * var_log_entry = fstab.find_mount_point( "/var/log" ); fstab.take( fstab.get_index_of( var_log_entry ) ); fstab.take( fstab.get_index_of( var_entry ) ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 3 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); fstab.add( var_entry ); fstab.add( var_log_entry ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var/log" ); } BOOST_AUTO_TEST_CASE( duplicate_mount_points ) { string_vec input = { /** 00 **/ "LABEL=root / ext4 defaults 1 1", /** 01 **/ "LABEL=data1 /data ext4 noauto,user 1 2", /** 02 **/ "LABEL=data2 /data xfs noauto,user 1 2", /** 03 **/ "LABEL=swap swap swap defaults 0 0" }; EtcFstab fstab; fstab.parse( input ); // // Check initial entries // int i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 4 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); // // Check and fix mount order // BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); fstab.fix_mount_order(); BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); // Reordering the /data entries is expected after trying to fix the mount // order. The critical thing to test here is that the algorithm actually // terminates and does not get into an endless loop. i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 4 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); // // Add yet another entry for the same mount point /data // FstabEntry * entry = new FstabEntry(); entry->parse( "LABEL=data3 /data xfs noauto,user 1 2" ); BOOST_CHECK_EQUAL( entry->get_device(), "LABEL=data3" ); BOOST_CHECK_EQUAL( entry->get_mount_point(), "/data" ); fstab.add( entry ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data3" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); } <commit_msg>Removed cruft<commit_after> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <boost/test/unit_test.hpp> #include <iostream> #include "storage/EtcFstab.h" #include "storage/Filesystems/FilesystemImpl.h" using namespace std; using namespace storage; BOOST_AUTO_TEST_CASE( parse_and_format ) { // This needs to be formatted exactly like the expected output string_vec input = { /** 00 **/ "LABEL=swap swap swap defaults 0 0", /** 01 **/ "LABEL=xfs-root / xfs defaults 0 0", /** 02 **/ "LABEL=btrfs-root /btrfs-root btrfs ro 1 2", /** 03 **/ "LABEL=space /space xfs noauto,user 1 2" }; EtcFstab fstab; fstab.parse( input ); // // Check formatting // string_vec output = fstab.format_lines(); BOOST_CHECK_EQUAL( fstab.get_entry_count(), input.size() ); for ( int i=0; i < fstab.get_entry_count(); ++i ) BOOST_CHECK_EQUAL( output[i], input[i] ); // // Check all fields // int i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=xfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=btrfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=space" ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "swap" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/btrfs-root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); i=0; BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "swap" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "xfs" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "btrfs" ); BOOST_CHECK_EQUAL( toString( fstab.get_entry( i++ )->get_fs_type() ), "xfs" ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), true ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), true ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), false ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_opts().empty(), false ); // // Check mount options // const MountOpts & opts_ref = fstab.get_entry( 1 )->get_mount_opts(); // xfs-root BOOST_CHECK_EQUAL( opts_ref.contains( "defaults" ), false ); MountOpts opts = fstab.get_entry( 2 )->get_mount_opts(); // btrfs-root partition BOOST_CHECK_EQUAL( opts.size(), 1 ); BOOST_CHECK_EQUAL( opts.get_opt( 0 ), "ro" ); BOOST_CHECK_EQUAL( opts.contains( "ro" ), true ); BOOST_CHECK_EQUAL( opts.contains( "wrglbrmpf" ), false ); BOOST_CHECK_EQUAL( opts.contains( "defaults" ), false ); opts = fstab.get_entry( 3 )->get_mount_opts(); // space partition BOOST_CHECK_EQUAL( opts.size(), 2 ); BOOST_CHECK_EQUAL( opts.contains( "user" ), true ); BOOST_CHECK_EQUAL( opts.contains( "noauto" ), true ); BOOST_CHECK_EQUAL( opts.contains( "auto" ), false ); // // Check setting mount options // opts << "umask=007" << "gid=42"; fstab.get_entry( 3 )->set_mount_opts( opts ); opts.clear(); // just making sure there are no leftovers opts = fstab.get_entry( 3 )->get_mount_opts(); BOOST_CHECK_EQUAL( opts.size(), 4 ); BOOST_CHECK_EQUAL( opts.contains( "umask=007" ), true ); BOOST_CHECK_EQUAL( opts.contains( "umask" ), false ); BOOST_CHECK_EQUAL( opts.contains( "gid=42" ), true ); BOOST_CHECK_EQUAL( opts.format(), "noauto,user,umask=007,gid=42" ); // // Check (historic) dump pass and fsck pass // i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 1 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_dump_pass(), 1 ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 0 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 2 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_fsck_pass(), 2 ); } BOOST_AUTO_TEST_CASE( mount_order ) { // Wrong mount order by intention string_vec input = { /** 00 **/ "LABEL=var-log /var/log ext4 defaults 1 2", /** 01 **/ "LABEL=var /var ext4 defaults 1 2", /** 02 **/ "LABEL=walk /space/walk xfs noauto,user 1 2", /** 03 **/ "LABEL=space /space xfs noauto,user 1 2", /** 04 **/ "LABEL=root / ext4 defaults 1 1" }; EtcFstab fstab; fstab.parse( input ); // // Check and fix mount order // BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); fstab.fix_mount_order(); BOOST_CHECK_EQUAL( fstab.check_mount_order(), true ); int i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var/log" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); // // Take out /var and re-insert it // FstabEntry * var_entry = fstab.find_mount_point( "/var" ); BOOST_CHECK_EQUAL( var_entry != 0, true ); BOOST_CHECK_EQUAL( var_entry->get_device(), "LABEL=var" ); int index = fstab.get_index_of( var_entry ); BOOST_CHECK_EQUAL( index, 1 ); CommentedConfigFile::Entry * entry = fstab.take( index ); BOOST_CHECK_EQUAL( entry == var_entry, true ); BOOST_CHECK_EQUAL( fstab.get_entry( 1 )->get_mount_point(), "/var/log" ); fstab.add( var_entry ); BOOST_CHECK_EQUAL( fstab.get_entry( 1 )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( 2 )->get_mount_point(), "/var/log" ); // // Take out /var and /var/log and reinsert them (they go to the end now) // var_entry = fstab.find_mount_point( "/var" ); FstabEntry * var_log_entry = fstab.find_mount_point( "/var/log" ); fstab.take( fstab.get_index_of( var_log_entry ) ); fstab.take( fstab.get_index_of( var_entry ) ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 3 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); fstab.add( var_entry ); fstab.add( var_log_entry ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/space/walk" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_mount_point(), "/var/log" ); } BOOST_AUTO_TEST_CASE( duplicate_mount_points ) { string_vec input = { /** 00 **/ "LABEL=root / ext4 defaults 1 1", /** 01 **/ "LABEL=data1 /data ext4 noauto,user 1 2", /** 02 **/ "LABEL=data2 /data xfs noauto,user 1 2", /** 03 **/ "LABEL=swap swap swap defaults 0 0" }; EtcFstab fstab; fstab.parse( input ); // // Check initial entries // int i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 4 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); // // Check and fix mount order // BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); fstab.fix_mount_order(); BOOST_CHECK_EQUAL( fstab.check_mount_order(), false ); // Reordering the /data entries is expected after trying to fix the mount // order. The critical thing to test here is that the algorithm actually // terminates and does not get into an endless loop. i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 4 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); // // Add yet another entry for the same mount point /data // FstabEntry * entry = new FstabEntry(); entry->parse( "LABEL=data3 /data xfs noauto,user 1 2" ); BOOST_CHECK_EQUAL( entry->get_device(), "LABEL=data3" ); BOOST_CHECK_EQUAL( entry->get_mount_point(), "/data" ); fstab.add( entry ); i=0; BOOST_CHECK_EQUAL( fstab.get_entry_count(), 5 ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=root" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data3" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data2" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=data1" ); BOOST_CHECK_EQUAL( fstab.get_entry( i++ )->get_device(), "LABEL=swap" ); } <|endoftext|>
<commit_before>/* test_ndx.cpp -- Console app for testing the B-tree indexing routines Copyright (c) 2005-2009 by Gerald Lindsly See <nub/Platform.h> for additional copyright information */ #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <conio.h> #include <nub/Index.h> using namespace nub; #define defaultFilename "test.ndx" Index ndx; void pret(int ret) { printf("ret = %d, ckey = \"%s\", %u\n", ret, ndx.key(), ndx.offset()); } char randKey[1024]; char* getRandKey(int len) { randKey[len] = '\0'; for (int j = 0; j < len; j++) randKey[j] = 'a' + rand() % 26; return randKey; } void addRandKey(int len) { pret(ndx.insert(getRandKey(len), 1)); } void main(int argc, char** argv) { FILE* outf; srand(2); // guarentee repeatable results char* filename = defaultFilename; if (argc > 1) filename = argv[1]; if (outf = fopen(filename, "rb")) { fclose(outf); ndx.open(filename); } else ndx.create(filename); int maxKeyLen = ndx.maxKeySize() - 1; printf("NDX Test - maxkeylen = %d\n", maxKeyLen); int ret; int count, len; while (1) { printf("\n" "A)dd, F)ind, D)elete, R)andom, L)ist, O)utput, B)reak, C)reate,\n" ".)Next, ,)Prev, 0)First, 9)Last, V)alidate, T)est, Q)uit, H)elp : "); char inp[256]; if (gets(inp)) switch(toupper(*inp)) { case 'H' : printf("\n" "A) Add a key\n" "F) Find a key\n" "D) Delete a key\n" "R) Add Count random keys of Length Len\n" "L) List all keys in the index\n" "O) Output the index tree to ndx.txt\n" "B) Used to enter the debugger. Only works if you set a breakpoint.\n" "C) Create the index from scratch\n" ".) Next key\n" ",) Previous key\n" "0) First key\n" "9) Last key\n" "V) Validate the index\n" "T) Continuous Test. Stops on key or invalid index.\n" "Q) Quit\n" "H) Display this help\n"); break; case 'B' : printf("Debug break\n"); // set a breakpoint here break; case '0' : pret(ndx.first()); break; case '9' : pret(ndx.last()); break; case '.' : pret(ndx.next()); break; case ',' : pret(ndx.prev()); break; case 'C' : ndx.close(); ndx.create(filename); printf("%s created.\n", filename); break; case 'A': printf("Add key: "); while (!gets(inp)) ; ret = ndx.insert(inp, 1); pret(ret); break; case 'F': printf("Find key: "); while (!gets(inp)) ; ret = ndx.find(inp); pret(ret); break; case 'D': printf("Delete key: "); while (!gets(inp)) ; ret = ndx.remove(inp); pret(ret); break; case 'R': printf("Add random keys -> Count, Len: "); if (scanf("%d, %d", &count, &len) == 2) { int i; for (i = 1; i <= count; i++) { printf("%5d: ", i); addRandKey(len); if (!ndx.valid()) { printf("Failed on key %d\n", i); break; } } } gets(inp); break; case 'L' : if (ndx.first()) do printf("%s\n", ndx.key()); while (ndx.next()); break; case 'O' : ndx.print("ndx.txt"); printf("Tree output to ndx.txt\n"); break; case 'Q' : ndx.close(); exit(1); case 'V' : printf("Validation %s.\n", ndx.valid() ? "successful" : "failed"); break; case 'T' : bool bValidate = inp[1] != '-'; int maxTests = 0; if (!bValidate) sscanf(inp+2, "%d", &maxTests); printf("Test: max test key len [<= %d]: ", maxKeyLen); int tLen; if (scanf("%d", &tLen) == 1 && tLen > 0 && tLen <= maxKeyLen) { gets(inp); count = 0; bool success = true; while (!_kbhit() && (maxTests == 0 || count < maxTests)) { if (bValidate && !ndx.valid()) { success = false; printf("Test failed. Iteration %d.\n", count); break; } printf("%6d ", ++count); switch (rand() % 3) { case 0 : printf("Add "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); pret(ndx.insert(randKey, 1)); break; case 1 : printf("Find "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); pret(ndx.find(randKey)); break; case 2 : printf("Del "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); if (!ndx.find(randKey)) printf("not found\n"); else pret(ndx.remove_current()); break; } } if (success && maxTests == 0) { int keycode = _getch(); if (keycode == 0 || keycode == 0xE0) _getch(); } } else gets(inp); break; } } } <commit_msg>linux conio.h subs<commit_after>/* test_ndx.cpp -- Console app for testing the B-tree indexing routines Copyright (c) 2005-2009 by Gerald Lindsly See <nub/Platform.h> for additional copyright information */ #define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <nub/Index.h> #if NUB_PLATFORM == NUB_PLATFORM_LINUX #include <iostream> #include <sys/select.h> bool _kbhit(void) { struct timeval tv; fd_set read_fd; /* Do not wait at all, not even a microsecond */ tv.tv_sec=0; tv.tv_usec=0; /* Must be done first to initialize read_fd */ FD_ZERO(&read_fd); /* Makes select() ask if input is ready: * 0 is the file descriptor for stdin */ FD_SET(0,&read_fd); /* The first parameter is the number of the * largest file descriptor to check + 1. */ if(select(1, &read_fd,NULL, /*No writes*/NULL, /*No exceptions*/&tv) == -1) return false; /* An error occured */ /* read_fd now holds a bit map of files that are * readable. We test the entry for the standard * input (file 0). */ if(FD_ISSET(0,&read_fd)) /* Character pending on stdin */ return true; /* no characters were pending */ return false; } #define getch() getchar() #else #include <conio.h> #endif using namespace nub; #define defaultFilename "test.ndx" Index ndx; void pret(int ret) { printf("ret = %d, ckey = \"%s\", %u\n", ret, ndx.key(), ndx.offset()); } char randKey[1024]; char* getRandKey(int len) { randKey[len] = '\0'; for (int j = 0; j < len; j++) randKey[j] = 'a' + rand() % 26; return randKey; } void addRandKey(int len) { pret(ndx.insert(getRandKey(len), 1)); } void main(int argc, char** argv) { FILE* outf; srand(2); // guarentee repeatable results char* filename = defaultFilename; if (argc > 1) filename = argv[1]; if (outf = fopen(filename, "rb")) { fclose(outf); ndx.open(filename); } else ndx.create(filename); int maxKeyLen = ndx.maxKeySize() - 1; printf("NDX Test - maxkeylen = %d\n", maxKeyLen); int ret; int count, len; while (1) { printf("\n" "A)dd, F)ind, D)elete, R)andom, L)ist, O)utput, B)reak, C)reate,\n" ".)Next, ,)Prev, 0)First, 9)Last, V)alidate, T)est, Q)uit, H)elp : "); char inp[256]; if (gets(inp)) switch(toupper(*inp)) { case 'H' : printf("\n" "A) Add a key\n" "F) Find a key\n" "D) Delete a key\n" "R) Add Count random keys of Length Len\n" "L) List all keys in the index\n" "O) Output the index tree to ndx.txt\n" "B) Used to enter the debugger. Only works if you set a breakpoint.\n" "C) Create the index from scratch\n" ".) Next key\n" ",) Previous key\n" "0) First key\n" "9) Last key\n" "V) Validate the index\n" "T) Continuous Test. Stops on key or invalid index.\n" "Q) Quit\n" "H) Display this help\n"); break; case 'B' : printf("Debug break\n"); // set a breakpoint here break; case '0' : pret(ndx.first()); break; case '9' : pret(ndx.last()); break; case '.' : pret(ndx.next()); break; case ',' : pret(ndx.prev()); break; case 'C' : ndx.close(); ndx.create(filename); printf("%s created.\n", filename); break; case 'A': printf("Add key: "); while (!gets(inp)) ; ret = ndx.insert(inp, 1); pret(ret); break; case 'F': printf("Find key: "); while (!gets(inp)) ; ret = ndx.find(inp); pret(ret); break; case 'D': printf("Delete key: "); while (!gets(inp)) ; ret = ndx.remove(inp); pret(ret); break; case 'R': printf("Add random keys -> Count, Len: "); if (scanf("%d, %d", &count, &len) == 2) { int i; for (i = 1; i <= count; i++) { printf("%5d: ", i); addRandKey(len); if (!ndx.valid()) { printf("Failed on key %d\n", i); break; } } } gets(inp); break; case 'L' : if (ndx.first()) do printf("%s\n", ndx.key()); while (ndx.next()); break; case 'O' : ndx.print("ndx.txt"); printf("Tree output to ndx.txt\n"); break; case 'Q' : ndx.close(); exit(1); case 'V' : printf("Validation %s.\n", ndx.valid() ? "successful" : "failed"); break; case 'T' : bool bValidate = inp[1] != '-'; int maxTests = 0; if (!bValidate) sscanf(inp+2, "%d", &maxTests); printf("Test: max test key len [<= %d]: ", maxKeyLen); int tLen; if (scanf("%d", &tLen) == 1 && tLen > 0 && tLen <= maxKeyLen) { gets(inp); count = 0; bool success = true; while (!_kbhit() && (maxTests == 0 || count < maxTests)) { if (bValidate && !ndx.valid()) { success = false; printf("Test failed. Iteration %d.\n", count); break; } printf("%6d ", ++count); switch (rand() % 3) { case 0 : printf("Add "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); pret(ndx.insert(randKey, 1)); break; case 1 : printf("Find "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); pret(ndx.find(randKey)); break; case 2 : printf("Del "); getRandKey(1 + rand() % tLen); printf("%s ", randKey); if (!ndx.find(randKey)) printf("not found\n"); else pret(ndx.remove_current()); break; } } if (success && maxTests == 0) { int keycode = _getch(); if (keycode == 0 || keycode == 0xE0) _getch(); } } else gets(inp); break; } } } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "nbostream.h" #include "hexdump.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> namespace vespalib { nbostream::nbostream(size_t initialSize) : _wbuf(), _rbuf(), _rp(0), _wp(0), _state(ok), _longLivedBuffer(false) { extend(initialSize); } nbostream::nbostream(const void * buf, size_t sz, bool longLivedBuffer) : _wbuf(), _rbuf(buf, sz), _rp(0), _wp(sz), _state(ok), _longLivedBuffer(longLivedBuffer) { } nbostream_longlivedbuf::nbostream_longlivedbuf(const void * buf, size_t sz) : nbostream(buf, sz, true) { } nbostream_longlivedbuf::nbostream_longlivedbuf(size_t initialSize) : nbostream(initialSize) { } nbostream::nbostream(const void * buf, size_t sz) : nbostream(buf, sz, false) { } nbostream::nbostream(Alloc && buf, size_t sz) : _wbuf(std::move(buf), sz), _rbuf(&_wbuf[0], sz), _rp(0), _wp(sz), _state(ok), _longLivedBuffer(false) { assert(_wbuf.size() >= sz); } nbostream::nbostream(const nbostream & rhs) : _wbuf(), _rbuf(), _rp(0), _wp(0), _state(ok), _longLivedBuffer(false) { extend(rhs.size()); _wp = rhs.size(); memcpy(&_wbuf[0], &rhs._rbuf[rhs._rp], _wp); } nbostream::nbostream(nbostream && rhs) noexcept : _wbuf(std::move(rhs._wbuf)), _rbuf(rhs._rbuf), _rp(rhs._rp), _wp(rhs._wp), _state(rhs._state), _longLivedBuffer(rhs._longLivedBuffer) { rhs._rp = 0; rhs._wp = 0; rhs._rbuf = ConstBufferRef(); if (!_longLivedBuffer && (_wbuf.capacity() == 0)) { _wbuf.resize(roundUp2inN(_rbuf.size())); memcpy(&_wbuf[0], &_rbuf[_rp], size()); _wp = size(); _rp = 0; _rbuf = ConstBufferRef(&_wbuf[0], _wbuf.capacity()); } } nbostream & nbostream::operator = (nbostream && rhs) noexcept { nbostream tmp(std::move(rhs)); swap(tmp); return *this; } nbostream & nbostream::operator = (const nbostream & rhs) { if (this != &rhs) { nbostream n(rhs); swap(n); } return *this; } nbostream::~nbostream() = default; void nbostream::fail(State s) { _state = static_cast<State>(_state | s); throw IllegalStateException(make_string("Stream failed bufsize(%zu), readp(%zu), writep(%zu)", _wbuf.size(), _rp, _wp), VESPA_STRLOC); } std::ostream & operator << (std::ostream & os, const nbostream & s) { return os << HexDump(&s._rbuf[s._rp], s.left()); } void nbostream::reserve(size_t sz) { if (capacity() < sz) { extend(sz - capacity()); } } void nbostream::compact() { memmove(&_wbuf[0], &_rbuf[_rp], left()); _wp = left(); _rp = 0; } void nbostream::extend(size_t extraSize) { if (_wbuf.data() != _rbuf.c_str()) { _wbuf.resize(roundUp2inN(_rbuf.size() + extraSize)); compact(); _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); } if (_rp != 0) { compact(); } if (space() < extraSize) { _wbuf.resize(roundUp2inN(_wbuf.size() + extraSize)); _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); } } void nbostream::swap(Buffer & buf) { if (_rp != 0) { compact(); } _wbuf.resize(size()); _wbuf.swap(buf); _rbuf = ConstBufferRef(&_wbuf[0], _wbuf.capacity()); _wp = _wbuf.size(); _rp = 0; _state = ok; } void nbostream::swap(nbostream & os) { std::swap(_rp, os._rp); std::swap(_wp, os._wp); std::swap(_state, os._state); _wbuf.swap(os._wbuf); std::swap(_rbuf, os._rbuf); std::swap(_longLivedBuffer, os._longLivedBuffer); } } <commit_msg>Use data() for more buffer pointer reads rather than subscript operator<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "nbostream.h" #include "hexdump.h" #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/stringfmt.h> #include <cassert> namespace vespalib { nbostream::nbostream(size_t initialSize) : _wbuf(), _rbuf(), _rp(0), _wp(0), _state(ok), _longLivedBuffer(false) { extend(initialSize); } nbostream::nbostream(const void * buf, size_t sz, bool longLivedBuffer) : _wbuf(), _rbuf(buf, sz), _rp(0), _wp(sz), _state(ok), _longLivedBuffer(longLivedBuffer) { } nbostream_longlivedbuf::nbostream_longlivedbuf(const void * buf, size_t sz) : nbostream(buf, sz, true) { } nbostream_longlivedbuf::nbostream_longlivedbuf(size_t initialSize) : nbostream(initialSize) { } nbostream::nbostream(const void * buf, size_t sz) : nbostream(buf, sz, false) { } nbostream::nbostream(Alloc && buf, size_t sz) : _wbuf(std::move(buf), sz), _rbuf(_wbuf.data(), sz), _rp(0), _wp(sz), _state(ok), _longLivedBuffer(false) { assert(_wbuf.size() >= sz); } nbostream::nbostream(const nbostream & rhs) : _wbuf(), _rbuf(), _rp(0), _wp(0), _state(ok), _longLivedBuffer(false) { extend(rhs.size()); _wp = rhs.size(); memcpy(_wbuf.data(), &rhs._rbuf[rhs._rp], _wp); } nbostream::nbostream(nbostream && rhs) noexcept : _wbuf(std::move(rhs._wbuf)), _rbuf(rhs._rbuf), _rp(rhs._rp), _wp(rhs._wp), _state(rhs._state), _longLivedBuffer(rhs._longLivedBuffer) { rhs._rp = 0; rhs._wp = 0; rhs._rbuf = ConstBufferRef(); if (!_longLivedBuffer && (_wbuf.capacity() == 0)) { _wbuf.resize(roundUp2inN(_rbuf.size())); memcpy(_wbuf.data(), &_rbuf[_rp], size()); _wp = size(); _rp = 0; _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); } } nbostream & nbostream::operator = (nbostream && rhs) noexcept { nbostream tmp(std::move(rhs)); swap(tmp); return *this; } nbostream & nbostream::operator = (const nbostream & rhs) { if (this != &rhs) { nbostream n(rhs); swap(n); } return *this; } nbostream::~nbostream() = default; void nbostream::fail(State s) { _state = static_cast<State>(_state | s); throw IllegalStateException(make_string("Stream failed bufsize(%zu), readp(%zu), writep(%zu)", _wbuf.size(), _rp, _wp), VESPA_STRLOC); } std::ostream & operator << (std::ostream & os, const nbostream & s) { return os << HexDump(&s._rbuf[s._rp], s.left()); } void nbostream::reserve(size_t sz) { if (capacity() < sz) { extend(sz - capacity()); } } void nbostream::compact() { memmove(_wbuf.data(), &_rbuf[_rp], left()); _wp = left(); _rp = 0; } void nbostream::extend(size_t extraSize) { if (_wbuf.data() != _rbuf.c_str()) { _wbuf.resize(roundUp2inN(_rbuf.size() + extraSize)); compact(); _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); } if (_rp != 0) { compact(); } if (space() < extraSize) { _wbuf.resize(roundUp2inN(_wbuf.size() + extraSize)); _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); } } void nbostream::swap(Buffer & buf) { if (_rp != 0) { compact(); } _wbuf.resize(size()); _wbuf.swap(buf); _rbuf = ConstBufferRef(_wbuf.data(), _wbuf.capacity()); _wp = _wbuf.size(); _rp = 0; _state = ok; } void nbostream::swap(nbostream & os) { std::swap(_rp, os._rp); std::swap(_wp, os._wp); std::swap(_state, os._state); _wbuf.swap(os._wbuf); std::swap(_rbuf, os._rbuf); std::swap(_longLivedBuffer, os._longLivedBuffer); } } <|endoftext|>
<commit_before>#include "game.h" #include <iostream> Game::Game() { //Constructor used for automatic initial board creation. for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { board[row][col] = pieceNeutral; } } } Game::~Game() { //dtor in case I need it } void Game::print_board() { for (int row = 0; row < MAX_ROWS; row++) { std::cout << "\n"; //Proper spacing for (int col = 0; col < MAX_COLS; col++) { std::cout << board[row][col]; } } std::cout << "\n\n"; //To avoid odd formatting. //Call it vertical padding I guess. } bool Game::is_valid_space(int xPosition, int yPosition) { if (board[xPosition][yPosition] != pieceNeutral) { return false; //Piece is not neutral therefore occupied. } return true; //All clear. Neutral piece is a green light. } bool Game::is_board_full() { //Static int because only this function shall use it, //and static so that I can call the function without //re-setting the value. static int blankTilesRemaining = 9; for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { if (board[row][col] != pieceNeutral) { blankTilesRemaining -= 1; } } } if (blankTilesRemaining <= 0) { //Board is full. return true; } else { return false; //The board is empty. } return false; } bool Game::add_new_piece(int xPosition, int yPosition, char piece) { if (is_valid_space(xPosition, yPosition)) { board[xPosition][yPosition] = piece; //All clear, place piece return true; } else { std::cout << "Error: Overlap on " << xPosition << ":" << yPosition << "...\n"; return false; //For sure exit, a possible logic error fix. } return false; //Cannot place the piece } void Game::reset() { //Add neutral piece's to the board, overwriting anything thats there already. for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { board[row][col] = pieceNeutral; } } } bool Game::is_victory(char piece) { if (is_win_horizontal(piece) || is_win_vertical(piece) || is_win_diagonal(piece)) { return true; //"piece" won in some way } return false; } //Our three private win-checking functions. I hope thats self explanatory. //Return true on success (a win), false otherwise. bool Game::is_win_vertical(char piece) { if (board[0][0] == piece && board[0][1] == piece && board[0][2] == piece) { return true; } if (board[1][0] == piece && board[1][1] == piece && board[1][2] == piece) { return true; } if (board[2][0] == piece && board[2][1] == piece && board[2][2] == piece) { return true; } return false; //No win if none of these return true. } bool Game::is_win_horizontal(char piece) { if (board[0][0] == piece && board[1][0] == piece && board[2][0] == piece) { return true; } if (board[0][1] == piece && board[1][1] == piece && board[2][1] == piece) { return true; } if (board[0][2] == piece && board[1][2] == piece && board[2][2] == piece) { return true; } return false; //No win if none of these return true. } bool Game::is_win_diagonal(char piece) { if (board[0][0] == piece && board[1][1] == piece && board[2][2] == piece) { return true; } if (board[2][0] == piece && board[1][1] == piece && board[0][2] == piece) { return true; } return false; //No win if none of these return true. } <commit_msg>Minor changes<commit_after>#include "game.h" #include <iostream> Game::Game() { //Constructor used for automatic initial board creation. for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { board[row][col] = pieceNeutral; } } } Game::~Game() { //dtor in case I need it } void Game::print_board() { for (int row = 0; row < MAX_ROWS; row++) { std::cout << "\n"; //Proper spacing for (int col = 0; col < MAX_COLS; col++) { std::cout << board[row][col]; } } std::cout << "\n\n"; //To avoid odd formatting. //Call it vertical padding I guess. } bool Game::is_valid_space(int xPosition, int yPosition) { if (board[xPosition][yPosition] != pieceNeutral) { return false; //Piece is not neutral therefore occupied. } return true; //All clear. Neutral piece is a green light. } bool Game::is_board_full() { //Static int because only this function shall use it, //and static so that I can call the function without //re-setting the value. static int blankTilesRemaining = 9; /* TODO: Implement proper stalemate detection... */ if (blankTilesRemaining <= 0) { //Board is full. return true; } else { return false; //The board is empty. } return false; } bool Game::add_new_piece(int xPosition, int yPosition, char piece) { if (is_valid_space(xPosition, yPosition)) { board[xPosition][yPosition] = piece; //All clear, place piece return true; } else { std::cout << "Error: Overlap on " << xPosition << ":" << yPosition << "...\n"; return false; //For sure exit, a possible logic error fix. } return false; //Cannot place the piece } void Game::reset() { //Add neutral piece's to the board, overwriting anything thats there already. for (int row = 0; row < MAX_ROWS; row++) { for (int col = 0; col < MAX_COLS; col++) { board[row][col] = pieceNeutral; } } } bool Game::is_victory(char piece) { if (is_win_horizontal(piece) || is_win_vertical(piece) || is_win_diagonal(piece)) { return true; //"piece" won in some way } return false; } //Our three private win-checking functions. I hope thats self explanatory. //Return true on success (a win), false otherwise. bool Game::is_win_vertical(char piece) { if (board[0][0] == piece && board[0][1] == piece && board[0][2] == piece) { return true; } if (board[1][0] == piece && board[1][1] == piece && board[1][2] == piece) { return true; } if (board[2][0] == piece && board[2][1] == piece && board[2][2] == piece) { return true; } return false; //No win if none of these return true. } bool Game::is_win_horizontal(char piece) { if (board[0][0] == piece && board[1][0] == piece && board[2][0] == piece) { return true; } if (board[0][1] == piece && board[1][1] == piece && board[2][1] == piece) { return true; } if (board[0][2] == piece && board[1][2] == piece && board[2][2] == piece) { return true; } return false; //No win if none of these return true. } bool Game::is_win_diagonal(char piece) { if (board[0][0] == piece && board[1][1] == piece && board[2][2] == piece) { return true; } if (board[2][0] == piece && board[1][1] == piece && board[0][2] == piece) { return true; } return false; //No win if none of these return true. } <|endoftext|>
<commit_before>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/connection> #include <pqxx/nontransaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Test program for libpqxx. Read and print table using field iterators. // // Usage: test082 [table] [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { connection C(argv[1] ? argv[2] : 0); nontransaction T(C, "test82"); const string Table = (argv[1] ? argv[1] : "pqxxevents"); result R( T.exec("SELECT * FROM " + Table) ); C.disconnect(); if (R.empty()) throw runtime_error("Got empty result!"); const string nullstr("[null]"); for (result::tuple::const_iterator f = R[0].begin(); f != R[0].end(); ++f) cout << f->name() << '\t'; cout << endl << endl; for (result::const_iterator r = R.begin(); r != R.end(); ++r) { result::tuple::const_iterator f2(r[0]); for (result::tuple::const_iterator f=r->begin(); f!=r->end(); ++f, f2++) { cout << f->c_str() << '\t'; if ((*f2).as(nullstr) != f->as(nullstr)) throw logic_error("Inconsistent iteration result: " "'" + (*f2).as<string>() + "' vs '" + f2->c_str() + "'"); } if (r->begin() + r->size() != r->end()) throw logic_error("Tuple end() appears to be in the wrong place"); if (r->size() + r->begin() != r->end()) throw logic_error("Field iterator addition not commutative"); if (r->begin()->num() != 0) throw logic_error("Unexpected column number at begin(): " + to_string(r->begin()->num())); result::tuple::const_iterator f3(r[r->size()]); if (!(f3 == r->end())) throw logic_error("Did not get end() at end of tuple"); if (f3 <= r->begin()) throw logic_error("Tuple end() appears to precede tuple begin()"); if (f3 < r->end() || !(r->begin() < f3)) throw logic_error("Field iterator < operator seems to be broken"); if (!(f3 > r->begin())) throw logic_error("Tuple end() not greater than begin(); empty tuple?"); result::tuple::const_iterator f4(*r, r->size()); if (f4 != f3) throw logic_error("Field iterator constructor with offset broken"); f3--; f4 -= 1; if (!(f3 < r->end())) throw logic_error("Last field in tuple not before end()"); if (!(f3 >= r.begin())) throw logic_error("Last field in tuple appears to precede begin()"); if (f3 != r.end()-1) throw logic_error("Back from end() does not yield end()-1"); if (r->end() - f3 != 1) throw logic_error("Wrong distance from last tuple to end(): " "expected 1, got " + to_string(r->end() - f3)); if (f4 != f3) throw logic_error("Looks like field iterator -= doesn't work"); f4 += 1; if (f4 != r->end()) throw logic_error("Looks like field iterator += doesn't work"); #ifdef PQXX_HAVE_REVERSE_ITERATOR for (result::tuple::const_reverse_iterator fr = r->rbegin(); fr != r->rend(); ++fr, --f3) { } #endif // PQXX_HAVE_REVERSE_ITERATOR cout <<endl; } } catch (const sql_error &e) { cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { cerr << "Unhandled exception" << endl; return 100; } return 0; } <commit_msg>Test result::tuple::const_reverse_iterator<commit_after>#include <pqxx/compiler.h> #include <iostream> #include <pqxx/connection> #include <pqxx/nontransaction> #include <pqxx/result> using namespace PGSTD; using namespace pqxx; // Test program for libpqxx. Read and print table using field iterators. // // Usage: test082 [table] [connect-string] // // Where connect-string is a set of connection options in Postgresql's // PQconnectdb() format, eg. "dbname=template1" to select from a database // called template1, or "host=foo.bar.net user=smith" to connect to a // backend running on host foo.bar.net, logging in as user smith. int main(int, char *argv[]) { try { connection C(argv[1] ? argv[2] : 0); nontransaction T(C, "test82"); const string Table = (argv[1] ? argv[1] : "pqxxevents"); result R( T.exec("SELECT * FROM " + Table) ); C.disconnect(); if (R.empty()) throw runtime_error("Got empty result!"); const string nullstr("[null]"); for (result::tuple::const_iterator f = R[0].begin(); f != R[0].end(); ++f) cout << f->name() << '\t'; cout << endl << endl; for (result::const_iterator r = R.begin(); r != R.end(); ++r) { result::tuple::const_iterator f2(r[0]); for (result::tuple::const_iterator f=r->begin(); f!=r->end(); ++f, f2++) { cout << f->c_str() << '\t'; if ((*f2).as(nullstr) != f->as(nullstr)) throw logic_error("Inconsistent iteration result: " "'" + (*f2).as<string>() + "' vs '" + f2->c_str() + "'"); } if (r->begin() + r->size() != r->end()) throw logic_error("Tuple end() appears to be in the wrong place"); if (r->size() + r->begin() != r->end()) throw logic_error("Field iterator addition not commutative"); if (r->begin()->num() != 0) throw logic_error("Unexpected column number at begin(): " + to_string(r->begin()->num())); result::tuple::const_iterator f3(r[r->size()]); if (!(f3 == r->end())) throw logic_error("Did not get end() at end of tuple"); if (f3 <= r->begin()) throw logic_error("Tuple end() appears to precede tuple begin()"); if (f3 < r->end() || !(r->begin() < f3)) throw logic_error("Field iterator < operator seems to be broken"); if (!(f3 > r->begin())) throw logic_error("Tuple end() not greater than begin(); empty tuple?"); result::tuple::const_iterator f4(*r, r->size()); if (f4 != f3) throw logic_error("Field iterator constructor with offset broken"); f3--; f4 -= 1; if (!(f3 < r->end())) throw logic_error("Last field in tuple not before end()"); if (!(f3 >= r.begin())) throw logic_error("Last field in tuple appears to precede begin()"); if (f3 != r.end()-1) throw logic_error("Back from end() does not yield end()-1"); if (r->end() - f3 != 1) throw logic_error("Wrong distance from last tuple to end(): " "expected 1, got " + to_string(r->end() - f3)); if (f4 != f3) throw logic_error("Looks like field iterator -= doesn't work"); f4 += 1; if (f4 != r->end()) throw logic_error("Looks like field iterator += doesn't work"); for (result::tuple::const_reverse_iterator fr = r->rbegin(); fr != r->rend(); ++fr, --f3) { if (*fr != *f3) throw logic_error("Reverse and regular traversal not consistent"); } cout <<endl; } // Thorough test for result::const_reverse_fielditerator result::tuple::const_reverse_iterator ri1(R.front().rbegin()), ri2(ri1), ri3(R.front().end()); ri2 = R.front().rbegin(); if (!(ri1 == ri2)) throw logic_error("Copy-constructed reverse_iterator " "not identical to assigned one"); if (ri2 != ri3) throw logic_error("result:end() does not generate rbegin()"); if (ri2 - ri3) throw logic_error("Distance between identical const_reverse_iterators " "is nonzero: " + to_string(ri2 - ri3)); if (ri2 != ri3 + 0) throw logic_error("reverse_iterator+0 gives strange result"); if (ri2 != ri3 - 0) throw logic_error("reverse_iterator-0 gives strange result"); if (ri3 < ri2) throw logic_error("Equality with reverse_iterator operator < wrong"); if (!(ri2 <= ri3)) throw logic_error("Equality with reverse_iterator operator <= wrong"); if (ri3++ != ri2) throw logic_error("reverse_iterator postfix ++ returns wrong result"); if (ri3 - ri2 != 1) throw logic_error("Nonzero reverse_iterator distance came out at " + to_string(ri3 - ri2) + ", " "expected 1"); if (!(ri3 > ri2)) throw logic_error("Something wrong with reverse_iterator operator >"); if (!(ri3 >= ri2)) throw logic_error("Something wrong with reverse_iterator operator >="); if (!(ri2 < ri3)) throw logic_error("Something wrong with reverse_iterator operator <"); if (!(ri2 <= ri3)) throw logic_error("Something wrong with reverse_iterator operator <="); if (ri3 != ri2 + 1) throw logic_error("Adding number to reverse_iterator goes wrong"); if (ri2 != ri3 - 1) throw logic_error("Subtracting from reverse_iterator goes wrong"); if (ri3 != ++ri2) throw logic_error("reverse_iterator prefix ++ returns wrong result"); if (!(ri3 >= ri2)) throw logic_error("Equality with reverse_iterator operator >= failed"); if (!(ri3 >= ri2)) throw logic_error("Equality with reverse_iterator operator <= failed"); if (ri3.base() != R.front().back()) throw logic_error("reverse_iterator does not arrive at back()"); if (ri1->c_str()[0] != (*ri1).c_str()[0]) throw logic_error("reverse_iterator -> differs from * operator"); if (ri2-- != ri3) throw logic_error("reverse_iterator postfix -- returns wrong result"); if (ri2 != --ri3) throw logic_error("reverse_iterator prefix -- returns wrong result"); if (ri2 != R.front().rbegin()) throw logic_error("Something wrong with reverse_iterator -- operator"); ri2 += 1; ri3 -= -1; if (ri2 == R.front().rbegin()) throw logic_error("Adding to reverse_iterator doesn't work"); if (ri3 != ri2) throw logic_error("reverse_iterator -= broken for negative numbers?"); ri2 -= 1; if (ri2 != R.front().rbegin()) throw logic_error("reverse_iterator += and -= do not cancel out"); } catch (const sql_error &e) { cerr << "SQL error: " << e.what() << endl << "Query was: '" << e.query() << "'" << endl; return 1; } catch (const exception &e) { cerr << "Exception: " << e.what() << endl; return 2; } catch (...) { cerr << "Unhandled exception" << endl; return 100; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2013 Gustaf Räntilä * * 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 <q/scheduler.hpp> #include <vector> namespace q { /** * Circular list. * * This container can be iterated forward forever, by circulating over the same * underlying list of elements. Useful for round-robin distribution. */ template< typename T > class circular_list { public: circular_list( ) // TODO: Use q::make_unique : mutex_( std::unique_ptr< q::mutex >( new q::mutex( Q_HERE, "circular_list" ) ) ) { next_ = list_.begin( ); } void add( T&& t ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); auto set_next = empty( ); list_.push_back( std::move( t ) ); if ( set_next ) next_ = list_.begin( ); } void remove( T&& t ) { ; // TODO: Implement } /** * Returns a pointer to the "next" element, or nullptr if the circular * list is empty. */ T next( ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); if ( list_.empty( ) ) return T( ); auto ret = next_; traverse( ); return ret; } template< typename Cond > T find_first( Cond&& cond ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); if ( list_.empty( ) ) return T( ); auto here = next_; do { if ( Cond( *next_ ) ) { auto ret = next_; traverse( ); return *ret; } traverse( ); } while ( here != next_ ); return T( ); } bool empty( ) const { return list_.empty( ); } private: void traverse( ) { if ( ++next_ == list_.end( ) ) next_ = list_.begin( ); } std::unique_ptr< q::mutex > mutex_; std::vector< T > list_; typename std::vector< T >::iterator next_; }; template< typename T > struct deduct_element_type { typedef typename T::element_type type; }; template< typename T > struct deduct_element_type< std::shared_ptr< T > > { typedef typename T::element_type type; }; template< typename P, typename T > class round_robin_priority_list { public: typedef typename deduct_element_type< T >::type element_type; round_robin_priority_list( ) = default; void add( P&& priority, T&& elem ) { auto iter = std::lower_bound( list_.begin( ), list_.end( ), priority ); if ( iter == list_.end( ) || iter->priority_ != priority ) { // Insert new unique priority circular list list_element_type element{ std::move( priority ) }; iter = list_.insert( iter, std::move( element ) ); } iter->circular_list_.add( std::move( elem ) ); } void remove( P&& priority, T&& elem ) { // TODO: Implement } element_type pop_next( ) { for ( auto& elem : list_ ) { if ( !elem.circular_list_.empty( ) ) { auto condition = [ ]( const queue_ptr& queue ) { return !queue->empty( ); }; auto found = elem.circular_list_.find_first( condition ); if ( !!found ) return found->pop( ); } } return element_type( ); } private: struct list_element_type { P priority_; circular_list< T > circular_list_; operator P( ) const { return priority_; } }; std::vector< list_element_type > list_; }; struct priority_scheduler::pimpl { pimpl( const event_dispatcher_ptr& event_dispatcher ) : event_dispatcher_( event_dispatcher ) { } event_dispatcher_ptr event_dispatcher_; round_robin_priority_list< priority_t, queue_ptr > queues_; }; priority_scheduler::priority_scheduler( const event_dispatcher_ptr& event_dispatcher ) : pimpl_( new pimpl( event_dispatcher ) ) { } priority_scheduler::~priority_scheduler( ) { } void priority_scheduler::add_queue( queue_ptr queue ) { pimpl_->queues_.add( queue->priority( ), queue_ptr( queue ) ); auto backlog = queue->set_consumer( std::bind( &priority_scheduler::poke, this ) ); for ( auto i = backlog; i > 0; --i ) poke( ); } void priority_scheduler::poke( ) { auto _this = shared_from_this( ); auto runner = [ _this ]( ) mutable { // TODO: Ensure this doesn't throw... auto t = _this->next_task( ); if ( !!t ) t( ); }; pimpl_->event_dispatcher_->add_task( std::move( runner ) ); } task priority_scheduler::next_task( ) { task ret = pimpl_->queues_.pop_next( ); return std::move( ret ); } struct direct_scheduler::pimpl { event_dispatcher_ptr event_dispatcher_; q::mutex mutex_; queue_ptr queue_; }; direct_scheduler::direct_scheduler( const event_dispatcher_ptr& event_dispatcher ) : pimpl_( new pimpl{ event_dispatcher, { Q_HERE, "direct_scheduler" } } ) { } direct_scheduler::~direct_scheduler( ) { } void direct_scheduler::add_queue( queue_ptr queue ) { Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_ ); if ( !pimpl_->queue_ ) { pimpl_->queue_ = queue; auto backlog = queue->set_consumer( std::bind( &direct_scheduler::poke, this ) ); for ( auto i = backlog; i > 0; --i ) poke( ); } else { Q_THROW( not_unique_exception( ) ); } } void direct_scheduler::poke( ) { auto _this = shared_from_this( ); auto runner = [ _this ]( ) mutable { // TODO: Ensure this doesn't throw... auto t = _this->next_task( ); if ( !!t ) t( ); }; pimpl_->event_dispatcher_->add_task( std::move( runner ) ); } task direct_scheduler::next_task( ) { task ret = pimpl_->queue_->pop( ); return std::move( ret ); } } // namespace q <commit_msg>Use q::make_unique<commit_after>/* * Copyright 2013 Gustaf Räntilä * * 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 <q/scheduler.hpp> #include <vector> namespace q { /** * Circular list. * * This container can be iterated forward forever, by circulating over the same * underlying list of elements. Useful for round-robin distribution. */ template< typename T > class circular_list { public: circular_list( ) // TODO: Use q::make_unique : mutex_( q::make_unique< q::mutex >( Q_HERE, "circular_list" ) ) { next_ = list_.begin( ); } void add( T&& t ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); auto set_next = empty( ); list_.push_back( std::move( t ) ); if ( set_next ) next_ = list_.begin( ); } void remove( T&& t ) { ; // TODO: Implement } /** * Returns a pointer to the "next" element, or nullptr if the circular * list is empty. */ T next( ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); if ( list_.empty( ) ) return T( ); auto ret = next_; traverse( ); return ret; } template< typename Cond > T find_first( Cond&& cond ) { Q_AUTO_UNIQUE_LOCK( *mutex_ ); if ( list_.empty( ) ) return T( ); auto here = next_; do { if ( Cond( *next_ ) ) { auto ret = next_; traverse( ); return *ret; } traverse( ); } while ( here != next_ ); return T( ); } bool empty( ) const { return list_.empty( ); } private: void traverse( ) { if ( ++next_ == list_.end( ) ) next_ = list_.begin( ); } std::unique_ptr< q::mutex > mutex_; std::vector< T > list_; typename std::vector< T >::iterator next_; }; template< typename T > struct deduct_element_type { typedef typename T::element_type type; }; template< typename T > struct deduct_element_type< std::shared_ptr< T > > { typedef typename T::element_type type; }; template< typename P, typename T > class round_robin_priority_list { public: typedef typename deduct_element_type< T >::type element_type; round_robin_priority_list( ) = default; void add( P&& priority, T&& elem ) { auto iter = std::lower_bound( list_.begin( ), list_.end( ), priority ); if ( iter == list_.end( ) || iter->priority_ != priority ) { // Insert new unique priority circular list list_element_type element{ std::move( priority ) }; iter = list_.insert( iter, std::move( element ) ); } iter->circular_list_.add( std::move( elem ) ); } void remove( P&& priority, T&& elem ) { // TODO: Implement } element_type pop_next( ) { for ( auto& elem : list_ ) { if ( !elem.circular_list_.empty( ) ) { auto condition = [ ]( const queue_ptr& queue ) { return !queue->empty( ); }; auto found = elem.circular_list_.find_first( condition ); if ( !!found ) return found->pop( ); } } return element_type( ); } private: struct list_element_type { P priority_; circular_list< T > circular_list_; operator P( ) const { return priority_; } }; std::vector< list_element_type > list_; }; struct priority_scheduler::pimpl { pimpl( const event_dispatcher_ptr& event_dispatcher ) : event_dispatcher_( event_dispatcher ) { } event_dispatcher_ptr event_dispatcher_; round_robin_priority_list< priority_t, queue_ptr > queues_; }; priority_scheduler::priority_scheduler( const event_dispatcher_ptr& event_dispatcher ) : pimpl_( new pimpl( event_dispatcher ) ) { } priority_scheduler::~priority_scheduler( ) { } void priority_scheduler::add_queue( queue_ptr queue ) { pimpl_->queues_.add( queue->priority( ), queue_ptr( queue ) ); auto backlog = queue->set_consumer( std::bind( &priority_scheduler::poke, this ) ); for ( auto i = backlog; i > 0; --i ) poke( ); } void priority_scheduler::poke( ) { auto _this = shared_from_this( ); auto runner = [ _this ]( ) mutable { // TODO: Ensure this doesn't throw... auto t = _this->next_task( ); if ( !!t ) t( ); }; pimpl_->event_dispatcher_->add_task( std::move( runner ) ); } task priority_scheduler::next_task( ) { task ret = pimpl_->queues_.pop_next( ); return std::move( ret ); } struct direct_scheduler::pimpl { event_dispatcher_ptr event_dispatcher_; q::mutex mutex_; queue_ptr queue_; }; direct_scheduler::direct_scheduler( const event_dispatcher_ptr& event_dispatcher ) : pimpl_( new pimpl{ event_dispatcher, { Q_HERE, "direct_scheduler" } } ) { } direct_scheduler::~direct_scheduler( ) { } void direct_scheduler::add_queue( queue_ptr queue ) { Q_AUTO_UNIQUE_LOCK( pimpl_->mutex_ ); if ( !pimpl_->queue_ ) { pimpl_->queue_ = queue; auto backlog = queue->set_consumer( std::bind( &direct_scheduler::poke, this ) ); for ( auto i = backlog; i > 0; --i ) poke( ); } else { Q_THROW( not_unique_exception( ) ); } } void direct_scheduler::poke( ) { auto _this = shared_from_this( ); auto runner = [ _this ]( ) mutable { // TODO: Ensure this doesn't throw... auto t = _this->next_task( ); if ( !!t ) t( ); }; pimpl_->event_dispatcher_->add_task( std::move( runner ) ); } task direct_scheduler::next_task( ) { task ret = pimpl_->queue_->pop( ); return std::move( ret ); } } // namespace q <|endoftext|>
<commit_before>#include "fs.h" #include "files.h" #include <unistd.h> #include <sys/types.h> #include <dirent.h> #include <string> #include <vector> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <host/CopyFile.h> using namespace std; static bool is_dir(const string& path) { int err; struct stat st; err = stat(path.c_str(), &st); return err != 0 || S_ISDIR(st.st_mode); } static int remove_file(const string& path) { int err = unlink(path.c_str()); if (err != 0) { fprintf(stderr, "error deleting file %s (%s)\n", path.c_str(), strerror(errno)); return errno; } return 0; } int remove_recursively(const string& path) { int err; if (is_dir(path)) { DIR *d = opendir(path.c_str()); if (d == NULL) { fprintf(stderr, "error getting directory contents %s (%s)\n", path.c_str(), strerror(errno)); return errno; } vector<string> files; vector<string> dirs; struct dirent *ent; while (NULL != (ent = readdir(d))) { if (0 == strcmp(".", ent->d_name) || 0 == strcmp("..", ent->d_name)) { continue; } string full = path; full += '/'; full += ent->d_name; #ifdef HAVE_DIRENT_D_TYPE bool is_directory = (ent->d_type == DT_DIR); #else // If dirent.d_type is missing, then use stat instead struct stat stat_buf; stat(full.c_str(), &stat_buf); bool is_directory = S_ISDIR(stat_buf.st_mode); #endif if (is_directory) { dirs.push_back(full); } else { files.push_back(full); } } closedir(d); for (vector<string>::iterator it=files.begin(); it!=files.end(); it++) { err = remove_file(*it); if (err != 0) { return err; } } for (vector<string>::iterator it=dirs.begin(); it!=dirs.end(); it++) { err = remove_recursively(*it); if (err != 0) { return err; } } err = rmdir(path.c_str()); if (err != 0) { fprintf(stderr, "error deleting directory %s (%s)\n", path.c_str(), strerror(errno)); return errno; } return 0; } else { return remove_file(path); } } int mkdir_recursively(const string& path) { int err; size_t pos = 0; while (true) { pos = path.find('/', pos); string p = path.substr(0, pos); struct stat st; err = stat(p.c_str(), &st); if (err != 0) { err = mkdir(p.c_str(), 0770); if (err != 0) { fprintf(stderr, "can't create directory %s (%s)\n", path.c_str(), strerror(errno)); return errno; } } else if (!S_ISDIR(st.st_mode)) { fprintf(stderr, "can't create directory %s because %s is a file.\n", path.c_str(), p.c_str()); return 1; } pos++; if (p == path) { return 0; } } } int copy_file(const string& src, const string& dst) { int err; err = copyFile(src.c_str(), dst.c_str(), COPY_NO_DEREFERENCE | COPY_FORCE | COPY_PERMISSIONS); return err; } <commit_msg>am 105a934f: am 9514fca5: merge from open-source master<commit_after>#include "fs.h" #include "files.h" #include <unistd.h> #include <sys/types.h> #include <dirent.h> #include <string> #include <vector> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <host/CopyFile.h> using namespace std; static bool is_dir(const string& path) { int err; struct stat st; err = stat(path.c_str(), &st); return err != 0 || S_ISDIR(st.st_mode); } static int remove_file(const string& path) { int err = unlink(path.c_str()); if (err != 0) { fprintf(stderr, "error deleting file %s (%s)\n", path.c_str(), strerror(errno)); return errno; } return 0; } int remove_recursively(const string& path) { int err; if (is_dir(path)) { DIR *d = opendir(path.c_str()); if (d == NULL) { fprintf(stderr, "error getting directory contents %s (%s)\n", path.c_str(), strerror(errno)); return errno; } vector<string> files; vector<string> dirs; struct dirent *ent; while (NULL != (ent = readdir(d))) { if (0 == strcmp(".", ent->d_name) || 0 == strcmp("..", ent->d_name)) { continue; } string full = path; full += '/'; full += ent->d_name; #ifdef HAVE_DIRENT_D_TYPE bool is_directory = (ent->d_type == DT_DIR); #else // If dirent.d_type is missing, then use stat instead struct stat stat_buf; stat(full.c_str(), &stat_buf); bool is_directory = S_ISDIR(stat_buf.st_mode); #endif if (is_directory) { dirs.push_back(full); } else { files.push_back(full); } } closedir(d); for (vector<string>::iterator it=files.begin(); it!=files.end(); it++) { err = remove_file(*it); if (err != 0) { return err; } } for (vector<string>::iterator it=dirs.begin(); it!=dirs.end(); it++) { err = remove_recursively(*it); if (err != 0) { return err; } } err = rmdir(path.c_str()); if (err != 0) { fprintf(stderr, "error deleting directory %s (%s)\n", path.c_str(), strerror(errno)); return errno; } return 0; } else { return remove_file(path); } } int mkdir_recursively(const string& path) { int err; size_t pos = 0; // For absolute pathnames, that starts with leading '/' // use appropriate initial value. if (path.length() != 0 and path[0] == '/') pos++; while (true) { pos = path.find('/', pos); string p = path.substr(0, pos); struct stat st; err = stat(p.c_str(), &st); if (err != 0) { err = mkdir(p.c_str(), 0770); if (err != 0) { fprintf(stderr, "can't create directory %s (%s)\n", path.c_str(), strerror(errno)); return errno; } } else if (!S_ISDIR(st.st_mode)) { fprintf(stderr, "can't create directory %s because %s is a file.\n", path.c_str(), p.c_str()); return 1; } pos++; if (p == path) { return 0; } } } int copy_file(const string& src, const string& dst) { int err; err = copyFile(src.c_str(), dst.c_str(), COPY_NO_DEREFERENCE | COPY_FORCE | COPY_PERMISSIONS); return err; } <|endoftext|>
<commit_before>#include "Halide.h" namespace { enum class BlurGPUSchedule { Inline, // Fully inlining schedule. Cache, // Schedule caching intermedia result of blur_x. Slide, // Schedule enabling sliding window opt within each // work-item or cuda thread. SlideVectorize, // The same as above plus vectorization per work-item. }; std::map<std::string, BlurGPUSchedule> blurGPUScheduleEnumMap() { return { {"inline", BlurGPUSchedule::Inline}, {"cache", BlurGPUSchedule::Cache}, {"slide", BlurGPUSchedule::Slide}, {"slide_vector", BlurGPUSchedule::SlideVectorize}, }; }; class HalideBlur : public Halide::Generator<HalideBlur> { public: GeneratorParam<BlurGPUSchedule> schedule{ "schedule", BlurGPUSchedule::SlideVectorize, blurGPUScheduleEnumMap() }; GeneratorParam<int> tile_x{"tile_x", 32}; // X tile. GeneratorParam<int> tile_y{"tile_y", 8}; // Y tile. ImageParam input{UInt(16), 2, "input"}; Func build() { Func blur_x("blur_x"), blur_y("blur_y"); Var x("x"), y("y"), xi("xi"), yi("yi"); // The algorithm blur_x(x, y) = (input(x, y) + input(x+1, y) + input(x+2, y))/3; blur_y(x, y) = (blur_x(x, y) + blur_x(x, y+1) + blur_x(x, y+2))/3; // How to schedule it if (get_target().has_gpu_feature()) { // GPU schedule. switch (schedule) { case BlurGPUSchedule::Inline: // - Fully inlining. blur_y.gpu_tile(x, y, xi, yi, tile_x, tile_y); break; case BlurGPUSchedule::Cache: // - Cache blur_x calculation. blur_y.gpu_tile(x, y, xi, yi, tile_x, tile_y); blur_x.compute_at(blur_y, xi).gpu_threads(x, y); break; case BlurGPUSchedule::Slide: { // - Instead caching blur_x calculation explicitly, the // alternative is to allow each work-item in OpenCL or thread // in CUDA to calculate more rows of blur_y so that temporary // blur_x calculation is re-used implicitly. This achieves // the similar schedule of sliding window. Var y_inner("y_inner"); blur_y.split(y, y, y_inner, tile_y).reorder(y_inner, x).unroll(y_inner) .gpu_tile(x, y, xi, yi, tile_x, 1); break; } case BlurGPUSchedule::SlideVectorize: { // Vectorization factor. int factor = sizeof(int)/sizeof(short); Var y_inner("y_inner"); blur_y.vectorize(x, factor) .split(y, y, y_inner, tile_y).reorder(y_inner, x).unroll(y_inner) .gpu_tile(x, y, xi, yi, tile_x, 1); break; } default: break; } } else { // CPU schedule. blur_y.split(y, y, yi, 8).parallel(y).vectorize(x, 8); blur_x.store_at(blur_y, y).compute_at(blur_y, yi).vectorize(x, 8); } return blur_y; } }; Halide::RegisterGenerator<HalideBlur> register_me{"halide_blur"}; } // namespace <commit_msg>fix compute_at()<commit_after>#include "Halide.h" namespace { enum class BlurGPUSchedule { Inline, // Fully inlining schedule. Cache, // Schedule caching intermedia result of blur_x. Slide, // Schedule enabling sliding window opt within each // work-item or cuda thread. SlideVectorize, // The same as above plus vectorization per work-item. }; std::map<std::string, BlurGPUSchedule> blurGPUScheduleEnumMap() { return { {"inline", BlurGPUSchedule::Inline}, {"cache", BlurGPUSchedule::Cache}, {"slide", BlurGPUSchedule::Slide}, {"slide_vector", BlurGPUSchedule::SlideVectorize}, }; }; class HalideBlur : public Halide::Generator<HalideBlur> { public: GeneratorParam<BlurGPUSchedule> schedule{ "schedule", BlurGPUSchedule::SlideVectorize, blurGPUScheduleEnumMap() }; GeneratorParam<int> tile_x{"tile_x", 32}; // X tile. GeneratorParam<int> tile_y{"tile_y", 8}; // Y tile. ImageParam input{UInt(16), 2, "input"}; Func build() { Func blur_x("blur_x"), blur_y("blur_y"); Var x("x"), y("y"), xi("xi"), yi("yi"); // The algorithm blur_x(x, y) = (input(x, y) + input(x+1, y) + input(x+2, y))/3; blur_y(x, y) = (blur_x(x, y) + blur_x(x, y+1) + blur_x(x, y+2))/3; // How to schedule it if (get_target().has_gpu_feature()) { // GPU schedule. switch (schedule) { case BlurGPUSchedule::Inline: // - Fully inlining. blur_y.gpu_tile(x, y, xi, yi, tile_x, tile_y); break; case BlurGPUSchedule::Cache: // - Cache blur_x calculation. blur_y.gpu_tile(x, y, xi, yi, tile_x, tile_y); blur_x.compute_at(blur_y, x).gpu_threads(x, y); break; case BlurGPUSchedule::Slide: { // - Instead caching blur_x calculation explicitly, the // alternative is to allow each work-item in OpenCL or thread // in CUDA to calculate more rows of blur_y so that temporary // blur_x calculation is re-used implicitly. This achieves // the similar schedule of sliding window. Var y_inner("y_inner"); blur_y.split(y, y, y_inner, tile_y).reorder(y_inner, x).unroll(y_inner) .gpu_tile(x, y, xi, yi, tile_x, 1); break; } case BlurGPUSchedule::SlideVectorize: { // Vectorization factor. int factor = sizeof(int)/sizeof(short); Var y_inner("y_inner"); blur_y.vectorize(x, factor) .split(y, y, y_inner, tile_y).reorder(y_inner, x).unroll(y_inner) .gpu_tile(x, y, xi, yi, tile_x, 1); break; } default: break; } } else { // CPU schedule. blur_y.split(y, y, yi, 8).parallel(y).vectorize(x, 8); blur_x.store_at(blur_y, y).compute_at(blur_y, yi).vectorize(x, 8); } return blur_y; } }; Halide::RegisterGenerator<HalideBlur> register_me{"halide_blur"}; } // namespace <|endoftext|>
<commit_before>/* * * Copyright 2019 Asylo 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 <cmath> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/base/macros.h" namespace { using ::testing::Eq; TEST(CmathTest, LongDoubleFunctions) { long double long_doubles[] = { std::hypotl(1.0, 2.0), std::sqrtl(1.0), }; EXPECT_THAT(ABSL_ARRAYSIZE(long_doubles), Eq(2)); } TEST(CmathTest, Tr1DoubleFunctions) { int quo; double doubles[] = { std::acosh(1.0), std::asinh(1.0), std::atanh(1.0), std::cbrt(1.0), std::copysign(1.0, 2.0), std::erf(1.0), std::erfc(1.0), std::exp2(1.0), std::expm1(1.0), std::fdim(1.0, 2.0), std::fma(1.0, 2.0, 3.0), std::fmax(1.0, 2.0), std::fmin(1.0, 2.0), std::hypot(1.0, 2.0), std::ilogb(1.0), std::lgamma(1.0), std::log1p(1.0), std::log2(1.0), std::logb(1.0), std::nan("NAN"), std::nearbyint(0.0), std::nextafter(1.0, HUGE_VAL), std::remainder(1.0, 2.0), std::remquo(1.0, 1.0, &quo), std::rint(1.0), std::round(1.0), std::scalbln(1.0, 3), std::scalbn(1.0, 3), std::tgamma(1.0), std::trunc(1.0), }; long int lvalues[] = { std::lrint(1.0), std::lround(1.0), }; long long int llvalues[] = { std::llrint(1.0), std::llround(1.0), }; EXPECT_THAT(ABSL_ARRAYSIZE(doubles), Eq(30)); EXPECT_THAT(ABSL_ARRAYSIZE(lvalues), Eq(2)); EXPECT_THAT(ABSL_ARRAYSIZE(llvalues), Eq(2)); } TEST(CmathTest, Tr1FloatFunctions) { int quo; float floats[] = { std::acoshf(1.0f), std::asinhf(1.0f), std::atanhf(1.0f), std::cbrtf(1.0f), std::copysignf(1.0f, 2.0f), std::erff(1.0f), std::erfcf(1.0f), std::exp2f(1.0f), std::expm1f(1.0f), std::fdimf(1.0f, 2.0f), std::fmaf(1.0f, 2.0f, 3.0f), std::fmaxf(1.0f, 2.0f), std::fminf(1.0f, 2.0f), std::hypotf(1.0f, 2.0f), std::ilogbf(1.0f), std::lgammaf(1.0f), std::log1pf(1.0f), std::log2f(1.0f), std::logbf(1.0f), std::nanf("NAN"), std::nearbyintf(0.2f), std::nextafterf(1.0f, HUGE_VALF), std::remainderf(1.0f, 2.0f), std::remquof(1.0f, 1.0f, &quo), std::rintf(1.0f), std::roundf(1.0f), std::scalblnf(1.0f, 3), std::scalbnf(1.0f, 3), std::tgammaf(1.0f), std::truncf(1.0f), }; long int lvalues[] = { std::lrintf(1.0f), std::lroundf(1.0f), }; long long int llvalues[] = { std::llrintf(1.0f), std::llroundf(1.0f), }; EXPECT_THAT(ABSL_ARRAYSIZE(floats), Eq(30)); EXPECT_THAT(ABSL_ARRAYSIZE(lvalues), Eq(2)); EXPECT_THAT(ABSL_ARRAYSIZE(llvalues), Eq(2)); } } // namespace <commit_msg>Fix int->double/float narrowing in cmath_test<commit_after>/* * * Copyright 2019 Asylo 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 <cmath> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/base/macros.h" namespace { using ::testing::Eq; TEST(CmathTest, LongDoubleFunctions) { long double long_doubles[] = { std::hypotl(1.0, 2.0), std::sqrtl(1.0), }; EXPECT_THAT(ABSL_ARRAYSIZE(long_doubles), Eq(2)); } TEST(CmathTest, Tr1DoubleFunctions) { int quo; double doubles[] = { std::acosh(1.0), std::asinh(1.0), std::atanh(1.0), std::cbrt(1.0), std::copysign(1.0, 2.0), std::erf(1.0), std::erfc(1.0), std::exp2(1.0), std::expm1(1.0), std::fdim(1.0, 2.0), std::fma(1.0, 2.0, 3.0), std::fmax(1.0, 2.0), std::fmin(1.0, 2.0), std::hypot(1.0, 2.0), static_cast<double>(std::ilogb(1.0)), std::lgamma(1.0), std::log1p(1.0), std::log2(1.0), std::logb(1.0), std::nan("NAN"), std::nearbyint(0.0), std::nextafter(1.0, HUGE_VAL), std::remainder(1.0, 2.0), std::remquo(1.0, 1.0, &quo), std::rint(1.0), std::round(1.0), std::scalbln(1.0, 3), std::scalbn(1.0, 3), std::tgamma(1.0), std::trunc(1.0), }; long int lvalues[] = { std::lrint(1.0), std::lround(1.0), }; long long int llvalues[] = { std::llrint(1.0), std::llround(1.0), }; EXPECT_THAT(ABSL_ARRAYSIZE(doubles), Eq(30)); EXPECT_THAT(ABSL_ARRAYSIZE(lvalues), Eq(2)); EXPECT_THAT(ABSL_ARRAYSIZE(llvalues), Eq(2)); } TEST(CmathTest, Tr1FloatFunctions) { int quo; float floats[] = { std::acoshf(1.0f), std::asinhf(1.0f), std::atanhf(1.0f), std::cbrtf(1.0f), std::copysignf(1.0f, 2.0f), std::erff(1.0f), std::erfcf(1.0f), std::exp2f(1.0f), std::expm1f(1.0f), std::fdimf(1.0f, 2.0f), std::fmaf(1.0f, 2.0f, 3.0f), std::fmaxf(1.0f, 2.0f), std::fminf(1.0f, 2.0f), std::hypotf(1.0f, 2.0f), static_cast<float>(std::ilogbf(1.0f)), std::lgammaf(1.0f), std::log1pf(1.0f), std::log2f(1.0f), std::logbf(1.0f), std::nanf("NAN"), std::nearbyintf(0.2f), std::nextafterf(1.0f, HUGE_VALF), std::remainderf(1.0f, 2.0f), std::remquof(1.0f, 1.0f, &quo), std::rintf(1.0f), std::roundf(1.0f), std::scalblnf(1.0f, 3), std::scalbnf(1.0f, 3), std::tgammaf(1.0f), std::truncf(1.0f), }; long int lvalues[] = { std::lrintf(1.0f), std::lroundf(1.0f), }; long long int llvalues[] = { std::llrintf(1.0f), std::llroundf(1.0f), }; EXPECT_THAT(ABSL_ARRAYSIZE(floats), Eq(30)); EXPECT_THAT(ABSL_ARRAYSIZE(lvalues), Eq(2)); EXPECT_THAT(ABSL_ARRAYSIZE(llvalues), Eq(2)); } } // namespace <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/proto_utils.h" #include "gtest/gtest.h" #include <cmath> #include <random> namespace caffe2 { namespace { void AddNoiseInput(const vector<TIndex>& shape, const string& name, Workspace* ws) { DeviceOption option; CPUContext context(option); Blob* blob = ws->CreateBlob(name); auto* tensor = blob->GetMutable<TensorCPU>(); tensor->Resize(shape); math::RandGaussian<float, CPUContext>( tensor->size(), 0.0f, 3.0f, tensor->mutable_data<float>(), &context); for (auto i = 0; i < tensor->size(); ++i) { tensor->mutable_data<float>()[i] = std::min(-5.0f, std::max(5.0f, tensor->mutable_data<float>()[i])); } } inline float relativeError(float a, float b) { return std::abs(a - b) / (0.5f * (std::abs(a) + std::abs(b))); } void compare( int N, int inputC, int H, int W, int outputC, int kernelH, int kernelW, int strideH, int strideW, int padT, int padL, int padB, int padR, int group, const std::string& algorithm, const std::string& convolutionTransformStrategy, float maxRelErr, float absErrForRelErrFailure) { LOG(INFO) << "running N " << N << " inputC " << inputC << " H " << H << " W " << W << " outputC " << outputC << " kernelH " << kernelH << " kernelW " << kernelW << " strideH " << strideH << " strideW " << strideW << " padT " << padT << " padL " << padL << " padB " << padB << " padR " << padR << " group " << group; Workspace ws; OperatorDef nnpackOpDef; nnpackOpDef.set_name("test"); nnpackOpDef.set_type("Conv"); nnpackOpDef.set_engine("NNPACK"); nnpackOpDef.add_input("X"); nnpackOpDef.add_input("W"); nnpackOpDef.add_input("B"); nnpackOpDef.add_output("Y_nnpack"); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("kernel_h", kernelH)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("kernel_w", kernelW)); if (!algorithm.empty()) { nnpackOpDef.add_arg()->CopyFrom(MakeArgument("algo", algorithm)); } if (!convolutionTransformStrategy.empty()) { nnpackOpDef.add_arg()->CopyFrom(MakeArgument( "convolution_transform_strategy", convolutionTransformStrategy)); } nnpackOpDef.add_arg()->CopyFrom(MakeArgument("stride_h", strideH)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("stride_w", strideW)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_t", padT)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_l", padL)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_b", padB)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_r", padR)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("group", group)); AddNoiseInput(vector<TIndex>{N, inputC, H, W}, "X", &ws); AddNoiseInput(vector<TIndex>{outputC, inputC / group , kernelH, kernelW}, "W", &ws); AddNoiseInput(vector<TIndex>{outputC}, "B", &ws); unique_ptr<OperatorBase> nnpackOp(CreateOperator(nnpackOpDef, &ws)); EXPECT_NE(nullptr, nnpackOp.get()); OperatorDef referenceOpDef; referenceOpDef.set_name("test"); referenceOpDef.set_type("Conv"); referenceOpDef.add_input("X"); referenceOpDef.add_input("W"); referenceOpDef.add_input("B"); referenceOpDef.add_output("Y_reference"); referenceOpDef.add_arg()->CopyFrom(MakeArgument("kernel_h", kernelH)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("kernel_w", kernelW)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("stride_h", strideH)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("stride_w", strideW)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_t", padT)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_l", padL)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_b", padB)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_r", padR)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("group", group)); unique_ptr<OperatorBase> referenceOp(CreateOperator(referenceOpDef, &ws)); EXPECT_NE(nullptr, referenceOp.get()); for (auto i = 0; i < 10; ++i) { EXPECT_TRUE(nnpackOp->Run()); } Blob* nnpackOutputBlob = ws.GetBlob("Y_nnpack"); EXPECT_NE(nullptr, nnpackOutputBlob); auto& nnpackOutput = nnpackOutputBlob->Get<TensorCPU>(); for (auto i = 0; i < 10; ++i) { EXPECT_TRUE(referenceOp->Run()); } Blob* referenceOutputBlob = ws.GetBlob("Y_reference"); EXPECT_NE(nullptr, referenceOutputBlob); auto& referenceOutput = referenceOutputBlob->Get<TensorCPU>(); // Compare all output points for (int n = 0; n < nnpackOutput.dim32(0); ++n) { for (int c = 0; c < nnpackOutput.dim32(1); ++c) { for (int h = 0; h < nnpackOutput.dim32(2); ++h) { for (int w = 0; w < nnpackOutput.dim32(3); ++w) { int offset = n * nnpackOutput.dim32(1) * nnpackOutput.dim32(2) * nnpackOutput.dim32(3) + c * nnpackOutput.dim32(2) * nnpackOutput.dim32(3) + h * nnpackOutput.dim32(3) + w; auto v1 = nnpackOutput.data<float>()[offset]; auto v2 = referenceOutput.data<float>()[offset]; float relErr = relativeError(v1, v2); float absErr = std::abs(v1 - v2); // For small values / small difference, the relative error // can be huge but the absolute error will be small EXPECT_TRUE( relErr <= maxRelErr || (relErr > maxRelErr && absErr <= absErrForRelErrFailure)) << v1 << " " << v2 << " (rel err " << relErr << ") " << "(" << n << " " << c << " " << h << " " << w << ") " << "running N " << N << " inputC " << inputC << " H " << H << " W " << W << " outputC " << outputC << " kernelH " << kernelH << " kernelW " << kernelW << " strideH " << strideH << " strideW " << strideW << " padT " << padT << " padL " << padL << " padB " << padB << " padR " << padR << " group " << group << " algorithm " << algorithm << " convolutionTransformStrategy " << convolutionTransformStrategy; } } } } } int randInt(int a, int b) { static std::random_device rd; static std::mt19937 gen(rd()); return std::uniform_int_distribution<int>(a, b)(gen); } void runConv(int kernelH, int kernelW, int strideH, int strideW, int group = 1, std::string algo = "", int planesIn = randInt(1, 6), int planesOut = randInt(1, 6), int n = randInt(1, 2), std::string convolutionTransformStrategy = "COMPUTE") { int h = randInt(20, 100); int w = randInt(20, 100); // This pad restriction is imposed by NNPACK int padT = std::min(randInt(0, 3), kernelH - 1); int padB = std::min(randInt(0, 3), kernelH - 1); int padL = std::min(randInt(0, 3), kernelW - 1); int padR = std::min(randInt(0, 3), kernelW - 1); caffe2::compare(n, planesIn, h, w, planesOut, kernelH, kernelW, strideH, strideW, padT, padL, padB, padR, group, algo, convolutionTransformStrategy, 0.05f, 0.1f); } } // unnamed namespace constexpr size_t kIters = 20; // TODO(#14383029) cblas_sgemm not yet implemented on limited mobile cases. #if !defined(CAFFE2_FB_LIMITED_MOBILE_CAPABILITY) TEST(MobileNNPACK, Conv_3x3s1) { for (int i = 0; i < kIters; ++i) { runConv(3, 3, 1, 1); } } TEST(MobileNNPACK, Conv_3x3s1_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(1, 2); runConv(3, 3, 1, 1, group, "WINOGRAD", group * randInt(1, 8), group * randInt(1, 8), 1, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_3x3s1_FP16) { for (int i = 0; i < kIters; ++i) { runConv(3, 3, 1, 1, 1, "WINOGRAD_FP16"); } } TEST(MobileNNPACK, Conv_3x3s1_FP16_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(1, 2); runConv(3, 3, 1, 1, group, "WINOGRAD_FP16", group * randInt(1, 8), group * randInt(1, 8), 1, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNs1) { for (int i = 0; i < kIters; ++i) { int kernel = randInt(2, 10); runConv(kernel, kernel, 1, 1); } } TEST(MobileNNPACK, Conv_1x1s1) { for (int i = 0; i < kIters; ++i) { auto group = randInt(1, 3); auto inChannels = randInt(1, 8) * group; auto outChannels = randInt(1, 8) * group; auto n = 1; runConv(1, 1, 1, 1, group, "DIRECT", inChannels, outChannels, n); } } TEST(MobileNNPACK, Conv_1x1s1_precompute) { for (int i = 0; i < kIters; ++i) { auto group = randInt(1, 3); auto inChannels = randInt(1, 8) * group; auto outChannels = randInt(1, 8) * group; auto n = 1; runConv(1, 1, 1, 1, group, "DIRECT", inChannels, outChannels, n, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNs_grouped) { for (int i = 0; i < kIters; ++i) { int group = randInt(2, 3); int iC = randInt(1, 6) * group; int oC = randInt(1, 6) * group; int kernel = randInt(2, 10); int n = randInt(1, 2); runConv(kernel, kernel, 1, 1, group, "", iC, oC, n); } } TEST(MobileNNPACK, Conv_NxNs_grouped_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(2, 3); int iC = randInt(1, 6) * group; int oC = randInt(1, 6) * group; int kernel = randInt(2, 10); int n = randInt(1, 2); runConv(kernel, kernel, 1, 1, group, "", iC, oC, n, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNsW) { for (int i = 0; i < 3; ++i) { int kernel = randInt(3, 5); int stride = randInt(1, kernel - 1); runConv(kernel, kernel, stride, stride); } } TEST(MobileNNPACK, Conv_HxWsHxW) { for (int i = 0; i < 3; ++i) { int kernelH = randInt(2, 5); int kernelW = randInt(2, 5); int strideH = randInt(1, kernelH - 1); int strideW = randInt(1, kernelW - 1); runConv(kernelH, kernelW, strideH, strideW); } } #endif } // namespace caffe2 <commit_msg>Depthwise F(2x2, 3x3) convolution<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "caffe2/core/init.h" #include "caffe2/core/operator.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/math.h" #include "caffe2/utils/proto_utils.h" #include "gtest/gtest.h" #include <cmath> #include <random> namespace caffe2 { namespace { void AddNoiseInput(const vector<TIndex>& shape, const string& name, Workspace* ws) { DeviceOption option; CPUContext context(option); Blob* blob = ws->CreateBlob(name); auto* tensor = blob->GetMutable<TensorCPU>(); tensor->Resize(shape); math::RandGaussian<float, CPUContext>( tensor->size(), 0.0f, 3.0f, tensor->mutable_data<float>(), &context); for (auto i = 0; i < tensor->size(); ++i) { tensor->mutable_data<float>()[i] = std::min(-5.0f, std::max(5.0f, tensor->mutable_data<float>()[i])); } } inline float relativeError(float a, float b) { return std::abs(a - b) / (0.5f * (std::abs(a) + std::abs(b))); } void compare( int N, int inputC, int H, int W, int outputC, int kernelH, int kernelW, int strideH, int strideW, int padT, int padL, int padB, int padR, int group, const std::string& algorithm, const std::string& convolutionTransformStrategy, float maxRelErr, float absErrForRelErrFailure) { LOG(INFO) << "running N " << N << " inputC " << inputC << " H " << H << " W " << W << " outputC " << outputC << " kernelH " << kernelH << " kernelW " << kernelW << " strideH " << strideH << " strideW " << strideW << " padT " << padT << " padL " << padL << " padB " << padB << " padR " << padR << " group " << group; Workspace ws; OperatorDef nnpackOpDef; nnpackOpDef.set_name("test"); nnpackOpDef.set_type("Conv"); nnpackOpDef.set_engine(algorithm == "DEPTHWISE_3x3" ? "DEPTHWISE_3x3" : "NNPACK"); nnpackOpDef.add_input("X"); nnpackOpDef.add_input("W"); nnpackOpDef.add_input("B"); nnpackOpDef.add_output("Y_nnpack"); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("kernel_h", kernelH)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("kernel_w", kernelW)); if (!algorithm.empty()) { nnpackOpDef.add_arg()->CopyFrom(MakeArgument("algo", algorithm)); } if (!convolutionTransformStrategy.empty()) { nnpackOpDef.add_arg()->CopyFrom(MakeArgument( "convolution_transform_strategy", convolutionTransformStrategy)); } nnpackOpDef.add_arg()->CopyFrom(MakeArgument("stride_h", strideH)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("stride_w", strideW)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_t", padT)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_l", padL)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_b", padB)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("pad_r", padR)); nnpackOpDef.add_arg()->CopyFrom(MakeArgument("group", group)); AddNoiseInput(vector<TIndex>{N, inputC, H, W}, "X", &ws); AddNoiseInput(vector<TIndex>{outputC, inputC / group , kernelH, kernelW}, "W", &ws); AddNoiseInput(vector<TIndex>{outputC}, "B", &ws); unique_ptr<OperatorBase> nnpackOp(CreateOperator(nnpackOpDef, &ws)); EXPECT_NE(nullptr, nnpackOp.get()); OperatorDef referenceOpDef; referenceOpDef.set_name("test"); referenceOpDef.set_type("Conv"); referenceOpDef.add_input("X"); referenceOpDef.add_input("W"); referenceOpDef.add_input("B"); referenceOpDef.add_output("Y_reference"); referenceOpDef.add_arg()->CopyFrom(MakeArgument("kernel_h", kernelH)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("kernel_w", kernelW)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("stride_h", strideH)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("stride_w", strideW)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_t", padT)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_l", padL)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_b", padB)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("pad_r", padR)); referenceOpDef.add_arg()->CopyFrom(MakeArgument("group", group)); unique_ptr<OperatorBase> referenceOp(CreateOperator(referenceOpDef, &ws)); EXPECT_NE(nullptr, referenceOp.get()); for (auto i = 0; i < 10; ++i) { EXPECT_TRUE(nnpackOp->Run()); } Blob* nnpackOutputBlob = ws.GetBlob("Y_nnpack"); EXPECT_NE(nullptr, nnpackOutputBlob); auto& nnpackOutput = nnpackOutputBlob->Get<TensorCPU>(); for (auto i = 0; i < 10; ++i) { EXPECT_TRUE(referenceOp->Run()); } Blob* referenceOutputBlob = ws.GetBlob("Y_reference"); EXPECT_NE(nullptr, referenceOutputBlob); auto& referenceOutput = referenceOutputBlob->Get<TensorCPU>(); // Compare all output points for (int n = 0; n < nnpackOutput.dim32(0); ++n) { for (int c = 0; c < nnpackOutput.dim32(1); ++c) { for (int h = 0; h < nnpackOutput.dim32(2); ++h) { for (int w = 0; w < nnpackOutput.dim32(3); ++w) { int offset = n * nnpackOutput.dim32(1) * nnpackOutput.dim32(2) * nnpackOutput.dim32(3) + c * nnpackOutput.dim32(2) * nnpackOutput.dim32(3) + h * nnpackOutput.dim32(3) + w; auto v1 = nnpackOutput.data<float>()[offset]; auto v2 = referenceOutput.data<float>()[offset]; float relErr = relativeError(v1, v2); float absErr = std::abs(v1 - v2); // For small values / small difference, the relative error // can be huge but the absolute error will be small EXPECT_TRUE( relErr <= maxRelErr || (relErr > maxRelErr && absErr <= absErrForRelErrFailure)) << v1 << " " << v2 << " (rel err " << relErr << ") " << "(" << n << " " << c << " " << h << " " << w << ") " << "running N " << N << " inputC " << inputC << " H " << H << " W " << W << " outputC " << outputC << " kernelH " << kernelH << " kernelW " << kernelW << " strideH " << strideH << " strideW " << strideW << " padT " << padT << " padL " << padL << " padB " << padB << " padR " << padR << " group " << group << " algorithm " << algorithm << " convolutionTransformStrategy " << convolutionTransformStrategy; } } } } } int randInt(int a, int b) { static std::random_device rd; static std::mt19937 gen(rd()); return std::uniform_int_distribution<int>(a, b)(gen); } void runConv(int kernelH, int kernelW, int strideH, int strideW, int group = 1, std::string algo = "", int planesIn = randInt(1, 6), int planesOut = randInt(1, 6), int n = randInt(1, 2), std::string convolutionTransformStrategy = "COMPUTE") { int h = randInt(20, 100); int w = randInt(20, 100); // This pad restriction is imposed by NNPACK int padT = std::min(randInt(0, 3), kernelH - 1); int padB = std::min(randInt(0, 3), kernelH - 1); int padL = std::min(randInt(0, 3), kernelW - 1); int padR = std::min(randInt(0, 3), kernelW - 1); caffe2::compare(n, planesIn, h, w, planesOut, kernelH, kernelW, strideH, strideW, padT, padL, padB, padR, group, algo, convolutionTransformStrategy, 0.05f, 0.1f); } } // unnamed namespace constexpr size_t kIters = 20; // TODO(#14383029) cblas_sgemm not yet implemented on limited mobile cases. #if !defined(CAFFE2_FB_LIMITED_MOBILE_CAPABILITY) TEST(MobileNNPACK, Conv_3x3s1) { for (int i = 0; i < kIters; ++i) { runConv(3, 3, 1, 1); } } TEST(MobileNNPACK, Conv_3x3s1_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(1, 2); runConv(3, 3, 1, 1, group, "WINOGRAD", group * randInt(1, 8), group * randInt(1, 8), 1, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_3x3s1_FP16) { for (int i = 0; i < kIters; ++i) { runConv(3, 3, 1, 1, 1, "WINOGRAD_FP16"); } } TEST(MobileNNPACK, Conv_3x3s1_FP16_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(1, 2); runConv(3, 3, 1, 1, group, "WINOGRAD_FP16", group * randInt(1, 8), group * randInt(1, 8), 1, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNs1) { for (int i = 0; i < kIters; ++i) { int kernel = randInt(2, 10); runConv(kernel, kernel, 1, 1); } } TEST(MobileNNPACK, Conv_1x1s1) { for (int i = 0; i < kIters; ++i) { auto group = randInt(1, 3); auto inChannels = randInt(1, 8) * group; auto outChannels = randInt(1, 8) * group; auto n = 1; runConv(1, 1, 1, 1, group, "DIRECT", inChannels, outChannels, n); } } TEST(MobileNNPACK, Conv_1x1s1_precompute) { for (int i = 0; i < kIters; ++i) { auto group = randInt(1, 3); auto inChannels = randInt(1, 8) * group; auto outChannels = randInt(1, 8) * group; auto n = 1; runConv(1, 1, 1, 1, group, "DIRECT", inChannels, outChannels, n, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNs_grouped) { for (int i = 0; i < kIters; ++i) { int group = randInt(2, 3); int iC = randInt(1, 6) * group; int oC = randInt(1, 6) * group; int kernel = randInt(2, 10); int n = randInt(1, 2); runConv(kernel, kernel, 1, 1, group, "", iC, oC, n); } } TEST(MobileNNPACK, Conv_NxNs_grouped_precompute) { for (int i = 0; i < kIters; ++i) { int group = randInt(2, 3); int iC = randInt(1, 6) * group; int oC = randInt(1, 6) * group; int kernel = randInt(2, 10); int n = randInt(1, 2); runConv(kernel, kernel, 1, 1, group, "", iC, oC, n, "PRECOMPUTE"); } } TEST(MobileNNPACK, Conv_NxNsW) { for (int i = 0; i < 3; ++i) { int kernel = randInt(3, 5); int stride = randInt(1, kernel - 1); runConv(kernel, kernel, stride, stride); } } TEST(MobileNNPACK, Conv_HxWsHxW) { for (int i = 0; i < 3; ++i) { int kernelH = randInt(2, 5); int kernelW = randInt(2, 5); int strideH = randInt(1, kernelH - 1); int strideW = randInt(1, kernelW - 1); runConv(kernelH, kernelW, strideH, strideW); } } TEST(MobileNNPACK, Depthwise3x3Conv) { for (int i = 0; i < kIters; ++i) { int channel = 2; runConv(3, 3, 1, 1, channel, "DEPTHWISE_3x3", channel, channel, randInt(1, 2)); } } #endif } // namespace caffe2 <|endoftext|>
<commit_before>/*********************************************************************** created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h" #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" #include "CEGUI/Exceptions.h" #include <OgreRenderSystem.h> #include <OgreCamera.h> #include <OgreViewport.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : d_owner(owner), d_renderSystem(rs), d_renderTarget(0), d_viewport(0), d_ogreViewportDimensions(0, 0, 0, 0), d_matrix(Ogre::Matrix4::IDENTITY), d_viewportValid(false) { } //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::~OgreRenderTarget() { delete d_viewport; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area) { d_ogreViewportDimensions = area; if (d_viewport) updateOgreViewportDimensions(d_viewport->getTarget()); d_viewportValid = false; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateOgreViewportDimensions( const Ogre::RenderTarget* const rt) { if (rt) { if(d_viewport) d_viewport->setDimensions( d_ogreViewportDimensions.left() / rt->getWidth(), d_ogreViewportDimensions.top() / rt->getHeight(), d_ogreViewportDimensions.getWidth() / rt->getWidth(), d_ogreViewportDimensions.getHeight() / rt->getHeight()); } } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::activate() { if (!d_matrixValid) updateMatrix(); if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); d_owner.setProjectionMatrix(d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::deactivate() { // currently nothing to do in the basic case } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff); const Ogre::Real midx = d_area.getWidth() * 0.5f; const Ogre::Real midy = d_area.getHeight() * 0.5f; // viewport matrix const Ogre::Matrix4 vpmat( midx, 0, 0, d_area.left() + midx, 0, -midy, 0, d_area.top() + midy, 0, 0, 1, 0, 0, 0, 0, 1 ); // matrices used for projecting and unprojecting points const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat); const Ogre::Matrix4 unproj(proj.inverse()); Ogre::Vector3 in; // unproject the ends of the ray in.x = midx; in.y = midy; in.z = -d_viewDistance; const Ogre::Vector3 r1(unproj * in); in.x = p_in.x; in.y = p_in.y; in.z = 0; // calculate vector of picking ray const Ogre::Vector3 rv(r1 - unproj * in); // project points to orientate them with GeometryBuffer plane in.x = 0.0; in.y = 0.0; const Ogre::Vector3 p1(proj * in); in.x = 1.0; in.y = 0.0; const Ogre::Vector3 p2(proj * in); in.x = 0.0; in.y = 1.0; const Ogre::Vector3 p3(proj * in); // calculate the plane normal const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1)); // calculate distance from origin const Ogre::Real plen = pn.length(); const Ogre::Real dist = -(p1.x * (pn.x / plen) + p1.y * (pn.y / plen) + p1.z * (pn.z / plen)); // calculate intersection of ray and plane const Ogre::Real pn_dot_rv = pn.dotProduct(rv); const Ogre::Real tmp = pn_dot_rv != 0.0 ? (pn.dotProduct(r1) + dist) / pn_dot_rv : 0.0f; p_out.x = static_cast<float>(r1.x - rv.x * tmp); p_out.y = static_cast<float>(r1.y - rv.y * tmp); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateMatrix() const { if (d_owner.usesOpenGL()) d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); else if(d_owner.usesDirect3D()) d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); else CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.")); RenderTarget::d_matrixValid = true; //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices RenderTarget::d_activationCounter = -1; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateViewport() { if (!d_viewport) { #ifdef CEGUI_USE_OGRE_COMPOSITOR2 d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1); #else d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0); #endif // CEGUI_USE_OGRE_COMPOSITOR2 updateOgreViewportDimensions(d_renderTarget); } d_viewport->_updateDimensions(); d_viewportValid = true; } //----------------------------------------------------------------------------// template <typename T> Renderer& OgreRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setArea(const Rectf& area) { setOgreViewportDimensions(area); RenderTarget::setArea(area); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>MOD: Adding missing qualifier<commit_after>/*********************************************************************** created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h" #include "CEGUI/GeometryBuffer.h" #include "CEGUI/RenderQueue.h" #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" #include "CEGUI/Exceptions.h" #include <OgreRenderSystem.h> #include <OgreCamera.h> #include <OgreViewport.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : d_owner(owner), d_renderSystem(rs), d_renderTarget(0), d_viewport(0), d_ogreViewportDimensions(0, 0, 0, 0), d_matrix(Ogre::Matrix4::IDENTITY), d_viewportValid(false) { } //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::~OgreRenderTarget() { delete d_viewport; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::draw(const GeometryBuffer& buffer) { buffer.draw(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::draw(const RenderQueue& queue) { queue.draw(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area) { d_ogreViewportDimensions = area; if (d_viewport) updateOgreViewportDimensions(d_viewport->getTarget()); d_viewportValid = false; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateOgreViewportDimensions( const Ogre::RenderTarget* const rt) { if (rt) { if(d_viewport) d_viewport->setDimensions( d_ogreViewportDimensions.left() / rt->getWidth(), d_ogreViewportDimensions.top() / rt->getHeight(), d_ogreViewportDimensions.getWidth() / rt->getWidth(), d_ogreViewportDimensions.getHeight() / rt->getHeight()); } } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::activate() { if (!d_matrixValid) updateMatrix(); if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); d_owner.setProjectionMatrix(d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::deactivate() { // currently nothing to do in the basic case } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff); const Ogre::Real midx = d_area.getWidth() * 0.5f; const Ogre::Real midy = d_area.getHeight() * 0.5f; // viewport matrix const Ogre::Matrix4 vpmat( midx, 0, 0, d_area.left() + midx, 0, -midy, 0, d_area.top() + midy, 0, 0, 1, 0, 0, 0, 0, 1 ); // matrices used for projecting and unprojecting points const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix()) * d_matrix * vpmat); const Ogre::Matrix4 unproj(proj.inverse()); Ogre::Vector3 in; // unproject the ends of the ray in.x = midx; in.y = midy; in.z = -RenderTarget::d_viewDistance; const Ogre::Vector3 r1(unproj * in); in.x = p_in.x; in.y = p_in.y; in.z = 0; // calculate vector of picking ray const Ogre::Vector3 rv(r1 - unproj * in); // project points to orientate them with GeometryBuffer plane in.x = 0.0; in.y = 0.0; const Ogre::Vector3 p1(proj * in); in.x = 1.0; in.y = 0.0; const Ogre::Vector3 p2(proj * in); in.x = 0.0; in.y = 1.0; const Ogre::Vector3 p3(proj * in); // calculate the plane normal const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1)); // calculate distance from origin const Ogre::Real plen = pn.length(); const Ogre::Real dist = -(p1.x * (pn.x / plen) + p1.y * (pn.y / plen) + p1.z * (pn.z / plen)); // calculate intersection of ray and plane const Ogre::Real pn_dot_rv = pn.dotProduct(rv); const Ogre::Real tmp = pn_dot_rv != 0.0 ? (pn.dotProduct(r1) + dist) / pn_dot_rv : 0.0f; p_out.x = static_cast<float>(r1.x - rv.x * tmp); p_out.y = static_cast<float>(r1.y - rv.y * tmp); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateMatrix() const { if (d_owner.usesOpenGL()) d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); else if(d_owner.usesDirect3D()) d_matrix = OgreRenderer::glmToOgreMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); else CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.")); RenderTarget::d_matrixValid = true; //! This will trigger the RenderTarget to notify all of its GeometryBuffers to regenerate their matrices RenderTarget::d_activationCounter = -1; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateViewport() { if (!d_viewport) { #ifdef CEGUI_USE_OGRE_COMPOSITOR2 d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1); #else d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0); #endif // CEGUI_USE_OGRE_COMPOSITOR2 updateOgreViewportDimensions(d_renderTarget); } d_viewport->_updateDimensions(); d_viewportValid = true; } //----------------------------------------------------------------------------// template <typename T> Renderer& OgreRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setArea(const Rectf& area) { setOgreViewportDimensions(area); RenderTarget::setArea(area); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/*********************************************************************** created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h" #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" #include "CEGUI/Exceptions.h" #include <OgreRenderSystem.h> #include <OgreCamera.h> #include <OgreViewport.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : d_owner(owner), d_renderSystem(rs), d_renderTarget(0), d_viewport(0), d_ogreViewportDimensions(0, 0, 0, 0), d_viewportValid(false) { } //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::~OgreRenderTarget() { delete d_viewport; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area) { d_ogreViewportDimensions = area; if (d_viewport) updateOgreViewportDimensions(d_viewport->getTarget()); d_viewportValid = false; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateOgreViewportDimensions( const Ogre::RenderTarget* const rt) { if (rt) { if(d_viewport) d_viewport->setDimensions( d_ogreViewportDimensions.left() / rt->getWidth(), d_ogreViewportDimensions.top() / rt->getHeight(), d_ogreViewportDimensions.getWidth() / rt->getWidth(), d_ogreViewportDimensions.getHeight() / rt->getHeight()); } } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::activate() { if (!d_matrixValid) updateMatrix(); if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); d_owner.setViewProjectionMatrix(RenderTarget::d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!d_matrixValid) updateMatrix(); const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff); const Ogre::Real midx = d_area.getWidth() * 0.5f; const Ogre::Real midy = d_area.getHeight() * 0.5f; // viewport matrix const Ogre::Matrix4 vpmat( midx, 0, 0, d_area.left() + midx, 0, -midy, 0, d_area.top() + midy, 0, 0, 1, 0, 0, 0, 0, 1 ); // matrices used for projecting and unprojecting points const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix() * RenderTarget::d_matrix) * vpmat); const Ogre::Matrix4 unproj(proj.inverse()); Ogre::Vector3 in; // unproject the ends of the ray in.x = midx; in.y = midy; in.z = -RenderTarget::d_viewDistance; const Ogre::Vector3 r1(unproj * in); in.x = p_in.x; in.y = p_in.y; in.z = 0; // calculate vector of picking ray const Ogre::Vector3 rv(r1 - unproj * in); // project points to orientate them with GeometryBuffer plane in.x = 0.0; in.y = 0.0; const Ogre::Vector3 p1(proj * in); in.x = 1.0; in.y = 0.0; const Ogre::Vector3 p2(proj * in); in.x = 0.0; in.y = 1.0; const Ogre::Vector3 p3(proj * in); // calculate the plane normal const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1)); // calculate distance from origin const Ogre::Real plen = pn.length(); const Ogre::Real dist = -(p1.x * (pn.x / plen) + p1.y * (pn.y / plen) + p1.z * (pn.z / plen)); // calculate intersection of ray and plane const Ogre::Real pn_dot_rv = pn.dotProduct(rv); const Ogre::Real tmp = pn_dot_rv != 0.0 ? (pn.dotProduct(r1) + dist) / pn_dot_rv : 0.0f; p_out.x = static_cast<float>(r1.x - rv.x * tmp); p_out.y = static_cast<float>(r1.y - rv.y * tmp); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateMatrix() const { if (d_owner.usesOpenGL()) RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); else if (d_owner.usesDirect3D()) RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); else CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.")); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateViewport() { if (!d_viewport) { #ifdef CEGUI_USE_OGRE_COMPOSITOR2 d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1); #else d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0); #endif // CEGUI_USE_OGRE_COMPOSITOR2 updateOgreViewportDimensions(d_renderTarget); } d_viewport->_updateDimensions(); d_viewportValid = true; } //----------------------------------------------------------------------------// template <typename T> OgreRenderer& OgreRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setArea(const Rectf& area) { setOgreViewportDimensions(area); RenderTarget::setArea(area); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>fix for the cleanup of member variables back to parent class<commit_after>/*********************************************************************** created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/RendererModules/Ogre/RenderTarget.h" #include "CEGUI/RendererModules/Ogre/GeometryBuffer.h" #include "CEGUI/Exceptions.h" #include <OgreRenderSystem.h> #include <OgreCamera.h> #include <OgreViewport.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::OgreRenderTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : d_owner(owner), d_renderSystem(rs), d_renderTarget(0), d_viewport(0), d_ogreViewportDimensions(0, 0, 0, 0), d_viewportValid(false) { } //----------------------------------------------------------------------------// template <typename T> OgreRenderTarget<T>::~OgreRenderTarget() { delete d_viewport; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setOgreViewportDimensions(const Rectf& area) { d_ogreViewportDimensions = area; if (d_viewport) updateOgreViewportDimensions(d_viewport->getTarget()); d_viewportValid = false; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateOgreViewportDimensions( const Ogre::RenderTarget* const rt) { if (rt) { if(d_viewport) d_viewport->setDimensions( d_ogreViewportDimensions.left() / rt->getWidth(), d_ogreViewportDimensions.top() / rt->getHeight(), d_ogreViewportDimensions.getWidth() / rt->getWidth(), d_ogreViewportDimensions.getHeight() / rt->getHeight()); } } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::activate() { if (!RenderTarget::d_matrixValid) updateMatrix(); if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); d_owner.setViewProjectionMatrix(RenderTarget::d_matrix); RenderTarget::activate(); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff, const glm::vec2& p_in, glm::vec2& p_out) const { if (!RenderTarget::d_matrixValid) updateMatrix(); const OgreGeometryBuffer& gb = static_cast<const OgreGeometryBuffer&>(buff); const Ogre::Real midx = RenderTarget::d_area.getWidth() * 0.5f; const Ogre::Real midy = RenderTarget::d_area.getHeight() * 0.5f; // viewport matrix const Ogre::Matrix4 vpmat( midx, 0, 0, RenderTarget::d_area.left() + midx, 0, -midy, 0, RenderTarget::d_area.top() + midy, 0, 0, 1, 0, 0, 0, 0, 1 ); // matrices used for projecting and unprojecting points const Ogre::Matrix4 proj(OgreRenderer::glmToOgreMatrix(gb.getModelMatrix() * RenderTarget::d_matrix) * vpmat); const Ogre::Matrix4 unproj(proj.inverse()); Ogre::Vector3 in; // unproject the ends of the ray in.x = midx; in.y = midy; in.z = -RenderTarget::d_viewDistance; const Ogre::Vector3 r1(unproj * in); in.x = p_in.x; in.y = p_in.y; in.z = 0; // calculate vector of picking ray const Ogre::Vector3 rv(r1 - unproj * in); // project points to orientate them with GeometryBuffer plane in.x = 0.0; in.y = 0.0; const Ogre::Vector3 p1(proj * in); in.x = 1.0; in.y = 0.0; const Ogre::Vector3 p2(proj * in); in.x = 0.0; in.y = 1.0; const Ogre::Vector3 p3(proj * in); // calculate the plane normal const Ogre::Vector3 pn((p2 - p1).crossProduct(p3 - p1)); // calculate distance from origin const Ogre::Real plen = pn.length(); const Ogre::Real dist = -(p1.x * (pn.x / plen) + p1.y * (pn.y / plen) + p1.z * (pn.z / plen)); // calculate intersection of ray and plane const Ogre::Real pn_dot_rv = pn.dotProduct(rv); const Ogre::Real tmp = pn_dot_rv != 0.0 ? (pn.dotProduct(r1) + dist) / pn_dot_rv : 0.0f; p_out.x = static_cast<float>(r1.x - rv.x * tmp); p_out.y = static_cast<float>(r1.y - rv.y * tmp); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateMatrix() const { if (d_owner.usesOpenGL()) RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() ); else if (d_owner.usesDirect3D()) RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForDirect3D() ); else CEGUI_THROW(RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.")); } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::updateViewport() { if (!d_viewport) { #ifdef CEGUI_USE_OGRE_COMPOSITOR2 d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1); #else d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0); #endif // CEGUI_USE_OGRE_COMPOSITOR2 updateOgreViewportDimensions(d_renderTarget); } d_viewport->_updateDimensions(); d_viewportValid = true; } //----------------------------------------------------------------------------// template <typename T> OgreRenderer& OgreRenderTarget<T>::getOwner() { return d_owner; } //----------------------------------------------------------------------------// template <typename T> void OgreRenderTarget<T>::setArea(const Rectf& area) { setOgreViewportDimensions(area); RenderTarget::setArea(area); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>#ifndef MJOLNIR_INPUT_READ_EXTERNAL_POTENTIAL_HPP #define MJOLNIR_INPUT_READ_EXTERNAL_POTENTIAL_HPP #include <extlib/toml/toml.hpp> #include <mjolnir/potential/external/HarmonicRestraintPotential.hpp> #include <mjolnir/potential/external/ImplicitMembranePotential.hpp> #include <mjolnir/potential/external/LennardJonesWallPotential.hpp> #include <mjolnir/potential/external/ExcludedVolumeWallPotential.hpp> #include <mjolnir/core/Topology.hpp> #include <mjolnir/util/string.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/logger.hpp> namespace mjolnir { // --------------------------------------------------------------------------- // Potential for External Force Fields // --------------------------------------------------------------------------- template<typename realT> ImplicitMembranePotential<realT> read_implicit_membrane_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto thickness = toml::find<real_type>(external, "thickness"); const auto magnitude = toml::find<real_type>(external, "interaction_magnitude"); const auto bend = toml::find<real_type>(external, "bend"); MJOLNIR_LOG_INFO("thickness = ", thickness); MJOLNIR_LOG_INFO("magnitude = ", magnitude); MJOLNIR_LOG_INFO("bend = ", bend ); const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO(ps.size(), " parameters are found"); std::vector<real_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = toml::find<std::size_t>(param, "index"); const auto h = toml::find<real_type >(param, "hydrophobicity"); if(params.size() <= idx) {params.resize(idx+1, real_type(0.0));} params.at(idx) = h; MJOLNIR_LOG_INFO("idx = ", idx, ", hydrophobicity = ", h); } return ImplicitMembranePotential<realT>( thickness, magnitude, bend, std::move(params)); } template<typename realT> LennardJonesWallPotential<realT> read_lennard_jones_wall_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO(ps.size(), " parameters are found"); std::vector<std::pair<real_type, real_type>> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = toml::find<std::size_t>(param, "index"); const auto s = toml::expect<real_type>(param, u8"σ").or_other( toml::expect<real_type>(param, "sigma")).unwrap(); const auto e = toml::expect<real_type>(param, u8"ε").or_other( toml::expect<real_type>(param, "epsilon")).unwrap(); if(params.size() <= idx) { params.resize(idx+1, std::make_pair(real_type(0), real_type(0))); } params.at(idx) = std::make_pair(s, e); MJOLNIR_LOG_INFO("idx = ", idx, ", sigma = ", s, ", epsilon = ", e); } return LennardJonesWallPotential<realT>(std::move(params)); } template<typename realT> ExcludedVolumeWallPotential<realT> read_excluded_volume_wall_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto eps = toml::expect<real_type>(external, u8"ε").or_other( toml::expect<real_type>(external, "epsilon")).unwrap(); MJOLNIR_LOG_INFO("epsilon = ", eps); const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO("number of parameters = ", ps.size()); std::vector<real_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = toml::find<std::size_t>(param, "index"); const auto rad = toml::find<real_type>(param, "radius"); if(params.size() <= idx) {params.resize(idx+1, real_type(0));} params.at(idx) = rad; MJOLNIR_LOG_INFO("idx = ", idx, ", radius = ", rad); } return ExcludedVolumeWallPotential<real_type>(eps, std::move(params)); } template<typename realT> HarmonicRestraintPotential<realT> read_harmonic_restraint_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; using potential_type = HarmonicRestraintPotential<real_type>; using parameter_type = typename potential_type::parameter_type; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO("number of parameters = ", ps.size()); std::vector<parameter_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = toml::find<std::size_t>(param, "index"); const auto k = toml::find<real_type >(param, "k"); const auto v0 = toml::find<real_type >(param, "v0"); if(params.size() <= idx) { params.resize(idx+1, parameter_type(0, 0)); } params.at(idx) = parameter_type(k, v0); MJOLNIR_LOG_INFO("idx = ", idx, ", k = ", k, ", v0 = ", v0); } return HarmonicRestraintPotential<real_type>(std::move(params)); } } // mjolnir #endif // MJOLNIR_READ_EXTERNAL_POTENTIAL_HPP <commit_msg>feat: enable to use env in external potential<commit_after>#ifndef MJOLNIR_INPUT_READ_EXTERNAL_POTENTIAL_HPP #define MJOLNIR_INPUT_READ_EXTERNAL_POTENTIAL_HPP #include <extlib/toml/toml.hpp> #include <mjolnir/input/utility.hpp> #include <mjolnir/potential/external/HarmonicRestraintPotential.hpp> #include <mjolnir/potential/external/ImplicitMembranePotential.hpp> #include <mjolnir/potential/external/LennardJonesWallPotential.hpp> #include <mjolnir/potential/external/ExcludedVolumeWallPotential.hpp> #include <mjolnir/core/Topology.hpp> #include <mjolnir/util/string.hpp> #include <mjolnir/util/make_unique.hpp> #include <mjolnir/util/logger.hpp> namespace mjolnir { // --------------------------------------------------------------------------- // Potential for External Force Fields // --------------------------------------------------------------------------- template<typename realT> ImplicitMembranePotential<realT> read_implicit_membrane_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto thickness = toml::find<real_type>(external, "thickness"); const auto magnitude = toml::find<real_type>(external, "interaction_magnitude"); const auto bend = toml::find<real_type>(external, "bend"); MJOLNIR_LOG_INFO("thickness = ", thickness); MJOLNIR_LOG_INFO("magnitude = ", magnitude); MJOLNIR_LOG_INFO("bend = ", bend ); const auto& env = external.as_table().count("env") == 1 ? external.as_table().at("env") : toml::value{}; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO(ps.size(), " parameters are found"); std::vector<real_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = find_parameter<std::size_t>(param, env, "index"); const auto h = find_parameter<real_type >(param, env, "hydrophobicity"); if(params.size() <= idx) {params.resize(idx+1, real_type(0.0));} params.at(idx) = h; MJOLNIR_LOG_INFO("idx = ", idx, ", hydrophobicity = ", h); } return ImplicitMembranePotential<realT>( thickness, magnitude, bend, std::move(params)); } template<typename realT> LennardJonesWallPotential<realT> read_lennard_jones_wall_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto& env = external.as_table().count("env") == 1 ? external.as_table().at("env") : toml::value{}; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO(ps.size(), " parameters are found"); std::vector<std::pair<real_type, real_type>> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = find_parameter<std::size_t>(param, env, "index"); const auto s = find_parameter<real_type>(param, env, "sigma", u8"σ"); const auto e = find_parameter<real_type>(param, env, "epsilon", u8"ε"); if(params.size() <= idx) { params.resize(idx+1, std::make_pair(real_type(0), real_type(0))); } params.at(idx) = std::make_pair(s, e); MJOLNIR_LOG_INFO("idx = ", idx, ", sigma = ", s, ", epsilon = ", e); } return LennardJonesWallPotential<realT>(std::move(params)); } template<typename realT> ExcludedVolumeWallPotential<realT> read_excluded_volume_wall_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; const auto eps = toml::expect<real_type>(external, u8"ε").or_other( toml::expect<real_type>(external, "epsilon")).unwrap(); MJOLNIR_LOG_INFO("epsilon = ", eps); const auto& env = external.as_table().count("env") == 1 ? external.as_table().at("env") : toml::value{}; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO("number of parameters = ", ps.size()); std::vector<real_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = find_parameter<std::size_t>(param, env, "index"); const auto rad = find_parameter<real_type >(param, env, "radius"); if(params.size() <= idx) {params.resize(idx+1, real_type(0));} params.at(idx) = rad; MJOLNIR_LOG_INFO("idx = ", idx, ", radius = ", rad); } return ExcludedVolumeWallPotential<real_type>(eps, std::move(params)); } template<typename realT> HarmonicRestraintPotential<realT> read_harmonic_restraint_potential(const toml::value& external) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using real_type = realT; using potential_type = HarmonicRestraintPotential<real_type>; using parameter_type = typename potential_type::parameter_type; const auto& ps = toml::find<toml::array>(external, "parameters"); MJOLNIR_LOG_INFO("number of parameters = ", ps.size()); const auto& env = external.as_table().count("env") == 1 ? external.as_table().at("env") : toml::value{}; std::vector<parameter_type> params; params.reserve(ps.size()); for(const auto& param : ps) { const auto idx = find_parameter<std::size_t>(param, env, "index"); const auto k = find_parameter<real_type >(param, env, "k"); const auto v0 = find_parameter<real_type >(param, env, "v0"); if(params.size() <= idx) { params.resize(idx+1, parameter_type(0, 0)); } params.at(idx) = parameter_type(k, v0); MJOLNIR_LOG_INFO("idx = ", idx, ", k = ", k, ", v0 = ", v0); } return HarmonicRestraintPotential<real_type>(std::move(params)); } } // mjolnir #endif // MJOLNIR_READ_EXTERNAL_POTENTIAL_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b2dvector.cxx,v $ * * $Revision: 1.16 $ * * last change: $Author: obo $ $Date: 2007-07-18 11:08:22 $ * * 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_basegfx.hxx" #ifndef _BGFX_VECTOR_B2DVECTOR_HXX #include <basegfx/vector/b2dvector.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_NUMERIC_FTOOLS_HXX #include <basegfx/numeric/ftools.hxx> #endif namespace basegfx { B2DVector& B2DVector::normalize() { double fLen(scalar(*this)); if(fTools::equalZero(fLen)) { mfX = 0.0; mfY = 0.0; } else { const double fOne(1.0); if(!fTools::equal(fOne, fLen)) { fLen = sqrt(fLen); if(!fTools::equalZero(fLen)) { mfX /= fLen; mfY /= fLen; } } } return *this; } B2DVector& B2DVector::operator=( const B2DTuple& rVec ) { mfX = rVec.getX(); mfY = rVec.getY(); return *this; } double B2DVector::getLength() const { return hypot( mfX, mfY ); } double B2DVector::scalar( const B2DVector& rVec ) const { return((mfX * rVec.mfX) + (mfY * rVec.mfY)); } double B2DVector::cross( const B2DVector& rVec ) const { return(mfX * rVec.getY() - mfY * rVec.getX()); } double B2DVector::angle( const B2DVector& rVec ) const { return atan2(mfX * rVec.getY() - mfY * rVec.getX(), mfX * rVec.getX() + mfY * rVec.getY()); } const B2DVector& B2DVector::getEmptyVector() { return (const B2DVector&) B2DTuple::getEmptyTuple(); } B2DVector& B2DVector::operator*=( const B2DHomMatrix& rMat ) { const double fTempX( rMat.get(0,0)*mfX + rMat.get(0,1)*mfY ); const double fTempY( rMat.get(1,0)*mfX + rMat.get(1,1)*mfY ); mfX = fTempX; mfY = fTempY; return *this; } B2DVector& B2DVector::setLength(double fLen) { double fLenNow(scalar(*this)); if(!fTools::equalZero(fLenNow)) { const double fOne(10.0); if(!fTools::equal(fOne, fLenNow)) { fLen /= sqrt(fLenNow); } mfX *= fLen; mfY *= fLen; } return *this; } bool B2DVector::isNormalized() const { const double fOne(1.0); const double fScalar(scalar(*this)); return fTools::equal(fOne, fScalar); } bool areParallel( const B2DVector& rVecA, const B2DVector& rVecB ) { const double fValA(rVecA.getX() * rVecB.getY()); const double fValB(rVecA.getY() * rVecB.getX()); return fTools::equal(fValA, fValB); } B2VectorOrientation getOrientation( const B2DVector& rVecA, const B2DVector& rVecB ) { double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX()); if(fTools::equalZero(fVal)) { return ORIENTATION_NEUTRAL; } if(fVal > 0.0) { return ORIENTATION_POSITIVE; } else { return ORIENTATION_NEGATIVE; } } B2DVector getPerpendicular( const B2DVector& rNormalizedVec ) { B2DVector aPerpendicular(-rNormalizedVec.getY(), rNormalizedVec.getX()); return aPerpendicular; } B2DVector getNormalizedPerpendicular( const B2DVector& rVec ) { B2DVector aPerpendicular(rVec); aPerpendicular.normalize(); const double aTemp(-aPerpendicular.getY()); aPerpendicular.setY(aPerpendicular.getX()); aPerpendicular.setX(aTemp); return aPerpendicular; } B2DVector operator*( const B2DHomMatrix& rMat, const B2DVector& rVec ) { B2DVector aRes( rVec ); return aRes*=rMat; } B2VectorContinuity getContinuity(const B2DVector& rBackVector, const B2DVector& rForwardVector ) { if(rBackVector.equalZero() || rForwardVector.equalZero()) { return CONTINUITY_NONE; } if(fTools::equal(rBackVector.getX(), -rForwardVector.getX()) && fTools::equal(rBackVector.getY(), -rForwardVector.getY())) { // same direction and same length -> C2 return CONTINUITY_C2; } if(areParallel(rBackVector, rForwardVector)) { // same direction -> C1 return CONTINUITY_C1; } return CONTINUITY_NONE; } } // end of namespace basegfx // eof <commit_msg>INTEGRATION: CWS changefileheader (1.16.30); FILE MERGED 2008/04/01 10:48:16 thb 1.16.30.2: #i85898# Stripping all external header guards 2008/03/28 16:05:58 rt 1.16.30.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: b2dvector.cxx,v $ * $Revision: 1.17 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basegfx.hxx" #include <basegfx/vector/b2dvector.hxx> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/numeric/ftools.hxx> namespace basegfx { B2DVector& B2DVector::normalize() { double fLen(scalar(*this)); if(fTools::equalZero(fLen)) { mfX = 0.0; mfY = 0.0; } else { const double fOne(1.0); if(!fTools::equal(fOne, fLen)) { fLen = sqrt(fLen); if(!fTools::equalZero(fLen)) { mfX /= fLen; mfY /= fLen; } } } return *this; } B2DVector& B2DVector::operator=( const B2DTuple& rVec ) { mfX = rVec.getX(); mfY = rVec.getY(); return *this; } double B2DVector::getLength() const { return hypot( mfX, mfY ); } double B2DVector::scalar( const B2DVector& rVec ) const { return((mfX * rVec.mfX) + (mfY * rVec.mfY)); } double B2DVector::cross( const B2DVector& rVec ) const { return(mfX * rVec.getY() - mfY * rVec.getX()); } double B2DVector::angle( const B2DVector& rVec ) const { return atan2(mfX * rVec.getY() - mfY * rVec.getX(), mfX * rVec.getX() + mfY * rVec.getY()); } const B2DVector& B2DVector::getEmptyVector() { return (const B2DVector&) B2DTuple::getEmptyTuple(); } B2DVector& B2DVector::operator*=( const B2DHomMatrix& rMat ) { const double fTempX( rMat.get(0,0)*mfX + rMat.get(0,1)*mfY ); const double fTempY( rMat.get(1,0)*mfX + rMat.get(1,1)*mfY ); mfX = fTempX; mfY = fTempY; return *this; } B2DVector& B2DVector::setLength(double fLen) { double fLenNow(scalar(*this)); if(!fTools::equalZero(fLenNow)) { const double fOne(10.0); if(!fTools::equal(fOne, fLenNow)) { fLen /= sqrt(fLenNow); } mfX *= fLen; mfY *= fLen; } return *this; } bool B2DVector::isNormalized() const { const double fOne(1.0); const double fScalar(scalar(*this)); return fTools::equal(fOne, fScalar); } bool areParallel( const B2DVector& rVecA, const B2DVector& rVecB ) { const double fValA(rVecA.getX() * rVecB.getY()); const double fValB(rVecA.getY() * rVecB.getX()); return fTools::equal(fValA, fValB); } B2VectorOrientation getOrientation( const B2DVector& rVecA, const B2DVector& rVecB ) { double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX()); if(fTools::equalZero(fVal)) { return ORIENTATION_NEUTRAL; } if(fVal > 0.0) { return ORIENTATION_POSITIVE; } else { return ORIENTATION_NEGATIVE; } } B2DVector getPerpendicular( const B2DVector& rNormalizedVec ) { B2DVector aPerpendicular(-rNormalizedVec.getY(), rNormalizedVec.getX()); return aPerpendicular; } B2DVector getNormalizedPerpendicular( const B2DVector& rVec ) { B2DVector aPerpendicular(rVec); aPerpendicular.normalize(); const double aTemp(-aPerpendicular.getY()); aPerpendicular.setY(aPerpendicular.getX()); aPerpendicular.setX(aTemp); return aPerpendicular; } B2DVector operator*( const B2DHomMatrix& rMat, const B2DVector& rVec ) { B2DVector aRes( rVec ); return aRes*=rMat; } B2VectorContinuity getContinuity(const B2DVector& rBackVector, const B2DVector& rForwardVector ) { if(rBackVector.equalZero() || rForwardVector.equalZero()) { return CONTINUITY_NONE; } if(fTools::equal(rBackVector.getX(), -rForwardVector.getX()) && fTools::equal(rBackVector.getY(), -rForwardVector.getY())) { // same direction and same length -> C2 return CONTINUITY_C2; } if(areParallel(rBackVector, rForwardVector)) { // same direction -> C1 return CONTINUITY_C1; } return CONTINUITY_NONE; } } // end of namespace basegfx // eof <|endoftext|>
<commit_before><commit_msg>Add TODO to look out for IMPALA-2208/PARQUET-251<commit_after><|endoftext|>
<commit_before>class Solution { public: int maxProfit(vector<int> &prices) { return maxProfit(prices, 0); } int maxProfit(vector<int> & prices, int start){ int max = 0; if(prices.size() - start < 2) return max; int minPrice = prices[start]; for(int i = 1+start; i != prices.size(); ++i){ if(prices[i] > minPrice) max = max > (prices[i] - minPrice) ? max:(prices[i] - minPrice); else if(prices[i] < minPrice){ int profit = maxProfit(prices, i); max = max > profit ? max : profit; return max; } } return max; } }; <commit_msg>a simplified solution<commit_after>class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size() < 2) return 0; int min = prices[0], profit = 0; for(int i = 1; i != prices.size(); ++i){ if(prices[i] < min) min = prices[i]; else{ if(prices[i] - min > profit) profit = prices[i] - min; } } return profit; } }; <|endoftext|>
<commit_before>#include "etl_audio.hpp" using namespace std; using namespace nervana; bool audio::config::set_config(nlohmann::json js) { // TODO } shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) { auto params = shared_ptr<audio::params>(new audio::params()); params->_width = _cfg->_width; params->_height = _cfg->_height; return params; } audio::decoded::decoded(shared_ptr<RawMedia> raw) : _raw(raw) { } MediaType audio::decoded::get_type() { return MediaType::AUDIO; } size_t audio::decoded::getSize() { return _raw->numSamples(); } audio::extractor::extractor(std::shared_ptr<const audio::config> config) { _codec = new Codec(config); avcodec_register_all(); } audio::extractor::~extractor() { delete _codec; } std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) { return make_shared<audio::decoded>(_codec->decode(item, itemSize)); } audio::transformer::transformer(std::shared_ptr<const audio::config> config) : _noiseClips(0), _state(0), _rng(config->_randomSeed) { _codec = new Codec(config); _specgram = new Specgram(config, config->_randomSeed); if (config->_noiseIndexFile != 0) { _noiseClips = new NoiseClips( config->_noiseIndexFile, config->_noiseDir, _codec ); } } audio::transformer::~transformer() { delete _specgram; delete _codec; } std::shared_ptr<audio::decoded> audio::transformer::transform( std::shared_ptr<audio::params> params, std::shared_ptr<audio::decoded> decoded) { if (_noiseClips != 0) { _noiseClips->addNoise(decoded->_raw, _state); } // set up _buf in decoded to accept data from generate decoded->_buf.resize(params->_width * params->_height); // convert from time domain to frequency domain decoded->_len = _specgram->generate( decoded->_raw, decoded->_buf.data(), params->_width * params->_height ); return decoded; } <commit_msg>only allocate a Codec in the transformer step if necessary<commit_after>#include "etl_audio.hpp" using namespace std; using namespace nervana; bool audio::config::set_config(nlohmann::json js) { // TODO } shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) { auto params = shared_ptr<audio::params>(new audio::params()); params->_width = _cfg->_width; params->_height = _cfg->_height; return params; } audio::decoded::decoded(shared_ptr<RawMedia> raw) : _raw(raw) { } MediaType audio::decoded::get_type() { return MediaType::AUDIO; } size_t audio::decoded::getSize() { return _raw->numSamples(); } audio::extractor::extractor(std::shared_ptr<const audio::config> config) { _codec = new Codec(config); avcodec_register_all(); } audio::extractor::~extractor() { delete _codec; } std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) { return make_shared<audio::decoded>(_codec->decode(item, itemSize)); } audio::transformer::transformer(std::shared_ptr<const audio::config> config) : _noiseClips(0), _state(0), _rng(config->_randomSeed), _codec(0) { _specgram = new Specgram(config, config->_randomSeed); if (config->_noiseIndexFile != 0) { _codec = new Codec(config); _noiseClips = new NoiseClips( config->_noiseIndexFile, config->_noiseDir, _codec ); } } audio::transformer::~transformer() { delete _specgram; if(_codec != 0) { delete _codec; } } std::shared_ptr<audio::decoded> audio::transformer::transform( std::shared_ptr<audio::params> params, std::shared_ptr<audio::decoded> decoded) { if (_noiseClips != 0) { _noiseClips->addNoise(decoded->_raw, _state); } // set up _buf in decoded to accept data from generate decoded->_buf.resize(params->_width * params->_height); // convert from time domain to frequency domain decoded->_len = _specgram->generate( decoded->_raw, decoded->_buf.data(), params->_width * params->_height ); return decoded; } <|endoftext|>
<commit_before>#include "tpunit++.hpp" #include "mock4cpp.h" #include <string> struct BasicVerification: tpunit::TestFixture { BasicVerification() : tpunit::TestFixture( // TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), // TEST(BasicVerification::verify_method_was_called_at_least_once), // TEST(BasicVerification::verify_method_was_called_exactly_once), // TEST(BasicVerification::verify_method_was_never_called), // TEST(BasicVerification::verify_method_was_called_exactly_x_times), // TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), // TEST(BasicVerification::verify_with_filter)) // { } struct SomeInterface { virtual int func(int) = 0; virtual void proc(int) = 0; }; void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_not_throw_exception_if_method_was_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_at_least_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_exactly_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]).Once(); Verify(mock[&SomeInterface::proc]).Once(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); } void verify_method_was_never_called() { Mock<SomeInterface> mock; Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException); } void verify_method_was_called_exactly_x_times() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); i.func(1); i.func(1); i.proc(1); i.proc(1); Verify(mock[&SomeInterface::func]).Times(2); Verify(mock[&SomeInterface::proc]).Times(2); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); } void should_throw_IllegalArgumentException_on_negative_times_argument() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException); } void verify_with_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); Verify(mock[&SomeInterface::func].Using(1)); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException); } } __BasicVerification; <commit_msg>refactor<commit_after>#include "tpunit++.hpp" #include "mock4cpp.h" #include <string> struct BasicVerification: tpunit::TestFixture { BasicVerification() : tpunit::TestFixture( // TEST(BasicVerification::verify_should_not_throw_exception_if_method_was_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_called), // TEST(BasicVerification::verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed), // TEST(BasicVerification::verify_method_was_called_at_least_once), // TEST(BasicVerification::verify_method_was_called_exactly_once), // TEST(BasicVerification::verify_method_was_never_called), // TEST(BasicVerification::verify_method_was_called_exactly_x_times), // TEST(BasicVerification::should_throw_IllegalArgumentException_on_negative_times_argument), // TEST(BasicVerification::verify_with_filter)) // { } struct SomeInterface { virtual int func(int) = 0; virtual void proc(int) = 0; }; void verify_should_throw_MethodCallVerificationException_if_method_was_not_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_throw_MethodCallVerificationException_if_method_was_not_stubbed() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); } void verify_should_not_throw_exception_if_method_was_called() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_at_least_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); i.func(1); i.proc(2); Verify(mock[&SomeInterface::func]); Verify(mock[&SomeInterface::proc]); } void verify_method_was_called_exactly_once() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); i.func(1); i.proc(1); Verify(mock[&SomeInterface::func]).Once(); Verify(mock[&SomeInterface::proc]).Once(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Once(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Once(), mock4cpp::MethodCallVerificationException); } void verify_method_was_never_called() { Mock<SomeInterface> mock; Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); Verify(mock[&SomeInterface::func]).Never(); Verify(mock[&SomeInterface::proc]).Never(); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Never(), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Never(), mock4cpp::MethodCallVerificationException); } void verify_method_was_called_exactly_x_times() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); i.func(1); i.func(1); i.proc(1); i.proc(1); Verify(mock[&SomeInterface::func]).Times(2); Verify(mock[&SomeInterface::proc]).Times(2); i.func(1); i.proc(1); ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(2), mock4cpp::MethodCallVerificationException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(2), mock4cpp::MethodCallVerificationException); } void should_throw_IllegalArgumentException_on_negative_times_argument() { Mock<SomeInterface> mock; ASSERT_THROW(Verify(mock[&SomeInterface::func]).Times(-1), mock4cpp::IllegalArgumentException); ASSERT_THROW(Verify(mock[&SomeInterface::proc]).Times(-1), mock4cpp::IllegalArgumentException); } void verify_with_filter() { Mock<SomeInterface> mock; Stub(mock[&SomeInterface::func], mock[&SomeInterface::proc]); SomeInterface &i = mock.get(); i.func(1); Verify(mock[&SomeInterface::func].Using(1)); ASSERT_THROW(Verify(mock[&SomeInterface::func].Using(2)), mock4cpp::MethodCallVerificationException); } // } __BasicVerification; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_View3D.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-03 13:38:25 $ * * 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_chart2.hxx" #include "dlg_View3D.hxx" #include "dlg_View3D.hrc" #include "Strings.hrc" #include "TabPages.hrc" #include "ResId.hxx" #include "NoWarningThisInCTOR.hxx" #include "tp_3D_SceneGeometry.hxx" #include "tp_3D_SceneAppearance.hxx" #include "tp_3D_SceneIllumination.hxx" #include "ChartModelHelper.hxx" #include "macros.hxx" #include "ControllerLockGuard.hxx" #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif // for RET_OK #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; //----------------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- // static USHORT View3DDialog::m_nLastPageId = 0; View3DDialog::View3DDialog(Window* pParent, const uno::Reference< frame::XModel > & xChartModel, XColorTable* pColorTable ) : TabDialog(pParent,SchResId(DLG_3D_VIEW)) , m_aTabControl(this,SchResId(TABCTRL)) , m_aBtnOK(this,SchResId(BTN_OK)) , m_aBtnCancel(this,SchResId(BTN_CANCEL)) , m_aBtnHelp(this,SchResId(BTN_HELP)) , m_pGeometry(0) , m_pAppearance(0) , m_pIllumination(0) , m_aControllerLocker(xChartModel) { FreeResource(); uno::Reference< beans::XPropertySet > xSceneProperties( ChartModelHelper::findDiagram( xChartModel ), uno::UNO_QUERY ); m_pGeometry = new ThreeD_SceneGeometry_TabPage(&m_aTabControl,xSceneProperties,m_aControllerLocker); m_pAppearance = new ThreeD_SceneAppearance_TabPage(&m_aTabControl,xChartModel,m_aControllerLocker); m_pIllumination = new ThreeD_SceneIllumination_TabPage(&m_aTabControl,xSceneProperties,xChartModel,pColorTable); m_aTabControl.InsertPage( TP_3D_SCENEGEOMETRY, String(SchResId(STR_PAGE_PERSPECTIVE)) ); m_aTabControl.InsertPage( TP_3D_SCENEAPPEARANCE, String(SchResId(STR_PAGE_APPEARANCE)) ); m_aTabControl.InsertPage( TP_3D_SCENEILLUMINATION, String(SchResId(STR_PAGE_ILLUMINATION)) ); m_aTabControl.SetTabPage( TP_3D_SCENEGEOMETRY, m_pGeometry ); m_aTabControl.SetTabPage( TP_3D_SCENEAPPEARANCE, m_pAppearance ); m_aTabControl.SetTabPage( TP_3D_SCENEILLUMINATION, m_pIllumination ); m_aTabControl.SelectTabPage( m_nLastPageId ); } View3DDialog::~View3DDialog() { delete m_pGeometry; delete m_pAppearance; delete m_pIllumination; m_nLastPageId = m_aTabControl.GetCurPageId(); } short View3DDialog::Execute() { short nResult = TabDialog::Execute(); if( nResult == RET_OK ) { if( m_pGeometry ) m_pGeometry->commitPendingChanges(); if( m_pAppearance ) m_pAppearance->commitPendingChanges(); if( m_pIllumination ) m_pIllumination->commitPendingChanges(); } return nResult; } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS changefileheader (1.3.106); FILE MERGED 2008/04/01 15:04:01 thb 1.3.106.3: #i85898# Stripping all external header guards 2008/04/01 10:50:19 thb 1.3.106.2: #i85898# Stripping all external header guards 2008/03/28 16:43:24 rt 1.3.106.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_View3D.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "dlg_View3D.hxx" #include "dlg_View3D.hrc" #include "Strings.hrc" #include "TabPages.hrc" #include "ResId.hxx" #include "NoWarningThisInCTOR.hxx" #include "tp_3D_SceneGeometry.hxx" #include "tp_3D_SceneAppearance.hxx" #include "tp_3D_SceneIllumination.hxx" #include "ChartModelHelper.hxx" #include "macros.hxx" #include "ControllerLockGuard.hxx" #include <com/sun/star/beans/XPropertySet.hpp> // for RET_OK #include <vcl/msgbox.hxx> //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::com::sun::star::chart2; //----------------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- // static USHORT View3DDialog::m_nLastPageId = 0; View3DDialog::View3DDialog(Window* pParent, const uno::Reference< frame::XModel > & xChartModel, XColorTable* pColorTable ) : TabDialog(pParent,SchResId(DLG_3D_VIEW)) , m_aTabControl(this,SchResId(TABCTRL)) , m_aBtnOK(this,SchResId(BTN_OK)) , m_aBtnCancel(this,SchResId(BTN_CANCEL)) , m_aBtnHelp(this,SchResId(BTN_HELP)) , m_pGeometry(0) , m_pAppearance(0) , m_pIllumination(0) , m_aControllerLocker(xChartModel) { FreeResource(); uno::Reference< beans::XPropertySet > xSceneProperties( ChartModelHelper::findDiagram( xChartModel ), uno::UNO_QUERY ); m_pGeometry = new ThreeD_SceneGeometry_TabPage(&m_aTabControl,xSceneProperties,m_aControllerLocker); m_pAppearance = new ThreeD_SceneAppearance_TabPage(&m_aTabControl,xChartModel,m_aControllerLocker); m_pIllumination = new ThreeD_SceneIllumination_TabPage(&m_aTabControl,xSceneProperties,xChartModel,pColorTable); m_aTabControl.InsertPage( TP_3D_SCENEGEOMETRY, String(SchResId(STR_PAGE_PERSPECTIVE)) ); m_aTabControl.InsertPage( TP_3D_SCENEAPPEARANCE, String(SchResId(STR_PAGE_APPEARANCE)) ); m_aTabControl.InsertPage( TP_3D_SCENEILLUMINATION, String(SchResId(STR_PAGE_ILLUMINATION)) ); m_aTabControl.SetTabPage( TP_3D_SCENEGEOMETRY, m_pGeometry ); m_aTabControl.SetTabPage( TP_3D_SCENEAPPEARANCE, m_pAppearance ); m_aTabControl.SetTabPage( TP_3D_SCENEILLUMINATION, m_pIllumination ); m_aTabControl.SelectTabPage( m_nLastPageId ); } View3DDialog::~View3DDialog() { delete m_pGeometry; delete m_pAppearance; delete m_pIllumination; m_nLastPageId = m_aTabControl.GetCurPageId(); } short View3DDialog::Execute() { short nResult = TabDialog::Execute(); if( nResult == RET_OK ) { if( m_pGeometry ) m_pGeometry->commitPendingChanges(); if( m_pAppearance ) m_pAppearance->commitPendingChanges(); if( m_pIllumination ) m_pIllumination->commitPendingChanges(); } return nResult; } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>// Floating Temple // Copyright 2015 Derek S. Snyder // // 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 "lua/hook_functions.h" #include <csetjmp> #include <string> #include <vector> #include "base/integral_types.h" #include "base/logging.h" #include "include/c++/thread.h" #include "include/c++/value.h" #include "lua/convert_value.h" #include "lua/interpreter_impl.h" #include "lua/table_local_object.h" #include "lua/third_party_lua_headers.h" using std::longjmp; using std::vector; namespace floating_temple { class ObjectReference; namespace lua { namespace { Thread* GetThreadObject() { return InterpreterImpl::instance()->GetThreadObject(); } InterpreterImpl::LongJumpTarget* GetLongJumpTarget() { return InterpreterImpl::instance()->GetLongJumpTarget(); } bool CallMethodHelper_GetTable(lua_State* lua_state, const TValue* table, const TValue* key, TValue* val) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(table).ft_obj); vector<Value> parameters(1); LuaValueToValue(key, &parameters[0]); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "gettable", parameters, &return_value)) { return false; } ValueToLuaValue(lua_state, return_value, val); return true; } bool CallMethodHelper_SetTable(lua_State* lua_state, const TValue* table, const TValue* key, const TValue* val) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(table).ft_obj); vector<Value> parameters(2); LuaValueToValue(key, &parameters[0]); LuaValueToValue(val, &parameters[1]); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "settable", parameters, &return_value)) { return false; } CHECK_EQ(return_value.type(), Value::EMPTY); return true; } bool CallMethodHelper_ObjLen(lua_State* lua_state, TValue* ra, const TValue* rb) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(rb).ft_obj); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "len", vector<Value>(), &return_value)) { return false; } ValueToLuaValue(lua_state, return_value, ra); return true; } bool CallMethodHelper_SetList(lua_State* lua_state, const TValue* ra, int n, int c) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(ra).ft_obj); vector<Value> parameters(n + 1); parameters[0].set_int64_value(LUA_TNONE, static_cast<int64>(c)); for (int i = n; i > 0; --i) { LuaValueToValue(ra + i, &parameters[i]); } Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "setlist", parameters, &return_value)) { return false; } CHECK_EQ(return_value.type(), Value::EMPTY); return true; } } // namespace void LockInterpreter() { InterpreterImpl::instance()->Lock(); } void UnlockInterpreter() { InterpreterImpl::instance()->Unlock(); } int AreObjectsEqual(const void* ft_obj1, const void* ft_obj2) { return GetThreadObject()->ObjectsAreIdentical( static_cast<const ObjectReference*>(ft_obj1), static_cast<const ObjectReference*>(ft_obj2)) ? 1 : 0; } int CreateTable(lua_State* lua_state, TValue* obj, int b, int c) { InterpreterImpl* const interpreter = InterpreterImpl::instance(); TableLocalObject* const local_object = new TableLocalObject(interpreter); local_object->Init(b, c); ObjectReference* const object_reference = interpreter->GetThreadObject()->CreateVersionedObject(local_object, ""); val_(obj).ft_obj = object_reference; settt_(obj, LUA_TTABLE); return 1; } // Since the following functions call longjmp(), they must not create any // objects that have destructors. int CallMethod_GetTable(lua_State* lua_state, const TValue* table, const TValue* key, TValue* val) { if (!ttisfloatingtemplateobject(table)) { return 0; } if (!CallMethodHelper_GetTable(lua_state, table, key, val)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_SetTable(lua_State* lua_state, const TValue* table, const TValue* key, const TValue* val) { if (!ttisfloatingtemplateobject(table)) { return 0; } if (!CallMethodHelper_SetTable(lua_state, table, key, val)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_ObjLen(lua_State* lua_state, TValue* ra, const TValue* rb) { if (!ttisfloatingtemplateobject(rb)) { return 0; } if (!CallMethodHelper_ObjLen(lua_state, ra, rb)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_SetList(lua_State* lua_state, const TValue* ra, int n, int c) { if (!ttisfloatingtemplateobject(ra)) { return 0; } if (!CallMethodHelper_SetList(lua_state, ra, n, c)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } } // namespace lua } // namespace floating_temple <commit_msg>Bug fix: When creating a Floating Temple object, the value type should be set to LUA_TFLOATINGTEMPLEOBJECT.<commit_after>// Floating Temple // Copyright 2015 Derek S. Snyder // // 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 "lua/hook_functions.h" #include <csetjmp> #include <string> #include <vector> #include "base/integral_types.h" #include "base/logging.h" #include "include/c++/thread.h" #include "include/c++/value.h" #include "lua/convert_value.h" #include "lua/interpreter_impl.h" #include "lua/table_local_object.h" #include "lua/third_party_lua_headers.h" using std::longjmp; using std::vector; namespace floating_temple { class ObjectReference; namespace lua { namespace { Thread* GetThreadObject() { return InterpreterImpl::instance()->GetThreadObject(); } InterpreterImpl::LongJumpTarget* GetLongJumpTarget() { return InterpreterImpl::instance()->GetLongJumpTarget(); } bool CallMethodHelper_GetTable(lua_State* lua_state, const TValue* table, const TValue* key, TValue* val) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(table).ft_obj); vector<Value> parameters(1); LuaValueToValue(key, &parameters[0]); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "gettable", parameters, &return_value)) { return false; } ValueToLuaValue(lua_state, return_value, val); return true; } bool CallMethodHelper_SetTable(lua_State* lua_state, const TValue* table, const TValue* key, const TValue* val) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(table).ft_obj); vector<Value> parameters(2); LuaValueToValue(key, &parameters[0]); LuaValueToValue(val, &parameters[1]); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "settable", parameters, &return_value)) { return false; } CHECK_EQ(return_value.type(), Value::EMPTY); return true; } bool CallMethodHelper_ObjLen(lua_State* lua_state, TValue* ra, const TValue* rb) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(rb).ft_obj); Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "len", vector<Value>(), &return_value)) { return false; } ValueToLuaValue(lua_state, return_value, ra); return true; } bool CallMethodHelper_SetList(lua_State* lua_state, const TValue* ra, int n, int c) { ObjectReference* const table_object_reference = static_cast<ObjectReference*>( val_(ra).ft_obj); vector<Value> parameters(n + 1); parameters[0].set_int64_value(LUA_TNONE, static_cast<int64>(c)); for (int i = n; i > 0; --i) { LuaValueToValue(ra + i, &parameters[i]); } Value return_value; if (!GetThreadObject()->CallMethod(table_object_reference, "setlist", parameters, &return_value)) { return false; } CHECK_EQ(return_value.type(), Value::EMPTY); return true; } } // namespace void LockInterpreter() { InterpreterImpl::instance()->Lock(); } void UnlockInterpreter() { InterpreterImpl::instance()->Unlock(); } int AreObjectsEqual(const void* ft_obj1, const void* ft_obj2) { return GetThreadObject()->ObjectsAreIdentical( static_cast<const ObjectReference*>(ft_obj1), static_cast<const ObjectReference*>(ft_obj2)) ? 1 : 0; } int CreateTable(lua_State* lua_state, TValue* obj, int b, int c) { InterpreterImpl* const interpreter = InterpreterImpl::instance(); TableLocalObject* const local_object = new TableLocalObject(interpreter); local_object->Init(b, c); ObjectReference* const object_reference = interpreter->GetThreadObject()->CreateVersionedObject(local_object, ""); val_(obj).ft_obj = object_reference; settt_(obj, LUA_TFLOATINGTEMPLEOBJECT); return 1; } // Since the following functions call longjmp(), they must not create any // objects that have destructors. int CallMethod_GetTable(lua_State* lua_state, const TValue* table, const TValue* key, TValue* val) { if (!ttisfloatingtemplateobject(table)) { return 0; } if (!CallMethodHelper_GetTable(lua_state, table, key, val)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_SetTable(lua_State* lua_state, const TValue* table, const TValue* key, const TValue* val) { if (!ttisfloatingtemplateobject(table)) { return 0; } if (!CallMethodHelper_SetTable(lua_state, table, key, val)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_ObjLen(lua_State* lua_state, TValue* ra, const TValue* rb) { if (!ttisfloatingtemplateobject(rb)) { return 0; } if (!CallMethodHelper_ObjLen(lua_state, ra, rb)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } int CallMethod_SetList(lua_State* lua_state, const TValue* ra, int n, int c) { if (!ttisfloatingtemplateobject(ra)) { return 0; } if (!CallMethodHelper_SetList(lua_state, ra, n, c)) { longjmp(GetLongJumpTarget()->env, 1); } return 1; } } // namespace lua } // namespace floating_temple <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file JPetCommonToolsTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetCommonToolsTest #include <boost/test/unit_test.hpp> #include <map> #include "JPetCommonTools.h" BOOST_AUTO_TEST_SUITE(CommonToolsTestSuite) BOOST_AUTO_TEST_CASE(findSubstringTest) { std::string str("There are two needles in this haystack with needles."); std::string str2("needle"); std::size_t found = JPetCommonTools::findSubstring(str, str2); BOOST_REQUIRE_EQUAL(found != std::string::npos, true); } BOOST_AUTO_TEST_CASE(ItoaTest) { int testNumber = 64; std::string intAsASting = JPetCommonTools::Itoa(testNumber); BOOST_REQUIRE_EQUAL(intAsASting == "64", true); } BOOST_AUTO_TEST_CASE(intToStringTest) { int testNumber = 64; std::string intAsASting = JPetCommonTools::intToString(testNumber); BOOST_REQUIRE_EQUAL(intAsASting == "64", true); } BOOST_AUTO_TEST_CASE(doubleToStringTest) { double testNumber = 256.3264; std::string doubleAsASting = JPetCommonTools::doubleToString(testNumber); BOOST_REQUIRE_EQUAL(doubleAsASting == "256.326", true); } BOOST_AUTO_TEST_CASE(stringToIntTest) { std::string testString = "1024"; int stringAsAInt = JPetCommonTools::stringToInt(testString); BOOST_REQUIRE_EQUAL(stringAsAInt == 1024, true); } BOOST_AUTO_TEST_CASE(toBoolTest) { std::string testString = "0"; bool stringAsABool = JPetCommonTools::to_bool(testString); BOOST_REQUIRE_EQUAL(stringAsABool == false, true); } BOOST_AUTO_TEST_CASE(ifFileExistingTest) { std::string fileTest = "run_tests.pl"; bool ifFileExisting = JPetCommonTools::ifFileExisting(fileTest); BOOST_REQUIRE_EQUAL(ifFileExisting, true); } BOOST_AUTO_TEST_CASE(mapAreEqualTest) { std::map<int, int> mapTestLeft, mapTestRight; bool areMapsEqual = JPetCommonTools::mapComparator(mapTestLeft, mapTestRight); BOOST_REQUIRE_EQUAL(areMapsEqual, true); } BOOST_AUTO_TEST_CASE(mapAreNotEqualTest) { std::map<char, int> first; first['a'] = 10; first['b'] = 30; first['c'] = 50; first['d'] = 70; std::map<char, int> second; bool areMapsEqual = JPetCommonTools::mapComparator(first, second); BOOST_REQUIRE_EQUAL(areMapsEqual, false); } BOOST_AUTO_TEST_CASE(stripFileNameSuffixTest) { std::string fileTest = "run_tests.pl"; std::string stripFileNameSuffix = JPetCommonTools::stripFileNameSuffix(fileTest); BOOST_REQUIRE_EQUAL(stripFileNameSuffix == "run_tests", true); } BOOST_AUTO_TEST_CASE(currentFullPathTest) { std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string(); std::string currentFullPath = JPetCommonTools::currentFullPath(); BOOST_REQUIRE_EQUAL(currentFullPath == currentFullPathTest, true); } BOOST_AUTO_TEST_CASE(extractPathFromFileTest) { std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string(); std::string currentFullPathTestWithFileName = currentFullPathTest + "/" + "run_tests.pl"; std::string result = JPetCommonTools::extractPathFromFile(currentFullPathTestWithFileName); BOOST_REQUIRE_EQUAL(result.compare(currentFullPathTest), 0); } BOOST_AUTO_TEST_CASE(isDirectory) { BOOST_REQUIRE(JPetCommonTools::isDirectory(boost::filesystem::initial_path().string())); BOOST_REQUIRE(!JPetCommonTools::isDirectory("fake/directory/baba")); } BOOST_AUTO_TEST_CASE(appendSlashToPathIfAbsent) { BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent(""), ""); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("./"), "./"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home/"), "/home/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home"), "/home/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("home/bbl/be"), "home/bbl/be/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("test"), "test/"); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Added tests for function exctracting suffix of file name<commit_after>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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. * * @file JPetCommonToolsTest.cpp */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE JPetCommonToolsTest #include <boost/test/unit_test.hpp> #include <map> #include "JPetCommonTools.h" BOOST_AUTO_TEST_SUITE(CommonToolsTestSuite) BOOST_AUTO_TEST_CASE(findSubstringTest) { std::string str("There are two needles in this haystack with needles."); std::string str2("needle"); std::size_t found = JPetCommonTools::findSubstring(str, str2); BOOST_REQUIRE_EQUAL(found != std::string::npos, true); } BOOST_AUTO_TEST_CASE(ItoaTest) { int testNumber = 64; std::string intAsASting = JPetCommonTools::Itoa(testNumber); BOOST_REQUIRE_EQUAL(intAsASting == "64", true); } BOOST_AUTO_TEST_CASE(intToStringTest) { int testNumber = 64; std::string intAsASting = JPetCommonTools::intToString(testNumber); BOOST_REQUIRE_EQUAL(intAsASting == "64", true); } BOOST_AUTO_TEST_CASE(doubleToStringTest) { double testNumber = 256.3264; std::string doubleAsASting = JPetCommonTools::doubleToString(testNumber); BOOST_REQUIRE_EQUAL(doubleAsASting == "256.326", true); } BOOST_AUTO_TEST_CASE(stringToIntTest) { std::string testString = "1024"; int stringAsAInt = JPetCommonTools::stringToInt(testString); BOOST_REQUIRE_EQUAL(stringAsAInt == 1024, true); } BOOST_AUTO_TEST_CASE(toBoolTest) { std::string testString = "0"; bool stringAsABool = JPetCommonTools::to_bool(testString); BOOST_REQUIRE_EQUAL(stringAsABool == false, true); } BOOST_AUTO_TEST_CASE(ifFileExistingTest) { std::string fileTest = "run_tests.pl"; bool ifFileExisting = JPetCommonTools::ifFileExisting(fileTest); BOOST_REQUIRE_EQUAL(ifFileExisting, true); } BOOST_AUTO_TEST_CASE(mapAreEqualTest) { std::map<int, int> mapTestLeft, mapTestRight; bool areMapsEqual = JPetCommonTools::mapComparator(mapTestLeft, mapTestRight); BOOST_REQUIRE_EQUAL(areMapsEqual, true); } BOOST_AUTO_TEST_CASE(mapAreNotEqualTest) { std::map<char, int> first; first['a'] = 10; first['b'] = 30; first['c'] = 50; first['d'] = 70; std::map<char, int> second; bool areMapsEqual = JPetCommonTools::mapComparator(first, second); BOOST_REQUIRE_EQUAL(areMapsEqual, false); } BOOST_AUTO_TEST_CASE(stripFileNameSuffixTest) { std::string fileTest = "run_tests.pl"; std::string stripFileNameSuffix = JPetCommonTools::stripFileNameSuffix(fileTest); BOOST_REQUIRE_EQUAL(stripFileNameSuffix == "run_tests", true); } BOOST_AUTO_TEST_CASE(extractFileNameSuffixTest) { std::string fileTest = "run_tests.pl"; std::string stripFileNameSuffix = JPetCommonTools::stripFileNameSuffix(fileTest); BOOST_REQUIRE_EQUAL(stripFileNameSuffix == ".pl", true); } BOOST_AUTO_TEST_CASE(currentFullPathTest) { std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string(); std::string currentFullPath = JPetCommonTools::currentFullPath(); BOOST_REQUIRE_EQUAL(currentFullPath == currentFullPathTest, true); } BOOST_AUTO_TEST_CASE(extractPathFromFileTest) { std::string currentFullPathTest = boost::filesystem::path(boost::filesystem::current_path()).string(); std::string currentFullPathTestWithFileName = currentFullPathTest + "/" + "run_tests.pl"; std::string result = JPetCommonTools::extractPathFromFile(currentFullPathTestWithFileName); BOOST_REQUIRE_EQUAL(result.compare(currentFullPathTest), 0); } BOOST_AUTO_TEST_CASE(isDirectory) { BOOST_REQUIRE(JPetCommonTools::isDirectory(boost::filesystem::initial_path().string())); BOOST_REQUIRE(!JPetCommonTools::isDirectory("fake/directory/baba")); } BOOST_AUTO_TEST_CASE(appendSlashToPathIfAbsent) { BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent(""), ""); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("./"), "./"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home/"), "/home/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("/home"), "/home/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("home/bbl/be"), "home/bbl/be/"); BOOST_REQUIRE_EQUAL(JPetCommonTools::appendSlashToPathIfAbsent("test"), "test/"); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "ruby.h" #include "vector" #include "iostream" #include "map" #include "RtAudio.h" typedef VALUE (ruby_method)(...); int tick( void *outputBuffer, void *inputBuffer, unsigned int inBufferFrames, double streamTime, RtAudioStreamStatus status, void *dataPointer ) { return 0; } class Dac { public: RtAudio *dac; RtAudio::DeviceInfo info; RtAudio::StreamParameters parameters; void hello(){ std::cout << "hello" << std::endl; } void probe(){ // Create an api map. std::map<int, std::string> apiMap; apiMap[RtAudio::MACOSX_CORE] = "OS-X Core Audio"; apiMap[RtAudio::WINDOWS_ASIO] = "Windows ASIO"; apiMap[RtAudio::WINDOWS_DS] = "Windows Direct Sound"; apiMap[RtAudio::UNIX_JACK] = "Jack Client"; apiMap[RtAudio::LINUX_ALSA] = "Linux ALSA"; apiMap[RtAudio::LINUX_OSS] = "Linux OSS"; apiMap[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy"; std::vector<RtAudio::Api> apis; RtAudio::getCompiledApi( apis ); std::cout << "\nCompiled APIs:\n"; for (unsigned int i=0; i < apis.size(); i++ ) std::cout << " " << apiMap[ apis[i] ] << std::endl; std::cout << "\nCurrent API: " << apiMap[ dac->getCurrentApi() ] << std::endl; unsigned int devices = dac->getDeviceCount(); std::cout << "\nFound " << devices << " device(s) ...\n"; for (unsigned int i=0; i < devices; i++) { info = dac->getDeviceInfo(i); std::cout << "\nDevice Name = " << info.name; } } void start() { RtAudioFormat format = RTAUDIO_FLOAT32; unsigned int bufferFrames = 0, sampleRate = 44100; try { dac->openStream( &parameters, NULL, format, sampleRate, &bufferFrames, &tick, NULL ); dac->startStream(); } catch ( RtError &error ) { error.printMessage(); } } void stop() { try { dac->closeStream(); } catch ( RtError &error ) { error.printMessage(); } } Dac() { dac = new RtAudio(); // some info and setup of the dac int device_id = dac->getDefaultOutputDevice(); int num_channels = dac->getDeviceInfo(device_id).outputChannels; parameters.deviceId = device_id; parameters.nChannels = 1; std::cout << "Default output device id: " << device_id << std::endl; std::cout << "Output channels: " << num_channels << std::endl; } ~Dac() { std::cout << "unmaking Audio" << std::endl; delete dac; } }; ///////////////////////////////////////////////// extern "C" { static void audio_free(Dac *simple) { delete simple; } // alloc static VALUE audio_alloc(VALUE klass) { Dac *audio = new Dac; return Data_Wrap_Struct(klass, 0, audio_free, audio); } // initialize static VALUE audio_initialize(VALUE self) { Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); return self; } static VALUE audio_hello(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->hello(); return Qnil; } static VALUE audio_probe(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->probe(); return Qnil; } static VALUE audio_start(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->start(); return Qnil; } static VALUE audio_stop(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->stop(); return Qnil; } //////////////////////////////////////////////////////////// VALUE cAudio; void Init_audio() { cAudio = rb_define_class("Audio", rb_cObject); rb_define_alloc_func(cAudio, audio_alloc); rb_define_method(cAudio, "initialize", (ruby_method*) &audio_initialize, 0); rb_define_method(cAudio, "hello", (ruby_method*) &audio_hello, 0); rb_define_method(cAudio, "probe", (ruby_method*) &audio_probe, 0); rb_define_method(cAudio, "start", (ruby_method*) &audio_start, 0); rb_define_method(cAudio, "stop", (ruby_method*) &audio_stop, 0); // rb_define_method(cAudio, "stop", (ruby_method*) &audio_stop, 0); //id_push = rb_intern("push"); } } // extern "C" <commit_msg>Added a distress signal<commit_after>/* This builds for me (with make) into an audio.bundle which Ruby seems to recognize, but when I try to load it with require("audio"), I get this cryptic (to me) error message: LoadError: dlopen(./audio.bundle, 9): Symbol not found: __ZTISt9exception Referenced from: /Users/tom/Projects/Mine/ruck/ruby/audio/audio.bundle Expected in: dynamic lookup - ./audio.bundle from ./audio.bundle from (irb):1 from :0 ... does anyone know how to make this work? */ #include "ruby.h" #include "vector" #include "iostream" #include "map" #include "RtAudio.h" typedef VALUE (ruby_method)(...); int tick( void *outputBuffer, void *inputBuffer, unsigned int inBufferFrames, double streamTime, RtAudioStreamStatus status, void *dataPointer ) { return 0; } class Dac { public: RtAudio *dac; RtAudio::DeviceInfo info; RtAudio::StreamParameters parameters; void hello(){ std::cout << "hello" << std::endl; } void probe(){ // Create an api map. std::map<int, std::string> apiMap; apiMap[RtAudio::MACOSX_CORE] = "OS-X Core Audio"; apiMap[RtAudio::WINDOWS_ASIO] = "Windows ASIO"; apiMap[RtAudio::WINDOWS_DS] = "Windows Direct Sound"; apiMap[RtAudio::UNIX_JACK] = "Jack Client"; apiMap[RtAudio::LINUX_ALSA] = "Linux ALSA"; apiMap[RtAudio::LINUX_OSS] = "Linux OSS"; apiMap[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy"; std::vector<RtAudio::Api> apis; RtAudio::getCompiledApi( apis ); std::cout << "\nCompiled APIs:\n"; for (unsigned int i=0; i < apis.size(); i++ ) std::cout << " " << apiMap[ apis[i] ] << std::endl; std::cout << "\nCurrent API: " << apiMap[ dac->getCurrentApi() ] << std::endl; unsigned int devices = dac->getDeviceCount(); std::cout << "\nFound " << devices << " device(s) ...\n"; for (unsigned int i=0; i < devices; i++) { info = dac->getDeviceInfo(i); std::cout << "\nDevice Name = " << info.name; } } void start() { RtAudioFormat format = RTAUDIO_FLOAT32; unsigned int bufferFrames = 0, sampleRate = 44100; try { dac->openStream( &parameters, NULL, format, sampleRate, &bufferFrames, &tick, NULL ); dac->startStream(); } catch ( RtError &error ) { error.printMessage(); } } void stop() { try { dac->closeStream(); } catch ( RtError &error ) { error.printMessage(); } } Dac() { dac = new RtAudio(); // some info and setup of the dac int device_id = dac->getDefaultOutputDevice(); int num_channels = dac->getDeviceInfo(device_id).outputChannels; parameters.deviceId = device_id; parameters.nChannels = 1; std::cout << "Default output device id: " << device_id << std::endl; std::cout << "Output channels: " << num_channels << std::endl; } ~Dac() { std::cout << "unmaking Audio" << std::endl; delete dac; } }; ///////////////////////////////////////////////// extern "C" { static void audio_free(Dac *simple) { delete simple; } // alloc static VALUE audio_alloc(VALUE klass) { Dac *audio = new Dac; return Data_Wrap_Struct(klass, 0, audio_free, audio); } // initialize static VALUE audio_initialize(VALUE self) { Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); return self; } static VALUE audio_hello(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->hello(); return Qnil; } static VALUE audio_probe(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->probe(); return Qnil; } static VALUE audio_start(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->start(); return Qnil; } static VALUE audio_stop(VALUE self){ Dac *audio = NULL; Data_Get_Struct(self, Dac, audio); audio->stop(); return Qnil; } //////////////////////////////////////////////////////////// VALUE cAudio; void Init_audio() { cAudio = rb_define_class("Audio", rb_cObject); rb_define_alloc_func(cAudio, audio_alloc); rb_define_method(cAudio, "initialize", (ruby_method*) &audio_initialize, 0); rb_define_method(cAudio, "hello", (ruby_method*) &audio_hello, 0); rb_define_method(cAudio, "probe", (ruby_method*) &audio_probe, 0); rb_define_method(cAudio, "start", (ruby_method*) &audio_start, 0); rb_define_method(cAudio, "stop", (ruby_method*) &audio_stop, 0); // rb_define_method(cAudio, "stop", (ruby_method*) &audio_stop, 0); //id_push = rb_intern("push"); } } // extern "C" <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ViewShellHint.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-03-23 13:57:57 $ * * 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 SD_VIEW_SHELL_HINT_HXX #define SD_VIEW_SHELL_HINT_HXX #ifndef _SFXHINT_HXX //autogen #include <svtools/hint.hxx> #endif namespace sd { /** Local derivation of the SfxHint class that defines some hint ids that are used by the ViewShell class and its decendants. */ class ViewShellHint : public SfxHint { public: enum HintId { // Indicate that a page resize is about to begin. HINT_PAGE_RESIZE_START, // Indicate that a page resize has been completed. HINT_PAGE_RESIZE_END, // Indicate that an edit mode change is about to begin. HINT_CHANGE_EDIT_MODE_START, // Indicate that an edit mode change has been completed. HINT_CHANGE_EDIT_MODE_END, HINT_COMPLEX_MODEL_CHANGE_START, HINT_COMPLEX_MODEL_CHANGE_END }; TYPEINFO(); ViewShellHint (HintId nHintId); HintId GetHintId (void) const; private: HintId meHintId; }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.3.154); FILE MERGED 2005/09/05 13:22:52 rt 1.3.154.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ViewShellHint.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:19:53 $ * * 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 SD_VIEW_SHELL_HINT_HXX #define SD_VIEW_SHELL_HINT_HXX #ifndef _SFXHINT_HXX //autogen #include <svtools/hint.hxx> #endif namespace sd { /** Local derivation of the SfxHint class that defines some hint ids that are used by the ViewShell class and its decendants. */ class ViewShellHint : public SfxHint { public: enum HintId { // Indicate that a page resize is about to begin. HINT_PAGE_RESIZE_START, // Indicate that a page resize has been completed. HINT_PAGE_RESIZE_END, // Indicate that an edit mode change is about to begin. HINT_CHANGE_EDIT_MODE_START, // Indicate that an edit mode change has been completed. HINT_CHANGE_EDIT_MODE_END, HINT_COMPLEX_MODEL_CHANGE_START, HINT_COMPLEX_MODEL_CHANGE_END }; TYPEINFO(); ViewShellHint (HintId nHintId); HintId GetHintId (void) const; private: HintId meHintId; }; } // end of namespace sd #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015 University of Basel * 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 project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <boost/program_options.hpp> #include <itkDataManager.h> #include <itkDirectory.h> #include <itkImageFileReader.h> #include <itkPCAModelBuilder.h> #include <itkStandardImageRepresenter.h> #include <itkStatisticalModel.h> #include "utils/statismo-build-models-utils.h" namespace po = boost::program_options; using namespace std; struct programOptions { bool bDisplayHelp; string strDataListFile; string strOutputFileName; float fNoiseVariance; unsigned uNumberOfDimensions; }; po::options_description initializeProgramOptions(programOptions& poParameters); bool isOptionsConflictPresent(programOptions& opt); template<unsigned Dimensions> void buildAndSaveDeformationModel(programOptions opt); int main(int argc, char** argv) { programOptions poParameters; po::positional_options_description optPositional; optPositional.add("output-file", 1); po::options_description optAllOptions = initializeProgramOptions(poParameters); po::variables_map vm; try { po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run(); po::store(parsedOptions, vm); po::notify(vm); } catch (po::error& e) { cerr << "An exception occurred while parsing the Command line:"<<endl; cerr << e.what() << endl; return EXIT_FAILURE; } if (poParameters.bDisplayHelp == true) { cout << optAllOptions << endl; return EXIT_SUCCESS; } if (isOptionsConflictPresent(poParameters) == true) { cerr << "A conflict in the options exists or insufficient options were set." << endl; cout << optAllOptions << endl; return EXIT_FAILURE; } try { if (poParameters.uNumberOfDimensions == 2) { buildAndSaveDeformationModel<2>(poParameters); } else { buildAndSaveDeformationModel<3>(poParameters); } } catch (ifstream::failure & e) { cerr << "Could not read the data-list:" << endl; cerr << e.what() << endl; return EXIT_FAILURE; } catch (itk::ExceptionObject & e) { cerr << "Could not build the model:" << endl; cerr << e.what() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } bool isOptionsConflictPresent(programOptions& opt) { if (opt.strDataListFile == "" || opt.strOutputFileName == "" ) { return true; } if (opt.strDataListFile == opt.strOutputFileName) { return true; } if (opt.fNoiseVariance < 0) { return true; } if (opt.uNumberOfDimensions != 2 && opt.uNumberOfDimensions != 3) { return true; } return false; } template<unsigned Dimensions> void buildAndSaveDeformationModel(programOptions opt) { typedef itk::Vector<float, Dimensions> VectorPixelType; typedef itk::Image<VectorPixelType, Dimensions> ImageType; typedef itk::StandardImageRepresenter<VectorPixelType, Dimensions > RepresenterType; typename RepresenterType::Pointer representer = RepresenterType::New(); typedef itk::DataManager<ImageType> DataManagerType; typename DataManagerType::Pointer dataManager = DataManagerType::New(); StringList fileNames = getFileList(opt.strDataListFile); typedef itk::ImageFileReader<ImageType> ImageReaderType; typedef vector<typename ImageReaderType::Pointer> ImageReaderList; if (fileNames.size() == 0) { itkGenericExceptionMacro( << "No Data was loaded and thus the model can't be built."); } bool firstPass = true; for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) { typename ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(it->c_str()); reader->Update(); if ( firstPass ) { representer->SetReference(reader->GetOutput()); dataManager->SetRepresenter(representer); firstPass = false; } dataManager->AddDataset(reader->GetOutput(), reader->GetFileName().c_str()); } typedef itk::StatisticalModel<ImageType> StatisticalModelType; typename StatisticalModelType::Pointer model; typedef itk::PCAModelBuilder<ImageType> ModelBuilderType; typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New(); model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance); model->Save(opt.strOutputFileName.c_str()); } po::options_description initializeProgramOptions(programOptions& poParameters) { po::options_description optMandatory("Mandatory options"); optMandatory.add_options() ("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build the deformation model from") ("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file") ("dimensionality,d", po::value<unsigned>(&poParameters.uNumberOfDimensions)->default_value(3), "Dimensionality of the input images in the data list") ; po::options_description optAdditional("Optional options"); optAdditional.add_options() ("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model") ("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message") ; po::options_description optAllOptions; optAllOptions.add(optMandatory).add(optAdditional); return optAllOptions; } <commit_msg>put scores back in<commit_after>/* * Copyright (c) 2015 University of Basel * 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 project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <boost/program_options.hpp> #include <itkDataManager.h> #include <itkDirectory.h> #include <itkImageFileReader.h> #include <itkPCAModelBuilder.h> #include <itkStandardImageRepresenter.h> #include <itkStatisticalModel.h> #include "utils/statismo-build-models-utils.h" namespace po = boost::program_options; using namespace std; struct programOptions { bool bDisplayHelp; bool bComputeScores; string strDataListFile; string strOutputFileName; float fNoiseVariance; unsigned uNumberOfDimensions; }; po::options_description initializeProgramOptions(programOptions& poParameters); bool isOptionsConflictPresent(programOptions& opt); template<unsigned Dimensions> void buildAndSaveDeformationModel(programOptions opt); int main(int argc, char** argv) { programOptions poParameters; po::positional_options_description optPositional; optPositional.add("output-file", 1); po::options_description optAllOptions = initializeProgramOptions(poParameters); po::variables_map vm; try { po::parsed_options parsedOptions = po::command_line_parser(argc, argv).options(optAllOptions).positional(optPositional).run(); po::store(parsedOptions, vm); po::notify(vm); } catch (po::error& e) { cerr << "An exception occurred while parsing the Command line:"<<endl; cerr << e.what() << endl; return EXIT_FAILURE; } if (poParameters.bDisplayHelp == true) { cout << optAllOptions << endl; return EXIT_SUCCESS; } if (isOptionsConflictPresent(poParameters) == true) { cerr << "A conflict in the options exists or insufficient options were set." << endl; cout << optAllOptions << endl; return EXIT_FAILURE; } try { if (poParameters.uNumberOfDimensions == 2) { buildAndSaveDeformationModel<2>(poParameters); } else { buildAndSaveDeformationModel<3>(poParameters); } } catch (ifstream::failure & e) { cerr << "Could not read the data-list:" << endl; cerr << e.what() << endl; return EXIT_FAILURE; } catch (itk::ExceptionObject & e) { cerr << "Could not build the model:" << endl; cerr << e.what() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } bool isOptionsConflictPresent(programOptions& opt) { if (opt.strDataListFile == "" || opt.strOutputFileName == "" ) { return true; } if (opt.strDataListFile == opt.strOutputFileName) { return true; } if (opt.fNoiseVariance < 0) { return true; } if (opt.uNumberOfDimensions != 2 && opt.uNumberOfDimensions != 3) { return true; } return false; } template<unsigned Dimensions> void buildAndSaveDeformationModel(programOptions opt) { typedef itk::Vector<float, Dimensions> VectorPixelType; typedef itk::Image<VectorPixelType, Dimensions> ImageType; typedef itk::StandardImageRepresenter<VectorPixelType, Dimensions > RepresenterType; typename RepresenterType::Pointer representer = RepresenterType::New(); typedef itk::DataManager<ImageType> DataManagerType; typename DataManagerType::Pointer dataManager = DataManagerType::New(); StringList fileNames = getFileList(opt.strDataListFile); typedef itk::ImageFileReader<ImageType> ImageReaderType; typedef vector<typename ImageReaderType::Pointer> ImageReaderList; if (fileNames.size() == 0) { itkGenericExceptionMacro( << "No Data was loaded and thus the model can't be built."); } bool firstPass = true; for (StringList::const_iterator it = fileNames.begin(); it != fileNames.end(); ++it) { typename ImageReaderType::Pointer reader = ImageReaderType::New(); reader->SetFileName(it->c_str()); reader->Update(); if ( firstPass ) { representer->SetReference(reader->GetOutput()); dataManager->SetRepresenter(representer); firstPass = false; } dataManager->AddDataset(reader->GetOutput(), reader->GetFileName().c_str()); } typedef itk::StatisticalModel<ImageType> StatisticalModelType; typename StatisticalModelType::Pointer model; typedef itk::PCAModelBuilder<ImageType> ModelBuilderType; typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New(); model = pcaModelBuilder->BuildNewModel(dataManager->GetData(), opt.fNoiseVariance, opt.bComputeScores); model->Save(opt.strOutputFileName.c_str()); } po::options_description initializeProgramOptions(programOptions& poParameters) { po::options_description optMandatory("Mandatory options"); optMandatory.add_options() ("data-list,l", po::value<string>(&poParameters.strDataListFile), "File containing a list of meshes to build the deformation model from") ("output-file,o", po::value<string>(&poParameters.strOutputFileName), "Name of the output file") ("dimensionality,d", po::value<unsigned>(&poParameters.uNumberOfDimensions)->default_value(3), "Dimensionality of the input images in the data list") ; po::options_description optAdditional("Optional options"); optAdditional.add_options() ("noise,n", po::value<float>(&poParameters.fNoiseVariance)->default_value(0), "Noise variance of the PPCA model") ("scores,s", po::value<bool>(&poParameters.bComputeScores)->default_value(true), "Compute scores (default true)") ("help,h", po::bool_switch(&poParameters.bDisplayHelp), "Display this help message") ; po::options_description optAllOptions; optAllOptions.add(optMandatory).add(optAdditional); return optAllOptions; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uobject.hh #ifndef URBI_UOBJECT_HH # define URBI_UOBJECT_HH # include <string> # include <libport/warning-push.hh> # include <libport/compiler.hh> # include <libport/fwd.hh> # include <libport/ufloat.h> # include <libport/utime.hh> # include <urbi/export.hh> # include <urbi/fwd.hh> # include <urbi/kernel-version.hh> # include <urbi/ucallbacks.hh> # include <urbi/utimer-callback.hh> # include <urbi/uvar.hh> # include <urbi/uobject-hub.hh> # include <urbi/ucontext.hh> // Tell our users that it is fine to use void returning functions. #define USE_VOID 1 #define URBI_UOBJECT_VERSION 2 /** Bind a variable to an object. This macro can only be called from within a class inheriting from UObject. It binds the UVar x within the object to a variable with the same name in the corresponding Urbi object. */ # define UBindVar(Obj,X) \ (X).init(__name, #X, ctx_) /** This macro inverts a UVar in/out accesses. After this call is made, writes by this module affect the sensed value, and reads read the target value. Writes by other modules and Urbi code affect the target value, and reads get the sensed value. Without this call, all operations affect the same underlying variable. */ # define UOwned(X) \ (X).setOwned() /// Backward compatibility. # define USensor(X) \ UOwned(X) /** Bind the function X in current Urbi object to the C++ member function of same name. The return value and arguments must be of a basic integral or floating types, char *, std::string, UValue, UBinary, USound or UImage, or any type that can cast to/from UValue. */ # define UBindFunction(Obj, X) \ ::urbi::createUCallback(__name, "function", static_cast<Obj*>(this), \ (&Obj::X), __name + "." #X, \ false) /** Registers a function X in current object that will be called each time the event of same name is triggered. The function will be called only if the number of arguments match between the function prototype and the Urbi event. */ # define UBindEvent(Obj, X) \ ::urbi::createUCallback(__name, "event", this, \ (&Obj::X), __name + "." #X, \ false) /** Registers a function \a X in current object that will be called each * time the event of same name is triggered, and a function fun called * when the event ends. The function will be called only if the number * of arguments match between the function prototype and the Urbi * event. */ # define UBindEventEnd(Obj, X, Fun) \ ::urbi::createUCallback(__name, "eventend", this, \ (&Obj::X),(&Obj::Fun), __name + "." #X, \ ) /// Register current object to the UObjectHub named \a Hub. # define URegister(Hub) \ do { \ objecthub = ::urbi::baseURBIStarterHub::find(#Hub); \ if (objecthub) \ objecthub->addMember(this); \ else \ ::urbi::echo("Error: hub name '" #Hub "' is unknown\n"); \ } while (0) //macro to send urbi commands # ifndef URBI /// Send unquoted Urbi commands to the server. /// Add an extra layer of parenthesis for safety. # define URBI(A) \ uobject_unarmorAndSend(# A) # endif /// Send \a Args (which is given to a stream and therefore can use <<) /// to \a C. # define URBI_SEND_C(C, Args) \ do { \ std::ostringstream os; \ os << Args; \ C << os.str(); \ } while (false) /// Send \a Args (which is given to a stream and therefore can use <<) /// to the server. # define URBI_SEND(Args) \ URBI_SEND_C(URBI(()), Args) /// Send "\a Args ; \n" to \a C. # define URBI_SEND_COMMAND_C(C, Args) \ URBI_SEND_C(C, Args << ';' << std::endl) # define URBI_SEND_COMMAND(Args) \ URBI_SEND_COMMAND_C(URBI(()), Args) /** Send "\a Args | \n" to \a C. * \b Warning: nothing is executed until a ';' or ',' is sent. */ # define URBI_SEND_PIPED_COMMAND_C(C, Args) \ URBI_SEND_C(C, Args << '|' << std::endl) # define URBI_SEND_PIPED_COMMAND(Args) \ URBI_SEND_PIPED_COMMAND_C(URBI(()), Args) namespace urbi { URBI_SDK_API UObjectHub* getUObjectHub(const std::string& n); URBI_SDK_API UObject* getUObject(const std::string& n); URBI_SDK_API void uobject_unarmorAndSend(const char* str); URBI_SDK_API void send(const char* str); URBI_SDK_API void send(const std::string&s); URBI_SDK_API void send(const void* buf, size_t size); URBI_SDK_API UObjectMode getRunningMode(); URBI_SDK_API bool isPluginMode(); URBI_SDK_API bool isRemoteMode(); typedef int UReturn; /** Main UObject class definition Each UObject instance corresponds to an URBI object. It provides mechanisms to bind variables and functions between C++ and Urbi. */ class URBI_SDK_API UObject: public UContext { public: UObject(const std::string&, impl::UContextImpl* impl = 0); /// Reserved for internal use UObject(int, impl::UContextImpl* impl = 0); virtual ~UObject(); // This call registers both an UObject (say of type // UObjectDerived), and a callback working on it (named here // fun). createUCallback wants both the object and the callback // to have the same type, which is not the casem this is static // type of the former is UObject (its runtime type is indeed // UObjectDerived though), and the callback wants a // UObjectDerived. So we need a cast, until a more elegant way // is found (e.g., using free standing functions instead of a // member functions). // These macros provide the following callbacks : // Notify // Access | const std::string& | int (T::*fun) () | const // Change | urbi::UVar& | int (T::*fun) (urbi::UVar&) | non-const // OnRequest | # ifdef DOXYGEN // Doxygen does not handle macros very well so feed it simplified code. /*! \brief Call a function each time a variable is modified. \param v the variable to monitor. \param fun the function to call each time the variable \b v is modified. The function is called rigth after the variable v is modified. */ void UNotifyChange(UVar& v, int (UObject::*fun)(UVar&)); /*! \brief Call a function each time a new variable value is available. \param v the variable to monitor. \param fun the function to call each time the variable \b v is modified. This function is similar to UNotifyChange(), but it does not monitor the changes on \b v. You must explicitly call UVar::requestValue() when you want the callback function to be called. The function is called rigth after the variable v is updated. */ void UNotifyOnRequest(UVar& v, int (UObject::*fun)(UVar&)); /*! \brief Call a function each time a variable is accessed. \param v the variable to monitor. \param fun the function to call each time the variable \b v is accessed. The function is called rigth \b before the variable v is accessed, giving \b fun the oportunity to modify it. */ void UNotifyAccess(UVar& v, int (UObject::*fun)(UVar&)); /// Call \a fun every \a t milliseconds. template <class T> void USetTimer(ufloat t, int (T::*fun)()); # else /// \internal # define MakeNotify(Type, Notified, Arg, Const, \ TypeString, Name, Owned, \ WithArg, StoreArg) \ template <class T> \ void UNotify##Type(Notified, int (T::*fun) (Arg) Const) \ { \ UGenericCallback* cb = \ createUCallback(__name, TypeString, \ dynamic_cast<T*>(this), \ fun, Name, Owned); \ \ if (WithArg && cb) \ cb->storage = StoreArg; \ } /// \internal # define MakeMetaNotifyArg(Type, Notified, TypeString, Owned, \ Name, StoreArg) \ MakeNotify(Type, Notified, /**/, /**/, TypeString, Name, \ Owned, false, StoreArg); \ MakeNotify(Type, Notified, /**/, const, TypeString, Name, \ Owned, false, StoreArg); \ MakeNotify(Type, Notified, UVar&, /**/, TypeString, Name, \ Owned, true, StoreArg); \ MakeNotify(Type, Notified, UVar&, const, TypeString, Name, \ Owned, true, StoreArg); /// \internal # define MakeMetaNotify(Type, TypeString) \ MakeMetaNotifyArg(Type, UVar& v, TypeString, \ v.owned, v.get_name (), &v); \ MakeMetaNotifyArg(Type, const std::string& name, TypeString, \ false, name, new UVar(name)); /// \internal MakeMetaNotify(Access, "varaccess"); /// \internal MakeMetaNotify(Change, "var"); /// \internal MakeMetaNotify(OnRequest, "var_onrequest"); # undef MakeNotify # undef MakeMetaNotifyArg # undef MakeMEtaNotify /// \internal # define MKUSetTimer(Const, Useless) \ template <class T> \ void USetTimer(ufloat t, int (T::*fun) () Const) \ { \ new UTimerCallbackobj<T> (__name, t, \ dynamic_cast<T*>(this), fun, ctx_); \ } MKUSetTimer (/**/, /**/); MKUSetTimer (const, /**/); # undef MKUSetTimer # endif //DOXYGEN /// Request permanent synchronization for v. void USync(UVar &v); /// Name of the object as seen in Urbi. std::string __name; /// Name of the class the object is derived from. std::string classname; /// True when the object has been newed by an urbi command. bool derived; UObjectList members; /// The hub, if it exists. UObjectHub* objecthub; /// Set a timer that will call the update function every 'period' /// milliseconds. void USetUpdate(ufloat period); virtual int update(); /// \name Autogroup. /// \{ /// These functions are obsoleted, they are not supported /// in Urbi SDK 2.0. /// Set autogrouping facility for each new subclass created. #ifdef BUILDING_URBI_SDK # define URBI_SDK_DEPRECATED #else # define URBI_SDK_DEPRECATED ATTRIBUTE_DEPRECATED #endif URBI_SDK_DEPRECATED void UAutoGroup(); /// Called when a subclass is created if autogroup is true. URBI_SDK_DEPRECATED virtual void addAutoGroup(); /// Join the uobject to the 'gpname' group. URBI_SDK_DEPRECATED virtual void UJoinGroup(const std::string& gpname); /// Add a group with a 's' after the base class name. URBI_SDK_DEPRECATED bool autogroup; #undef DEPRECATED /// \} /// Void function used in USync callbacks. int voidfun(); /// Flag to know whether the UObject is in remote mode or not bool remote; /// Remove all bindings, this method is called by the destructor. void clean(); /// The load attribute is standard and can be used to control the /// activity of the object. UVar load; baseURBIStarter* cloner; private: /// Pointer to a globalData structure specific to the /// remote/plugin architectures who defines it. UObjectData* objectData; impl::UObjectImpl* impl_; }; } // end namespace urbi // This file needs the definition of UObject, so included last. // To be cleaned later. # include <urbi/ustarter.hh> # include <urbi/uobject.hxx> # include <libport/warning-pop.hh> #endif // ! URBI_UOBJECT_HH <commit_msg>MSVC: remove incorrect dllexports.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file urbi/uobject.hh #ifndef URBI_UOBJECT_HH # define URBI_UOBJECT_HH # include <string> # include <libport/warning-push.hh> # include <libport/compiler.hh> # include <libport/fwd.hh> # include <libport/ufloat.h> # include <libport/utime.hh> # include <urbi/export.hh> # include <urbi/fwd.hh> # include <urbi/kernel-version.hh> # include <urbi/ucallbacks.hh> # include <urbi/utimer-callback.hh> # include <urbi/uvar.hh> # include <urbi/uobject-hub.hh> # include <urbi/ucontext.hh> // Tell our users that it is fine to use void returning functions. #define USE_VOID 1 #define URBI_UOBJECT_VERSION 2 /** Bind a variable to an object. This macro can only be called from within a class inheriting from UObject. It binds the UVar x within the object to a variable with the same name in the corresponding Urbi object. */ # define UBindVar(Obj,X) \ (X).init(__name, #X, ctx_) /** This macro inverts a UVar in/out accesses. After this call is made, writes by this module affect the sensed value, and reads read the target value. Writes by other modules and Urbi code affect the target value, and reads get the sensed value. Without this call, all operations affect the same underlying variable. */ # define UOwned(X) \ (X).setOwned() /// Backward compatibility. # define USensor(X) \ UOwned(X) /** Bind the function X in current Urbi object to the C++ member function of same name. The return value and arguments must be of a basic integral or floating types, char *, std::string, UValue, UBinary, USound or UImage, or any type that can cast to/from UValue. */ # define UBindFunction(Obj, X) \ ::urbi::createUCallback(__name, "function", static_cast<Obj*>(this), \ (&Obj::X), __name + "." #X, \ false) /** Registers a function X in current object that will be called each time the event of same name is triggered. The function will be called only if the number of arguments match between the function prototype and the Urbi event. */ # define UBindEvent(Obj, X) \ ::urbi::createUCallback(__name, "event", this, \ (&Obj::X), __name + "." #X, \ false) /** Registers a function \a X in current object that will be called each * time the event of same name is triggered, and a function fun called * when the event ends. The function will be called only if the number * of arguments match between the function prototype and the Urbi * event. */ # define UBindEventEnd(Obj, X, Fun) \ ::urbi::createUCallback(__name, "eventend", this, \ (&Obj::X),(&Obj::Fun), __name + "." #X, \ ) /// Register current object to the UObjectHub named \a Hub. # define URegister(Hub) \ do { \ objecthub = ::urbi::baseURBIStarterHub::find(#Hub); \ if (objecthub) \ objecthub->addMember(this); \ else \ ::urbi::echo("Error: hub name '" #Hub "' is unknown\n"); \ } while (0) //macro to send urbi commands # ifndef URBI /// Send unquoted Urbi commands to the server. /// Add an extra layer of parenthesis for safety. # define URBI(A) \ uobject_unarmorAndSend(# A) # endif /// Send \a Args (which is given to a stream and therefore can use <<) /// to \a C. # define URBI_SEND_C(C, Args) \ do { \ std::ostringstream os; \ os << Args; \ C << os.str(); \ } while (false) /// Send \a Args (which is given to a stream and therefore can use <<) /// to the server. # define URBI_SEND(Args) \ URBI_SEND_C(URBI(()), Args) /// Send "\a Args ; \n" to \a C. # define URBI_SEND_COMMAND_C(C, Args) \ URBI_SEND_C(C, Args << ';' << std::endl) # define URBI_SEND_COMMAND(Args) \ URBI_SEND_COMMAND_C(URBI(()), Args) /** Send "\a Args | \n" to \a C. * \b Warning: nothing is executed until a ';' or ',' is sent. */ # define URBI_SEND_PIPED_COMMAND_C(C, Args) \ URBI_SEND_C(C, Args << '|' << std::endl) # define URBI_SEND_PIPED_COMMAND(Args) \ URBI_SEND_PIPED_COMMAND_C(URBI(()), Args) namespace urbi { UObjectHub* getUObjectHub(const std::string& n); UObject* getUObject(const std::string& n); void uobject_unarmorAndSend(const char* str); void send(const char* str); void send(const std::string&s); void send(const void* buf, size_t size); UObjectMode getRunningMode(); bool isPluginMode(); bool isRemoteMode(); typedef int UReturn; /** Main UObject class definition Each UObject instance corresponds to an URBI object. It provides mechanisms to bind variables and functions between C++ and Urbi. */ class URBI_SDK_API UObject: public UContext { public: UObject(const std::string&, impl::UContextImpl* impl = 0); /// Reserved for internal use UObject(int, impl::UContextImpl* impl = 0); virtual ~UObject(); // This call registers both an UObject (say of type // UObjectDerived), and a callback working on it (named here // fun). createUCallback wants both the object and the callback // to have the same type, which is not the casem this is static // type of the former is UObject (its runtime type is indeed // UObjectDerived though), and the callback wants a // UObjectDerived. So we need a cast, until a more elegant way // is found (e.g., using free standing functions instead of a // member functions). // These macros provide the following callbacks : // Notify // Access | const std::string& | int (T::*fun) () | const // Change | urbi::UVar& | int (T::*fun) (urbi::UVar&) | non-const // OnRequest | # ifdef DOXYGEN // Doxygen does not handle macros very well so feed it simplified code. /*! \brief Call a function each time a variable is modified. \param v the variable to monitor. \param fun the function to call each time the variable \b v is modified. The function is called rigth after the variable v is modified. */ void UNotifyChange(UVar& v, int (UObject::*fun)(UVar&)); /*! \brief Call a function each time a new variable value is available. \param v the variable to monitor. \param fun the function to call each time the variable \b v is modified. This function is similar to UNotifyChange(), but it does not monitor the changes on \b v. You must explicitly call UVar::requestValue() when you want the callback function to be called. The function is called rigth after the variable v is updated. */ void UNotifyOnRequest(UVar& v, int (UObject::*fun)(UVar&)); /*! \brief Call a function each time a variable is accessed. \param v the variable to monitor. \param fun the function to call each time the variable \b v is accessed. The function is called rigth \b before the variable v is accessed, giving \b fun the oportunity to modify it. */ void UNotifyAccess(UVar& v, int (UObject::*fun)(UVar&)); /// Call \a fun every \a t milliseconds. template <class T> void USetTimer(ufloat t, int (T::*fun)()); # else /// \internal # define MakeNotify(Type, Notified, Arg, Const, \ TypeString, Name, Owned, \ WithArg, StoreArg) \ template <class T> \ void UNotify##Type(Notified, int (T::*fun) (Arg) Const) \ { \ UGenericCallback* cb = \ createUCallback(__name, TypeString, \ dynamic_cast<T*>(this), \ fun, Name, Owned); \ \ if (WithArg && cb) \ cb->storage = StoreArg; \ } /// \internal # define MakeMetaNotifyArg(Type, Notified, TypeString, Owned, \ Name, StoreArg) \ MakeNotify(Type, Notified, /**/, /**/, TypeString, Name, \ Owned, false, StoreArg); \ MakeNotify(Type, Notified, /**/, const, TypeString, Name, \ Owned, false, StoreArg); \ MakeNotify(Type, Notified, UVar&, /**/, TypeString, Name, \ Owned, true, StoreArg); \ MakeNotify(Type, Notified, UVar&, const, TypeString, Name, \ Owned, true, StoreArg); /// \internal # define MakeMetaNotify(Type, TypeString) \ MakeMetaNotifyArg(Type, UVar& v, TypeString, \ v.owned, v.get_name (), &v); \ MakeMetaNotifyArg(Type, const std::string& name, TypeString, \ false, name, new UVar(name)); /// \internal MakeMetaNotify(Access, "varaccess"); /// \internal MakeMetaNotify(Change, "var"); /// \internal MakeMetaNotify(OnRequest, "var_onrequest"); # undef MakeNotify # undef MakeMetaNotifyArg # undef MakeMEtaNotify /// \internal # define MKUSetTimer(Const, Useless) \ template <class T> \ void USetTimer(ufloat t, int (T::*fun) () Const) \ { \ new UTimerCallbackobj<T> (__name, t, \ dynamic_cast<T*>(this), fun, ctx_); \ } MKUSetTimer (/**/, /**/); MKUSetTimer (const, /**/); # undef MKUSetTimer # endif //DOXYGEN /// Request permanent synchronization for v. void USync(UVar &v); /// Name of the object as seen in Urbi. std::string __name; /// Name of the class the object is derived from. std::string classname; /// True when the object has been newed by an urbi command. bool derived; UObjectList members; /// The hub, if it exists. UObjectHub* objecthub; /// Set a timer that will call the update function every 'period' /// milliseconds. void USetUpdate(ufloat period); virtual int update(); /// \name Autogroup. /// \{ /// These functions are obsoleted, they are not supported /// in Urbi SDK 2.0. /// Set autogrouping facility for each new subclass created. #ifdef BUILDING_URBI_SDK # define URBI_SDK_DEPRECATED #else # define URBI_SDK_DEPRECATED ATTRIBUTE_DEPRECATED #endif URBI_SDK_DEPRECATED void UAutoGroup(); /// Called when a subclass is created if autogroup is true. URBI_SDK_DEPRECATED virtual void addAutoGroup(); /// Join the uobject to the 'gpname' group. URBI_SDK_DEPRECATED virtual void UJoinGroup(const std::string& gpname); /// Add a group with a 's' after the base class name. URBI_SDK_DEPRECATED bool autogroup; #undef DEPRECATED /// \} /// Void function used in USync callbacks. int voidfun(); /// Flag to know whether the UObject is in remote mode or not bool remote; /// Remove all bindings, this method is called by the destructor. void clean(); /// The load attribute is standard and can be used to control the /// activity of the object. UVar load; baseURBIStarter* cloner; private: /// Pointer to a globalData structure specific to the /// remote/plugin architectures who defines it. UObjectData* objectData; impl::UObjectImpl* impl_; }; } // end namespace urbi // This file needs the definition of UObject, so included last. // To be cleaned later. # include <urbi/ustarter.hh> # include <urbi/uobject.hxx> # include <libport/warning-pop.hh> #endif // ! URBI_UOBJECT_HH <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_device/audio_device_config.h" #include "webrtc/modules/audio_device/ios/audio_device_utility_ios.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { AudioDeviceUtilityIOS::AudioDeviceUtilityIOS(const int32_t id) : _critSect(*CriticalSectionWrapper::CreateCriticalSection()), _id(id), _lastError(AudioDeviceModule::kAdmErrNone) { WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id, "%s created", __FUNCTION__); } AudioDeviceUtilityIOS::~AudioDeviceUtilityIOS() { WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id, "%s destroyed", __FUNCTION__); CriticalSectionScoped lock(&_critSect); delete &_critSect; } int32_t AudioDeviceUtilityIOS::Init() { WEBRTC_TRACE(kTraceModuleCall, kTraceAudioDevice, _id, "%s", __FUNCTION__); WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id, " OS info: %s", "iOS"); return 0; } } // namespace webrtc <commit_msg>Fix crash in AudioDeviceUtilityIOS::~AudioDeviceUtilityIOS.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_device/audio_device_config.h" #include "webrtc/modules/audio_device/ios/audio_device_utility_ios.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { AudioDeviceUtilityIOS::AudioDeviceUtilityIOS(const int32_t id) : _critSect(*CriticalSectionWrapper::CreateCriticalSection()), _id(id), _lastError(AudioDeviceModule::kAdmErrNone) { WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id, "%s created", __FUNCTION__); } AudioDeviceUtilityIOS::~AudioDeviceUtilityIOS() { WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id, "%s destroyed", __FUNCTION__); { CriticalSectionScoped lock(&_critSect); } delete &_critSect; } int32_t AudioDeviceUtilityIOS::Init() { WEBRTC_TRACE(kTraceModuleCall, kTraceAudioDevice, _id, "%s", __FUNCTION__); WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, _id, " OS info: %s", "iOS"); return 0; } } // namespace webrtc <|endoftext|>