commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
84694ff59a1ff1db482f5b7d09b1f404af9821ad
|
libqimessaging/qimessaging/type.hpp
|
libqimessaging/qimessaging/type.hpp
|
#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QIMESSAGING_TYPE_HPP_
#define _QIMESSAGING_TYPE_HPP_
#include <typeinfo>
#include <boost/preprocessor.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/details/dynamicvalue.hpp>
namespace qi{
/** Interface for all the operations we need on any type:
*
* - cloning/destruction in clone() and destroy()
* - type conversion is made by going through the generic container
* GenericValue, using the toValue() and fromValue() functions,
* - Serialization through serialize() and deserialize() to transmit
* the value through some kind of pipe.
*
* Our aim is to transport arbitrary values through:
* - synchronous calls: Nothing to do, values are just transported and
converted.
* - asynchronous call/thread change: Values are copied.
* - process change: Values are serialized.
*
*/
class QIMESSAGING_API Type
{
public:
virtual const std::type_info& info() =0;
const char* infoString() { return info().name();} // for easy gdb access
/// @return the serialization signature used by this type.
virtual std::string signature()=0;
virtual void* clone(void*)=0;
virtual void destroy(void*)=0;
virtual bool toValue(const void*, qi::detail::DynamicValue&)=0;
virtual void* fromValue(const qi::detail::DynamicValue&)=0;
// Default impl does toValue.serialize()
virtual void serialize(ODataStream& s, const void*)=0;
// Default impl does deserialize(GenericValue&) then fromValue
virtual void* deserialize(IDataStream& s)=0;
/* When someone makes a call with arguments that do not match the
* target signature (ex: int vs float), we want to handle it.
* For this, given the known correct signature S and known incorrect
* GenericValue v, we want to be able to obtain a new Type T that
* serializes with type S, and then try to convert o into type T.
*
* For this we need a map<Signature, Type> that we will feed with
* known types.
*
*/
typedef std::map<std::string, Type*> TypeSignatureMap;
static TypeSignatureMap& typeSignatureMap()
{
static TypeSignatureMap res;
return res;
}
static Type* getCompatibleTypeWithSignature(const std::string& sig)
{
TypeSignatureMap::iterator i = typeSignatureMap().find(sig);
if (i == typeSignatureMap().end())
return 0;
else
return i->second;
}
static bool registerCompatibleType(const std::string& sig,
Type* mt)
{
typeSignatureMap()[sig] = mt;
return true;
}
#define QI_REGISTER_MAPPING(sig, type) \
static bool BOOST_PP_CAT(_qireg_map_ , __LINE__) = ::qi::Type::registerCompatibleType(sig, \
::qi::typeOf<type>());
};
/** Meta-type specialization.
* Use the aspect pattern, make a class per feature group
* (Clone, GenericValue, Serialize)
*
*/
template<typename T> class TypeDefaultClone
{
public:
void* clone(void* src)
{
return new T(*(T*)src);
}
void destroy(void* ptr)
{
delete (T*)ptr;
}
};
template<typename T> class TypeNoClone
{
public:
void* clone(void* src)
{
return src;
}
void destroy(void* ptr)
{
/* Assume a TypeNoClone is not serializable
* So it cannot have been allocated by us.
* So the destroy comes after a clone->ignore it
*/
}
};
template<typename T>class TypeDefaultValue
{
public:
bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
detail::DynamicValueConverter<T>::writeDynamicValue(*(T*)ptr, val);
return true;
}
void* fromValue(const qi::detail::DynamicValue& val)
{
T* res = new T();
detail::DynamicValueConverter<T>::readDynamicValue(val, *res);
return res;
}
};
template<typename T>class TypeNoValue
{
public:
bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
qiLogWarning("qi.type") << "toValue not implemented for type ";
return false;
}
void* fromValue(const qi::detail::DynamicValue& val)
{
qiLogWarning("qi.type") << "fromValue not implemented for type ";
T* res = new T();
return res;
}
};
template<typename T> class TypeDefaultSerialize
{
public:
void serialize(ODataStream& s, const void* ptr)
{
s << *(T*)ptr;
}
void* deserialize(IDataStream& s)
{
T* val = new T();
s >> *val;
return val;
}
std::string signature()
{
return signatureFromType<T>::value();
}
};
template<typename T> class TypeNoSerialize
{
public:
void serialize(ODataStream& s, const void* ptr)
{
qiLogWarning("qi.meta") << "type not serializable";
}
void* deserialize(IDataStream& s)
{
qiLogWarning("qi.meta") << "type not serializable";
T* val = new T();
return val;
}
std::string signature()
{
std::string res;
res += (char)Signature::Type_Unknown;
return res;
}
};
/* TypeImpl implementation that bounces to the various aspect
* subclasses.
*
* That way we can split the various aspects in different classes
* for better reuse, without the cost of a second virtual call.
*/
template<typename T, typename Cloner = TypeDefaultClone<T>
, typename Value = TypeNoValue<T>
, typename Serialize = TypeNoSerialize<T>
> class DefaultTypeImpl
: public Cloner
, public Value
, public Serialize
, public virtual Type
{
virtual const std::type_info& info()
{
static T v; return typeid(v);
}
virtual void* clone(void* src)
{
return Cloner::clone(src);
}
virtual void destroy(void* ptr)
{
Cloner::destroy(ptr);
}
virtual bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
return Value::toValue(ptr, val);
}
virtual void* fromValue(const qi::detail::DynamicValue& val)
{
return Value::fromValue(val);
}
virtual std::string signature()
{
return Serialize::signature();
}
virtual void serialize(ODataStream& s, const void* ptr)
{
Serialize::serialize(s, ptr);
}
virtual void* deserialize(IDataStream& s)
{
return Serialize::deserialize(s);
}
};
/* Type "factory". Specialize this class to provide a custom
* Type for a given type.
*/
template<typename T> class TypeImpl: public virtual DefaultTypeImpl<T>
{
};
/// Declare a type that is convertible to GenericValue, and serializable
#define QI_TYPE_CONVERTIBLE_SERIALIZABLE(T) \
namespace qi { \
template<> class TypeImpl<T>: \
public DefaultTypeImpl<T, \
TypeDefaultClone<T>, \
TypeDefaultValue<T>, \
TypeDefaultSerialize<T> \
>{}; }
/** Declare that a type is not convertible to GenericValue.
* Must be called outside any namespace.
*/
#define QI_TYPE_SERIALIZABLE(T) \
namespace qi { \
template<> class TypeImpl<T>: \
public DefaultTypeImpl<T, \
TypeDefaultClone<T>, \
TypeNoValue<T>, \
TypeDefaultSerialize<T> \
>{}; }
/// Declare that a type has no metatype and cannot be used in a Value
#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}
/// Get type from a type. No need to delete the result
template<typename T> Type* typeOf();
/// Get type from a value. No need to delete the result
template<typename T> Type* typeOf(const T& v)
{
return typeOf<T>();
}
}
QI_TYPE_SERIALIZABLE(Buffer);
#include <qimessaging/details/type.hxx>
#endif // _QIMESSAGING_TYPE_HPP_
|
#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QIMESSAGING_TYPE_HPP_
#define _QIMESSAGING_TYPE_HPP_
#include <typeinfo>
#include <boost/preprocessor.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/details/dynamicvalue.hpp>
namespace qi{
/** Interface for all the operations we need on any type:
*
* - cloning/destruction in clone() and destroy()
* - type conversion is made by going through the generic container
* GenericValue, using the toValue() and fromValue() functions,
* - Serialization through serialize() and deserialize() to transmit
* the value through some kind of pipe.
*
* Our aim is to transport arbitrary values through:
* - synchronous calls: Nothing to do, values are just transported and
converted.
* - asynchronous call/thread change: Values are copied.
* - process change: Values are serialized.
*
*/
class QIMESSAGING_API Type
{
public:
virtual const std::type_info& info() =0;
const char* infoString() { return info().name();} // for easy gdb access
/// @return the serialization signature used by this type.
virtual std::string signature()=0;
virtual void* clone(void*)=0;
virtual void destroy(void*)=0;
virtual bool toValue(const void*, qi::detail::DynamicValue&)=0;
virtual void* fromValue(const qi::detail::DynamicValue&)=0;
// Default impl does toValue.serialize()
virtual void serialize(ODataStream& s, const void*)=0;
// Default impl does deserialize(GenericValue&) then fromValue
virtual void* deserialize(IDataStream& s)=0;
/* When someone makes a call with arguments that do not match the
* target signature (ex: int vs float), we want to handle it.
* For this, given the known correct signature S and known incorrect
* GenericValue v, we want to be able to obtain a new Type T that
* serializes with type S, and then try to convert o into type T.
*
* For this we need a map<Signature, Type> that we will feed with
* known types.
*
*/
typedef std::map<std::string, Type*> TypeSignatureMap;
static TypeSignatureMap& typeSignatureMap()
{
static TypeSignatureMap res;
return res;
}
static Type* getCompatibleTypeWithSignature(const std::string& sig)
{
TypeSignatureMap::iterator i = typeSignatureMap().find(sig);
if (i == typeSignatureMap().end())
return 0;
else
return i->second;
}
static bool registerCompatibleType(const std::string& sig,
Type* mt)
{
typeSignatureMap()[sig] = mt;
return true;
}
#define QI_REGISTER_MAPPING(sig, type) \
static bool BOOST_PP_CAT(_qireg_map_ , __LINE__) = ::qi::Type::registerCompatibleType(sig, \
::qi::typeOf<type>());
};
/** Meta-type specialization.
* Use the aspect pattern, make a class per feature group
* (Clone, GenericValue, Serialize)
*
*/
template<typename T> class TypeDefaultClone
{
public:
static void* clone(void* src)
{
return new T(*(T*)src);
}
static void destroy(void* ptr)
{
delete (T*)ptr;
}
};
template<typename T> class TypeNoClone
{
public:
static void* clone(void* src)
{
return src;
}
static void destroy(void* ptr)
{
/* Assume a TypeNoClone is not serializable
* So it cannot have been allocated by us.
* So the destroy comes after a clone->ignore it
*/
}
};
template<typename T>class TypeDefaultValue
{
public:
static bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
detail::DynamicValueConverter<T>::writeDynamicValue(*(T*)ptr, val);
return true;
}
static void* fromValue(const qi::detail::DynamicValue& val)
{
T* res = new T();
detail::DynamicValueConverter<T>::readDynamicValue(val, *res);
return res;
}
};
template<typename T>class TypeNoValue
{
public:
static bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
qiLogWarning("qi.type") << "toValue not implemented for type " << typeid(T).name();
return false;
}
static void* fromValue(const qi::detail::DynamicValue& val)
{
qiLogWarning("qi.type") << "fromValue not implemented for type ";
T* res = new T();
return res;
}
};
template<typename T> class TypeDefaultSerialize
{
public:
static void serialize(ODataStream& s, const void* ptr)
{
s << *(T*)ptr;
}
static void* deserialize(IDataStream& s)
{
T* val = new T();
s >> *val;
return val;
}
static std::string signature()
{
return signatureFromType<T>::value();
}
};
template<typename T> class TypeNoSerialize
{
public:
static void serialize(ODataStream& s, const void* ptr)
{
qiLogWarning("qi.meta") << "serialize not implemented for " << typeid(T).name();
}
static void* deserialize(IDataStream& s)
{
qiLogWarning("qi.meta") << "type not serializable";
T* val = new T();
return val;
}
std::string signature()
{
std::string res;
res += (char)Signature::Type_Unknown;
return res;
}
};
/* TypeImpl implementation that bounces to the various aspect
* subclasses.
*
* That way we can split the various aspects in different classes
* for better reuse, without the cost of a second virtual call.
*/
template<typename T, typename Cloner = TypeDefaultClone<T>
, typename Value = TypeNoValue<T>
, typename Serialize = TypeNoSerialize<T>
> class DefaultTypeImpl
: public Cloner
, public Value
, public Serialize
, public virtual Type
{
virtual const std::type_info& info()
{
static T v; return typeid(v);
}
virtual void* clone(void* src)
{
return Cloner::clone(src);
}
virtual void destroy(void* ptr)
{
Cloner::destroy(ptr);
}
virtual bool toValue(const void* ptr, qi::detail::DynamicValue& val)
{
return Value::toValue(ptr, val);
}
virtual void* fromValue(const qi::detail::DynamicValue& val)
{
return Value::fromValue(val);
}
virtual std::string signature()
{
return Serialize::signature();
}
virtual void serialize(ODataStream& s, const void* ptr)
{
Serialize::serialize(s, ptr);
}
virtual void* deserialize(IDataStream& s)
{
return Serialize::deserialize(s);
}
};
/* Type "factory". Specialize this class to provide a custom
* Type for a given type.
*/
template<typename T> class TypeImpl: public virtual DefaultTypeImpl<T>
{
};
/// Declare a type that is convertible to GenericValue, and serializable
#define QI_TYPE_CONVERTIBLE_SERIALIZABLE(T) \
namespace qi { \
template<> class TypeImpl<T>: \
public DefaultTypeImpl<T, \
TypeDefaultClone<T>, \
TypeDefaultValue<T>, \
TypeDefaultSerialize<T> \
>{}; }
/** Declare that a type is not convertible to GenericValue.
* Must be called outside any namespace.
*/
#define QI_TYPE_SERIALIZABLE(T) \
namespace qi { \
template<> class TypeImpl<T>: \
public DefaultTypeImpl<T, \
TypeDefaultClone<T>, \
TypeNoValue<T>, \
TypeDefaultSerialize<T> \
>{}; }
/// Declare that a type has no metatype and cannot be used in a Value
#define QI_NO_TYPE(T) namespace qi {template<> class TypeImpl<T> {};}
/// Get type from a type. No need to delete the result
template<typename T> Type* typeOf();
/// Get type from a value. No need to delete the result
template<typename T> Type* typeOf(const T& v)
{
return typeOf<T>();
}
}
QI_TYPE_SERIALIZABLE(Buffer);
#include <qimessaging/details/type.hxx>
#endif // _QIMESSAGING_TYPE_HPP_
|
Mark methods static where we can.
|
Type: Mark methods static where we can.
Change-Id: Ide63e0b6d5246af7e197a0bf03091b36405b6aca
|
C++
|
bsd-3-clause
|
aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi,aldebaran/libqi-java,bsautron/libqi,aldebaran/libqi-java,aldebaran/libqi,aldebaran/libqi-java
|
64f4610ba883def3b2c922691a20d66173c0ba5a
|
lxqt-admin-time/timeadmindialog.cpp
|
lxqt-admin-time/timeadmindialog.cpp
|
/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://lxqt.org
*
* Copyright: 2014 LXQt team
* Authors:
* Hong Jen Yee (PCMan) <[email protected]>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "timeadmindialog.h"
#include <QLabel>
#include <QCloseEvent>
#include <QMessageBox>
#include <QDateTime>
#include <QMap>
#include <QDebug>
#include "datetime.h"
#include "timezone.h"
#define ZONETAB_PATH "/usr/share/zoneinfo/zone.tab"
TimeAdminDialog::TimeAdminDialog(QWidget *parent):
LXQt::ConfigDialog(tr("Time and date configuration"),new LXQt::Settings("TimeDate"), parent)
{
setMinimumSize(QSize(400,400));
mWindowTitle = windowTitle();
mDateTimeWidget = new DateTimePage(mTimeDateCtl.useNtp(), mTimeDateCtl.localRtc(), this);
addPage(mDateTimeWidget,tr("Date and time"));
connect(this,SIGNAL(reset()),mDateTimeWidget,SLOT(reload()));
connect(mDateTimeWidget,&DateTimePage::changed,this,&TimeAdminDialog::onChanged);
QStringList zones;
QString currentZone;
loadTimeZones(zones,currentZone);
mTimezoneWidget = new TimezonePage(zones,currentZone,this);
addPage(mTimezoneWidget,tr("Timezone"));
connect(this,&TimeAdminDialog::reset,mTimezoneWidget,&TimezonePage::reload);
connect(mTimezoneWidget,&TimezonePage::changed,this,&TimeAdminDialog::onChanged);
setButtons(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
connect(this, &LXQt::ConfigDialog::clicked, this, &TimeAdminDialog::onButtonClicked);
}
TimeAdminDialog::~TimeAdminDialog()
{
}
void TimeAdminDialog::onChanged()
{
showChangedStar();
}
void TimeAdminDialog::showChangedStar()
{
if(mTimezoneWidget->isChanged() || mDateTimeWidget->modified())
setWindowTitle(mWindowTitle + "*");
else
setWindowTitle(mWindowTitle);
}
void TimeAdminDialog::loadTimeZones(QStringList & timeZones, QString & currentTimezone)
{
currentTimezone = mTimeDateCtl.timeZone();
timeZones.clear();
QFile file(ZONETAB_PATH);
if(file.open(QIODevice::ReadOnly))
{
QByteArray line;
while(!file.atEnd())
{
line = file.readLine().trimmed();
if(line.isEmpty() || line[0] == '#') // skip comments or empty lines
continue;
QList<QByteArray> items = line.split('\t');
if(items.length() <= 2)
continue;
timeZones.append(QLatin1String(items[2]));
}
file.close();
}
}
void TimeAdminDialog::saveChangesToSystem()
{
QString errorMessage;
if(mTimezoneWidget->isChanged())
{
QString timeZone = mTimezoneWidget->timezone();
if(!timeZone.isEmpty())
{
if(false == mTimeDateCtl.setTimeZone(timeZone, errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
}
auto modified = mDateTimeWidget->modified();
bool useNtp = mDateTimeWidget->useNtp();
if(modified.testFlag(DateTimePage::M_NTP))
{
if(false == mTimeDateCtl.setUseNtp(useNtp, errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
if(modified.testFlag(DateTimePage::M_LOCAL_RTC))
{
if(false == mTimeDateCtl.setLocalRtc(mDateTimeWidget->localRtc(), errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
// we can only change the date & time explicitly when NTP is disabled.
if(false == useNtp)
{
if(modified.testFlag(DateTimePage::M_DATE) || modified.testFlag(DateTimePage::M_TIME))
{
if(false == mTimeDateCtl.setDateTime(mDateTimeWidget->dateTime(), errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
}
}
void TimeAdminDialog::onButtonClicked(QDialogButtonBox::StandardButton button)
{
if(button == QDialogButtonBox::Ok)
{
saveChangesToSystem();
accept();
}
else if(button == QDialogButtonBox::Cancel)
{
reject();
}
}
|
/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* http://lxqt.org
*
* Copyright: 2014 LXQt team
* Authors:
* Hong Jen Yee (PCMan) <[email protected]>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "timeadmindialog.h"
#include <QLabel>
#include <QCloseEvent>
#include <QMessageBox>
#include <QDateTime>
#include <QMap>
#include <QDebug>
#include "datetime.h"
#include "timezone.h"
#define ZONETAB_PATH "/usr/share/zoneinfo/zone.tab"
TimeAdminDialog::TimeAdminDialog(QWidget *parent):
LXQt::ConfigDialog(tr("Time and date configuration"),new LXQt::Settings("TimeDate"), parent)
{
setMinimumSize(QSize(400,400));
mWindowTitle = windowTitle();
mDateTimeWidget = new DateTimePage(mTimeDateCtl.useNtp(), mTimeDateCtl.localRtc(), this);
addPage(mDateTimeWidget,tr("Date and time"));
connect(this,SIGNAL(reset()),mDateTimeWidget,SLOT(reload()));
connect(mDateTimeWidget,&DateTimePage::changed,this,&TimeAdminDialog::onChanged);
QStringList zones;
QString currentZone;
loadTimeZones(zones,currentZone);
mTimezoneWidget = new TimezonePage(zones,currentZone,this);
addPage(mTimezoneWidget,tr("Timezone"));
connect(this,&TimeAdminDialog::reset,mTimezoneWidget,&TimezonePage::reload);
connect(mTimezoneWidget,&TimezonePage::changed,this,&TimeAdminDialog::onChanged);
setButtons(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
connect(this, &LXQt::ConfigDialog::clicked, this, &TimeAdminDialog::onButtonClicked);
adjustSize();
}
TimeAdminDialog::~TimeAdminDialog()
{
}
void TimeAdminDialog::onChanged()
{
showChangedStar();
}
void TimeAdminDialog::showChangedStar()
{
if(mTimezoneWidget->isChanged() || mDateTimeWidget->modified())
setWindowTitle(mWindowTitle + "*");
else
setWindowTitle(mWindowTitle);
}
void TimeAdminDialog::loadTimeZones(QStringList & timeZones, QString & currentTimezone)
{
currentTimezone = mTimeDateCtl.timeZone();
timeZones.clear();
QFile file(ZONETAB_PATH);
if(file.open(QIODevice::ReadOnly))
{
QByteArray line;
while(!file.atEnd())
{
line = file.readLine().trimmed();
if(line.isEmpty() || line[0] == '#') // skip comments or empty lines
continue;
QList<QByteArray> items = line.split('\t');
if(items.length() <= 2)
continue;
timeZones.append(QLatin1String(items[2]));
}
file.close();
}
}
void TimeAdminDialog::saveChangesToSystem()
{
QString errorMessage;
if(mTimezoneWidget->isChanged())
{
QString timeZone = mTimezoneWidget->timezone();
if(!timeZone.isEmpty())
{
if(false == mTimeDateCtl.setTimeZone(timeZone, errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
}
auto modified = mDateTimeWidget->modified();
bool useNtp = mDateTimeWidget->useNtp();
if(modified.testFlag(DateTimePage::M_NTP))
{
if(false == mTimeDateCtl.setUseNtp(useNtp, errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
if(modified.testFlag(DateTimePage::M_LOCAL_RTC))
{
if(false == mTimeDateCtl.setLocalRtc(mDateTimeWidget->localRtc(), errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
// we can only change the date & time explicitly when NTP is disabled.
if(false == useNtp)
{
if(modified.testFlag(DateTimePage::M_DATE) || modified.testFlag(DateTimePage::M_TIME))
{
if(false == mTimeDateCtl.setDateTime(mDateTimeWidget->dateTime(), errorMessage)) {
QMessageBox::critical(this, tr("Error"), errorMessage);
}
}
}
}
void TimeAdminDialog::onButtonClicked(QDialogButtonBox::StandardButton button)
{
if(button == QDialogButtonBox::Ok)
{
saveChangesToSystem();
accept();
}
else if(button == QDialogButtonBox::Cancel)
{
reject();
}
}
|
Adjust dialog size on startup
|
lxqt-admin-time: Adjust dialog size on startup
In some situations part of the labels text was not shown.
|
C++
|
lgpl-2.1
|
pmattern/lxqt-admin,lxde/lxqt-admin,lxde/lxqt-admin,stefonarch/lxqt-admin,pmattern/lxqt-admin,stefonarch/lxqt-admin
|
9e9a1b7fcdaf6de29ba9ddafeecef9ad88903128
|
Motor2D/j1Scene.cpp
|
Motor2D/j1Scene.cpp
|
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1PathFinding.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Scene.h"
#include "Soldier.h"
#include "j1Player.h"
#include "j1DynamicObjects.h"
#include "j1FileSystem.h"
#include "j1Collision.h"
j1Scene::j1Scene() : j1Module()
{
name="scene";
}
// Destructor
j1Scene::~j1Scene()
{}
// Called before render is available
bool j1Scene::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1Scene::Start()
{
TitleScreen_letters=App->tex->Load("gui/title_screen/letters.png");
TitleScreen_bg = App->tex->Load("gui/title_screen/bg_anim.jpg");
switch_map = 0;
App->audio->PlayMusic("audio/music/ZELDA/ZeldaScreenSelection.ogg");
return true;
}
// Called each loop iteration
bool j1Scene::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1Scene::Update(float dt)
{
if (ingame==true)
{
AssignValues(gems, player->gems);
AssignValues(bombs, player->bombs);
AssignValues(arrows, player->arrows);
force->Hitbox.w = player->charge;
App->map->Draw();
if (enemy.size() > 0 && enemy.begin()._Ptr->_Myval != NULL)//TODO HIGH -> when enemy die on put this code?
{
if (enemy.begin()._Ptr->_Myval->hp == 0)
{
items.push_back(App->entity_elements->CreateItem(1));
enemy.begin()._Ptr->_Myval->AddItem(items.begin()._Ptr->_Myval);
enemy.begin()._Ptr->_Myval->Drop_item();
App->entity_elements->DeleteEnemy(enemy.begin()._Ptr->_Myval);
enemy.begin()._Ptr->_Myval = NULL;
}
}
//enemy.push_back(App->entity_elements->CreateEnemy(iPoint(80, 70), 1));
if (switch_map == 2)
{
//TODO need destroy all enemies and items
if (App->map->CleanUp())
{
Load_new_map(2);
/*dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(176, 245), 3));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(224, 273), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(224, 289), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(240, 273), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(240, 289), 4));*/
}
switch_map = 0;
}
if (switch_map == 1)
{
if (App->map->CleanUp())
{
App->collision->EreseAllColiderPlayer();
App->entity_elements->DelteElements();
//App->entity_elements->DeleteEnemy(enemy.begin()._Ptr->_Myval);
std::list<Soldier*>::iterator item = enemy.begin();
if (enemy.size() > 0)
{
while (item != enemy.end())
{
enemy.pop_back();
item++;
}
enemy.clear();
}
std::list<Item*>::iterator item_s = items.begin();
if (items.size() > 0)
{
while (item_s != items.end())
{
items.pop_back();
item_s++;
}
items.clear();
}
Load_new_map(1);
}
switch_map = 0;
}
}
else {
if (bg_anim < -120 ) {
right=true;
}
if (bg_anim > 0) {
right=false;
}
if (right)
{
bg_anim+=0.5;
}
else
{
bg_anim-=0.5;
}
App->render->Blit(TitleScreen_bg, bg_anim, 0, NULL, NULL, false);
App->render->Blit(TitleScreen_letters, 0, 0, NULL, NULL, false);
if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN)
{
App->audio->FadeMusic(2);
LoadUi();
Load_new_map(1);
ingame = true;
}
}
return true;
}
// Called each loop iteration
bool j1Scene::PostUpdate()
{
bool ret = true;
if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
ret = false;
return ret;
}
// Called before quitting
bool j1Scene::CleanUp()
{
LOG("Freeing scene");
return true;
}
void j1Scene::AssignValues(Image* assigner, uint var)
{
std::list<Image*>::iterator value = assigner->elements.end();
value--;
int number = var % 10;
value._Ptr->_Myval->AssignNumber(number);
value--;
number = var / 10;
number %= 10;
value._Ptr->_Myval->AssignNumber(number);
value--;
if (assigner->elements.size() > 2)
{
number = var/ 100;
value._Ptr->_Myval->AssignNumber(number);
}
}
void j1Scene::LoadUi()
{
//UI
charge = App->gui->CreateImage({ 18,44,42,16 }, { 12,35 }, "charge");
force = App->gui->CreateImage({ 21,61,34,10 }, { 4,3 });
charge->elements.push_back(force);
item = App->gui->CreateImage({ 37,20,22,22 }, { 22,12 });
gems = App->gui->CreateImage({ 72,15,8,8 }, { 72,15 });
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -7,10 }));
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 1,10 }));
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 9,10 }));
bombs = App->gui->CreateImage({ 100,15,8,8 }, { 100,15 });
bombs->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -3,9 }));
bombs->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 5,9 }));
arrows = App->gui->CreateImage({ 121,15,14,8 }, { 121,15 });
arrows->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -3,9 }));
arrows->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 5,9 }));
life = App->gui->CreateImage({ 178,15,44,7 }, { 178,15 });
//House load
// else {// for all the other maps
}
bool j1Scene::Load_new_map(int n)
{
if (player == NULL)
{
player = App->entity_elements->CreatePlayer();
}
bool stop_rearch = false;
pugi::xml_document config_file;
pugi::xml_node config;
config = LoadConfig(config_file);
for (pugi::xml_node temp = config.child("maps").child("map"); stop_rearch == false; temp = temp.next_sibling())
{
if (temp.attribute("n").as_int(0) == n)
{
//player position
player->position.x = temp.child("player").attribute("pos_x").as_int(0);
player->position.y = temp.child("player").attribute("pos_y").as_int(0);
//Enemies
pugi::xml_node temp_enemy = temp.child("enemies").child("enemy");
for (int i = 0; i < temp.child("enemies").attribute("num").as_int(0); i++)
{
enemy.push_back(App->entity_elements->CreateSoldier(temp_enemy.attribute("id").as_int(0), temp_enemy));
temp_enemy = temp_enemy.next_sibling();
}
//map
std::string name_map = temp.attribute("file").as_string("");
App->map->Load(name_map.c_str(), n);
//Camera position
int scale = App->win->GetScale();
App->render->camera.x = -((temp.child("player").attribute("pos_x").as_int(0) - (256 / 2)) * scale);
App->render->camera.y = -((temp.child("player").attribute("pos_y").as_int(0) - (224 / 2)) * scale);
stop_rearch = true;
}
}
//enemy = App->entity_elements->CreateEnemy(iPoint(200, 400), 1);
//items = App->entity_elements->CreateItem(iPoint(300, 200), 1);
//
//enemy->AddItem(items);
return true;
}
// ---------------------------------------------
pugi::xml_node j1Scene::LoadConfig(pugi::xml_document& config_file) const
{
pugi::xml_node ret;
char* buf;
int size = App->fs->Load("config.xml", &buf);
pugi::xml_parse_result result = config_file.load_buffer(buf, size);
RELEASE(buf);
if (result == NULL)
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
else
ret = config_file.child("config");
return ret;
}
|
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1PathFinding.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
#include "j1Scene.h"
#include "Soldier.h"
#include "j1Player.h"
#include "j1DynamicObjects.h"
#include "j1FileSystem.h"
#include "j1Collision.h"
j1Scene::j1Scene() : j1Module()
{
name="scene";
}
// Destructor
j1Scene::~j1Scene()
{}
// Called before render is available
bool j1Scene::Awake()
{
LOG("Loading Scene");
bool ret = true;
return ret;
}
// Called before the first frame
bool j1Scene::Start()
{
TitleScreen_letters=App->tex->Load("gui/title_screen/letters.png");
TitleScreen_bg = App->tex->Load("gui/title_screen/bg_anim.jpg");
switch_map = 0;
App->audio->PlayMusic("audio/music/ZELDA/ZeldaScreenSelection.ogg");
return true;
}
// Called each loop iteration
bool j1Scene::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1Scene::Update(float dt)
{
if (ingame==true)
{
AssignValues(gems, player->gems);
AssignValues(bombs, player->bombs);
AssignValues(arrows, player->arrows);
force->Hitbox.w = player->charge;
App->map->Draw();
if (enemy.size() > 0 && enemy.begin()._Ptr->_Myval != NULL)//TODO HIGH -> when enemy die on put this code?
{
if (enemy.begin()._Ptr->_Myval->hp == 0)
{
items.push_back(App->entity_elements->CreateItem(1));
enemy.begin()._Ptr->_Myval->AddItem(items.begin()._Ptr->_Myval);
enemy.begin()._Ptr->_Myval->Drop_item();
App->entity_elements->DeleteEnemy(enemy.begin()._Ptr->_Myval);
enemy.begin()._Ptr->_Myval = NULL;
}
}
//enemy.push_back(App->entity_elements->CreateEnemy(iPoint(80, 70), 1));
if (switch_map == 2)
{
//TODO need destroy all enemies and items
if (App->map->CleanUp())
{
App->entity_elements->DelteElements();
Load_new_map(2);
/*dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(176, 245), 3));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(224, 273), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(224, 289), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(240, 273), 4));
dynobjects.push_back(App->entity_elements->CreateDynObject(iPoint(240, 289), 4));*/
}
switch_map = 0;
}
if (switch_map == 1)
{
if (App->map->CleanUp())
{
App->collision->EreseAllColiderPlayer();
App->entity_elements->DelteElements();
//App->entity_elements->DeleteEnemy(enemy.begin()._Ptr->_Myval);
std::list<Soldier*>::iterator item = enemy.begin();
if (enemy.size() > 0)
{
while (item != enemy.end())
{
enemy.pop_back();
item++;
}
enemy.clear();
}
std::list<Item*>::iterator item_s = items.begin();
if (items.size() > 0)
{
while (item_s != items.end())
{
items.pop_back();
item_s++;
}
items.clear();
}
Load_new_map(1);
}
switch_map = 0;
}
}
else {
if (bg_anim < -120 ) {
right=true;
}
if (bg_anim > 0) {
right=false;
}
if (right)
{
bg_anim+=0.5;
}
else
{
bg_anim-=0.5;
}
App->render->Blit(TitleScreen_bg, bg_anim, 0, NULL, NULL, false);
App->render->Blit(TitleScreen_letters, 0, 0, NULL, NULL, false);
if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN)
{
App->audio->FadeMusic(2);
LoadUi();
Load_new_map(1);
ingame = true;
}
}
return true;
}
// Called each loop iteration
bool j1Scene::PostUpdate()
{
bool ret = true;
if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
ret = false;
return ret;
}
// Called before quitting
bool j1Scene::CleanUp()
{
LOG("Freeing scene");
return true;
}
void j1Scene::AssignValues(Image* assigner, uint var)
{
std::list<Image*>::iterator value = assigner->elements.end();
value--;
int number = var % 10;
value._Ptr->_Myval->AssignNumber(number);
value--;
number = var / 10;
number %= 10;
value._Ptr->_Myval->AssignNumber(number);
value--;
if (assigner->elements.size() > 2)
{
number = var/ 100;
value._Ptr->_Myval->AssignNumber(number);
}
}
void j1Scene::LoadUi()
{
//UI
charge = App->gui->CreateImage({ 18,44,42,16 }, { 12,35 }, "charge");
force = App->gui->CreateImage({ 21,61,34,10 }, { 4,3 });
charge->elements.push_back(force);
item = App->gui->CreateImage({ 37,20,22,22 }, { 22,12 });
gems = App->gui->CreateImage({ 72,15,8,8 }, { 72,15 });
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -7,10 }));
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 1,10 }));
gems->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 9,10 }));
bombs = App->gui->CreateImage({ 100,15,8,8 }, { 100,15 });
bombs->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -3,9 }));
bombs->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 5,9 }));
arrows = App->gui->CreateImage({ 121,15,14,8 }, { 121,15 });
arrows->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { -3,9 }));
arrows->elements.push_back(App->gui->CreateImage({ 259,13,7,7 }, { 5,9 }));
life = App->gui->CreateImage({ 178,15,44,7 }, { 178,15 });
//House load
// else {// for all the other maps
}
bool j1Scene::Load_new_map(int n)
{
if (player == NULL)
{
player = App->entity_elements->CreatePlayer();
}
bool stop_rearch = false;
pugi::xml_document config_file;
pugi::xml_node config;
config = LoadConfig(config_file);
for (pugi::xml_node temp = config.child("maps").child("map"); stop_rearch == false; temp = temp.next_sibling())
{
if (temp.attribute("n").as_int(0) == n)
{
//player position
player->position.x = temp.child("player").attribute("pos_x").as_int(0);
player->position.y = temp.child("player").attribute("pos_y").as_int(0);
//Enemies
pugi::xml_node temp_enemy = temp.child("enemies").child("enemy");
for (int i = 0; i < temp.child("enemies").attribute("num").as_int(0); i++)
{
enemy.push_back(App->entity_elements->CreateSoldier(temp_enemy.attribute("id").as_int(0), temp_enemy));
temp_enemy = temp_enemy.next_sibling();
}
//map
std::string name_map = temp.attribute("file").as_string("");
App->map->Load(name_map.c_str(), n);
//Camera position
int scale = App->win->GetScale();
App->render->camera.x = -((temp.child("player").attribute("pos_x").as_int(0) - (256 / 2)) * scale);
App->render->camera.y = -((temp.child("player").attribute("pos_y").as_int(0) - (224 / 2)) * scale);
stop_rearch = true;
}
}
//enemy = App->entity_elements->CreateEnemy(iPoint(200, 400), 1);
//items = App->entity_elements->CreateItem(iPoint(300, 200), 1);
//
//enemy->AddItem(items);
return true;
}
// ---------------------------------------------
pugi::xml_node j1Scene::LoadConfig(pugi::xml_document& config_file) const
{
pugi::xml_node ret;
char* buf;
int size = App->fs->Load("config.xml", &buf);
pugi::xml_parse_result result = config_file.load_buffer(buf, size);
RELEASE(buf);
if (result == NULL)
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
else
ret = config_file.child("config");
return ret;
}
|
Delete Dynobjects when map changing
|
Delete Dynobjects when map changing
|
C++
|
apache-2.0
|
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE,NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
|
c217e4b3d4c3f1ce559f6559c319d806586f3a57
|
chrome/browser/task_management/providers/web_contents/extension_tag_browsertest.cc
|
chrome/browser/task_management/providers/web_contents/extension_tag_browsertest.cc
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/task_management/task_management_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/browser/test_image_loader.h"
#include "extensions/common/constants.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/skia_util.h"
namespace task_management {
class ExtensionTagsTest : public ExtensionBrowserTest {
public:
ExtensionTagsTest() {}
~ExtensionTagsTest() override {}
protected:
// ExtensionBrowserTest:
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionBrowserTest::SetUpCommandLine(command_line);
// Do not launch device discovery process.
command_line->AppendSwitch(switches::kDisableDeviceDiscoveryNotifications);
}
const std::vector<WebContentsTag*>& tracked_tags() const {
return WebContentsTagsManager::GetInstance()->tracked_tags();
}
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionTagsTest);
};
// Tests loading, disabling, enabling and unloading extensions and how that will
// affect the recording of tags.
IN_PROC_BROWSER_TEST_F(ExtensionTagsTest, Basic) {
// Browser tests start with a single tab.
EXPECT_EQ(1U, tracked_tags().size());
const extensions::Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0"));
ASSERT_TRUE(extension);
EXPECT_EQ(2U, tracked_tags().size());
DisableExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
EnableExtension(extension->id());
EXPECT_EQ(2U, tracked_tags().size());
UnloadExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
}
#if defined(OS_WIN)
// Test disabled due to flakiness on Windows XP.
// See bug: http://crbug.com/519333
#define MAYBE_PreAndPostExistingTaskProviding \
DISABLED_PreAndPostExistingTaskProviding
#else
#define MAYBE_PreAndPostExistingTaskProviding PreAndPostExistingTaskProviding
#endif
IN_PROC_BROWSER_TEST_F(ExtensionTagsTest,
MAYBE_PreAndPostExistingTaskProviding) {
// Browser tests start with a single tab.
EXPECT_EQ(1U, tracked_tags().size());
MockWebContentsTaskManager task_manager;
EXPECT_TRUE(task_manager.tasks().empty());
const extensions::Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0"));
ASSERT_TRUE(extension);
EXPECT_EQ(2U, tracked_tags().size());
EXPECT_TRUE(task_manager.tasks().empty());
base::RunLoop run_loop;
run_loop.RunUntilIdle();
// Start observing, pre-existing tasks will be provided.
task_manager.StartObserving();
ASSERT_EQ(2U, task_manager.tasks().size());
const Task* extension_task = task_manager.tasks().back();
EXPECT_EQ(Task::EXTENSION, extension_task->GetType());
SkBitmap expected_bitmap =
extensions::TestImageLoader::LoadAndGetExtensionBitmap(
extension,
"icon_128.png",
extension_misc::EXTENSION_ICON_SMALL);
ASSERT_FALSE(expected_bitmap.empty());
EXPECT_TRUE(gfx::BitmapsAreEqual(*extension_task->icon().bitmap(),
expected_bitmap));
// Unload the extension and expect that the task manager now shows only the
// about:blank tab.
UnloadExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
ASSERT_EQ(1U, task_manager.tasks().size());
const Task* about_blank_task = task_manager.tasks().back();
EXPECT_EQ(Task::RENDERER, about_blank_task->GetType());
EXPECT_EQ(base::UTF8ToUTF16("Tab: about:blank"), about_blank_task->title());
// Reload the extension, the task manager should show it again.
ReloadExtension(extension->id());
EXPECT_EQ(2U, tracked_tags().size());
EXPECT_EQ(2U, task_manager.tasks().size());
EXPECT_EQ(Task::EXTENSION, task_manager.tasks().back()->GetType());
}
} // namespace task_management
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/task_management/task_management_browsertest_util.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/browser/test_image_loader.h"
#include "extensions/common/constants.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/skia_util.h"
namespace task_management {
class ExtensionTagsTest : public ExtensionBrowserTest {
public:
ExtensionTagsTest() {}
~ExtensionTagsTest() override {}
protected:
// ExtensionBrowserTest:
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionBrowserTest::SetUpCommandLine(command_line);
// Do not launch device discovery process.
command_line->AppendSwitch(switches::kDisableDeviceDiscoveryNotifications);
}
const std::vector<WebContentsTag*>& tracked_tags() const {
return WebContentsTagsManager::GetInstance()->tracked_tags();
}
private:
DISALLOW_COPY_AND_ASSIGN(ExtensionTagsTest);
};
// Tests loading, disabling, enabling and unloading extensions and how that will
// affect the recording of tags.
IN_PROC_BROWSER_TEST_F(ExtensionTagsTest, Basic) {
// Browser tests start with a single tab.
EXPECT_EQ(1U, tracked_tags().size());
const extensions::Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0"));
ASSERT_TRUE(extension);
EXPECT_EQ(2U, tracked_tags().size());
DisableExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
EnableExtension(extension->id());
EXPECT_EQ(2U, tracked_tags().size());
UnloadExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
}
#if defined(OS_WIN) || defined(OS_LINUX)
// Test disabled due to flakiness on Windows XP and Linux.
// See bug: http://crbug.com/519333
#define MAYBE_PreAndPostExistingTaskProviding \
DISABLED_PreAndPostExistingTaskProviding
#else
#define MAYBE_PreAndPostExistingTaskProviding PreAndPostExistingTaskProviding
#endif
IN_PROC_BROWSER_TEST_F(ExtensionTagsTest,
MAYBE_PreAndPostExistingTaskProviding) {
// Browser tests start with a single tab.
EXPECT_EQ(1U, tracked_tags().size());
MockWebContentsTaskManager task_manager;
EXPECT_TRUE(task_manager.tasks().empty());
const extensions::Extension* extension = LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0"));
ASSERT_TRUE(extension);
EXPECT_EQ(2U, tracked_tags().size());
EXPECT_TRUE(task_manager.tasks().empty());
base::RunLoop run_loop;
run_loop.RunUntilIdle();
// Start observing, pre-existing tasks will be provided.
task_manager.StartObserving();
ASSERT_EQ(2U, task_manager.tasks().size());
const Task* extension_task = task_manager.tasks().back();
EXPECT_EQ(Task::EXTENSION, extension_task->GetType());
SkBitmap expected_bitmap =
extensions::TestImageLoader::LoadAndGetExtensionBitmap(
extension,
"icon_128.png",
extension_misc::EXTENSION_ICON_SMALL);
ASSERT_FALSE(expected_bitmap.empty());
EXPECT_TRUE(gfx::BitmapsAreEqual(*extension_task->icon().bitmap(),
expected_bitmap));
// Unload the extension and expect that the task manager now shows only the
// about:blank tab.
UnloadExtension(extension->id());
EXPECT_EQ(1U, tracked_tags().size());
ASSERT_EQ(1U, task_manager.tasks().size());
const Task* about_blank_task = task_manager.tasks().back();
EXPECT_EQ(Task::RENDERER, about_blank_task->GetType());
EXPECT_EQ(base::UTF8ToUTF16("Tab: about:blank"), about_blank_task->title());
// Reload the extension, the task manager should show it again.
ReloadExtension(extension->id());
EXPECT_EQ(2U, tracked_tags().size());
EXPECT_EQ(2U, task_manager.tasks().size());
EXPECT_EQ(Task::EXTENSION, task_manager.tasks().back()->GetType());
}
} // namespace task_management
|
Disable PreAndPostExistingTaskProviding test on Linux
|
Disable PreAndPostExistingTaskProviding test on Linux
ExtensionTagsTest.PreAndPostExistingTaskProviding has failed on Linux
bots 2 of the last 200 runs.
BUG=519333
TBR=afakhry
Review URL: https://codereview.chromium.org/1308563007
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#346404}
|
C++
|
bsd-3-clause
|
ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend
|
921833c215f1afc4e840f666faa9efc772c188bc
|
aikido/tests/test_VanDerCorput.cpp
|
aikido/tests/test_VanDerCorput.cpp
|
// #include <cstdlib>
#include <gtest/gtest.h>
#include <aikido/util/VanDerCorput.hpp>
using aikido::util::VanDerCorput;
TEST(VanDerCorput, IncludesEndpoints)
{
VanDerCorput vdc{1, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(1.0, vdc());
}
TEST(VanDerCorput, ExcludesEndpoints)
{
VanDerCorput vdc{1, false};
EXPECT_DOUBLE_EQ(0.5, vdc());
}
TEST(VanDerCorput, DefaultConstructorExcludesEndpoints)
{
VanDerCorput vdc;
EXPECT_DOUBLE_EQ(0.5, vdc());
}
TEST(VanDerCorput, FirstThreeValuesWithoutEndpoints)
{
VanDerCorput vdc{1, false};
EXPECT_DOUBLE_EQ(1./2, vdc());
EXPECT_DOUBLE_EQ(1./4, vdc());
EXPECT_DOUBLE_EQ(3./4, vdc());
EXPECT_DOUBLE_EQ(1./8, vdc());
EXPECT_DOUBLE_EQ(5./8, vdc());
EXPECT_DOUBLE_EQ(3./8, vdc());
EXPECT_DOUBLE_EQ(7./8, vdc());
}
TEST(VanDerCorput, FirstFiveValuesWithEndpoints)
{
VanDerCorput vdc{1, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(1.0, vdc());
EXPECT_DOUBLE_EQ(1./2, vdc());
EXPECT_DOUBLE_EQ(1./4, vdc());
EXPECT_DOUBLE_EQ(3./4, vdc());
EXPECT_DOUBLE_EQ(1./8, vdc());
EXPECT_DOUBLE_EQ(5./8, vdc());
EXPECT_DOUBLE_EQ(3./8, vdc());
EXPECT_DOUBLE_EQ(7./8, vdc());
}
TEST(VanDerCorput, ScaleProperlyOverSpanWithEndpoints)
{
VanDerCorput vdc{2, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(2.0, vdc());
EXPECT_DOUBLE_EQ(2.0/2, vdc());
EXPECT_DOUBLE_EQ(2.0/4, vdc());
EXPECT_DOUBLE_EQ(6.0/4, vdc());
EXPECT_DOUBLE_EQ(2.0/8, vdc());
EXPECT_DOUBLE_EQ(10./8, vdc());
EXPECT_DOUBLE_EQ(6.0/8, vdc());
EXPECT_DOUBLE_EQ(14./8, vdc());
}
TEST(VanDerCorput, ResolutionAtEndpoints)
{
VanDerCorput vdc{1, true};
vdc();
EXPECT_DOUBLE_EQ(1.0, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1.0, vdc.current_resolution());
}
TEST(VanDerCorput, ResolutionWhenAllDistancesTheSame)
{
VanDerCorput vdc{1, false};
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
}
TEST(VanDerCorput, ResolutionAtAllPoints)
{
VanDerCorput vdc{1, false};
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./16, vdc.current_resolution());
}
|
// #include <cstdlib>
#include <gtest/gtest.h>
#include <aikido/util/VanDerCorput.hpp>
using aikido::util::VanDerCorput;
TEST(VanDerCorput, IncludesEndpoints)
{
VanDerCorput vdc{1, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(1.0, vdc());
}
TEST(VanDerCorput, ExcludesEndpoints)
{
VanDerCorput vdc{1, false};
EXPECT_DOUBLE_EQ(0.5, vdc());
}
TEST(VanDerCorput, DefaultConstructorExcludesEndpoints)
{
VanDerCorput vdc;
EXPECT_DOUBLE_EQ(0.5, vdc());
}
TEST(VanDerCorput, FirstSevenValuesWithoutEndpoints)
{
VanDerCorput vdc{1, false};
EXPECT_DOUBLE_EQ(1./2, vdc());
EXPECT_DOUBLE_EQ(1./4, vdc());
EXPECT_DOUBLE_EQ(3./4, vdc());
EXPECT_DOUBLE_EQ(1./8, vdc());
EXPECT_DOUBLE_EQ(5./8, vdc());
EXPECT_DOUBLE_EQ(3./8, vdc());
EXPECT_DOUBLE_EQ(7./8, vdc());
}
TEST(VanDerCorput, FirstNineValuesWithEndpoints)
{
VanDerCorput vdc{1, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(1.0, vdc());
EXPECT_DOUBLE_EQ(1./2, vdc());
EXPECT_DOUBLE_EQ(1./4, vdc());
EXPECT_DOUBLE_EQ(3./4, vdc());
EXPECT_DOUBLE_EQ(1./8, vdc());
EXPECT_DOUBLE_EQ(5./8, vdc());
EXPECT_DOUBLE_EQ(3./8, vdc());
EXPECT_DOUBLE_EQ(7./8, vdc());
}
TEST(VanDerCorput, ScaleProperlyOverSpanWithEndpoints)
{
VanDerCorput vdc{2, true};
EXPECT_DOUBLE_EQ(0.0, vdc());
EXPECT_DOUBLE_EQ(2.0, vdc());
EXPECT_DOUBLE_EQ(2.0/2, vdc());
EXPECT_DOUBLE_EQ(2.0/4, vdc());
EXPECT_DOUBLE_EQ(6.0/4, vdc());
EXPECT_DOUBLE_EQ(2.0/8, vdc());
EXPECT_DOUBLE_EQ(10./8, vdc());
EXPECT_DOUBLE_EQ(6.0/8, vdc());
EXPECT_DOUBLE_EQ(14./8, vdc());
}
TEST(VanDerCorput, ResolutionAtEndpoints)
{
VanDerCorput vdc{1, true};
vdc();
EXPECT_DOUBLE_EQ(1.0, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1.0, vdc.current_resolution());
}
TEST(VanDerCorput, ResolutionWhenAllDistancesTheSame)
{
VanDerCorput vdc{1, false};
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
}
TEST(VanDerCorput, ResolutionAtAllPoints)
{
VanDerCorput vdc{1, false};
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./2, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./4, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./8, vdc.current_resolution());
vdc();
EXPECT_DOUBLE_EQ(1./16, vdc.current_resolution());
}
|
rename tests
|
rename tests
|
C++
|
bsd-3-clause
|
personalrobotics/aikido,personalrobotics/aikido,personalrobotics/aikido,personalrobotics/aikido
|
9673f971d064dd9943db2ebf2a93356a222c7b81
|
SDC_sample/main.cpp
|
SDC_sample/main.cpp
|
//=====================================================================//
/*! @file
@brief SD カードの読み書き、サンプル
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "G13/system.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
namespace {
void wait_()
{
asm("nop");
}
// 送信、受信バッファの定義
typedef utils::fifo<64> buffer;
// UART の定義(SAU2、SAU3)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint8_t> itm_;
// CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi;
csi csi_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi, card_select, card_power, card_detect> sdc_(csi_);
utils::command<64> command_;
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
return 0;
}
};
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
PM4.B3 = 0; // output
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
sdc_.initialize();
uart_.puts("Start RL78/G13 SD-CARD Access sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
if(command_.cmp_word(0, "dir")) {
sdc_.dir("");
}
}
}
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
|
//=====================================================================//
/*! @file
@brief SD カードの読み書き、サンプル
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include <cstring>
#include "G13/system.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/itimer.hpp"
#include "common/format.hpp"
#include "common/delay.hpp"
#include "common/csi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
namespace {
void wait_()
{
asm("nop");
}
// 送信、受信バッファの定義
typedef utils::fifo<64> buffer;
// UART の定義(SAU2、SAU3)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
// インターバル・タイマー
device::itimer<uint16_t> itm_;
// CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0
typedef device::csi_io<device::SAU00> csi;
csi csi_;
// FatFS インターフェースの定義
typedef device::PORT<device::port_no::P0, device::bitpos::B0> card_select; ///< カード選択信号
typedef device::PORT<device::port_no::P0, device::bitpos::B1> card_power; ///< カード電源制御
typedef device::PORT<device::port_no::P14, device::bitpos::B6> card_detect; ///< カード検出
utils::sdc_io<csi, card_select, card_power, card_detect> sdc_(csi_);
utils::command<64> command_;
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ nullptr,
/* 14 */ nullptr,
/* 15 */ nullptr,
/* 16 */ reinterpret_cast<void*>(uart_.send_task),
/* 17 */ reinterpret_cast<void*>(uart_.recv_task),
/* 18 */ reinterpret_cast<void*>(uart_.error_task),
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
DSTATUS disk_initialize(BYTE drv) {
return sdc_.at_mmc().disk_initialize(drv);
}
DSTATUS disk_status(BYTE drv) {
return sdc_.at_mmc().disk_status(drv);
}
DRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_read(drv, buff, sector, count);
}
DRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {
return sdc_.at_mmc().disk_write(drv, buff, sector, count);
}
DRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {
return sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);
}
DWORD get_fattime(void) {
return 0;
}
};
namespace {
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
bool create_test_file_(const char* fname, uint32_t size)
{
utils::format("SD Write test...\n");
uint8_t buff[512];
for(uint16_t i = 0; i < sizeof(buff); ++i) {
buff[i] = rand_();
}
auto st = itm_.get_counter();
FIL fp;
if(f_open(&fp, fname, FA_WRITE | FA_CREATE_ALWAYS) != FR_OK) {
utils::format("Can't create file: '%s'\n") % fname;
return false;
}
auto rs = size;
while(rs > 0) {
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
UINT bw;
f_write(&fp, buff, sz, &bw);
rs -= bw;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Write frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Write: %d Bytes/Sec\n") % pbyte;
utils::format("Write: %d KBytes/Sec\n") % (pbyte / 1024);
return true;
}
void test_all_()
{
const char* test_file = { "TEST.BIN" };
uint32_t size = 1024L * 1024L;
if(!create_test_file_(test_file, size)) {
return;
}
utils::format("SD Speed test start...\n");
auto st = itm_.get_counter();
utils::format("SD Read test...\n");
FIL fp;
if(f_open(&fp, test_file, FA_READ) != FR_OK) {
utils::format("Can't read file: '%s'\n") % test_file;
}
auto rs = size;
while(rs > 0) {
uint8_t buff[512];
UINT rb;
UINT sz = sizeof(buff);
if(sz > rs) sz = rs;
f_read(&fp, buff, sz, &rb);
rs -= rb;
}
f_close(&fp);
auto ed = itm_.get_counter();
uint32_t len;
if(ed > st) len = ed - st;
else len = 65536 + ed - st;
utils::format("Read frame: %d\n") % len;
auto pbyte = size * 60 / len;
utils::format("Read: %d Bytes/Sec\n") % pbyte;
utils::format("Read: %d KBytes/Sec\n") % (pbyte / 1024);
}
}
int main(int argc, char* argv[])
{
using namespace device;
utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
PM4.B3 = 0; // output
// インターバル・タイマー開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART 開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
sdc_.initialize();
uart_.puts("Start RL78/G13 SD-CARD Access sample\n");
command_.set_prompt("# ");
uint8_t n = 0;
while(1) {
itm_.sync();
sdc_.service();
// コマンド入力と、コマンド解析
if(command_.service()) {
auto cmdn = command_.get_words();
if(cmdn >= 1) {
bool f = false;
if(command_.cmp_word(0, "dir")) {
sdc_.dir("");
f = true;
} else if(command_.cmp_word(0, "speed")) {
test_all_();
f = true;
}
if(!f) {
char tmp[16];
command_.get_word(0, sizeof(tmp), tmp);
utils::format("Command error: '%s'\n") % tmp;
}
}
}
++n;
if(n >= 30) n = 0;
P4.B3 = n < 10 ? false : true;
}
}
|
add speed command
|
add speed command
|
C++
|
bsd-3-clause
|
hirakuni45/RL78,hirakuni45/RL78,hirakuni45/RL78
|
601790d81004e8e2cb086b89dd5638872e72d7ed
|
STEER/AliAODPid.cxx
|
STEER/AliAODPid.cxx
|
/**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// AOD Pid class to store additional pid information
// Author: Annalisa Mastroserio
//-------------------------------------------------------------------------
#include "AliAODPid.h"
#include "AliESDtrack.h"
#include "AliLog.h"
ClassImp(AliAODPid)
//______________________________________________________________________________
AliAODPid::AliAODPid():
fITSsignal(0),
fTPCsignal(0),
fTPCsignalN(0),
fTPCmomentum(0),
fTRDnSlices(0),
fTRDslices(0x0),
fTOFesdsignal(0),
fHMPIDsignal(0)
{
// default constructor
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=0;
for(Int_t i=0; i<3; i++) fEMCALPosition[i] = 0.;
}
//______________________________________________________________________________
AliAODPid::~AliAODPid()
{
delete [] fTRDslices;
fTRDslices = 0;
// destructor
}
//______________________________________________________________________________
AliAODPid::AliAODPid(const AliAODPid& pid) :
TObject(pid),
fITSsignal(pid.fITSsignal),
fTPCsignal(pid.fTPCsignal),
fTPCsignalN(pid.fTPCsignalN),
fTPCmomentum(pid.fTPCmomentum),
fTRDnSlices(pid.fTRDnSlices),
fTRDslices(0x0),
fTOFesdsignal(pid.fTOFesdsignal),
fHMPIDsignal(pid.fHMPIDsignal)
{
// Copy constructor
fTRDslices = new Double32_t[fTRDnSlices];
for(Int_t i=0; i< fTRDnSlices; i++) fTRDslices[i]=pid.fTRDslices[i];
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=pid.fIntTime[i];
for(Int_t i=0; i<3; i++) fEMCALPosition[i]=pid.fEMCALPosition[i];
}
//______________________________________________________________________________
AliAODPid& AliAODPid::operator=(const AliAODPid& pid)
{
// Assignment operator
if(this!=&pid) {
// copy stuff
fITSsignal=pid.fITSsignal;
fTPCsignal=pid.fTPCsignal;
if(pid.fTRDnSlices<=0||(fTRDnSlices!=pid.fTRDnSlices)){
// only delete if number changed or is 0
delete [] fTRDslices;
fTRDslices = 0;
if(pid.fTRDnSlices>0) fTRDslices = new Double32_t[fTRDnSlices];
}
fTRDnSlices=pid.fTRDnSlices;
for(Int_t i=0; i< fTRDnSlices; i++) fTRDslices[i]=pid.fTRDslices[i];
fTOFesdsignal=pid.fTOFesdsignal;
fHMPIDsignal=pid.fHMPIDsignal;
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=pid.fIntTime[i];
for(Int_t i=0; i<3; i++) fEMCALPosition[i]=pid.fEMCALPosition[i];
}
return *this;
}
//_______________________________________________________________________________
void AliAODPid::GetIntegratedTimes(Double_t timeint[kSPECIES]) const
{
// Returns the array with integrated times for each particle hypothesis
for(Int_t i=0; i<kSPECIES; i++) timeint[i]=fIntTime[i];
}
//_______________________________________________________________________________
void AliAODPid::SetIntegratedTimes(Double_t timeint[kSPECIES])
{
// Returns the array with integrated times for each particle hypothesis
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=timeint[i];
}
//_______________________________________________________________________________
void AliAODPid::GetEMCALPosition(Double_t emcalpos[3]) const
{
// Returns the array with extrapolated track position at the EMCAL surface
for(Int_t i=0; i<3; i++) emcalpos[i]=fEMCALPosition[i];
}
//_______________________________________________________________________________
void AliAODPid::SetEMCALPosition(Double_t emcpos[3])
{
// Sets the array with extrapolated track position at the EMCAL surface
for(Int_t i=0; i<3; i++) fEMCALPosition[i]=emcpos[i];
}
//_______________________________________________________________________________
void AliAODPid::GetEMCALMomentum(Double_t emcalmom[3]) const
{
// Returns the array with extrapolated track momentum at the EMCAL surface
for(Int_t i=0; i<3; i++) emcalmom[i]=fEMCALMomentum[i];
}
//_______________________________________________________________________________
void AliAODPid::SetEMCALMomentum(Double_t emcmom[3])
{
// Sets the array with extrapolated track momentum at the EMCAL surface
for(Int_t i=0; i<3; i++) fEMCALMomentum[i]=emcmom[i];
}
|
/**************************************************************************
* Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// AOD Pid class to store additional pid information
// Author: Annalisa Mastroserio
//-------------------------------------------------------------------------
#include "AliAODPid.h"
#include "AliESDtrack.h"
#include "AliLog.h"
ClassImp(AliAODPid)
//______________________________________________________________________________
AliAODPid::AliAODPid():
fITSsignal(0),
fTPCsignal(0),
fTPCsignalN(0),
fTPCmomentum(0),
fTRDnSlices(0),
fTRDslices(0x0),
fTOFesdsignal(0),
fHMPIDsignal(0)
{
// default constructor
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=0;
for(Int_t i=0; i<3; i++) fEMCALPosition[i] = 0.;
}
//______________________________________________________________________________
AliAODPid::~AliAODPid()
{
delete [] fTRDslices;
fTRDslices = 0;
// destructor
}
//______________________________________________________________________________
AliAODPid::AliAODPid(const AliAODPid& pid) :
TObject(pid),
fITSsignal(pid.fITSsignal),
fTPCsignal(pid.fTPCsignal),
fTPCsignalN(pid.fTPCsignalN),
fTPCmomentum(pid.fTPCmomentum),
fTRDnSlices(pid.fTRDnSlices),
fTRDslices(0x0),
fTOFesdsignal(pid.fTOFesdsignal),
fHMPIDsignal(pid.fHMPIDsignal)
{
// Copy constructor
fTRDslices = new Double32_t[fTRDnSlices];
for(Int_t i=0; i< fTRDnSlices; i++) fTRDslices[i]=pid.fTRDslices[i];
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=pid.fIntTime[i];
for(Int_t i=0; i<3; i++) {
fEMCALPosition[i]=pid.fEMCALPosition[i];
fEMCALMomentum[i]=pid.fEMCALMomentum[i];
}
for(Int_t i=0; i<6; i++) fTRDmomentum[i]=pid.fTRDmomentum[i];
}
//______________________________________________________________________________
AliAODPid& AliAODPid::operator=(const AliAODPid& pid)
{
// Assignment operator
if(this!=&pid) {
// copy stuff
fITSsignal=pid.fITSsignal;
fTPCsignal=pid.fTPCsignal;
if(pid.fTRDnSlices<=0||(fTRDnSlices!=pid.fTRDnSlices)){
// only delete if number changed or is 0
delete [] fTRDslices;
fTRDslices = 0;
if(pid.fTRDnSlices>0) fTRDslices = new Double32_t[fTRDnSlices];
}
fTRDnSlices=pid.fTRDnSlices;
for(Int_t i=0; i< fTRDnSlices; i++) fTRDslices[i]=pid.fTRDslices[i];
fTOFesdsignal=pid.fTOFesdsignal;
fHMPIDsignal=pid.fHMPIDsignal;
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=pid.fIntTime[i];
for(Int_t i=0; i<6; i++) fTRDmomentum[i]=pid.fTRDmomentum[i];
for(Int_t i=0; i<3; i++) {
fEMCALPosition[i]=pid.fEMCALPosition[i];
fEMCALMomentum[i]=pid.fEMCALMomentum[i];
}
}
return *this;
}
//_______________________________________________________________________________
void AliAODPid::GetIntegratedTimes(Double_t timeint[kSPECIES]) const
{
// Returns the array with integrated times for each particle hypothesis
for(Int_t i=0; i<kSPECIES; i++) timeint[i]=fIntTime[i];
}
//_______________________________________________________________________________
void AliAODPid::SetIntegratedTimes(Double_t timeint[kSPECIES])
{
// Returns the array with integrated times for each particle hypothesis
for(Int_t i=0; i<kSPECIES; i++) fIntTime[i]=timeint[i];
}
//_______________________________________________________________________________
void AliAODPid::GetEMCALPosition(Double_t emcalpos[3]) const
{
// Returns the array with extrapolated track position at the EMCAL surface
for(Int_t i=0; i<3; i++) emcalpos[i]=fEMCALPosition[i];
}
//_______________________________________________________________________________
void AliAODPid::SetEMCALPosition(Double_t emcpos[3])
{
// Sets the array with extrapolated track position at the EMCAL surface
for(Int_t i=0; i<3; i++) fEMCALPosition[i]=emcpos[i];
}
//_______________________________________________________________________________
void AliAODPid::GetEMCALMomentum(Double_t emcalmom[3]) const
{
// Returns the array with extrapolated track momentum at the EMCAL surface
for(Int_t i=0; i<3; i++) emcalmom[i]=fEMCALMomentum[i];
}
//_______________________________________________________________________________
void AliAODPid::SetEMCALMomentum(Double_t emcmom[3])
{
// Sets the array with extrapolated track momentum at the EMCAL surface
for(Int_t i=0; i<3; i++) fEMCALMomentum[i]=emcmom[i];
}
|
Correct copy and assignment operator (Jochen Klein)
|
Correct copy and assignment operator (Jochen Klein)
|
C++
|
bsd-3-clause
|
ALICEHLT/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,shahor02/AliRoot,coppedis/AliRoot,mkrzewic/AliRoot,shahor02/AliRoot,shahor02/AliRoot,alisw/AliRoot,miranov25/AliRoot,alisw/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,miranov25/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,coppedis/AliRoot,shahor02/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,ecalvovi/AliRoot
|
d418f92fe4f04b58ca3c60c36f521e4c9b465aec
|
MMOCoreORB/src/server/zone/objects/tangible/components/droid/DroidRepairModuleDataComponent.cpp
|
MMOCoreORB/src/server/zone/objects/tangible/components/droid/DroidRepairModuleDataComponent.cpp
|
/*
* Copyright <SWGEmu>
See file COPYING for copying conditions. */
#include "DroidRepairModuleDataComponent.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/tangible/component/droid/DroidComponent.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/managers/creature/PetManager.h"
DroidRepairModuleDataComponent::DroidRepairModuleDataComponent() {
setLoggingName("DroidRepairModule");
}
DroidRepairModuleDataComponent::~DroidRepairModuleDataComponent() {
}
String DroidRepairModuleDataComponent::getModuleName() {
return String("repair_module");
}
void DroidRepairModuleDataComponent::initializeTransientMembers() {
// no op
}
void DroidRepairModuleDataComponent::fillAttributeList(AttributeListMessage* alm, CreatureObject* droid) {
alm->insertAttribute( "repair_module", "Installed" );
}
void DroidRepairModuleDataComponent::fillObjectMenuResponse(SceneObject* droidObject, ObjectMenuResponse* menuResponse, CreatureObject* player) {
// Add to Droid Options subradial from PetMenuComponent
menuResponse->addRadialMenuItemToRadialID(132, REPAIR_MODULE_ACTIVATE, 3, "Repair" );
// Add to Program subradial from PetMenuComponent
ManagedReference<DroidObject*> droid = getDroidObject();
if (droid == NULL)
return;
// converse droid can not have their repair command changed. droids without a personality chip are considered base and get all normal radials
if (droid->getOptionsBitmask() & OptionBitmask::CONVERSE)
return;
menuResponse->addRadialMenuItemToRadialID(141, REPAIR_MODULE_TRAIN, 3, "@pet/pet_menu:menu_repair_other" ); // "Repair Other Droid"
}
int DroidRepairModuleDataComponent::handleObjectMenuSelect(CreatureObject* player, byte selectedID, PetControlDevice* controller) {
// Handle repair request
if( selectedID == REPAIR_MODULE_ACTIVATE ){
PetManager* petManager = player->getZoneServer()->getPetManager();
if( petManager == NULL )
return 0;
petManager->enqueuePetCommand(player, getDroidObject(), String("petRepair").toLowerCase().hashCode(), "");
}
// Handle command training
else if( selectedID == REPAIR_MODULE_TRAIN ){
if( controller == NULL )
return 0;
controller->setTrainingCommand( PetManager::REPAIR );
}
return 0;
}
void DroidRepairModuleDataComponent::handlePetCommand(String cmd, CreatureObject* speaker){
ManagedReference<DroidObject*> droid = getDroidObject();
if( droid == NULL )
return;
ManagedReference<PetControlDevice*> pcd = droid->getControlDevice().get().castTo<PetControlDevice*>();
if( pcd == NULL )
return;
PetManager* petManager = droid->getZoneServer()->getPetManager();
if( petManager == NULL )
return;
// Owner-only command
if( droid->getLinkedCreature() != speaker )
return;
if( petManager->isTrainedCommand( pcd, PetManager::REPAIR, cmd ) ){
petManager->enqueuePetCommand(speaker, droid, String("petRepair").toLowerCase().hashCode(), "");
}
}
int DroidRepairModuleDataComponent::getBatteryDrain() {
return 0; // No constant drain, but each activation will use power
}
String DroidRepairModuleDataComponent::toString(){
return BaseDroidModuleComponent::toString();
}
|
/*
* Copyright <SWGEmu>
See file COPYING for copying conditions. */
#include "DroidRepairModuleDataComponent.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/tangible/component/droid/DroidComponent.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/managers/creature/PetManager.h"
DroidRepairModuleDataComponent::DroidRepairModuleDataComponent() {
setLoggingName("DroidRepairModule");
}
DroidRepairModuleDataComponent::~DroidRepairModuleDataComponent() {
}
String DroidRepairModuleDataComponent::getModuleName() {
return String("repair_module");
}
void DroidRepairModuleDataComponent::initializeTransientMembers() {
// no op
}
void DroidRepairModuleDataComponent::fillAttributeList(AttributeListMessage* alm, CreatureObject* droid) {
alm->insertAttribute( "repair_module", "Installed" );
}
void DroidRepairModuleDataComponent::fillObjectMenuResponse(SceneObject* droidObject, ObjectMenuResponse* menuResponse, CreatureObject* player) {
// Add to Droid Options subradial from PetMenuComponent
menuResponse->addRadialMenuItemToRadialID(132, REPAIR_MODULE_ACTIVATE, 3, "Repair" );
// Add to Program subradial from PetMenuComponent
ManagedReference<DroidObject*> droid = getDroidObject();
if (droid == NULL)
return;
// converse droid can not have their repair command changed. droids without a personality chip are considered base and get all normal radials
if (droid->getOptionsBitmask() & OptionBitmask::CONVERSE)
return;
menuResponse->addRadialMenuItemToRadialID(141, REPAIR_MODULE_TRAIN, 3, "@pet/pet_menu:menu_repair_other" ); // "Repair Other Droid"
}
int DroidRepairModuleDataComponent::handleObjectMenuSelect(CreatureObject* player, byte selectedID, PetControlDevice* controller) {
// Handle repair request
if( selectedID == REPAIR_MODULE_ACTIVATE ){
PetManager* petManager = player->getZoneServer()->getPetManager();
if( petManager == NULL )
return 0;
petManager->enqueuePetCommand(player, getDroidObject(), String("petRepair").toLowerCase().hashCode(), "");
}
// Handle command training
else if( selectedID == REPAIR_MODULE_TRAIN ){
if( controller == NULL )
return 0;
Locker controllerLocker(controller);
controller->setTrainingCommand( PetManager::REPAIR );
}
return 0;
}
void DroidRepairModuleDataComponent::handlePetCommand(String cmd, CreatureObject* speaker){
ManagedReference<DroidObject*> droid = getDroidObject();
if( droid == NULL )
return;
ManagedReference<PetControlDevice*> pcd = droid->getControlDevice().get().castTo<PetControlDevice*>();
if( pcd == NULL )
return;
PetManager* petManager = droid->getZoneServer()->getPetManager();
if( petManager == NULL )
return;
// Owner-only command
if( droid->getLinkedCreature() != speaker )
return;
if( petManager->isTrainedCommand( pcd, PetManager::REPAIR, cmd ) ){
petManager->enqueuePetCommand(speaker, droid, String("petRepair").toLowerCase().hashCode(), "");
}
}
int DroidRepairModuleDataComponent::getBatteryDrain() {
return 0; // No constant drain, but each activation will use power
}
String DroidRepairModuleDataComponent::toString(){
return BaseDroidModuleComponent::toString();
}
|
add missing locker in DroidRepairModuleDataComponent::handleObjectMenuSelect
|
add missing locker in DroidRepairModuleDataComponent::handleObjectMenuSelect
GDB:#4 0x0000000000d7b317 in server::zone::objects::tangible::components:
:droid::DroidRepairModuleDataComponent::handleObjectMenuSelect (this=<optimized out>,
player=<optimized out>, selectedID=<optimized out>, controller=<optimized out>)
at ../../../src/server/zone/objects/tangible/components/droid/DroidRepairModuleDataComponent.cpp:60
Change-Id: I86ba5e2d63cc71c00d8b0c3adf5e41d4106679cd
|
C++
|
agpl-3.0
|
lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
|
22e90e195efe73d9b9fe3142c3bd2f233a58de82
|
CStyle/3.cpp
|
CStyle/3.cpp
|
//
// Created by yashal on 10/5/16.
// Program to draw a color cube and spin it using OpenGL transformation matrices
//
#include "GL/glut.h"
GLfloat vertices[]={-0.5f,-0.5f,-0.5f, -0.5f,0.5f,-0.5f, 0.5f,0.5f,-0.5f, 0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f, -0.5f,0.5f,0.5f, 0.5f,0.5f,0.5f, 0.5f,-0.5f,0.5f};
GLfloat colors[] = {0,0,0, 0,0,1, 0,1,0, 0,1,1,
1,0,0, 1,0,1, 1,1,0, 1,1,1};
GLbyte faces[] = {0,1,2,3, 2,3,7,6, 4,5,6,7, 4,5,1,0, 5,6,2,1, 0,3,7,4};
int currentAxis[3] = {0, 0, 1};
void mouseClickListener(int btn, int state, int x, int y) {
// Bind one axis to one button
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 1;
currentAxis[1] = 0;
currentAxis[2] = 0;
}
if (btn == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 0;
currentAxis[1] = 1;
currentAxis[2] = 0;
}
if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 0;
currentAxis[1] = 0;
currentAxis[2] = 1;
}
}
void reshape(int w, int h) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h); // Resize viewport to show new w and h.
if (h>=w) //This is needed to main proper aspect ratio; otherwise the image would appear stretched
glOrtho(-1.0, 1.0, (GLfloat) -h / w, (GLfloat) h / w, -1.0, 1.0); //width is smaller than height
else
glOrtho((GLfloat) -w / h, (GLfloat) w / h, -1.0, 1.0, -1.0, 1.0); //height is smaller
}
void display() {
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glRotated(0.06, currentAxis[0], currentAxis[1], currentAxis[2]); // Rotate the selected axis
// glDrawElements(mode,count,type,pointer), specifies the indices in vertex and color pointer) 6 faces * 4 vertices total
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, faces);
glFlush();
}
void glInit() {
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// glEnableClientState — enable or disable client-side capability
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Sets the pointers. Takes size,type,stride and pointer.
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
// Enable hidden surface removal.
glEnable(GL_DEPTH_TEST);
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitWindowSize(700, 700);
glutCreateWindow("Click to spin the cube");
glutDisplayFunc(display);
glutIdleFunc(display); // Sets global idle for animations etc.
glutMouseFunc(mouseClickListener); // Handles mouse click callback
glutReshapeFunc(reshape); // Handles resizing of window; Not very necessary
glInit();
glutMainLoop();
}
|
//
// Created by yashal on 10/5/16.
// Program to draw a color cube and spin it using OpenGL transformation matrices
//
/*
5-------6
/| /|
/ | / |
1--|----2 |
| 4----|--7
| / | /
0-------3
*/
#include "GL/glut.h"
GLfloat vertices[]={-0.5f,-0.5f,-0.5f, -0.5f,0.5f,-0.5f, 0.5f,0.5f,-0.5f, 0.5f,-0.5f,-0.5f,
-0.5f,-0.5f,0.5f, -0.5f,0.5f,0.5f, 0.5f,0.5f,0.5f, 0.5f,-0.5f,0.5f};
GLfloat colors[] = {0,0,0, 0,0,1, 0,1,0, 0,1,1,
1,0,0, 1,0,1, 1,1,0, 1,1,1};
GLbyte faces[] = {0,1,2,3, 2,3,7,6, 4,5,6,7, 4,5,1,0, 5,6,2,1, 0,3,7,4};
int currentAxis[3] = {0, 0, 1};
void mouseClickListener(int btn, int state, int x, int y) {
// Bind one axis to one button
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 1;
currentAxis[1] = 0;
currentAxis[2] = 0;
}
if (btn == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 0;
currentAxis[1] = 1;
currentAxis[2] = 0;
}
if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
currentAxis[0] = 0;
currentAxis[1] = 0;
currentAxis[2] = 1;
}
}
void reshape(int w, int h) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h); // Resize viewport to show new w and h.
if (h>=w) //This is needed to main proper aspect ratio; otherwise the image would appear stretched
glOrtho(-1.0, 1.0, (GLfloat) -h / w, (GLfloat) h / w, -1.0, 1.0); //width is smaller than height
else
glOrtho((GLfloat) -w / h, (GLfloat) w / h, -1.0, 1.0, -1.0, 1.0); //height is smaller
}
void display() {
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glRotated(0.06, currentAxis[0], currentAxis[1], currentAxis[2]); // Rotate the selected axis
// glDrawElements(mode,count,type,pointer), specifies the indices in vertex and color pointer) 6 faces * 4 vertices total
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, faces);
glFlush();
}
void glInit() {
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// glEnableClientState — enable or disable client-side capability
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Sets the pointers. Takes size,type,stride and pointer.
glVertexPointer(3, GL_FLOAT, 0, vertices);
glColorPointer(3, GL_FLOAT, 0, colors);
// Enable hidden surface removal.
glEnable(GL_DEPTH_TEST);
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitWindowSize(700, 700);
glutCreateWindow("Click to spin the cube");
glutDisplayFunc(display);
glutIdleFunc(display); // Sets global idle for animations etc.
glutMouseFunc(mouseClickListener); // Handles mouse click callback
glutReshapeFunc(reshape); // Handles resizing of window; Not very necessary
glInit();
glutMainLoop();
}
|
Add cube
|
Add cube
|
C++
|
mit
|
YashalShakti/ComputerGraphicsUsingOpenGL-10CSL67,YashalShakti/ComputerGraphicsUsingOpenGL-10CSL67
|
a5f52369329d61d327351cd3ad6f88a7344a790e
|
Controls.cpp
|
Controls.cpp
|
/*
* @File: Controls.cpp
* @Description: Constrols class handles output to motors and motor controllers.
* @Author: Rikin Katyal
*/
#include "Controls.h"
Controls::Controls() {
library = &getLibrary();
// Get variables from Data class
this -> update();
// Initialize Talons for drive system
talon1 = CANTalon(DN1);
talon2 = CANTalon(DN2);
talon3 = CANTalon(DN3);
talon4 = CANTalon(DN4);
// Set starting variables
trianglesLowered = false;
this -> resetSpeed();
}
Controls::~Controls() {
// Controls destructor
}
void Controls::driveBase(int x, int y) {
// Get variables from Data class
this -> update();
// Driving base left/right
if (x != 0) {
// Divide by 2 to moderate speed
speed1 += x / 2.0;
speed2 += x / 2.0;
speed3 += x / 2.0;
speed4 += x / 2.0;
}
// Driving base up/down
if (y != 0) {
// Divide by 2 to moderate speed
speed1 += y / 2.0;
speed2 += y / 2.0;
speed3 += y / 2.0;
speed4 += y / 2.0;
}
// Sets the talons for the base
this -> setDriveTalons(speed1, speed2, speed3, speed4);
// reset speeds to 0
this -> resetSpeed();
}
void Controls::pivotLeft() {
}
void Controls::pivotRight() {
}
void Controls::grabBall() {
}
void Controls::reverseBall() {
}
void Controls::launchBall() {
}
void Controls::liftTriangles() {
}
void Controls::lowerTriangles() {
}
void Controls::toggleTriangles() {
if (trianglesLowered) {
this -> liftTriangles();
}
else {
this -> lowerTriangles();
}
}
void Controls::update() {
}
void Controls::resetSpeed() {
speed1 = 0;
speed2 = 0;
speed3 = 0;
speed4 = 0;
}
void Controls::setDriveTalons(double speed1, double speed2, double speed3, double speed4) {
// Sets the talons for the base
this -> setTalon(library::getTalon(library::FRONT_L), speed1);
this -> setTalon(library::getTalon(library::FRONT_R), speed2);
this -> setTalon(library::getTalon(library::BACK_L), speed3);
this -> setTalon(library::getTalon(library::BACK_R), speed4);
}
void Controls::setTalon(CANTalon talon, double value) {
talon.Set(value);
}
|
/*
* @File: Controls.cpp
* @Description: Constrols class handles output to motors and motor controllers.
* @Author: Rikin Katyal
*/
#include "Controls.h"
Controls::Controls() {
library = &getLibrary();
// Get variables from Data class
update();
// Initialize Talons for drive system
talon1 = CANTalon(DN1);
talon2 = CANTalon(DN2);
talon3 = CANTalon(DN3);
talon4 = CANTalon(DN4);
// Set starting variables
trianglesLowered = false;
resetSpeed();
}
Controls::~Controls() {
// Controls destructor
}
void Controls::driveBase(int x, int y) {
// Get variables from Data class
update();
// Driving base left/right
if (x != 0) {
// Divide by 2 to moderate speed
speed1 += x / 2.0;
speed2 += x / 2.0;
speed3 += x / 2.0;
speed4 += x / 2.0;
}
// Driving base up/down
if (y != 0) {
// Divide by 2 to moderate speed
speed1 += y / 2.0;
speed2 += y / 2.0;
speed3 += y / 2.0;
speed4 += y / 2.0;
}
// Sets the talons for the base
setDriveTalons(speed1, speed2, speed3, speed4);
// reset speeds to 0
resetSpeed();
}
void Controls::pivotLeft() {
}
void Controls::pivotRight() {
}
void Controls::grabBall() {
}
void Controls::reverseBall() {
}
void Controls::launchBall() {
}
void Controls::liftTriangles() {
}
void Controls::lowerTriangles() {
}
void Controls::toggleTriangles() {
if (trianglesLowered) {
liftTriangles();
}
else {
lowerTriangles();
}
}
void Controls::update() {
}
void Controls::resetSpeed() {
speed1 = 0;
speed2 = 0;
speed3 = 0;
speed4 = 0;
}
void Controls::setDriveTalons(double speed1, double speed2, double speed3, double speed4) {
// Sets the talons for the base
setTalon(library::getTalon(library::FRONT_L), speed1);
setTalon(library::getTalon(library::FRONT_R), speed2);
setTalon(library::getTalon(library::BACK_L), speed3);
setTalon(library::getTalon(library::BACK_R), speed4);
}
void Controls::setTalon(CANTalon talon, double value) {
talon.Set(value);
}
|
remove this
|
remove this
|
C++
|
mit
|
VincentMasseyRobotics/Stronghold,VincentMasseyRobotics/Stronghold
|
c372422606ac74621f111fbb305d49ca324ddf51
|
chrome/browser/chromeos/login/managed/managed_user_creation_controller_new.cc
|
chrome/browser/chromeos/login/managed/managed_user_creation_controller_new.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/managed/managed_user_creation_controller_new.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "chrome/browser/chromeos/login/auth/key.h"
#include "chrome/browser/chromeos/login/auth/mount_manager.h"
#include "chrome/browser/chromeos/login/auth/user_context.h"
#include "chrome/browser/chromeos/login/managed/locally_managed_user_constants.h"
#include "chrome/browser/chromeos/login/managed/supervised_user_authentication.h"
#include "chrome/browser/chromeos/login/users/supervised_user_manager.h"
#include "chrome/browser/chromeos/login/users/user.h"
#include "chrome/browser/chromeos/login/users/user_manager.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "crypto/random.h"
#include "google_apis/gaia/google_service_auth_error.h"
namespace chromeos {
namespace {
const int kUserCreationTimeoutSeconds = 30; // 30 seconds.
bool StoreManagedUserFiles(const std::string& token,
const base::FilePath& base_path) {
if (!base::SysInfo::IsRunningOnChromeOS()) {
// If running on desktop, cryptohome stub does not create home directory.
base::CreateDirectory(base_path);
}
base::FilePath token_file = base_path.Append(kManagedUserTokenFilename);
int bytes = base::WriteFile(token_file, token.c_str(), token.length());
return bytes >= 0;
}
} // namespace
ManagedUserCreationControllerNew::ManagedUserCreationControllerNew(
ManagedUserCreationControllerNew::StatusConsumer* consumer,
const std::string& manager_id)
: ManagedUserCreationController(consumer),
stage_(STAGE_INITIAL),
weak_factory_(this) {
creation_context_.reset(
new ManagedUserCreationControllerNew::UserCreationContext());
creation_context_->manager_id = manager_id;
}
ManagedUserCreationControllerNew::~ManagedUserCreationControllerNew() {}
ManagedUserCreationControllerNew::UserCreationContext::UserCreationContext() {}
ManagedUserCreationControllerNew::UserCreationContext::~UserCreationContext() {}
void ManagedUserCreationControllerNew::SetManagerProfile(
Profile* manager_profile) {
creation_context_->manager_profile = manager_profile;
}
Profile* ManagedUserCreationControllerNew::GetManagerProfile() {
return creation_context_->manager_profile;
}
void ManagedUserCreationControllerNew::StartCreation(
const base::string16& display_name,
const std::string& password,
int avatar_index) {
DCHECK(creation_context_);
creation_context_->creation_type = NEW_USER;
creation_context_->display_name = display_name;
creation_context_->password = password;
creation_context_->avatar_index = avatar_index;
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartImport(
const base::string16& display_name,
const std::string& password,
int avatar_index,
const std::string& sync_id,
const std::string& master_key) {
DCHECK(creation_context_);
creation_context_->creation_type = USER_IMPORT_OLD;
creation_context_->display_name = display_name;
creation_context_->password = password;
creation_context_->avatar_index = avatar_index;
creation_context_->sync_user_id = sync_id;
creation_context_->master_key = master_key;
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartImport(
const base::string16& display_name,
int avatar_index,
const std::string& sync_id,
const std::string& master_key,
const base::DictionaryValue* password_data,
const std::string& encryption_key,
const std::string& signature_key) {
DCHECK(creation_context_);
creation_context_->creation_type = USER_IMPORT_NEW;
creation_context_->display_name = display_name;
creation_context_->avatar_index = avatar_index;
creation_context_->sync_user_id = sync_id;
creation_context_->master_key = master_key;
password_data->GetStringWithoutPathExpansion(
kEncryptedPassword, &creation_context_->salted_password);
creation_context_->signature_key = signature_key;
creation_context_->encryption_key = encryption_key;
creation_context_->password_data.MergeDictionary(password_data);
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartCreationImpl() {
DCHECK(creation_context_);
DCHECK_EQ(STAGE_INITIAL, stage_);
VLOG(1) << "Starting supervised user creation";
VLOG(1) << " Phase 1 : Prepare keys";
SupervisedUserManager* manager =
UserManager::Get()->GetSupervisedUserManager();
manager->StartCreationTransaction(creation_context_->display_name);
creation_context_->local_user_id = manager->GenerateUserId();
if (creation_context_->creation_type == NEW_USER) {
creation_context_->sync_user_id =
ManagedUserRegistrationUtility::GenerateNewManagedUserId();
}
manager->SetCreationTransactionUserId(creation_context_->local_user_id);
stage_ = TRANSACTION_STARTED;
manager->CreateUserRecord(creation_context_->manager_id,
creation_context_->local_user_id,
creation_context_->sync_user_id,
creation_context_->display_name);
SupervisedUserAuthentication* authentication =
UserManager::Get()->GetSupervisedUserManager()->GetAuthentication();
// When importing M35+ users we need only to store data, for all other cases
// we need to create some keys.
if (creation_context_->creation_type != USER_IMPORT_NEW) {
// Of all required keys old imported users have only master key.
// Otherwise they are the same as newly created users in terms of keys.
if (creation_context_->creation_type == NEW_USER) {
creation_context_->master_key = authentication->GenerateMasterKey();
}
base::DictionaryValue extra;
authentication->FillDataForNewUser(creation_context_->local_user_id,
creation_context_->password,
&creation_context_->password_data,
&extra);
creation_context_->password_data.GetStringWithoutPathExpansion(
kEncryptedPassword, &creation_context_->salted_password);
extra.GetStringWithoutPathExpansion(kPasswordEncryptionKey,
&creation_context_->encryption_key);
extra.GetStringWithoutPathExpansion(kPasswordSignatureKey,
&creation_context_->signature_key);
}
authentication->StorePasswordData(creation_context_->local_user_id,
creation_context_->password_data);
stage_ = KEYS_GENERATED;
VLOG(1) << " Phase 2 : Create cryptohome";
timeout_timer_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kUserCreationTimeoutSeconds),
this,
&ManagedUserCreationControllerNew::CreationTimedOut);
authenticator_ = new ExtendedAuthenticator(this);
UserContext user_context;
user_context.SetKey(Key(creation_context_->master_key));
authenticator_->TransformKeyIfNeeded(
user_context,
base::Bind(&ManagedUserCreationControllerNew::OnKeyTransformedIfNeeded,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnKeyTransformedIfNeeded(
const UserContext& user_context) {
VLOG(1) << " Phase 2.1 : Got hashed master key";
creation_context_->salted_master_key = user_context.GetKey()->GetSecret();
// Create home dir with two keys.
std::vector<cryptohome::KeyDefinition> keys;
// Main key is the master key. Just as keys for plain GAIA users, it is salted
// with system salt. It has all usual privileges.
cryptohome::KeyDefinition master_key(creation_context_->salted_master_key,
kCryptohomeMasterKeyLabel,
cryptohome::PRIV_DEFAULT);
keys.push_back(master_key);
authenticator_->CreateMount(
creation_context_->local_user_id,
keys,
base::Bind(&ManagedUserCreationControllerNew::OnMountSuccess,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnAuthenticationFailure(
ExtendedAuthenticator::AuthState error) {
timeout_timer_.Stop();
ErrorCode code = NO_ERROR;
switch (error) {
case ManagedUserAuthenticator::NO_MOUNT:
code = CRYPTOHOME_NO_MOUNT;
break;
case ManagedUserAuthenticator::FAILED_MOUNT:
code = CRYPTOHOME_FAILED_MOUNT;
break;
case ManagedUserAuthenticator::FAILED_TPM:
code = CRYPTOHOME_FAILED_TPM;
break;
default:
NOTREACHED();
}
stage_ = STAGE_ERROR;
if (consumer_)
consumer_->OnCreationError(code);
}
void ManagedUserCreationControllerNew::OnMountSuccess(
const std::string& mount_hash) {
DCHECK(creation_context_);
DCHECK_EQ(KEYS_GENERATED, stage_);
VLOG(1) << " Phase 2.2 : Created home dir with master key";
creation_context_->mount_hash = mount_hash;
// Plain text password, hashed and salted with individual salt.
// It can be used for mounting homedir, and can be replaced only when signed.
cryptohome::KeyDefinition password_key(creation_context_->salted_password,
kCryptohomeManagedUserKeyLabel,
kCryptohomeManagedUserKeyPrivileges);
base::Base64Decode(creation_context_->encryption_key,
&password_key.encryption_key);
base::Base64Decode(creation_context_->signature_key,
&password_key.signature_key);
Key key(Key::KEY_TYPE_SALTED_PBKDF2_AES256_1234,
creation_context_->salted_master_key,
std::string()); // The salt is stored elsewhere.
key.SetLabel(kCryptohomeMasterKeyLabel);
UserContext context(creation_context_->local_user_id);
context.SetKey(key);
context.SetIsUsingOAuth(false);
authenticator_->AddKey(
context,
password_key,
true,
base::Bind(&ManagedUserCreationControllerNew::OnAddKeySuccess,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnAddKeySuccess() {
DCHECK(creation_context_);
DCHECK_EQ(KEYS_GENERATED, stage_);
stage_ = CRYPTOHOME_CREATED;
VLOG(1) << " Phase 3 : Create/update user on chrome.com/manage";
ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetInstance()->GetForProfile(
creation_context_->manager_profile);
ProfileSyncService::SyncStatusSummary status =
sync_service->QuerySyncStatusSummary();
if (status == ProfileSyncService::DATATYPES_NOT_INITIALIZED)
consumer_->OnLongCreationWarning();
creation_context_->registration_utility =
ManagedUserRegistrationUtility::Create(
creation_context_->manager_profile);
ManagedUserRegistrationInfo info(creation_context_->display_name,
creation_context_->avatar_index);
info.master_key = creation_context_->master_key;
info.password_signature_key = creation_context_->signature_key;
info.password_encryption_key = creation_context_->encryption_key;
info.password_data.MergeDictionary(&creation_context_->password_data);
// Registration utility will update user data if user already exist.
creation_context_->registration_utility->Register(
creation_context_->sync_user_id,
info,
base::Bind(&ManagedUserCreationControllerNew::RegistrationCallback,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::RegistrationCallback(
const GoogleServiceAuthError& error,
const std::string& token) {
DCHECK(creation_context_);
DCHECK_EQ(CRYPTOHOME_CREATED, stage_);
stage_ = DASHBOARD_CREATED;
if (error.state() == GoogleServiceAuthError::NONE) {
creation_context_->token = token;
PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&StoreManagedUserFiles,
creation_context_->token,
MountManager::GetHomeDir(creation_context_->mount_hash)),
base::Bind(&ManagedUserCreationControllerNew::OnManagedUserFilesStored,
weak_factory_.GetWeakPtr()));
} else {
stage_ = STAGE_ERROR;
LOG(ERROR) << "Managed user creation failed. Error code " << error.state();
if (consumer_)
consumer_->OnCreationError(CLOUD_SERVER_ERROR);
}
}
void ManagedUserCreationControllerNew::OnManagedUserFilesStored(bool success) {
DCHECK(creation_context_);
DCHECK_EQ(DASHBOARD_CREATED, stage_);
if (!success) {
stage_ = STAGE_ERROR;
if (consumer_)
consumer_->OnCreationError(TOKEN_WRITE_FAILED);
return;
}
// Assume that new token is valid. It will be automatically invalidated if
// sync service fails to use it.
UserManager::Get()->SaveUserOAuthStatus(creation_context_->local_user_id,
User::OAUTH2_TOKEN_STATUS_VALID);
stage_ = TOKEN_WRITTEN;
timeout_timer_.Stop();
UserManager::Get()->GetSupervisedUserManager()->CommitCreationTransaction();
content::RecordAction(
base::UserMetricsAction("ManagedMode_LocallyManagedUserCreated"));
stage_ = TRANSACTION_COMMITTED;
if (consumer_)
consumer_->OnCreationSuccess();
}
void ManagedUserCreationControllerNew::CreationTimedOut() {
LOG(ERROR) << "Supervised user creation timed out. stage = " << stage_;
if (consumer_)
consumer_->OnCreationTimeout();
}
void ManagedUserCreationControllerNew::FinishCreation() {
chrome::AttemptUserExit();
}
void ManagedUserCreationControllerNew::CancelCreation() {
creation_context_->registration_utility.reset();
chrome::AttemptUserExit();
}
std::string ManagedUserCreationControllerNew::GetManagedUserId() {
DCHECK(creation_context_);
return creation_context_->local_user_id;
}
} // namespace chromeos
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/managed/managed_user_creation_controller_new.h"
#include "base/base64.h"
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/task_runner_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "chrome/browser/chromeos/login/auth/key.h"
#include "chrome/browser/chromeos/login/auth/mount_manager.h"
#include "chrome/browser/chromeos/login/auth/user_context.h"
#include "chrome/browser/chromeos/login/managed/locally_managed_user_constants.h"
#include "chrome/browser/chromeos/login/managed/supervised_user_authentication.h"
#include "chrome/browser/chromeos/login/users/supervised_user_manager.h"
#include "chrome/browser/chromeos/login/users/user.h"
#include "chrome/browser/chromeos/login/users/user_manager.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/user_metrics.h"
#include "crypto/random.h"
#include "google_apis/gaia/google_service_auth_error.h"
namespace chromeos {
namespace {
const int kUserCreationTimeoutSeconds = 30; // 30 seconds.
bool StoreManagedUserFiles(const std::string& token,
const base::FilePath& base_path) {
if (!base::SysInfo::IsRunningOnChromeOS()) {
// If running on desktop, cryptohome stub does not create home directory.
base::CreateDirectory(base_path);
}
base::FilePath token_file = base_path.Append(kManagedUserTokenFilename);
int bytes = base::WriteFile(token_file, token.c_str(), token.length());
return bytes >= 0;
}
} // namespace
ManagedUserCreationControllerNew::ManagedUserCreationControllerNew(
ManagedUserCreationControllerNew::StatusConsumer* consumer,
const std::string& manager_id)
: ManagedUserCreationController(consumer),
stage_(STAGE_INITIAL),
weak_factory_(this) {
creation_context_.reset(
new ManagedUserCreationControllerNew::UserCreationContext());
creation_context_->manager_id = manager_id;
}
ManagedUserCreationControllerNew::~ManagedUserCreationControllerNew() {}
ManagedUserCreationControllerNew::UserCreationContext::UserCreationContext() {}
ManagedUserCreationControllerNew::UserCreationContext::~UserCreationContext() {}
void ManagedUserCreationControllerNew::SetManagerProfile(
Profile* manager_profile) {
creation_context_->manager_profile = manager_profile;
}
Profile* ManagedUserCreationControllerNew::GetManagerProfile() {
return creation_context_->manager_profile;
}
void ManagedUserCreationControllerNew::StartCreation(
const base::string16& display_name,
const std::string& password,
int avatar_index) {
DCHECK(creation_context_);
creation_context_->creation_type = NEW_USER;
creation_context_->display_name = display_name;
creation_context_->password = password;
creation_context_->avatar_index = avatar_index;
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartImport(
const base::string16& display_name,
const std::string& password,
int avatar_index,
const std::string& sync_id,
const std::string& master_key) {
DCHECK(creation_context_);
creation_context_->creation_type = USER_IMPORT_OLD;
creation_context_->display_name = display_name;
creation_context_->password = password;
creation_context_->avatar_index = avatar_index;
creation_context_->sync_user_id = sync_id;
creation_context_->master_key = master_key;
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartImport(
const base::string16& display_name,
int avatar_index,
const std::string& sync_id,
const std::string& master_key,
const base::DictionaryValue* password_data,
const std::string& encryption_key,
const std::string& signature_key) {
DCHECK(creation_context_);
creation_context_->creation_type = USER_IMPORT_NEW;
creation_context_->display_name = display_name;
creation_context_->avatar_index = avatar_index;
creation_context_->sync_user_id = sync_id;
creation_context_->master_key = master_key;
password_data->GetStringWithoutPathExpansion(
kEncryptedPassword, &creation_context_->salted_password);
creation_context_->signature_key = signature_key;
creation_context_->encryption_key = encryption_key;
creation_context_->password_data.MergeDictionary(password_data);
StartCreationImpl();
}
void ManagedUserCreationControllerNew::StartCreationImpl() {
DCHECK(creation_context_);
DCHECK_EQ(STAGE_INITIAL, stage_);
VLOG(1) << "Starting supervised user creation";
VLOG(1) << " Phase 1 : Prepare keys";
SupervisedUserManager* manager =
UserManager::Get()->GetSupervisedUserManager();
manager->StartCreationTransaction(creation_context_->display_name);
creation_context_->local_user_id = manager->GenerateUserId();
if (creation_context_->creation_type == NEW_USER) {
creation_context_->sync_user_id =
ManagedUserRegistrationUtility::GenerateNewManagedUserId();
}
manager->SetCreationTransactionUserId(creation_context_->local_user_id);
stage_ = TRANSACTION_STARTED;
manager->CreateUserRecord(creation_context_->manager_id,
creation_context_->local_user_id,
creation_context_->sync_user_id,
creation_context_->display_name);
SupervisedUserAuthentication* authentication =
UserManager::Get()->GetSupervisedUserManager()->GetAuthentication();
// When importing M35+ users we need only to store data, for all other cases
// we need to create some keys.
if (creation_context_->creation_type != USER_IMPORT_NEW) {
// Of all required keys old imported users have only master key.
// Otherwise they are the same as newly created users in terms of keys.
if (creation_context_->creation_type == NEW_USER) {
creation_context_->master_key = authentication->GenerateMasterKey();
}
base::DictionaryValue extra;
authentication->FillDataForNewUser(creation_context_->local_user_id,
creation_context_->password,
&creation_context_->password_data,
&extra);
creation_context_->password_data.GetStringWithoutPathExpansion(
kEncryptedPassword, &creation_context_->salted_password);
extra.GetStringWithoutPathExpansion(kPasswordEncryptionKey,
&creation_context_->encryption_key);
extra.GetStringWithoutPathExpansion(kPasswordSignatureKey,
&creation_context_->signature_key);
}
authentication->StorePasswordData(creation_context_->local_user_id,
creation_context_->password_data);
stage_ = KEYS_GENERATED;
VLOG(1) << " Phase 2 : Create cryptohome";
timeout_timer_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kUserCreationTimeoutSeconds),
this,
&ManagedUserCreationControllerNew::CreationTimedOut);
authenticator_ = new ExtendedAuthenticator(this);
UserContext user_context;
user_context.SetKey(Key(creation_context_->master_key));
authenticator_->TransformKeyIfNeeded(
user_context,
base::Bind(&ManagedUserCreationControllerNew::OnKeyTransformedIfNeeded,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnKeyTransformedIfNeeded(
const UserContext& user_context) {
VLOG(1) << " Phase 2.1 : Got hashed master key";
creation_context_->salted_master_key = user_context.GetKey()->GetSecret();
// Create home dir with two keys.
std::vector<cryptohome::KeyDefinition> keys;
// Main key is the master key. Just as keys for plain GAIA users, it is salted
// with system salt. It has all usual privileges.
cryptohome::KeyDefinition master_key(creation_context_->salted_master_key,
kCryptohomeMasterKeyLabel,
cryptohome::PRIV_DEFAULT);
keys.push_back(master_key);
authenticator_->CreateMount(
creation_context_->local_user_id,
keys,
base::Bind(&ManagedUserCreationControllerNew::OnMountSuccess,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnAuthenticationFailure(
ExtendedAuthenticator::AuthState error) {
timeout_timer_.Stop();
ErrorCode code = NO_ERROR;
switch (error) {
case ManagedUserAuthenticator::NO_MOUNT:
code = CRYPTOHOME_NO_MOUNT;
break;
case ManagedUserAuthenticator::FAILED_MOUNT:
code = CRYPTOHOME_FAILED_MOUNT;
break;
case ManagedUserAuthenticator::FAILED_TPM:
code = CRYPTOHOME_FAILED_TPM;
break;
default:
NOTREACHED();
}
stage_ = STAGE_ERROR;
if (consumer_)
consumer_->OnCreationError(code);
}
void ManagedUserCreationControllerNew::OnMountSuccess(
const std::string& mount_hash) {
DCHECK(creation_context_);
DCHECK_EQ(KEYS_GENERATED, stage_);
VLOG(1) << " Phase 2.2 : Created home dir with master key";
creation_context_->mount_hash = mount_hash;
// Plain text password, hashed and salted with individual salt.
// It can be used for mounting homedir, and can be replaced only when signed.
cryptohome::KeyDefinition password_key(creation_context_->salted_password,
kCryptohomeManagedUserKeyLabel,
kCryptohomeManagedUserKeyPrivileges);
base::Base64Decode(creation_context_->encryption_key,
&password_key.encryption_key);
base::Base64Decode(creation_context_->signature_key,
&password_key.signature_key);
Key key(Key::KEY_TYPE_SALTED_PBKDF2_AES256_1234,
std::string(), // The salt is stored elsewhere.
creation_context_->salted_master_key);
key.SetLabel(kCryptohomeMasterKeyLabel);
UserContext context(creation_context_->local_user_id);
context.SetKey(key);
context.SetIsUsingOAuth(false);
authenticator_->AddKey(
context,
password_key,
true,
base::Bind(&ManagedUserCreationControllerNew::OnAddKeySuccess,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::OnAddKeySuccess() {
DCHECK(creation_context_);
DCHECK_EQ(KEYS_GENERATED, stage_);
stage_ = CRYPTOHOME_CREATED;
VLOG(1) << " Phase 3 : Create/update user on chrome.com/manage";
ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetInstance()->GetForProfile(
creation_context_->manager_profile);
ProfileSyncService::SyncStatusSummary status =
sync_service->QuerySyncStatusSummary();
if (status == ProfileSyncService::DATATYPES_NOT_INITIALIZED)
consumer_->OnLongCreationWarning();
creation_context_->registration_utility =
ManagedUserRegistrationUtility::Create(
creation_context_->manager_profile);
ManagedUserRegistrationInfo info(creation_context_->display_name,
creation_context_->avatar_index);
info.master_key = creation_context_->master_key;
info.password_signature_key = creation_context_->signature_key;
info.password_encryption_key = creation_context_->encryption_key;
info.password_data.MergeDictionary(&creation_context_->password_data);
// Registration utility will update user data if user already exist.
creation_context_->registration_utility->Register(
creation_context_->sync_user_id,
info,
base::Bind(&ManagedUserCreationControllerNew::RegistrationCallback,
weak_factory_.GetWeakPtr()));
}
void ManagedUserCreationControllerNew::RegistrationCallback(
const GoogleServiceAuthError& error,
const std::string& token) {
DCHECK(creation_context_);
DCHECK_EQ(CRYPTOHOME_CREATED, stage_);
stage_ = DASHBOARD_CREATED;
if (error.state() == GoogleServiceAuthError::NONE) {
creation_context_->token = token;
PostTaskAndReplyWithResult(
content::BrowserThread::GetBlockingPool(),
FROM_HERE,
base::Bind(&StoreManagedUserFiles,
creation_context_->token,
MountManager::GetHomeDir(creation_context_->mount_hash)),
base::Bind(&ManagedUserCreationControllerNew::OnManagedUserFilesStored,
weak_factory_.GetWeakPtr()));
} else {
stage_ = STAGE_ERROR;
LOG(ERROR) << "Managed user creation failed. Error code " << error.state();
if (consumer_)
consumer_->OnCreationError(CLOUD_SERVER_ERROR);
}
}
void ManagedUserCreationControllerNew::OnManagedUserFilesStored(bool success) {
DCHECK(creation_context_);
DCHECK_EQ(DASHBOARD_CREATED, stage_);
if (!success) {
stage_ = STAGE_ERROR;
if (consumer_)
consumer_->OnCreationError(TOKEN_WRITE_FAILED);
return;
}
// Assume that new token is valid. It will be automatically invalidated if
// sync service fails to use it.
UserManager::Get()->SaveUserOAuthStatus(creation_context_->local_user_id,
User::OAUTH2_TOKEN_STATUS_VALID);
stage_ = TOKEN_WRITTEN;
timeout_timer_.Stop();
UserManager::Get()->GetSupervisedUserManager()->CommitCreationTransaction();
content::RecordAction(
base::UserMetricsAction("ManagedMode_LocallyManagedUserCreated"));
stage_ = TRANSACTION_COMMITTED;
if (consumer_)
consumer_->OnCreationSuccess();
}
void ManagedUserCreationControllerNew::CreationTimedOut() {
LOG(ERROR) << "Supervised user creation timed out. stage = " << stage_;
if (consumer_)
consumer_->OnCreationTimeout();
}
void ManagedUserCreationControllerNew::FinishCreation() {
chrome::AttemptUserExit();
}
void ManagedUserCreationControllerNew::CancelCreation() {
creation_context_->registration_utility.reset();
chrome::AttemptUserExit();
}
std::string ManagedUserCreationControllerNew::GetManagedUserId() {
DCHECK(creation_context_);
return creation_context_->local_user_id;
}
} // namespace chromeos
|
Fix parameters order.
|
Fix parameters order.
BUG=378338
Review URL: https://codereview.chromium.org/301353008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@274476 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,markYoungH/chromium.src,dednal/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,fujunwei/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,dednal/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,Just-D/chromium-1,Jonekee/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,Fireblend/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,Just-D/chromium-1,Jonekee/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,dednal/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Just-D/chromium-1,Chilledheart/chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,jaruba/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,littlstar/chromium.src,markYoungH/chromium.src
|
e9db6c4a10c4084edf555ec4b2247f44b83a3b92
|
moveit_ros/planning/planning_scene_monitor_tools/src/display_random_state.cpp
|
moveit_ros/planning/planning_scene_monitor_tools/src/display_random_state.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "display_random_state");
bool valid = false;
bool invalid = false;
for (int i = 0 ; i < argc ; ++i)
{
if (strcmp(argv[i], "--valid") == 0)
{
valid = true;
break;
}
if (strcmp(argv[i], "--invalid") == 0)
{
invalid = true;
break;
}
}
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
planning_models_loader::KinematicModelLoader::Options opt;
opt.robot_description_ = "robot_description";
planning_models_loader::KinematicModelLoaderPtr kml(new planning_models_loader::KinematicModelLoader(opt));
planning_scene_monitor::PlanningSceneMonitor psm(kml);
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
ros::Publisher pub_scene = nh.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
ros::Duration(0.5).sleep();
do
{
if(!psm.getPlanningScene())
{
ROS_ERROR("Planning scene did not load properly, exiting...");
break;
}
std::cout << "Type a number and hit Enter. That number of ";
if (valid)
std::cout << "valid ";
else
if (invalid)
std::cout << "invalid ";
std::cout << "states will be randomly generated at an interval of one second and published as a planning scene." << std::endl;
std::size_t n;
std::cin >> n;
for (std::size_t i = 0 ; i < n ; ++i)
{
if (valid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentState().setToRandomValues();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = !res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find valid state" << std::cout;
continue;
}
}
else
if (invalid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentState().setToRandomValues();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find invalid state" << std::cout;
continue;
}
}
else
psm.getPlanningScene()->getCurrentState().setToRandomValues();
psm.getPlanningScene()->getCurrentState().setToDefaultValues();
// r0
double v[7] = { 2.09642, 0.90423, -0.420767, -0.195229, 2.32139 ,-1.5101, -1.02677 };
std::vector<double> vv; vv.insert(vv.end(), v, v+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("left_arm")->setVariableValues(vv);
double q[7] = {-1.3675, 0.224576 ,-1.81731, -1.37681, 2.778 ,-0.983775, -1.19062 } ;
std::vector<double> qq; qq.insert(qq.end(), q, q+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("right_arm")->setVariableValues(qq);
/*
// r7
double v[7] = { -0.146608 ,0.838234, -0.201172, -0.33163, 1.55722 ,-1.09131 ,0.793076};
std::vector<double> vv; vv.insert(vv.end(), v, v+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("left_arm")->setStateValues(vv);
double q[7] = { 0.0692123, 0.310049, -2.50733, -0.752757, -1.93879, -1.67769, -0.489014 } ;
std::vector<double> qq; qq.insert(qq.end(), q, q+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("right_arm")->setStateValues(qq);
*/
/*
// r10 (tucked)
double v[7] = {0.0654119 ,1.27547, 1.81169, -1.6877, -1.70563 ,-0.134536, -0.0694477 };
std::vector<double> vv; vv.insert(vv.end(), v, v+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("left_arm")->setStateValues(vv);
double q[7] = {-0.0544564 ,1.08707 ,-1.52602, -2.1115 ,-1.40485, -1.83555, 0.214071 } ;
std::vector<double> qq; qq.insert(qq.end(), q, q+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("right_arm")->setStateValues(qq);
*/
/*
// r9
double v[7] = { 0.467443, 0.300118, -0.281953, -1.1776, 0.867952, -0.520881, 2.39421};
std::vector<double> vv; vv.insert(vv.end(), v, v+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("left_arm")->setStateValues(vv);
double q[7] = {0.513607 ,0.362847, -2.99738, -2.00923, 0.13881, -1.24666, -0.234934 } ;
std::vector<double> qq; qq.insert(qq.end(), q, q+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("right_arm")->setStateValues(qq);
*/
/*
// r4
double v[7] = {0.300959, 0.440359, 0.927072, -0.46064, 1.67819, -0.337447, -2.24238};
std::vector<double> vv; vv.insert(vv.end(), v, v+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("left_arm")->setStateValues(vv);
double q[7] = { 0.287, 0.872195, -1.59107, -1.77545, 2.87086, -0.381915, -2.22692} ;
std::vector<double> qq; qq.insert(qq.end(), q, q+7);
psm.getPlanningScene()->getCurrentState().getJointStateGroup("right_arm")->setStateValues(qq);
*/
moveit_msgs::PlanningScene psmsg;
psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
pub_scene.publish(psmsg);
psm.getPlanningScene()->getCurrentState().printStateInfo();
sleep(1);
}
} while (nh.ok());
ros::shutdown();
return 0;
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "display_random_state");
bool valid = false;
bool invalid = false;
for (int i = 0 ; i < argc ; ++i)
{
if (strcmp(argv[i], "--valid") == 0)
{
valid = true;
break;
}
if (strcmp(argv[i], "--invalid") == 0)
{
invalid = true;
break;
}
}
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle nh;
planning_models_loader::KinematicModelLoader::Options opt;
opt.robot_description_ = "robot_description";
planning_models_loader::KinematicModelLoaderPtr kml(new planning_models_loader::KinematicModelLoader(opt));
planning_scene_monitor::PlanningSceneMonitor psm(kml);
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
ros::Publisher pub_scene = nh.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
ros::Duration(0.5).sleep();
do
{
if(!psm.getPlanningScene())
{
ROS_ERROR("Planning scene did not load properly, exiting...");
break;
}
std::cout << "Type a number and hit Enter. That number of ";
if (valid)
std::cout << "valid ";
else
if (invalid)
std::cout << "invalid ";
std::cout << "states will be randomly generated at an interval of one second and published as a planning scene." << std::endl;
std::size_t n;
std::cin >> n;
for (std::size_t i = 0 ; i < n ; ++i)
{
if (valid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentState().setToRandomValues();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = !res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find valid state" << std::cout;
continue;
}
}
else
if (invalid)
{
bool found = false;
unsigned int attempts = 0;
do
{
attempts++;
psm.getPlanningScene()->getCurrentState().setToRandomValues();
collision_detection::CollisionRequest req;
collision_detection::CollisionResult res;
psm.getPlanningScene()->checkCollision(req, res);
found = res.collision;
} while (!found && attempts < 100);
if (!found)
{
std::cout << "Unable to find invalid state" << std::cout;
continue;
}
}
else
psm.getPlanningScene()->getCurrentState().setToRandomValues();
moveit_msgs::PlanningScene psmsg;
psm.getPlanningScene()->getPlanningSceneMsg(psmsg);
pub_scene.publish(psmsg);
psm.getPlanningScene()->getCurrentState().printStateInfo();
sleep(1);
}
} while (nh.ok());
ros::shutdown();
return 0;
}
|
remove forgotten temp code
|
remove forgotten temp code
|
C++
|
bsd-3-clause
|
ros-planning/moveit,davetcoleman/moveit,ros-planning/moveit,v4hn/moveit,ros-planning/moveit,ros-planning/moveit,davetcoleman/moveit,v4hn/moveit,davetcoleman/moveit,v4hn/moveit,ros-planning/moveit,v4hn/moveit,davetcoleman/moveit
|
ba70b1707ce14fd3bdbc5c9f5a4db0dc603b4898
|
src-qt5/core/lumina-desktop/desktop-plugins/applauncher/AppLauncherPlugin.cpp
|
src-qt5/core/lumina-desktop/desktop-plugins/applauncher/AppLauncherPlugin.cpp
|
#include "AppLauncherPlugin.h"
#include "../../LSession.h"
#include "OutlineToolButton.h"
#include <QClipboard>
#define OUTMARGIN 10 //special margin for fonts due to the outlining effect from the OutlineToolbutton
AppLauncherPlugin::AppLauncherPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){
QVBoxLayout *lay = new QVBoxLayout();
inputDLG = 0;
this->setLayout(lay);
lay->setContentsMargins(0,0,0,0);
button = new OutlineToolButton(this);
button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
button->setAutoRaise(true);
button->setText("...\n..."); //Need to set something here so that initial sizing works properly
button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
lay->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(DoubleClicked()), this, SLOT(buttonClicked()) );
button->setContextMenuPolicy(Qt::NoContextMenu);
watcher = new QFileSystemWatcher(this);
connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT( loadButton()) );
connect(this, SIGNAL(PluginActivated()), this, SLOT(buttonClicked()) ); //in case they use the context menu to launch it.
this->setContextMenu( new QMenu(this) );
connect(this->contextMenu(), SIGNAL(triggered(QAction*)), this, SLOT(actionTriggered(QAction*)) );
loadButton();
//QTimer::singleShot(0,this, SLOT(loadButton()) );
}
void AppLauncherPlugin::Cleanup(){
//This is run only when the plugin was forcibly closed/removed
}
void AppLauncherPlugin::loadButton(){
QString def = this->ID().section("::",1,50).section("---",0,0).simplified();
QString path = this->readSetting("applicationpath",def).toString(); //use the default if necessary
QFileInfo info(path);
this->contextMenu()->clear();
//qDebug() << "Default Application Launcher:" << def << path;
bool ok = QFile::exists(path);
if(!ok){ emit RemovePlugin(this->ID()); return;}
int icosize = this->height()-4 - 2.2*button->fontMetrics().height();
button->setFixedSize( this->width()-4, this->height()-4);
button->setIconSize( QSize(icosize,icosize) );
button->setToolTip("");
QString txt;
if(path.endsWith(".desktop") && ok){
XDGDesktop file(path);
ok = !file.name.isEmpty();
if(!ok){
button->setWhatsThis("");
button->setIcon( QIcon(LXDG::findIcon("quickopen-file","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
txt = tr("Click to Set");
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
}else{
button->setWhatsThis(file.filePath);
button->setIcon( QIcon(LXDG::findIcon(file.icon,"system-run").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
if(!file.comment.isEmpty()){button->setToolTip(file.comment); }
txt = file.name;
//Put the simple Open action first (no open-with for .desktop files)
this->contextMenu()->addAction(button->icon(), QString(tr("Launch %1")).arg(file.name), this, SLOT(buttonClicked()) );
//See if there are any "actions" listed for this file, and put them in the context menu as needed.
if(!file.actions.isEmpty()){
for(int i=0; i<file.actions.length(); i++){
QAction *tmp = this->contextMenu()->addAction( file.actions[i].name );
tmp->setIcon( LXDG::findIcon(file.actions[i].icon,"quickopen-file") );
tmp->setWhatsThis( file.actions[i].ID );
}
}
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
watcher->addPath(file.filePath); //make sure to update this shortcut if the file changes
}
}else if(ok){
button->setWhatsThis(info.absoluteFilePath());
if(info.isDir()){
if(path.startsWith("/media/")){
//Could add device ID parsing here to determine what "type" of device it is - will be OS-specific though
button->setIcon( LXDG::findIcon("drive-removable-media","") );
}
else{ button->setIcon( LXDG::findIcon("folder","") ); }
}else if(LUtils::imageExtensions().contains(info.suffix().toLower()) ){
QPixmap pix;
if(pix.load(path)){ button->setIcon( QIcon(pix.scaled(256,256)) ); } //max size for thumbnails in memory
else{ button->setIcon( LXDG::findIcon("dialog-cancel","") ); }
}else{
button->setIcon( QIcon(LXDG::findMimeIcon(path).pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
}
txt = info.fileName();
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
watcher->addPath(path); //make sure to update this shortcut if the file changes
}else{
//InValid File
button->setWhatsThis("");
button->setIcon( QIcon(LXDG::findIcon("quickopen","dialog-cancel").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
button->setText( tr("Click to Set") );
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
}
//Now adjust the context menu for the button as needed
if(this->contextMenu()->isEmpty()){
this->contextMenu()->addAction(LXDG::findIcon("document-open",""), tr("Open"), this, SLOT(buttonClicked()) );
this->contextMenu()->addAction(LXDG::findIcon("document-preview",""), tr("Open With"), this, SLOT(openWith()) );
}
this->contextMenu()->addAction(LXDG::findIcon("document-properties",""), tr("View Properties"), this, SLOT(fileProperties()) );
this->contextMenu()->addSection(tr("File Operations"));
if(!path.endsWith(".desktop")){
this->contextMenu()->addAction(LXDG::findIcon("edit-rename","edit-new"), tr("Rename"), this, SLOT(fileRename()) );
}
this->contextMenu()->addAction(LXDG::findIcon("edit-copy",""), tr("Copy"), this, SLOT(fileCopy()) );
if(info.isWritable() || (info.isSymLink() && QFileInfo(info.canonicalPath()).isWritable() ) ){
this->contextMenu()->addAction(LXDG::findIcon("edit-cut",""), tr("Cut"), this, SLOT(fileCut()) );
this->contextMenu()->addAction(LXDG::findIcon("document-close",""), tr("Delete"), this, SLOT(fileDelete()) );
}
//If the file is a symlink, put the overlay on the icon
if(info.isSymLink()){
QImage img = button->icon().pixmap(QSize(icosize,icosize)).toImage();
int oSize = icosize/3; //overlay size
QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QPainter painter(&img);
painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner
button->setIcon( QIcon(QPixmap::fromImage(img)) );
}
//Now adjust the visible text as necessary based on font/grid sizing
if(button->toolTip().isEmpty()){ button->setToolTip(txt); }
//Double check that the visual icon size matches the requested size - otherwise upscale the icon
if(button->fontMetrics().width(txt) > (button->width()-OUTMARGIN) ){
//Text too long, try to show it on two lines
//txt = button->fontMetrics().elidedText(txt, Qt::ElideRight, 2*(button->width()-OUTMARGIN), Qt::TextWordWrap);
txt =txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks
//Go through and combine any lines
if(txt.contains("\n")){
//need to check each line
QStringList txtL = txt.split("\n");
for(int i=0; i<txtL.length(); i++){
if(( i+1<txtL.length()) && (button->fontMetrics().width(txtL[i]) < button->width()/2) ){
txtL[i] = txtL[i]+" "+txtL[i+1];
txtL.removeAt(i+1);
}
}
txt = txtL.join("\n").section("\n",0,2);
}
if(txt.contains("\n")){
//need to check each line
QStringList txtL = txt.split("\n");
for(int i=0; i<txtL.length(); i++){
if(i>1){ txtL.removeAt(i); i--; } //Only take the first two lines
else{ txtL[i] = button->fontMetrics().elidedText(txtL[i], Qt::ElideRight, (button->width()-OUTMARGIN) ); }
}
txt = txtL.join("\n");
}else{
txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(button->width()-OUTMARGIN));
//Now split the line in half for the two lines
txt.insert( ((txt.count())/2), "\n");
}
}
if(!txt.contains("\n")){ txt.append("\n "); } //always use two lines
//qDebug() << " - Setting Button Text:" << txt;
button->setText(txt);
QTimer::singleShot(100, this, SLOT(update()) ); //Make sure to re-draw the image in a moment
}
void AppLauncherPlugin::buttonClicked(bool openwith){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path) ){
//prompt for the user to select an application
QList<XDGDesktop*> apps = LSession::handle()->applicationMenu()->currentAppHash()->value("All"); //LXDG::sortDesktopNames( LXDG::systemDesktopFiles() );
QStringList names;
for(int i=0; i<apps.length(); i++){ names << apps[i]->name; }
bool ok = false;
QString app = QInputDialog::getItem(this, tr("Select Application"), tr("Name:"), names, 0, false, &ok);
if(!ok || names.indexOf(app)<0){ return; } //cancelled
this->saveSetting("applicationpath", apps[ names.indexOf(app) ]->filePath);
QTimer::singleShot(0,this, SLOT(loadButton()));
}else if(openwith){
LSession::LaunchApplication("lumina-open -select \""+path+"\"");
}else{
LSession::LaunchApplication("lumina-open \""+path+"\"");
}
}
void AppLauncherPlugin::actionTriggered(QAction *act){
if(act->whatsThis().isEmpty()){ return; }
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
LSession::LaunchApplication("lumina-open -action \""+act->whatsThis()+"\" \""+path+"\"");
}
void AppLauncherPlugin::openWith(){
buttonClicked(true);
}
void AppLauncherPlugin::fileProperties(){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
LSession::LaunchApplication("lumina-fileinfo \""+path+"\"");
}
void AppLauncherPlugin::fileDelete(){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
QFile::remove(path);
}
void AppLauncherPlugin::fileCut(){
QString path = button->whatsThis();
QList<QUrl> urilist; //Also assemble a URI list for cros-app compat (no copy/cut distinguishing)
urilist << QUrl::fromLocalFile(path);
path.prepend("cut::::");
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", path.toLocal8Bit());
dat->setUrls(urilist); //the text/uri-list mimetype - built in Qt conversion/use
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void AppLauncherPlugin::fileCopy(){
QString path = button->whatsThis();
QList<QUrl> urilist; //Also assemble a URI list for cros-app compat (no copy/cut distinguishing)
urilist << QUrl::fromLocalFile(path);
path.prepend("copy::::");
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", path.toLocal8Bit());
dat->setUrls(urilist); //the text/uri-list mimetype - built in Qt conversion/use
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void AppLauncherPlugin::fileRename(){
if(inputDLG == 0){
inputDLG = new QInputDialog(0, Qt::Dialog | Qt::WindowStaysOnTopHint);
inputDLG->setInputMode(QInputDialog::TextInput);
inputDLG->setTextValue(button->whatsThis().section("/",-1));
inputDLG->setTextEchoMode(QLineEdit::Normal);
inputDLG->setLabelText( tr("New Filename") );
connect(inputDLG, SIGNAL(finished(int)), this, SLOT(renameFinished(int)) );
}
inputDLG->showNormal();
}
void AppLauncherPlugin::renameFinished(int result){
QString newname = inputDLG->textValue();
inputDLG->deleteLater();
inputDLG = 0;
qDebug() << "Got Rename Result:" << result << QDialog::Accepted << newname;
if(result != QDialog::Accepted){ return; }
QString newpath = button->whatsThis().section("/",0,-2)+"/"+newname;
qDebug() << "Move File:" << button->whatsThis() << newpath;
if( QFile::rename(button->whatsThis(), newpath) ){
//No special actions here yet - TODO
qDebug() << " - SUCCESS";
}
}
|
#include "AppLauncherPlugin.h"
#include "../../LSession.h"
#include "OutlineToolButton.h"
#include <QClipboard>
#define OUTMARGIN 10 //special margin for fonts due to the outlining effect from the OutlineToolbutton
AppLauncherPlugin::AppLauncherPlugin(QWidget* parent, QString ID) : LDPlugin(parent, ID){
QVBoxLayout *lay = new QVBoxLayout();
inputDLG = 0;
this->setLayout(lay);
lay->setContentsMargins(0,0,0,0);
button = new OutlineToolButton(this);
button->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
button->setAutoRaise(true);
button->setText("...\n..."); //Need to set something here so that initial sizing works properly
button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
lay->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(DoubleClicked()), this, SLOT(buttonClicked()) );
button->setContextMenuPolicy(Qt::NoContextMenu);
watcher = new QFileSystemWatcher(this);
connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT( loadButton()) );
connect(this, SIGNAL(PluginActivated()), this, SLOT(buttonClicked()) ); //in case they use the context menu to launch it.
this->setContextMenu( new QMenu(this) );
connect(this->contextMenu(), SIGNAL(triggered(QAction*)), this, SLOT(actionTriggered(QAction*)) );
loadButton();
//QTimer::singleShot(0,this, SLOT(loadButton()) );
}
void AppLauncherPlugin::Cleanup(){
//This is run only when the plugin was forcibly closed/removed
}
void AppLauncherPlugin::loadButton(){
QString def = this->ID().section("::",1,50).section("---",0,0).simplified();
QString path = this->readSetting("applicationpath",def).toString(); //use the default if necessary
QFileInfo info(path);
this->contextMenu()->clear();
//qDebug() << "Default Application Launcher:" << def << path;
bool ok = QFile::exists(path);
if(!ok){ emit RemovePlugin(this->ID()); return;}
int icosize = this->height()-4 - 2.2*button->fontMetrics().height();
button->setFixedSize( this->width()-4, this->height()-4);
button->setIconSize( QSize(icosize,icosize) );
button->setToolTip("");
QString txt;
if(path.endsWith(".desktop") && ok){
XDGDesktop file(path);
ok = !file.name.isEmpty();
if(!ok){
button->setWhatsThis("");
button->setIcon( QIcon(LXDG::findIcon("quickopen-file","").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
txt = tr("Click to Set");
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
}else{
button->setWhatsThis(file.filePath);
button->setIcon( QIcon(LXDG::findIcon(file.icon,"system-run").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
if(!file.comment.isEmpty()){button->setToolTip(file.comment); }
txt = file.name;
//Put the simple Open action first (no open-with for .desktop files)
this->contextMenu()->addAction(button->icon(), QString(tr("Launch %1")).arg(file.name), this, SLOT(buttonClicked()) );
//See if there are any "actions" listed for this file, and put them in the context menu as needed.
if(!file.actions.isEmpty()){
for(int i=0; i<file.actions.length(); i++){
QAction *tmp = this->contextMenu()->addAction( file.actions[i].name );
tmp->setIcon( LXDG::findIcon(file.actions[i].icon,"quickopen-file") );
tmp->setWhatsThis( file.actions[i].ID );
}
}
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
watcher->addPath(file.filePath); //make sure to update this shortcut if the file changes
}
}else if(ok){
button->setWhatsThis(info.absoluteFilePath());
if(info.isDir()){
if(path.startsWith("/media/")){
//Could add device ID parsing here to determine what "type" of device it is - will be OS-specific though
button->setIcon( LXDG::findIcon("drive-removable-media","") );
}
else{ button->setIcon( LXDG::findIcon("folder","") ); }
}else if(LUtils::imageExtensions().contains(info.suffix().toLower()) ){
QPixmap pix;
if(pix.load(path)){ button->setIcon( QIcon(pix.scaled(256,256)) ); } //max size for thumbnails in memory
else{ button->setIcon( LXDG::findIcon("dialog-cancel","") ); }
}else{
button->setIcon( QIcon(LXDG::findMimeIcon(path).pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
}
txt = info.fileName();
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
watcher->addPath(path); //make sure to update this shortcut if the file changes
}else{
//InValid File
button->setWhatsThis("");
button->setIcon( QIcon(LXDG::findIcon("quickopen","dialog-cancel").pixmap(QSize(icosize,icosize)).scaledToHeight(icosize, Qt::SmoothTransformation) ) );
button->setText( tr("Click to Set") );
if(!watcher->files().isEmpty()){ watcher->removePaths(watcher->files()); }
}
//Now adjust the context menu for the button as needed
if(this->contextMenu()->isEmpty()){
this->contextMenu()->addAction(LXDG::findIcon("document-open",""), tr("Open"), this, SLOT(buttonClicked()) );
this->contextMenu()->addAction(LXDG::findIcon("document-preview",""), tr("Open With"), this, SLOT(openWith()) );
}
this->contextMenu()->addAction(LXDG::findIcon("document-properties",""), tr("View Properties"), this, SLOT(fileProperties()) );
this->contextMenu()->addSection(tr("File Operations"));
if(!path.endsWith(".desktop")){
this->contextMenu()->addAction(LXDG::findIcon("edit-rename","edit-new"), tr("Rename"), this, SLOT(fileRename()) );
}
this->contextMenu()->addAction(LXDG::findIcon("edit-copy",""), tr("Copy"), this, SLOT(fileCopy()) );
if(info.isWritable() || (info.isSymLink() && QFileInfo(info.absolutePath()).isWritable() ) ){
this->contextMenu()->addAction(LXDG::findIcon("edit-cut",""), tr("Cut"), this, SLOT(fileCut()) );
this->contextMenu()->addAction(LXDG::findIcon("document-close",""), tr("Delete"), this, SLOT(fileDelete()) );
}
//If the file is a symlink, put the overlay on the icon
if(info.isSymLink()){
QImage img = button->icon().pixmap(QSize(icosize,icosize)).toImage();
int oSize = icosize/3; //overlay size
QPixmap overlay = LXDG::findIcon("emblem-symbolic-link").pixmap(oSize,oSize).scaled(oSize,oSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QPainter painter(&img);
painter.drawPixmap(icosize-oSize,icosize-oSize,overlay); //put it in the bottom-right corner
button->setIcon( QIcon(QPixmap::fromImage(img)) );
}
//Now adjust the visible text as necessary based on font/grid sizing
if(button->toolTip().isEmpty()){ button->setToolTip(txt); }
//Double check that the visual icon size matches the requested size - otherwise upscale the icon
if(button->fontMetrics().width(txt) > (button->width()-OUTMARGIN) ){
//Text too long, try to show it on two lines
//txt = button->fontMetrics().elidedText(txt, Qt::ElideRight, 2*(button->width()-OUTMARGIN), Qt::TextWordWrap);
txt =txt.section(" ",0,2).replace(" ","\n"); //First take care of any natural breaks
//Go through and combine any lines
if(txt.contains("\n")){
//need to check each line
QStringList txtL = txt.split("\n");
for(int i=0; i<txtL.length(); i++){
if(( i+1<txtL.length()) && (button->fontMetrics().width(txtL[i]) < button->width()/2) ){
txtL[i] = txtL[i]+" "+txtL[i+1];
txtL.removeAt(i+1);
}
}
txt = txtL.join("\n").section("\n",0,2);
}
if(txt.contains("\n")){
//need to check each line
QStringList txtL = txt.split("\n");
for(int i=0; i<txtL.length(); i++){
if(i>1){ txtL.removeAt(i); i--; } //Only take the first two lines
else{ txtL[i] = button->fontMetrics().elidedText(txtL[i], Qt::ElideRight, (button->width()-OUTMARGIN) ); }
}
txt = txtL.join("\n");
}else{
txt = this->fontMetrics().elidedText(txt,Qt::ElideRight, 2*(button->width()-OUTMARGIN));
//Now split the line in half for the two lines
txt.insert( ((txt.count())/2), "\n");
}
}
if(!txt.contains("\n")){ txt.append("\n "); } //always use two lines
//qDebug() << " - Setting Button Text:" << txt;
button->setText(txt);
QTimer::singleShot(100, this, SLOT(update()) ); //Make sure to re-draw the image in a moment
}
void AppLauncherPlugin::buttonClicked(bool openwith){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path) ){
//prompt for the user to select an application
QList<XDGDesktop*> apps = LSession::handle()->applicationMenu()->currentAppHash()->value("All"); //LXDG::sortDesktopNames( LXDG::systemDesktopFiles() );
QStringList names;
for(int i=0; i<apps.length(); i++){ names << apps[i]->name; }
bool ok = false;
QString app = QInputDialog::getItem(this, tr("Select Application"), tr("Name:"), names, 0, false, &ok);
if(!ok || names.indexOf(app)<0){ return; } //cancelled
this->saveSetting("applicationpath", apps[ names.indexOf(app) ]->filePath);
QTimer::singleShot(0,this, SLOT(loadButton()));
}else if(openwith){
LSession::LaunchApplication("lumina-open -select \""+path+"\"");
}else{
LSession::LaunchApplication("lumina-open \""+path+"\"");
}
}
void AppLauncherPlugin::actionTriggered(QAction *act){
if(act->whatsThis().isEmpty()){ return; }
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
LSession::LaunchApplication("lumina-open -action \""+act->whatsThis()+"\" \""+path+"\"");
}
void AppLauncherPlugin::openWith(){
buttonClicked(true);
}
void AppLauncherPlugin::fileProperties(){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
LSession::LaunchApplication("lumina-fileinfo \""+path+"\"");
}
void AppLauncherPlugin::fileDelete(){
QString path = button->whatsThis();
if(path.isEmpty() || !QFile::exists(path)){ return; } //invalid file
QFile::remove(path);
}
void AppLauncherPlugin::fileCut(){
QString path = button->whatsThis();
QList<QUrl> urilist; //Also assemble a URI list for cros-app compat (no copy/cut distinguishing)
urilist << QUrl::fromLocalFile(path);
path.prepend("cut::::");
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", path.toLocal8Bit());
dat->setUrls(urilist); //the text/uri-list mimetype - built in Qt conversion/use
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void AppLauncherPlugin::fileCopy(){
QString path = button->whatsThis();
QList<QUrl> urilist; //Also assemble a URI list for cros-app compat (no copy/cut distinguishing)
urilist << QUrl::fromLocalFile(path);
path.prepend("copy::::");
//Now save that data to the global clipboard
QMimeData *dat = new QMimeData;
dat->clear();
dat->setData("x-special/lumina-copied-files", path.toLocal8Bit());
dat->setUrls(urilist); //the text/uri-list mimetype - built in Qt conversion/use
QApplication::clipboard()->clear();
QApplication::clipboard()->setMimeData(dat);
}
void AppLauncherPlugin::fileRename(){
if(inputDLG == 0){
inputDLG = new QInputDialog(0, Qt::Dialog | Qt::WindowStaysOnTopHint);
inputDLG->setInputMode(QInputDialog::TextInput);
inputDLG->setTextValue(button->whatsThis().section("/",-1));
inputDLG->setTextEchoMode(QLineEdit::Normal);
inputDLG->setLabelText( tr("New Filename") );
connect(inputDLG, SIGNAL(finished(int)), this, SLOT(renameFinished(int)) );
}
inputDLG->showNormal();
}
void AppLauncherPlugin::renameFinished(int result){
QString newname = inputDLG->textValue();
inputDLG->deleteLater();
inputDLG = 0;
qDebug() << "Got Rename Result:" << result << QDialog::Accepted << newname;
if(result != QDialog::Accepted){ return; }
QString newpath = button->whatsThis().section("/",0,-2)+"/"+newname;
qDebug() << "Move File:" << button->whatsThis() << newpath;
if( QFile::rename(button->whatsThis(), newpath) ){
//No special actions here yet - TODO
qDebug() << " - SUCCESS";
}
}
|
Make sure the cut/delete options for desktop icons are still possible if the "file" is actually a symlink somewhere else on the system (will just remove the symlink)
|
Make sure the cut/delete options for desktop icons are still possible if the "file" is actually a symlink somewhere else on the system (will just remove the symlink)
|
C++
|
bsd-3-clause
|
sasongko26/lumina,sasongko26/lumina,cpforbes/lumina,pcbsd/lumina,sasongko26/lumina,cpforbes/lumina,cpforbes/lumina,sasongko26/lumina,cpforbes/lumina,sasongko26/lumina,pcbsd/lumina,cpforbes/lumina,trueos/lumina,sasongko26/lumina,sasongko26/lumina,trueos/lumina,pcbsd/lumina,trueos/lumina,trueos/lumina,trueos/lumina,trueos/lumina,cpforbes/lumina,trueos/lumina,sasongko26/lumina,cpforbes/lumina,cpforbes/lumina,trueos/lumina
|
b4e9fdb80b1f3df466f1a26db4f7007b03b72348
|
DiscreteFourierTransform/DiscreteFourierTransform/DiscreteFourierTransform.cpp
|
DiscreteFourierTransform/DiscreteFourierTransform/DiscreteFourierTransform.cpp
|
#include <cmath>
#include <iostream>
using namespace std;
#define M_PI 3.1415926
// naive implementation of discrete fourier transform
// can be used efficiently for small inputs
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag);
// my first implementation of fast fourier transform
// note that length has to be a power of 2
void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag);
int _tmain(int argc, _TCHAR* argv[])q
{
double input_real[4];
double input_imag[4];
double output_real[4];
double output_imag[4];
double temp_real[4];
double temp_imag[4];
input_real[0] = 1;
input_real[1] = 2;
input_real[2] = 3;
input_real[3] = 4;
input_imag[0] = 0;
input_imag[1] = 0;
input_imag[2] = 0;
input_imag[3] = 0;
// discrete_fourier_transform(4, input_real, input_imag, output_real, output_imag);
fast_fourier_transform(4, input_real, input_imag, output_real, output_imag, temp_real, temp_imag);
for (unsigned int i = 0; i < 4; i++)
{
cout << output_real[i] << " " << output_imag[i] << "j" << endl;
}
return 0;
}
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag)
{
for (unsigned int k = 0; k < length; k++)
{
output_real[k] = 0;
output_imag[k] = 0;
for (unsigned int n = 0; n < length; n++)
{
double angle = -2 * M_PI / length * n * k;
double complex_real = cos(angle);
double complex_imag = sin(angle);
output_real[k] += input_real[n] * complex_real - input_imag[n] * complex_imag;
output_imag[k] += input_real[n] * complex_imag + input_imag[n] * complex_real;
}
}
}
void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag)
{
// Step 1: Base case handling
if (length == 1)
{
output_real[0] = input_real[0];
output_imag[0] = input_imag[0];
return;
}
// Step 1: Decimation in time
unsigned int half = length / 2;
for (unsigned int i = 0; i < half; i++)
{
temp_real[i] = input_real[2 * i];
temp_imag[i] = input_imag[2 * i];
temp_real[i + half] = input_real[2 * i + 1];
temp_imag[i + half] = input_imag[2 * i + 1];
}
for (unsigned int i = 0; i < length; i++)
{
input_real[i] = temp_real[i];
input_imag[i] = temp_imag[i];
}
// Step 2: Recursive calls
fast_fourier_transform(half, input_real , input_imag , temp_real , temp_imag , output_real , output_imag );
fast_fourier_transform(half, input_real + half, input_imag + half, temp_real + half, temp_imag + half, output_real + half, output_imag + half);
// Step 3: Merge results
for (unsigned int i = 0; i < half; i++)
{
double angle = -2 * M_PI / length * i;
double cosine = cos(angle);
double sine = sin(angle);
output_real[i] = temp_real[i] + temp_real[i + half] * cosine - temp_imag[i + half] * sine ;
output_imag[i] = temp_imag[i] + temp_real[i + half] * sine + temp_imag[i + half] * cosine;
output_real[i + half] = temp_real[i] - temp_real[i + half] * cosine + temp_imag[i + half] * sine ;
output_imag[i + half] = temp_imag[i] - temp_real[i + half] * sine - temp_imag[i + half] * cosine;
}
}
|
#include "stdafx.h"
#include <cmath>
#include <iostream>
using namespace std;
#define M_PI 3.1415926
// naive implementation of discrete fourier transform
// can be used efficiently for small inputs
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag);
// my first implementation of fast fourier transform
// note that length has to be a power of 2
void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag);
int _tmain(int argc, _TCHAR* argv[])
{
double input_real[4];
double input_imag[4];
double output_real[4];
double output_imag[4];
double temp_real[4];
double temp_imag[4];
input_real[0] = 1;
input_real[1] = 2;
input_real[2] = 3;
input_real[3] = 4;
input_imag[0] = 0;
input_imag[1] = 0;
input_imag[2] = 0;
input_imag[3] = 0;
// discrete_fourier_transform(4, input_real, input_imag, output_real, output_imag);
fast_fourier_transform(4, input_real, input_imag, output_real, output_imag, temp_real, temp_imag);
for (unsigned int i = 0; i < 4; i++)
{
cout << output_real[i] << " " << output_imag[i] << "j" << endl;
}
return 0;
}
void discrete_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag)
{
for (unsigned int k = 0; k < length; k++)
{
output_real[k] = 0;
output_imag[k] = 0;
for (unsigned int n = 0; n < length; n++)
{
double angle = -2 * M_PI / length * n * k;
double complex_real = cos(angle);
double complex_imag = sin(angle);
output_real[k] += input_real[n] * complex_real - input_imag[n] * complex_imag;
output_imag[k] += input_real[n] * complex_imag + input_imag[n] * complex_real;
}
}
}
void fast_fourier_transform(unsigned int length, double* input_real, double* input_imag, double* output_real, double* output_imag, double* temp_real, double* temp_imag)
{
// Step 1: Base case handling
if (length == 1)
{
output_real[0] = input_real[0];
output_imag[0] = input_imag[0];
return;
}
// Step 1: Decimation in time
unsigned int half = length / 2;
for (unsigned int i = 0; i < half; i++)
{
temp_real[i] = input_real[2 * i];
temp_imag[i] = input_imag[2 * i];
temp_real[i + half] = input_real[2 * i + 1];
temp_imag[i + half] = input_imag[2 * i + 1];
}
for (unsigned int i = 0; i < length; i++)
{
input_real[i] = temp_real[i];
input_imag[i] = temp_imag[i];
}
// Step 2: Recursive calls
fast_fourier_transform(half, input_real , input_imag , temp_real , temp_imag , output_real , output_imag );
fast_fourier_transform(half, input_real + half, input_imag + half, temp_real + half, temp_imag + half, output_real + half, output_imag + half);
// Step 3: Merge results
for (unsigned int i = 0; i < half; i++)
{
double angle = -2 * M_PI / length * i;
double cosine = cos(angle);
double sine = sin(angle);
output_real[i] = temp_real[i] + temp_real[i + half] * cosine - temp_imag[i + half] * sine ;
output_imag[i] = temp_imag[i] + temp_real[i + half] * sine + temp_imag[i + half] * cosine;
output_real[i + half] = temp_real[i] - temp_real[i + half] * cosine + temp_imag[i + half] * sine ;
output_imag[i + half] = temp_imag[i] - temp_real[i + half] * sine - temp_imag[i + half] * cosine;
}
}
|
Fix bug
|
Fix bug
|
C++
|
mit
|
cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab,cshung/MiscLab
|
fcf0aa7f6f6242238ad56ce064ab35436ae9773f
|
demos/scheduling_group_demo.cc
|
demos/scheduling_group_demo.cc
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 Scylla DB Ltd
*/
#include <seastar/core/app-template.hh>
#include <seastar/core/future.hh>
#include <seastar/core/scheduling.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/reactor.hh>
#include <seastar/util/defer.hh>
#include <fmt/printf.h>
#include <chrono>
#include <cmath>
using namespace seastar;
using namespace std::chrono_literals;
template <typename Func, typename Duration>
future<>
compute_intensive_task(Duration duration, unsigned& counter, Func func) {
auto end = std::chrono::steady_clock::now() + duration;
while (std::chrono::steady_clock::now() < end) {
func();
}
++counter;
return make_ready_future<>();
}
future<>
heavy_task(unsigned& counter) {
return compute_intensive_task(1ms, counter, [] {
static thread_local double x = 1;
x = std::exp(x) / 3;
});
}
future<>
light_task(unsigned& counter) {
return compute_intensive_task(100us, counter, [] {
static thread_local double x = 0.1;
x = std::log(x + 1);
});
}
future<>
medium_task(unsigned& counter) {
return compute_intensive_task(400us, counter, [] {
static thread_local double x = 0.1;
x = std::cos(x);
});
}
using done_func = std::function<bool ()>;
future<>
run_compute_intensive_tasks(seastar::scheduling_group sg, done_func done, unsigned concurrency, unsigned& counter, std::function<future<> (unsigned& counter)> task) {
return seastar::async([task, sg, concurrency, done, &counter] {
while (!done()) {
parallel_for_each(boost::irange(0u, concurrency), [task, sg, &counter] (unsigned i) {
return with_scheduling_group(sg, [task, &counter] {
return task(counter);
});
}).get();
}
});
}
future<>
run_compute_intensive_tasks_in_threads(seastar::scheduling_group sg, done_func done, unsigned concurrency, unsigned& counter, std::function<future<> (unsigned& counter)> task) {
auto attr = seastar::thread_attributes();
attr.sched_group = sg;
return parallel_for_each(boost::irange(0u, concurrency), [attr, done, &counter, task] (unsigned i) {
return seastar::async(attr, [done, &counter, task] {
while (!done()) {
task(counter).get();
}
});
});
}
future<>
run_with_duty_cycle(float utilization, std::chrono::steady_clock::duration period, done_func done, std::function<future<> (done_func done)> task) {
return seastar::async([=] {
bool duty_toggle = true;
auto t0 = std::chrono::steady_clock::now();
condition_variable cv;
timer<> tmr_on([&] { duty_toggle = true; cv.signal(); });
timer<> tmr_off([&] { duty_toggle = false; });
tmr_on.arm(t0, period);
tmr_off.arm(t0 + std::chrono::duration_cast<decltype(t0)::duration>(period * utilization), period);
auto combined_done = [&] {
return done() || !duty_toggle;
};
while (!done()) {
while (!combined_done()) {
task(std::cref(combined_done)).get();
}
cv.wait([&] {
return done() || duty_toggle;
}).get();
}
tmr_on.cancel();
tmr_off.cancel();
});
}
#include <fenv.h>
template <typename T>
auto var_fn(T& var) {
return [&var] { return var; };
}
int main(int ac, char** av) {
app_template app;
return app.run(ac, av, [] {
return seastar::async([] {
auto sg100 = seastar::create_scheduling_group("sg100", 100).get0();
auto ksg100 = seastar::defer([&] { seastar::destroy_scheduling_group(sg100).get(); });
auto sg20 = seastar::create_scheduling_group("sg20", 20).get0();
auto ksg20 = seastar::defer([&] { seastar::destroy_scheduling_group(sg20).get(); });
auto sg50 = seastar::create_scheduling_group("sg50", 50).get0();
auto ksg50 = seastar::defer([&] { seastar::destroy_scheduling_group(sg50).get(); });
bool done = false;
auto end = timer<>([&done] {
done = true;
});
end.arm(10s);
unsigned ctr100 = 0, ctr20 = 0, ctr50 = 0;
fmt::print("running three scheduling groups with 100% duty cycle each:\n");
when_all(
run_compute_intensive_tasks(sg100, var_fn(done), 5, ctr100, heavy_task),
run_compute_intensive_tasks(sg20, var_fn(done), 3, ctr20, light_task),
run_compute_intensive_tasks_in_threads(sg50, var_fn(done), 2, ctr50, medium_task)
).get();
fmt::print("{:10} {:15} {:10} {:12} {:8}\n", "shares", "task_time (us)", "executed", "runtime (ms)", "vruntime");
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 100, 1000, ctr100, ctr100 * 1000 / 1000, ctr100 * 1000 / 1000 / 100.);
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 20, 100, ctr20, ctr20 * 100 / 1000, ctr20 * 100 / 1000 / 20.);
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 50, 400, ctr50, ctr50 * 400 / 1000, ctr50 * 400 / 1000 / 50.);
fmt::print("\n");
fmt::print("running two scheduling groups with 100%/50% duty cycles (period=1s:\n");
unsigned ctr100_2 = 0, ctr50_2 = 0;
done = false;
end.arm(10s);
when_all(
run_compute_intensive_tasks(sg50, var_fn(done), 5, ctr50_2, heavy_task),
run_with_duty_cycle(0.5, 1s, var_fn(done), [=, &ctr100_2] (done_func done) {
return run_compute_intensive_tasks(sg100, done, 4, ctr100_2, heavy_task);
})
).get();
fmt::print("{:10} {:10} {:15} {:10} {:12} {:8}\n", "shares", "duty", "task_time (us)", "executed", "runtime (ms)", "vruntime");
fmt::print("{:10d} {:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 100, 50, 1000, ctr100_2, ctr100_2 * 1000 / 1000, ctr100_2 * 1000 / 1000 / 100.);
fmt::print("{:10d} {:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 50, 100, 400, ctr50_2, ctr50_2 * 1000 / 1000, ctr50_2 * 1000 / 1000 / 50.);
return 0;
});
});
}
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2016 Scylla DB Ltd
*/
#include <seastar/core/app-template.hh>
#include <seastar/core/future.hh>
#include <seastar/core/scheduling.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/reactor.hh>
#include <seastar/util/defer.hh>
#include <fmt/printf.h>
#include <chrono>
#include <cmath>
using namespace seastar;
using namespace std::chrono_literals;
template <typename Func, typename Duration>
future<>
compute_intensive_task(Duration duration, unsigned& counter, Func func) {
auto end = std::chrono::steady_clock::now() + duration;
while (std::chrono::steady_clock::now() < end) {
func();
}
++counter;
return make_ready_future<>();
}
future<>
heavy_task(unsigned& counter) {
return compute_intensive_task(1ms, counter, [] {
static thread_local double x = 1;
x = std::exp(x) / 3;
});
}
future<>
light_task(unsigned& counter) {
return compute_intensive_task(100us, counter, [] {
static thread_local double x = 0.1;
x = std::log(x + 1);
});
}
future<>
medium_task(unsigned& counter) {
return compute_intensive_task(400us, counter, [] {
static thread_local double x = 0.1;
x = std::cos(x);
});
}
using done_func = std::function<bool ()>;
future<>
run_compute_intensive_tasks(seastar::scheduling_group sg, done_func done, unsigned concurrency, unsigned& counter, std::function<future<> (unsigned& counter)> task) {
return seastar::async([task, sg, concurrency, done, &counter] {
while (!done()) {
parallel_for_each(boost::irange(0u, concurrency), [task, sg, &counter] (unsigned i) {
return with_scheduling_group(sg, [task, &counter] {
return task(counter);
});
}).get();
thread::maybe_yield();
}
});
}
future<>
run_compute_intensive_tasks_in_threads(seastar::scheduling_group sg, done_func done, unsigned concurrency, unsigned& counter, std::function<future<> (unsigned& counter)> task) {
auto attr = seastar::thread_attributes();
attr.sched_group = sg;
return parallel_for_each(boost::irange(0u, concurrency), [attr, done, &counter, task] (unsigned i) {
return seastar::async(attr, [done, &counter, task] {
while (!done()) {
task(counter).get();
thread::maybe_yield();
}
});
});
}
future<>
run_with_duty_cycle(float utilization, std::chrono::steady_clock::duration period, done_func done, std::function<future<> (done_func done)> task) {
return seastar::async([=] {
bool duty_toggle = true;
auto t0 = std::chrono::steady_clock::now();
condition_variable cv;
timer<> tmr_on([&] { duty_toggle = true; cv.signal(); });
timer<> tmr_off([&] { duty_toggle = false; });
tmr_on.arm(t0, period);
tmr_off.arm(t0 + std::chrono::duration_cast<decltype(t0)::duration>(period * utilization), period);
auto combined_done = [&] {
return done() || !duty_toggle;
};
while (!done()) {
while (!combined_done()) {
task(std::cref(combined_done)).get();
thread::maybe_yield();
}
cv.wait([&] {
return done() || duty_toggle;
}).get();
}
tmr_on.cancel();
tmr_off.cancel();
});
}
#include <fenv.h>
template <typename T>
auto var_fn(T& var) {
return [&var] { return var; };
}
int main(int ac, char** av) {
app_template app;
return app.run(ac, av, [] {
return seastar::async([] {
auto sg100 = seastar::create_scheduling_group("sg100", 100).get0();
auto ksg100 = seastar::defer([&] { seastar::destroy_scheduling_group(sg100).get(); });
auto sg20 = seastar::create_scheduling_group("sg20", 20).get0();
auto ksg20 = seastar::defer([&] { seastar::destroy_scheduling_group(sg20).get(); });
auto sg50 = seastar::create_scheduling_group("sg50", 50).get0();
auto ksg50 = seastar::defer([&] { seastar::destroy_scheduling_group(sg50).get(); });
bool done = false;
auto end = timer<>([&done] {
done = true;
});
end.arm(10s);
unsigned ctr100 = 0, ctr20 = 0, ctr50 = 0;
fmt::print("running three scheduling groups with 100% duty cycle each:\n");
when_all(
run_compute_intensive_tasks(sg100, var_fn(done), 5, ctr100, heavy_task),
run_compute_intensive_tasks(sg20, var_fn(done), 3, ctr20, light_task),
run_compute_intensive_tasks_in_threads(sg50, var_fn(done), 2, ctr50, medium_task)
).get();
fmt::print("{:10} {:15} {:10} {:12} {:8}\n", "shares", "task_time (us)", "executed", "runtime (ms)", "vruntime");
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 100, 1000, ctr100, ctr100 * 1000 / 1000, ctr100 * 1000 / 1000 / 100.);
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 20, 100, ctr20, ctr20 * 100 / 1000, ctr20 * 100 / 1000 / 20.);
fmt::print("{:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 50, 400, ctr50, ctr50 * 400 / 1000, ctr50 * 400 / 1000 / 50.);
fmt::print("\n");
fmt::print("running two scheduling groups with 100%/50% duty cycles (period=1s:\n");
unsigned ctr100_2 = 0, ctr50_2 = 0;
done = false;
end.arm(10s);
when_all(
run_compute_intensive_tasks(sg50, var_fn(done), 5, ctr50_2, heavy_task),
run_with_duty_cycle(0.5, 1s, var_fn(done), [=, &ctr100_2] (done_func done) {
return run_compute_intensive_tasks(sg100, done, 4, ctr100_2, heavy_task);
})
).get();
fmt::print("{:10} {:10} {:15} {:10} {:12} {:8}\n", "shares", "duty", "task_time (us)", "executed", "runtime (ms)", "vruntime");
fmt::print("{:10d} {:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 100, 50, 1000, ctr100_2, ctr100_2 * 1000 / 1000, ctr100_2 * 1000 / 1000 / 100.);
fmt::print("{:10d} {:10d} {:15d} {:10d} {:12d} {:8.2f}\n", 50, 100, 400, ctr50_2, ctr50_2 * 1000 / 1000, ctr50_2 * 1000 / 1000 / 50.);
return 0;
});
});
}
|
add explicit yields since future::get() no longer does
|
scheduling_group_demo: add explicit yields since future::get() no longer does
With 7e2483a, future::get() is no longer an implicit yield. This causes
the threads spawned in scheduling_group_demo to never yield and the demo
no longer works.
Adding explicit yields makes it work again.
Message-Id: <[email protected]>
|
C++
|
apache-2.0
|
scylladb/seastar,scylladb/seastar,syuu1228/seastar,dreamsxin/seastar,syuu1228/seastar,cloudius-systems/seastar,cloudius-systems/seastar,dreamsxin/seastar,avikivity/seastar,avikivity/seastar,cloudius-systems/seastar,dreamsxin/seastar,scylladb/seastar,avikivity/seastar,syuu1228/seastar
|
ad7f3eb90a981df77b406722b909846acd9fc5b7
|
eval/src/tests/instruction/join_with_number/join_with_number_function_test.cpp
|
eval/src/tests/instruction/join_with_number/join_with_number_function_test.cpp
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/eval/eval/test/param_variants.h>
#include <vespa/eval/instruction/join_with_number_function.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
using vespalib::make_string_short::fmt;
using Primary = JoinWithNumberFunction::Primary;
namespace vespalib::eval {
std::ostream &operator<<(std::ostream &os, Primary primary)
{
switch(primary) {
case Primary::LHS: return os << "LHS";
case Primary::RHS: return os << "RHS";
}
abort();
}
}
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
EvalFixture::ParamRepo make_params() {
auto repo = EvalFixture::ParamRepo()
.add("a", spec(1.5))
.add("number", spec(2.5))
.add("dense", spec({y(5)}, N()))
.add_matrix("x", 3, "y", 5);
add_variants(repo, "mixed", {x({"a"}),y(5),z({"d","e"})}, N());
add_variants(repo, "sparse", {x({"a","b","c"}),z({"d","e","f"})}, N());
return repo;
}
EvalFixture::ParamRepo param_repo = make_params();
void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) {
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<JoinWithNumberFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
EXPECT_EQUAL(info[0]->primary(), primary);
EXPECT_EQUAL(info[0]->inplace(), inplace);
int p_inplace = inplace ? ((primary == Primary::LHS) ? 0 : 1) : -1;
EXPECT_TRUE((p_inplace == -1) || (fixture.num_params() > size_t(p_inplace)));
for (size_t i = 0; i < fixture.num_params(); ++i) {
if (i == size_t(p_inplace)) {
EXPECT_EQUAL(fixture.get_param(i), fixture.result());
} else {
EXPECT_NOT_EQUAL(fixture.get_param(i), fixture.result());
}
}
}
void verify_not_optimized(const vespalib::string &expr) {
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<JoinWithNumberFunction>();
EXPECT_TRUE(info.empty());
}
TEST("require that dense number join can be optimized") {
TEST_DO(verify_optimized("x3y5+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+x3y5", Primary::RHS, false));
TEST_DO(verify_optimized("x3y5f*a", Primary::LHS, false));
TEST_DO(verify_optimized("a*x3y5f", Primary::RHS, false));
}
TEST("require that dense number join can be inplace") {
TEST_DO(verify_optimized("@x3y5*a", Primary::LHS, true));
TEST_DO(verify_optimized("a*@x3y5", Primary::RHS, true));
TEST_DO(verify_optimized("@x3y5f+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@x3y5f", Primary::RHS, true));
}
TEST("require that asymmetric operations work") {
TEST_DO(verify_optimized("x3y5/a", Primary::LHS, false));
TEST_DO(verify_optimized("a/x3y5", Primary::RHS, false));
TEST_DO(verify_optimized("x3y5f-a", Primary::LHS, false));
TEST_DO(verify_optimized("a-x3y5f", Primary::RHS, false));
}
TEST("require that sparse number join can be optimized") {
TEST_DO(verify_optimized("sparse+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+sparse", Primary::RHS, false));
TEST_DO(verify_optimized("sparse<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<sparse", Primary::RHS, false));
TEST_DO(verify_optimized("sparse_f+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+sparse_f", Primary::RHS, false));
TEST_DO(verify_optimized("sparse_f<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<sparse_f", Primary::RHS, false));
}
TEST("require that sparse number join can be inplace") {
TEST_DO(verify_optimized("@sparse+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@sparse_f", Primary::RHS, true));
TEST_DO(verify_optimized("@sparse_f<a", Primary::LHS, true));
TEST_DO(verify_optimized("a<@sparse", Primary::RHS, true));
}
TEST("require that mixed number join can be optimized") {
TEST_DO(verify_optimized("mixed+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+mixed", Primary::RHS, false));
TEST_DO(verify_optimized("mixed<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<mixed", Primary::RHS, false));
TEST_DO(verify_optimized("mixed_f+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+mixed_f", Primary::RHS, false));
TEST_DO(verify_optimized("mixed_f<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<mixed_f", Primary::RHS, false));
}
TEST("require that mixed number join can be inplace") {
TEST_DO(verify_optimized("@mixed+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@mixed_f", Primary::RHS, true));
TEST_DO(verify_optimized("@mixed_f<a", Primary::LHS, true));
TEST_DO(verify_optimized("a<@mixed", Primary::RHS, true));
}
TEST("require that all appropriate cases are optimized, others not") {
int optimized = 0;
for (vespalib::string lhs: {"number", "dense", "sparse", "mixed"}) {
for (vespalib::string rhs: {"number", "dense", "sparse", "mixed"}) {
auto expr = fmt("%s+%s", lhs.c_str(), rhs.c_str());
TEST_STATE(expr.c_str());
if ((lhs == "number") != (rhs == "number")) {
auto which = (rhs == "number") ? Primary::LHS : Primary::RHS;
verify_optimized(expr, which, false);
++optimized;
} else {
verify_not_optimized(expr);
}
}
}
EXPECT_EQUAL(optimized, 6);
}
TEST_MAIN() { TEST_RUN_ALL(); }
|
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/eval/instruction/join_with_number_function.h>
#include <vespa/vespalib/util/stringfmt.h>
using namespace vespalib;
using namespace vespalib::eval;
using namespace vespalib::eval::test;
using namespace vespalib::eval::tensor_function;
using vespalib::make_string_short::fmt;
using Primary = JoinWithNumberFunction::Primary;
namespace vespalib::eval {
std::ostream &operator<<(std::ostream &os, Primary primary)
{
switch(primary) {
case Primary::LHS: return os << "LHS";
case Primary::RHS: return os << "RHS";
}
abort();
}
}
const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();
TensorSpec spec(double v) { return TensorSpec("double").add({}, v); }
EvalFixture::ParamRepo make_params() {
auto repo = EvalFixture::ParamRepo()
.add("a", spec(1.5))
.add("number", spec(2.5))
.add("dense", GenSpec().idx("y", 5).gen())
.add_variants("x3y5", GenSpec().idx("x", 3).idx("y", 5))
.add_variants("mixed", GenSpec().map("x", {"a"}).idx("y", 5).map("z", {"d","e"}))
.add_variants("sparse", GenSpec().map("x", {"a","b","c"}).map("z", {"d","e","f"}));
return repo;
}
EvalFixture::ParamRepo param_repo = make_params();
void verify_optimized(const vespalib::string &expr, Primary primary, bool inplace) {
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<JoinWithNumberFunction>();
ASSERT_EQUAL(info.size(), 1u);
EXPECT_TRUE(info[0]->result_is_mutable());
EXPECT_EQUAL(info[0]->primary(), primary);
EXPECT_EQUAL(info[0]->inplace(), inplace);
int p_inplace = inplace ? ((primary == Primary::LHS) ? 0 : 1) : -1;
EXPECT_TRUE((p_inplace == -1) || (fixture.num_params() > size_t(p_inplace)));
for (size_t i = 0; i < fixture.num_params(); ++i) {
if (i == size_t(p_inplace)) {
EXPECT_EQUAL(fixture.get_param(i), fixture.result());
} else {
EXPECT_NOT_EQUAL(fixture.get_param(i), fixture.result());
}
}
}
void verify_not_optimized(const vespalib::string &expr) {
EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
EvalFixture fixture(prod_factory, expr, param_repo, true);
EXPECT_EQUAL(fixture.result(), EvalFixture::ref(expr, param_repo));
EXPECT_EQUAL(fixture.result(), slow_fixture.result());
auto info = fixture.find_all<JoinWithNumberFunction>();
EXPECT_TRUE(info.empty());
}
TEST("require that dense number join can be optimized") {
TEST_DO(verify_optimized("x3y5+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+x3y5", Primary::RHS, false));
TEST_DO(verify_optimized("x3y5_f*a", Primary::LHS, false));
TEST_DO(verify_optimized("a*x3y5_f", Primary::RHS, false));
}
TEST("require that dense number join can be inplace") {
TEST_DO(verify_optimized("@x3y5*a", Primary::LHS, true));
TEST_DO(verify_optimized("a*@x3y5", Primary::RHS, true));
TEST_DO(verify_optimized("@x3y5_f+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@x3y5_f", Primary::RHS, true));
}
TEST("require that asymmetric operations work") {
TEST_DO(verify_optimized("x3y5/a", Primary::LHS, false));
TEST_DO(verify_optimized("a/x3y5", Primary::RHS, false));
TEST_DO(verify_optimized("x3y5_f-a", Primary::LHS, false));
TEST_DO(verify_optimized("a-x3y5_f", Primary::RHS, false));
}
TEST("require that sparse number join can be optimized") {
TEST_DO(verify_optimized("sparse+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+sparse", Primary::RHS, false));
TEST_DO(verify_optimized("sparse<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<sparse", Primary::RHS, false));
TEST_DO(verify_optimized("sparse_f+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+sparse_f", Primary::RHS, false));
TEST_DO(verify_optimized("sparse_f<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<sparse_f", Primary::RHS, false));
}
TEST("require that sparse number join can be inplace") {
TEST_DO(verify_optimized("@sparse+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@sparse_f", Primary::RHS, true));
TEST_DO(verify_optimized("@sparse_f<a", Primary::LHS, true));
TEST_DO(verify_optimized("a<@sparse", Primary::RHS, true));
}
TEST("require that mixed number join can be optimized") {
TEST_DO(verify_optimized("mixed+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+mixed", Primary::RHS, false));
TEST_DO(verify_optimized("mixed<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<mixed", Primary::RHS, false));
TEST_DO(verify_optimized("mixed_f+a", Primary::LHS, false));
TEST_DO(verify_optimized("a+mixed_f", Primary::RHS, false));
TEST_DO(verify_optimized("mixed_f<a", Primary::LHS, false));
TEST_DO(verify_optimized("a<mixed_f", Primary::RHS, false));
}
TEST("require that mixed number join can be inplace") {
TEST_DO(verify_optimized("@mixed+a", Primary::LHS, true));
TEST_DO(verify_optimized("a+@mixed_f", Primary::RHS, true));
TEST_DO(verify_optimized("@mixed_f<a", Primary::LHS, true));
TEST_DO(verify_optimized("a<@mixed", Primary::RHS, true));
}
TEST("require that all appropriate cases are optimized, others not") {
int optimized = 0;
for (vespalib::string lhs: {"number", "dense", "sparse", "mixed"}) {
for (vespalib::string rhs: {"number", "dense", "sparse", "mixed"}) {
auto expr = fmt("%s+%s", lhs.c_str(), rhs.c_str());
TEST_STATE(expr.c_str());
if ((lhs == "number") != (rhs == "number")) {
auto which = (rhs == "number") ? Primary::LHS : Primary::RHS;
verify_optimized(expr, which, false);
++optimized;
} else {
verify_not_optimized(expr);
}
}
}
EXPECT_EQUAL(optimized, 6);
}
TEST_MAIN() { TEST_RUN_ALL(); }
|
use GenSpec in join_with_number_function_test
|
use GenSpec in join_with_number_function_test
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
cba990cd52dcc1477292fbe983614a039c83ce48
|
dstar-lite/src/dstar_from_grid.cpp
|
dstar-lite/src/dstar_from_grid.cpp
|
/* dstar_from_grid.cpp
*/
#ifdef MACOS
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <unistd.h>
#include "dstar_lite/dstar.h"
int hh, ww;
int window;
Dstar *dstar;
int scale = 50;
int mbutton = 0;
int mstate = 0;
bool b_autoreplan = false;
void InitGL(int Width, int Height) {
hh = Height;
ww = Width;
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0);
glViewport(0,0,Width,Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Width,0,Height,-100,100);
glMatrixMode(GL_MODELVIEW);
}
void ReSizeGLScene(int Width, int Height) {
hh = Height;
ww = Width;
glViewport(0,0,Width,Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Width,0,Height,-100,100);
glMatrixMode(GL_MODELVIEW);
}
void DrawGLScene() {
usleep(100);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glScaled(scale,scale,1);
if (b_autoreplan) dstar->replan();
dstar->draw();
glPopMatrix();
glutSwapBuffers();
}
void keyPressed(unsigned char key, int x, int y) {
usleep(100);
switch(key) {
case 'q':
case 'Q':
glutDestroyWindow(window);
exit(0);
break;
case 'r':
case 'R':
dstar->replan();
break;
case 'a':
case 'A':
b_autoreplan = !b_autoreplan;
break;
case 'c':
case 'C':
dstar->init(1, 1, 3, 3);
break;
}
}
void mouseFunc(int button, int state, int x, int y) {
y = hh -y+scale/2;
x += scale/2;
mbutton = button;
if ((mstate = state) == GLUT_DOWN) {
if (button == GLUT_LEFT_BUTTON) {
dstar->updateCell(x/scale, y/scale, -1);
} else if (button == GLUT_RIGHT_BUTTON) {
dstar->updateStart(x/scale, y/scale);
} else if (button == GLUT_MIDDLE_BUTTON) {
dstar->updateGoal(x/scale, y/scale);
}
}
}
void mouseMotionFunc(int x, int y) {
y = hh -y+scale/2;
x += scale/2;
y /= scale;
x /= scale;
if (mstate == GLUT_DOWN) {
if (mbutton == GLUT_LEFT_BUTTON) {
dstar->updateCell(x, y, -1);
} else if (mbutton == GLUT_RIGHT_BUTTON) {
dstar->updateStart(x, y);
} else if (mbutton == GLUT_MIDDLE_BUTTON) {
dstar->updateGoal(x, y);
}
}
}
int main(int argc, char **argv) {
if (argc > 1) {
std::cout << argv[1] << std::endl;
}
// Init GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
// Parse csv file with world grids.
// Currently only loads the first grid in the csv file...
ifstream file("../resources/gridworld_8.csv");
std::vector<string> value;
string tmp;
if (file.is_open()) {
while (getline(file, tmp)) {
value.push_back(tmp);
}
file.close();
} else {
cout << "Could not open the csv file." << endl;
}
// Construct a grid.
const uint grid_size = (uint)std::sqrt(value.size());
std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size));
uint i = 0;
uint j = 0;
bool first = true;
// Reshape input to a grid with x, y coordinates
for (uint k = 0; k < value.size(); k++) {
j = k % ((uint)std::sqrt(value.size()));
// Check that we are not out of bounds.
if ( i < grid_size && j < grid_size) {
occupancy_grid[i][j] = std::atoi(&value.at(k).at(0));
} else {
cerr << "Index out of bounds, check that input grid is squared." << endl;
}
if (j == 0) {
if (first) {
first = false;
} else {
i++;
}
}
}
// Initialize window for visualization.
glutInitWindowSize(500, 500);
glutInitWindowPosition(20, 20);
window = glutCreateWindow("Dstar Visualizer");
glutDisplayFunc(&DrawGLScene);
glutIdleFunc(&DrawGLScene);
glutReshapeFunc(&ReSizeGLScene);
glutKeyboardFunc(&keyPressed);
glutMouseFunc(&mouseFunc);
glutMotionFunc(&mouseMotionFunc);
InitGL(30, 20);
dstar = new Dstar();
dstar->init(3, 2, 6, 6);
for (uint i = 0; i < occupancy_grid.size(); i++) {
for (uint j = 0; j < occupancy_grid.at(i).size(); j++) {
std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n';
if (occupancy_grid.at(i).at(j) == 1) {
dstar->updateCell(i+1, j+1, -1);
}
}
}
dstar->draw();
printf("----------------------------------\n");
printf("Dstar Visualizer\n");
printf("Commands:\n");
printf("[q/Q] - Quit\n");
printf("[r/R] - Replan\n");
printf("[a/A] - Toggle Auto Replan\n");
printf("[c/C] - Clear (restart)\n");
printf("left mouse click - make cell untraversable (cost -1)\n");
printf("middle mouse click - move goal to cell\n");
printf("right mouse click - move start to cell\n");
printf("----------------------------------\n");
glutMainLoop();
return 1;
}
|
/* dstar_from_grid.cpp
*/
#ifdef MACOS
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <unistd.h>
#include "dstar_lite/dstar.h"
int hh, ww;
int window;
Dstar *dstar;
int scale = 50;
int mbutton = 0;
int mstate = 0;
bool b_autoreplan = false;
void InitGL(int Width, int Height) {
hh = Height;
ww = Width;
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0);
glViewport(0,0,Width,Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Width,0,Height,-100,100);
glMatrixMode(GL_MODELVIEW);
}
void ReSizeGLScene(int Width, int Height) {
hh = Height;
ww = Width;
glViewport(0,0,Width,Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,Width,0,Height,-100,100);
glMatrixMode(GL_MODELVIEW);
}
void DrawGLScene() {
usleep(100);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glScaled(scale,scale,1);
if (b_autoreplan) dstar->replan();
dstar->draw();
glPopMatrix();
glutSwapBuffers();
}
void keyPressed(unsigned char key, int x, int y) {
usleep(100);
switch(key) {
case 'q':
case 'Q':
glutDestroyWindow(window);
exit(0);
break;
case 'r':
case 'R':
dstar->replan();
break;
case 'a':
case 'A':
b_autoreplan = !b_autoreplan;
break;
case 'c':
case 'C':
dstar->init(1, 1, 3, 3);
break;
}
}
void mouseFunc(int button, int state, int x, int y) {
y = hh -y+scale/2;
x += scale/2;
mbutton = button;
if ((mstate = state) == GLUT_DOWN) {
if (button == GLUT_LEFT_BUTTON) {
dstar->updateCell(x/scale, y/scale, -1);
} else if (button == GLUT_RIGHT_BUTTON) {
dstar->updateStart(x/scale, y/scale);
} else if (button == GLUT_MIDDLE_BUTTON) {
dstar->updateGoal(x/scale, y/scale);
}
}
}
void mouseMotionFunc(int x, int y) {
y = hh -y+scale/2;
x += scale/2;
y /= scale;
x /= scale;
if (mstate == GLUT_DOWN) {
if (mbutton == GLUT_LEFT_BUTTON) {
dstar->updateCell(x, y, -1);
} else if (mbutton == GLUT_RIGHT_BUTTON) {
dstar->updateStart(x, y);
} else if (mbutton == GLUT_MIDDLE_BUTTON) {
dstar->updateGoal(x, y);
}
}
}
int main(int argc, char **argv) {
// Init GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
// Parse csv file with world grids.
// Currently only loads the first grid in the csv file...
ifstream file("../resources/gridworld_8.csv");
std::vector<string> value;
string tmp;
if (file.is_open()) {
while (getline(file, tmp)) {
value.push_back(tmp);
}
file.close();
} else {
cout << "Could not open the csv file." << endl;
}
// Construct a grid.
const uint grid_size = (uint)std::sqrt(value.size());
std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size));
// Reshape input to a grid with x, y coordinates
bool first = true;
for (uint i, j, k = 0; k < value.size(); k++) {
j = k % ((uint)std::sqrt(value.size()));
// Check that we are not out of bounds.
if ( i < grid_size && j < grid_size) {
occupancy_grid[i][j] = std::atoi(&value.at(k).at(0));
} else {
cerr << "Index out of bounds, check that input grid is squared." << endl;
}
if (j == 0) {
if (first) {
first = false;
} else {
i++;
}
}
}
// Initialize window for visualization.
glutInitWindowSize(500, 500);
glutInitWindowPosition(20, 20);
window = glutCreateWindow("Dstar Visualizer");
glutDisplayFunc(&DrawGLScene);
glutIdleFunc(&DrawGLScene);
glutReshapeFunc(&ReSizeGLScene);
glutKeyboardFunc(&keyPressed);
glutMouseFunc(&mouseFunc);
glutMotionFunc(&mouseMotionFunc);
InitGL(30, 20);
dstar = new Dstar();
dstar->init(3, 2, 6, 6);
for (uint i = 0; i < occupancy_grid.size(); i++) {
for (uint j = 0; j < occupancy_grid.at(i).size(); j++) {
std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n';
if (occupancy_grid.at(i).at(j) == 1) {
dstar->updateCell(i+1, j+1, -1);
}
}
}
dstar->draw();
printf("----------------------------------\n");
printf("Dstar Visualizer\n");
printf("Commands:\n");
printf("[q/Q] - Quit\n");
printf("[r/R] - Replan\n");
printf("[a/A] - Toggle Auto Replan\n");
printf("[c/C] - Clear (restart)\n");
printf("left mouse click - make cell untraversable (cost -1)\n");
printf("middle mouse click - move goal to cell\n");
printf("right mouse click - move start to cell\n");
printf("----------------------------------\n");
glutMainLoop();
return 1;
}
|
Clean dstar_from_grid
|
Clean dstar_from_grid
|
C++
|
mit
|
ToniRV/Learning-to-navigate-without-a-map,ToniRV/Learning-to-navigate-without-a-map
|
e29cf4e6b5fc8d6ef60842e20839554af2cd17c0
|
dune/gdt/operator/prolongations.hh
|
dune/gdt/operator/prolongations.hh
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#define DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#include <type_traits>
#include <vector>
#include <limits>
#include <dune/common/dynmatrix.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/geometry/quadraturerules.hh>
#include <dune/stuff/grid/search.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>
namespace Dune {
namespace GDT {
namespace ProlongationOperator {
template <class GridPartType>
class L2
{
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
public:
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{
}
/**
* \todo This is only correct for DG functions. For CG/in general we need a global solve here!
*/
template <class SourceSpaceType, class VS, class RangeSpaceType, class VR>
void apply(const ConstDiscreteFunction<SourceSpaceType, VS>& source,
DiscreteFunction<RangeSpaceType, VR>& range) const
{
// check
static_assert(
std::is_same<typename SourceSpaceType::RangeFieldType, typename RangeSpaceType::RangeFieldType>::value,
"Types do not match!");
static_assert(SourceSpaceType::dimRange == RangeSpaceType::dimRange, "Dimensions do not match!");
static_assert(SourceSpaceType::dimRangeCols == RangeSpaceType::dimRangeCols, "Dimensions do not match!");
static_assert(SourceSpaceType::dimRangeCols == 1, "Not implemented yet!");
typedef typename RangeSpaceType::BaseFunctionSetType::DomainType DomainType;
typedef typename RangeSpaceType::BaseFunctionSetType::RangeType RangeType;
typedef typename RangeSpaceType::BaseFunctionSetType::RangeFieldType RangeFieldType;
// clear
range.vector().backend() *= RangeFieldType(0);
// create search in the source grid part
typedef typename SourceSpaceType::GridPartType::GridViewType SourceGridViewType;
typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch;
EntitySearch entity_search(source.space().gridPart()->gridView());
// walk the grid
RangeType source_value(0);
std::vector<RangeType> basis_values(range.space().mapper().maxNumDofs());
const auto entity_it_end = grid_part_.template end<0>();
for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
// prepare
const auto& entity = *entity_it;
const auto local_basis = range.space().baseFunctionSet(entity);
auto local_range = range.local_discrete_function(entity);
DynamicMatrix<RangeFieldType> local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0));
DynamicVector<RangeFieldType> local_vector(local_basis.size(), RangeFieldType(0));
// create quadrature
const size_t quadrature_order = local_range.order();
assert((2 * quadrature_order + 1) < std::numeric_limits<int>::max());
const auto& quadrature =
QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), int(2 * quadrature_order + 1));
// get global quadrature points
std::vector<DomainType> quadrature_points;
for (const auto& quadrature_point : quadrature)
quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position()));
// get source entities
const auto source_entities = entity_search(quadrature_points);
assert(source_entities.size() == quadrature_points.size());
// loop over all quadrature points
size_t pp = 0;
for (const auto& quadrature_point : quadrature) {
const auto local_point = quadrature_point.position();
const auto quadrature_weight = quadrature_point.weight();
const auto integration_element = entity.geometry().integrationElement(local_point);
// evaluate source
const auto source_entity_ptr = source_entities[pp];
const auto& source_entity = *source_entity_ptr;
const auto local_source = source.local_function(source_entity);
local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value);
// evaluate
local_basis.evaluate(local_point, basis_values);
// compute integrals
for (size_t ii = 0; ii < local_basis.size(); ++ii) {
local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
auto& local_matrix_row = local_matrix[ii];
for (size_t jj = 0; jj < local_basis.size(); ++jj) {
local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
}
}
++pp;
} // loop over all quadrature points
// compute local DoFs
DynamicVector<RangeFieldType> local_DoFs(local_basis.size(), 0);
local_matrix.solve(local_DoFs, local_vector);
// set local DoFs
auto local_range_vector = local_range.vector();
for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
local_range_vector.set(ii, local_DoFs[ii]);
} // walk the grid
} // ... apply(...)
private:
const GridPartType& grid_part_;
}; // class L2
template <class GridPartType>
class Generic
{
public:
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
Generic(const GridPartType& grid_part)
: grid_part_(grid_part)
{
}
template <class SGP, int sp, class R, int r, class SV, class RGP, int rp, class RV>
void apply(const ConstDiscreteFunction<ContinuousLagrangeSpace::FemWrapper<SGP, sp, R, r>, SV>& source,
DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<RGP, rp, R, r>, RV>& range) const
{
// create search in the source grid part
typedef ConstDiscreteFunction<ContinuousLagrangeSpace::FemWrapper<SGP, sp, R, r>, SV> SourceType;
typedef DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<RGP, rp, R, r>, RV> TargetType;
typedef typename SourceType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = SourceType::dimRange;
typedef typename SourceType::SpaceType::GridPartType::GridViewType SourceGridViewType;
typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch;
EntitySearch entity_search(source.space().gridPart()->gridView());
// set all dofs to infinity
const auto infinity = std::numeric_limits<RangeFieldType>::infinity();
for (size_t ii = 0; ii < range.vector().size(); ++ii)
range.vector().set(ii, infinity);
// walk the grid
const auto entity_it_end = grid_part_.template end<0>();
for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get global lagrange point coordinates
const auto lagrange_point_set = range.space().backend().lagrangePointSet(entity);
typedef FieldVector<typename SourceGridViewType::ctype, SourceGridViewType::dimension> DomainType;
std::vector<DomainType> lagrange_points(lagrange_point_set.nop());
for (size_t ii = 0; ii < lagrange_point_set.nop(); ++ii)
lagrange_points[ii] = entity.geometry().global(lagrange_point_set.point(ii));
// get source entities
const auto source_entities = entity_search(lagrange_points);
assert(source_entities.size() == lagrange_points.size());
auto local_range = range.local_discrete_function(entity);
auto local_range_vector = local_range.vector();
size_t kk = 0;
for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
if (std::isinf(local_range_vector.get(kk))) {
const auto& global_point = lagrange_points[ii];
// evaluate source function
const auto source_entity_ptr = source_entities[ii];
const auto& source_entity = *source_entity_ptr;
const auto local_source_point = source_entity.geometry().local(global_point);
const auto local_source = source.local_function(source_entity);
const auto source_value = local_source->evaluate(local_source_point);
for (size_t jj = 0; jj < dimRange; ++jj, ++kk)
local_range_vector.set(kk, source_value[jj]);
} else
kk += dimRange;
}
} // walk the grid
} // ... apply(...)
private:
const GridPartType& grid_part_;
}; // class Generic
} // namespace ProlongationOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PROLONGATIONS_HH
|
// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#define DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#include <type_traits>
#include <vector>
#include <limits>
#include <dune/common/dynmatrix.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/geometry/quadraturerules.hh>
#include <dune/stuff/grid/search.hh>
#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>
#include <dune/gdt/space/continuouslagrange/fem-localfunctions.hh>
namespace Dune {
namespace GDT {
namespace ProlongationOperator {
template <class GridPartType>
class L2
{
typedef typename GridPartType::template Codim<0>::EntityType EntityType;
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
public:
L2(const GridPartType& grid_part)
: grid_part_(grid_part)
{
}
/**
* \todo This is only correct for DG functions. For CG/in general we need a global solve here!
*/
template <class SourceSpaceType, class VS, class RangeSpaceType, class VR>
void apply(const ConstDiscreteFunction<SourceSpaceType, VS>& source,
DiscreteFunction<RangeSpaceType, VR>& range) const
{
// check
static_assert(
std::is_same<typename SourceSpaceType::RangeFieldType, typename RangeSpaceType::RangeFieldType>::value,
"Types do not match!");
static_assert(SourceSpaceType::dimRange == RangeSpaceType::dimRange, "Dimensions do not match!");
static_assert(SourceSpaceType::dimRangeCols == RangeSpaceType::dimRangeCols, "Dimensions do not match!");
static_assert(SourceSpaceType::dimRangeCols == 1, "Not implemented yet!");
typedef typename RangeSpaceType::BaseFunctionSetType::DomainType DomainType;
typedef typename RangeSpaceType::BaseFunctionSetType::RangeType RangeType;
typedef typename RangeSpaceType::BaseFunctionSetType::RangeFieldType RangeFieldType;
// clear
range.vector().backend() *= RangeFieldType(0);
// create search in the source grid part
typedef typename SourceSpaceType::GridPartType::GridViewType SourceGridViewType;
typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch;
EntitySearch entity_search(source.space().gridPart()->gridView());
// walk the grid
RangeType source_value(0);
std::vector<RangeType> basis_values(range.space().mapper().maxNumDofs());
const auto entity_it_end = grid_part_.template end<0>();
for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
// prepare
const auto& entity = *entity_it;
const auto local_basis = range.space().baseFunctionSet(entity);
auto local_range = range.local_discrete_function(entity);
DynamicMatrix<RangeFieldType> local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0));
DynamicVector<RangeFieldType> local_vector(local_basis.size(), RangeFieldType(0));
// create quadrature
const size_t quadrature_order = local_range.order();
assert((2 * quadrature_order + 1) < std::numeric_limits<int>::max());
const auto& quadrature =
QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), int(2 * quadrature_order + 1));
// get global quadrature points
std::vector<DomainType> quadrature_points;
for (const auto& quadrature_point : quadrature)
quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position()));
// get source entities
const auto source_entities = entity_search(quadrature_points);
assert(source_entities.size() == quadrature_points.size());
// loop over all quadrature points
size_t pp = 0;
for (const auto& quadrature_point : quadrature) {
const auto local_point = quadrature_point.position();
const auto quadrature_weight = quadrature_point.weight();
const auto integration_element = entity.geometry().integrationElement(local_point);
// evaluate source
const auto source_entity_ptr = source_entities[pp];
const auto& source_entity = *source_entity_ptr;
const auto local_source = source.local_function(source_entity);
local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value);
// evaluate
local_basis.evaluate(local_point, basis_values);
// compute integrals
for (size_t ii = 0; ii < local_basis.size(); ++ii) {
local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
auto& local_matrix_row = local_matrix[ii];
for (size_t jj = 0; jj < local_basis.size(); ++jj) {
local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
}
}
++pp;
} // loop over all quadrature points
// compute local DoFs
DynamicVector<RangeFieldType> local_DoFs(local_basis.size(), 0);
local_matrix.solve(local_DoFs, local_vector);
// set local DoFs
auto local_range_vector = local_range.vector();
for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
local_range_vector.set(ii, local_DoFs[ii]);
} // walk the grid
} // ... apply(...)
private:
const GridPartType& grid_part_;
}; // class L2
template <class GridPartType>
class Generic
{
public:
typedef typename GridPartType::ctype DomainFieldType;
static const unsigned int dimDomain = GridPartType::dimension;
Generic(const GridPartType& grid_part)
: grid_part_(grid_part)
{
}
template <class SGP, int sp, class R, int r, class SV, class RGP, int rp, class RV>
void apply(const ConstDiscreteFunction<ContinuousLagrangeSpace::FemWrapper<SGP, sp, R, r>, SV>& source,
DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<RGP, rp, R, r>, RV>& range) const
{
// create search in the source grid part
typedef ConstDiscreteFunction<ContinuousLagrangeSpace::FemWrapper<SGP, sp, R, r>, SV> SourceType;
typedef DiscreteFunction<ContinuousLagrangeSpace::FemWrapper<RGP, rp, R, r>, RV> TargetType;
typedef typename SourceType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = SourceType::dimRange;
typedef typename SourceType::SpaceType::GridPartType::GridViewType SourceGridViewType;
typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch;
EntitySearch entity_search(source.space().gridPart()->gridView());
// set all dofs to infinity
const auto infinity = std::numeric_limits<RangeFieldType>::infinity();
for (size_t ii = 0; ii < range.vector().size(); ++ii)
range.vector().set(ii, infinity);
// walk the grid
const auto entity_it_end = grid_part_.template end<0>();
for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get global lagrange point coordinates
const auto lagrange_point_set = range.space().backend().lagrangePointSet(entity);
typedef FieldVector<typename SourceGridViewType::ctype, SourceGridViewType::dimension> DomainType;
std::vector<DomainType> lagrange_points(lagrange_point_set.nop());
for (size_t ii = 0; ii < lagrange_point_set.nop(); ++ii)
lagrange_points[ii] = entity.geometry().global(lagrange_point_set.point(ii));
// get source entities
const auto source_entities = entity_search(lagrange_points);
assert(source_entities.size() == lagrange_points.size());
auto local_range = range.local_discrete_function(entity);
auto local_range_vector = local_range.vector();
size_t kk = 0;
for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
if (std::isinf(local_range_vector.get(kk))) {
const auto& global_point = lagrange_points[ii];
// evaluate source function
const auto source_entity_ptr = source_entities[ii];
const auto& source_entity = *source_entity_ptr;
const auto local_source_point = source_entity.geometry().local(global_point);
const auto local_source = source.local_function(source_entity);
const auto source_value = local_source->evaluate(local_source_point);
for (size_t jj = 0; jj < dimRange; ++jj, ++kk)
local_range_vector.set(kk, source_value[jj]);
} else
kk += dimRange;
}
} // walk the grid
} // ... apply(...)
template <class SGP, int sp, class R, int r, class SV, class RGP, int rp, class RV>
void apply(const ConstDiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<SGP, sp, R, r>, SV>& source,
DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<RGP, rp, R, r>, RV>& range) const
{
// create search in the source grid part
typedef ConstDiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<SGP, sp, R, r>, SV> SourceType;
typedef DiscreteFunction<ContinuousLagrangeSpace::FemLocalfunctionsWrapper<RGP, rp, R, r>, RV> TargetType;
typedef typename SourceType::RangeFieldType RangeFieldType;
static const unsigned int dimRange = SourceType::dimRange;
typedef typename SourceType::SpaceType::GridPartType::GridViewType SourceGridViewType;
typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch;
EntitySearch entity_search(source.space().gridPart()->gridView());
// set all dofs to infinity
const auto infinity = std::numeric_limits<RangeFieldType>::infinity();
for (size_t ii = 0; ii < range.vector().size(); ++ii)
range.vector().set(ii, infinity);
// walk the grid
const auto entity_it_end = grid_part_.template end<0>();
for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) {
const auto& entity = *entity_it;
// get global lagrange point coordinates
typedef FieldVector<typename SourceGridViewType::ctype, SourceGridViewType::dimension> DomainType;
std::vector<DomainType> lagrange_points = range.space().lagrange_points(entity);
for (size_t ii = 0; ii < lagrange_points.size(); ++ii)
lagrange_points[ii] = entity.geometry().global(lagrange_points[ii]);
// get source entities
const auto source_entities = entity_search(lagrange_points);
assert(source_entities.size() == lagrange_points.size());
auto local_range = range.local_discrete_function(entity);
auto local_range_vector = local_range.vector();
size_t kk = 0;
for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
if (std::isinf(local_range_vector.get(kk))) {
const auto& global_point = lagrange_points[ii];
// evaluate source function
const auto source_entity_ptr = source_entities[ii];
const auto& source_entity = *source_entity_ptr;
const auto local_source_point = source_entity.geometry().local(global_point);
const auto local_source = source.local_function(source_entity);
const auto source_value = local_source->evaluate(local_source_point);
for (size_t jj = 0; jj < dimRange; ++jj, ++kk)
local_range_vector.set(kk, source_value[jj]);
} else
kk += dimRange;
}
} // walk the grid
} // ... apply(...)
private:
const GridPartType& grid_part_;
}; // class Generic
} // namespace ProlongationOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATOR_PROLONGATIONS_HH
|
add Generic::apply(s, r) for another combination
|
[operator.prolongations] add Generic::apply(s, r) for another combination
|
C++
|
bsd-2-clause
|
pymor/dune-gdt
|
5c02209770ffa3acd3c6e28024ad28e2feb2d850
|
dune/gdt/operators/advection-fv.hh
|
dune/gdt/operators/advection-fv.hh
|
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
// René Fritze (2018)
// Tobias Leibner (2018)
#ifndef DUNE_GDT_OPERATORS_ADVECTION_FV_HH
#define DUNE_GDT_OPERATORS_ADVECTION_FV_HH
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/filters.hh>
#include <dune/xt/la/container.hh>
#include <dune/gdt/local/assembler/operator-fd-jacobian-assemblers.hh>
#include <dune/gdt/local/operators/advection-fv.hh>
#include "interfaces.hh"
#include "localizable-operator.hh"
namespace Dune {
namespace GDT {
/**
* \attention This operator will not work on a grid view with hanging nodes.
*
* \todo Refactor the coupling op as in the DG case to be applied on each side individually.
*
* \note See OperatorInterface for a description of the template arguments.
*
* \sa OperatorInterface
*/
template <class M, class SGV, size_t m = 1, class RGV = SGV>
class AdvectionFvOperator : public OperatorInterface<M, SGV, m, 1, m, 1, RGV>
{
using ThisType = AdvectionFvOperator<M, SGV, m, RGV>;
using BaseType = OperatorInterface<M, SGV, m, 1, m, 1, RGV>;
public:
using typename BaseType::F;
using typename BaseType::V;
using NumericalFluxType = NumericalFluxInterface<SGV::dimension, m, F>;
using I = XT::Grid::extract_intersection_t<SGV>;
using BoundaryTreatmentByCustomNumericalFluxOperatorType =
LocalAdvectionFvBoundaryTreatmentByCustomNumericalFluxOperator<I, V, SGV, m, F, F, RGV, V>;
using BoundaryTreatmentByCustomExtrapolationOperatorType =
LocalAdvectionFvBoundaryTreatmentByCustomExtrapolationOperator<I, V, SGV, m, F, F, RGV, V>;
using typename BaseType::MatrixOperatorType;
using typename BaseType::RangeSpaceType;
using typename BaseType::SourceSpaceType;
using typename BaseType::VectorType;
AdvectionFvOperator(
const SGV& assembly_grid_view,
const NumericalFluxType& numerical_flux,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const XT::Grid::IntersectionFilter<SGV>& periodicity_exception = XT::Grid::ApplyOn::NoIntersections<SGV>())
: BaseType(numerical_flux.parameter_type())
, assembly_grid_view_(assembly_grid_view)
, numerical_flux_(numerical_flux.copy())
, source_space_(source_space)
, range_space_(range_space)
, periodicity_exception_(periodicity_exception.copy())
{}
AdvectionFvOperator(ThisType&& source) = default;
bool linear() const override final
{
return numerical_flux_->linear();
}
const SourceSpaceType& source_space() const override final
{
return source_space_;
}
const RangeSpaceType& range_space() const override final
{
return range_space_;
}
/// \name Non-periodic boundary treatment
/// \{
ThisType&
append(typename BoundaryTreatmentByCustomNumericalFluxOperatorType::LambdaType numerical_boundary_treatment_flux,
const XT::Common::ParameterType& boundary_treatment_parameter_type = {},
const XT::Grid::IntersectionFilter<SGV>& filter = XT::Grid::ApplyOn::BoundaryIntersections<SGV>())
{
boundary_treatments_by_custom_numerical_flux_.emplace_back(
new BoundaryTreatmentByCustomNumericalFluxOperatorType(numerical_boundary_treatment_flux,
boundary_treatment_parameter_type),
filter.copy());
return *this;
}
ThisType& append(typename BoundaryTreatmentByCustomExtrapolationOperatorType::LambdaType extrapolation,
const XT::Common::ParameterType& extrapolation_parameter_type = {},
const XT::Grid::IntersectionFilter<SGV>& filter = XT::Grid::ApplyOn::BoundaryIntersections<SGV>())
{
boundary_treatments_by_custom_extrapolation_.emplace_back(
new BoundaryTreatmentByCustomExtrapolationOperatorType(
*numerical_flux_, extrapolation, extrapolation_parameter_type),
filter.copy());
return *this;
}
/// \}
using BaseType::apply;
void apply(const VectorType& source, VectorType& range, const XT::Common::Parameter& param = {}) const override final
{
// some checks
DUNE_THROW_IF(!source.valid(), Exceptions::operator_error, "source contains inf or nan!");
DUNE_THROW_IF(!(this->parameter_type() <= param.type()),
Exceptions::operator_error,
"this->parameter_type() = " << this->parameter_type() << "\n param.type() = " << param.type());
range.set_all(0);
const auto source_function = make_discrete_function(source_space_, source);
auto range_function = make_discrete_function(range_space_, range);
// set up the actual operator
auto localizable_op = make_localizable_operator(assembly_grid_view_, source_function, range_function);
// contributions from inner intersections
localizable_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
param,
XT::Grid::ApplyOn::InnerIntersectionsOnce<SGV>());
// contributions from periodic boundaries
localizable_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
param,
*(XT::Grid::ApplyOn::PeriodicBoundaryIntersectionsOnce<SGV>() && !(*periodicity_exception_)));
// contributions from other boundaries by custom numerical flux
for (const auto& boundary_treatment : boundary_treatments_by_custom_numerical_flux_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
localizable_op.append(boundary_op, param, filter);
}
// contributions from other boundaries by custom extrapolation
for (const auto& boundary_treatment : boundary_treatments_by_custom_extrapolation_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
localizable_op.append(boundary_op, param, filter);
}
// do the actual work
localizable_op.assemble(/*use_tbb=*/true);
DUNE_THROW_IF(!range.valid(), Exceptions::operator_error, "range contains inf or nan!");
} // ... apply(...)
std::vector<std::string> jacobian_options() const override final
{
return {"finite-differences"};
}
XT::Common::Configuration jacobian_options(const std::string& type) const override final
{
DUNE_THROW_IF(type != this->jacobian_options().at(0), Exceptions::operator_error, "type = " << type);
return {{"type", type}, {"eps", "1e-7"}};
}
using BaseType::jacobian;
void jacobian(const VectorType& source,
MatrixOperatorType& jacobian_op,
const XT::Common::Configuration& opts,
const XT::Common::Parameter& param = {}) const override final
{
// some checks
DUNE_THROW_IF(!source.valid(), Exceptions::operator_error, "source contains inf or nan!");
DUNE_THROW_IF(!(this->parameter_type() <= param.type()),
Exceptions::operator_error,
"this->parameter_type() = " << this->parameter_type() << "\n param.type() = " << param.type());
DUNE_THROW_IF(!opts.has_key("type"), Exceptions::operator_error, opts);
DUNE_THROW_IF(opts.get<std::string>("type") != jacobian_options().at(0), Exceptions::operator_error, opts);
const auto default_opts = jacobian_options(jacobian_options().at(0));
const auto eps = opts.get("eps", default_opts.template get<double>("eps"));
const auto parameter = param + XT::Common::Parameter({"finite-difference-jacobians.eps", eps});
// append the same local ops with the same filters as in apply() above
// contributions from inner intersections
jacobian_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
source,
parameter,
XT::Grid::ApplyOn::InnerIntersectionsOnce<SGV>());
// contributions from periodic boundaries
jacobian_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
source,
parameter,
*(XT::Grid::ApplyOn::PeriodicBoundaryIntersectionsOnce<SGV>() && !(*periodicity_exception_)));
// contributions from other boundaries by custom numerical flux
for (const auto& boundary_treatment : boundary_treatments_by_custom_numerical_flux_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
jacobian_op.append(boundary_op, source, parameter, filter);
}
// contributions from other boundaries by custom extrapolation
for (const auto& boundary_treatment : boundary_treatments_by_custom_extrapolation_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
jacobian_op.append(boundary_op, source, parameter, filter);
}
} // ... jacobian(...)
private:
const SGV assembly_grid_view_;
const std::unique_ptr<const NumericalFluxType> numerical_flux_;
const SourceSpaceType& source_space_;
const RangeSpaceType& range_space_;
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>> periodicity_exception_;
std::list<std::pair<std::unique_ptr<BoundaryTreatmentByCustomNumericalFluxOperatorType>,
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>>>>
boundary_treatments_by_custom_numerical_flux_;
std::list<std::pair<std::unique_ptr<BoundaryTreatmentByCustomExtrapolationOperatorType>,
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>>>>
boundary_treatments_by_custom_extrapolation_;
}; // class AdvectionFvOperator
template <class MatrixType, class SGV, size_t m, class F, class RGV>
std::enable_if_t<XT::LA::is_matrix<MatrixType>::value, AdvectionFvOperator<MatrixType, SGV, m, RGV>>
make_advection_fv_operator(
const SGV& assembly_grid_view,
const NumericalFluxInterface<SGV::dimension, m, F>& numerical_flux,
const SpaceInterface<SGV, m, 1, F>& source_space,
const SpaceInterface<RGV, m, 1, F>& range_space,
const XT::Grid::IntersectionFilter<SGV>& periodicity_exception = XT::Grid::ApplyOn::NoIntersections<SGV>())
{
return AdvectionFvOperator<MatrixType, SGV, m, RGV>(
assembly_grid_view, numerical_flux, source_space, range_space, periodicity_exception);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ADVECTION_FV_HH
|
// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
// René Fritze (2018)
// Tobias Leibner (2018)
#ifndef DUNE_GDT_OPERATORS_ADVECTION_FV_HH
#define DUNE_GDT_OPERATORS_ADVECTION_FV_HH
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/grid/filters.hh>
#include <dune/xt/la/container.hh>
#include <dune/gdt/local/assembler/operator-fd-jacobian-assemblers.hh>
#include <dune/gdt/local/operators/advection-fv.hh>
#include "interfaces.hh"
#include "localizable-operator.hh"
namespace Dune {
namespace GDT {
/**
* \attention This operator will not work on a grid view with hanging nodes.
*
* \todo Refactor the coupling op as in the DG case to be applied on each side individually.
*
* \note See OperatorInterface for a description of the template arguments.
*
* \sa OperatorInterface
*/
template <class M, class SGV, size_t m = 1, class RGV = SGV>
class AdvectionFvOperator : public OperatorInterface<M, SGV, m, 1, m, 1, RGV>
{
using ThisType = AdvectionFvOperator<M, SGV, m, RGV>;
using BaseType = OperatorInterface<M, SGV, m, 1, m, 1, RGV>;
public:
using typename BaseType::F;
using typename BaseType::V;
using NumericalFluxType = NumericalFluxInterface<SGV::dimension, m, F>;
using I = XT::Grid::extract_intersection_t<SGV>;
using BoundaryTreatmentByCustomNumericalFluxOperatorType =
LocalAdvectionFvBoundaryTreatmentByCustomNumericalFluxOperator<I, V, SGV, m, F, F, RGV, V>;
using BoundaryTreatmentByCustomExtrapolationOperatorType =
LocalAdvectionFvBoundaryTreatmentByCustomExtrapolationOperator<I, V, SGV, m, F, F, RGV, V>;
using typename BaseType::MatrixOperatorType;
using typename BaseType::RangeSpaceType;
using typename BaseType::SourceSpaceType;
using typename BaseType::VectorType;
AdvectionFvOperator(
const SGV& assembly_grid_view,
const NumericalFluxType& numerical_flux,
const SourceSpaceType& source_space,
const RangeSpaceType& range_space,
const XT::Grid::IntersectionFilter<SGV>& periodicity_exception = XT::Grid::ApplyOn::NoIntersections<SGV>())
: BaseType(numerical_flux.parameter_type())
, assembly_grid_view_(assembly_grid_view)
, numerical_flux_(numerical_flux.copy())
, source_space_(source_space)
, range_space_(range_space)
, periodicity_exception_(periodicity_exception.copy())
{}
AdvectionFvOperator(ThisType&& source) = default;
bool linear() const override final
{
return numerical_flux_->linear();
}
const SourceSpaceType& source_space() const override final
{
return source_space_;
}
const RangeSpaceType& range_space() const override final
{
return range_space_;
}
/// \name Non-periodic boundary treatment
/// \{
ThisType&
append(typename BoundaryTreatmentByCustomNumericalFluxOperatorType::LambdaType numerical_boundary_treatment_flux,
const XT::Common::ParameterType& boundary_treatment_parameter_type = {},
const XT::Grid::IntersectionFilter<SGV>& filter = XT::Grid::ApplyOn::BoundaryIntersections<SGV>())
{
boundary_treatments_by_custom_numerical_flux_.emplace_back(
new BoundaryTreatmentByCustomNumericalFluxOperatorType(numerical_boundary_treatment_flux,
boundary_treatment_parameter_type),
filter.copy());
return *this;
}
ThisType& append(typename BoundaryTreatmentByCustomExtrapolationOperatorType::LambdaType extrapolation,
const XT::Common::ParameterType& extrapolation_parameter_type = {},
const XT::Grid::IntersectionFilter<SGV>& filter = XT::Grid::ApplyOn::BoundaryIntersections<SGV>())
{
boundary_treatments_by_custom_extrapolation_.emplace_back(
new BoundaryTreatmentByCustomExtrapolationOperatorType(
*numerical_flux_, extrapolation, extrapolation_parameter_type),
filter.copy());
return *this;
}
/// \}
using BaseType::apply;
void apply(const VectorType& source, VectorType& range, const XT::Common::Parameter& param = {}) const override final
{
// some checks
DUNE_THROW_IF(!source.valid(), Exceptions::operator_error, "source contains inf or nan!");
DUNE_THROW_IF(!(this->parameter_type() <= param.type()),
Exceptions::operator_error,
"this->parameter_type() = " << this->parameter_type() << "\n param.type() = " << param.type());
range.set_all(0);
const auto source_function = make_discrete_function(source_space_, source);
auto range_function = make_discrete_function(range_space_, range);
// set up the actual operator
auto localizable_op = make_localizable_operator(assembly_grid_view_, source_function, range_function);
// contributions from inner intersections
localizable_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
param,
XT::Grid::ApplyOn::InnerIntersectionsOnce<SGV>());
// contributions from periodic boundaries
localizable_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
param,
*(XT::Grid::ApplyOn::PeriodicBoundaryIntersectionsOnce<SGV>() && !(*periodicity_exception_)));
// contributions from other boundaries by custom numerical flux
for (const auto& boundary_treatment : boundary_treatments_by_custom_numerical_flux_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
localizable_op.append(boundary_op, param, filter);
}
// contributions from other boundaries by custom extrapolation
for (const auto& boundary_treatment : boundary_treatments_by_custom_extrapolation_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
localizable_op.append(boundary_op, param, filter);
}
// do the actual work
localizable_op.assemble(/*use_tbb=*/true);
DUNE_THROW_IF(!range.valid(), Exceptions::operator_error, "range contains inf or nan!");
} // ... apply(...)
std::vector<std::string> jacobian_options() const override final
{
return {"finite-differences"};
}
XT::Common::Configuration jacobian_options(const std::string& type) const override final
{
DUNE_THROW_IF(type != this->jacobian_options().at(0), Exceptions::operator_error, "type = " << type);
return {{"type", type}, {"eps", "1e-7"}};
}
using BaseType::jacobian;
void jacobian(const VectorType& source,
MatrixOperatorType& jacobian_op,
const XT::Common::Configuration& opts,
const XT::Common::Parameter& param = {}) const override final
{
// some checks
DUNE_THROW_IF(!source.valid(), Exceptions::operator_error, "source contains inf or nan!");
DUNE_THROW_IF(!(this->parameter_type() <= param.type()),
Exceptions::operator_error,
"this->parameter_type() = " << this->parameter_type() << "\n param.type() = " << param.type());
DUNE_THROW_IF(!opts.has_key("type"), Exceptions::operator_error, opts);
DUNE_THROW_IF(opts.get<std::string>("type") != jacobian_options().at(0), Exceptions::operator_error, opts);
const auto default_opts = jacobian_options(jacobian_options().at(0));
const auto eps = opts.get("eps", default_opts.template get<double>("eps"));
const auto parameter = param + XT::Common::Parameter({"finite-difference-jacobians.eps", eps});
// append the same local ops with the same filters as in apply() above
// contributions from inner intersections
jacobian_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
source,
parameter,
XT::Grid::ApplyOn::InnerIntersectionsOnce<SGV>());
// contributions from periodic boundaries
jacobian_op.append(LocalAdvectionFvCouplingOperator<I, V, SGV, m, F, F, RGV, V>(*numerical_flux_),
source,
parameter,
*(XT::Grid::ApplyOn::PeriodicBoundaryIntersectionsOnce<SGV>() && !(*periodicity_exception_)));
// contributions from other boundaries by custom numerical flux
for (const auto& boundary_treatment : boundary_treatments_by_custom_numerical_flux_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
jacobian_op.append(boundary_op, source, parameter, filter);
}
// contributions from other boundaries by custom extrapolation
for (const auto& boundary_treatment : boundary_treatments_by_custom_extrapolation_) {
const auto& boundary_op = *boundary_treatment.first;
const auto& filter = *boundary_treatment.second;
jacobian_op.append(boundary_op, source, parameter, filter);
}
} // ... jacobian(...)
private:
const SGV assembly_grid_view_;
std::unique_ptr<const NumericalFluxType> numerical_flux_;
const SourceSpaceType& source_space_;
const RangeSpaceType& range_space_;
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>> periodicity_exception_;
std::list<std::pair<std::unique_ptr<BoundaryTreatmentByCustomNumericalFluxOperatorType>,
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>>>>
boundary_treatments_by_custom_numerical_flux_;
std::list<std::pair<std::unique_ptr<BoundaryTreatmentByCustomExtrapolationOperatorType>,
std::unique_ptr<XT::Grid::IntersectionFilter<SGV>>>>
boundary_treatments_by_custom_extrapolation_;
}; // class AdvectionFvOperator
template <class MatrixType, class SGV, size_t m, class F, class RGV>
std::enable_if_t<XT::LA::is_matrix<MatrixType>::value, AdvectionFvOperator<MatrixType, SGV, m, RGV>>
make_advection_fv_operator(
const SGV& assembly_grid_view,
const NumericalFluxInterface<SGV::dimension, m, F>& numerical_flux,
const SpaceInterface<SGV, m, 1, F>& source_space,
const SpaceInterface<RGV, m, 1, F>& range_space,
const XT::Grid::IntersectionFilter<SGV>& periodicity_exception = XT::Grid::ApplyOn::NoIntersections<SGV>())
{
return AdvectionFvOperator<MatrixType, SGV, m, RGV>(
assembly_grid_view, numerical_flux, source_space, range_space, periodicity_exception);
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_ADVECTION_FV_HH
|
make movable
|
[operators.advection-fv] make movable
|
C++
|
bsd-2-clause
|
pymor/dune-gdt
|
b2d2c90eb333cf20e75e1ea15ef640326545bd4d
|
codec/decoder/core/src/compression_stream.cpp
|
codec/decoder/core/src/compression_stream.cpp
|
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
#include "error_code.h"
#include "macroblock_model.h"
#include "compression_stream.h"
#include <sstream>
using namespace WelsDec;
void warnme() {
fprintf(stderr, "DOING 431\n");
}
#define H264ErrorNil ERR_NONE
namespace {
static CompressionStream css;
static InputCompressionStream icss;
}
CompressionStream &oMovie() {
return css;
}
InputCompressionStream &iMovie() {
return icss;
}
CompressionStream::CompressionStream() {
isRecoding = false;
pModel = new MacroblockModel;
}
CompressionStream::~CompressionStream() {
delete pModel;
}
BitStream::BitStream() {
bitsWrittenSinceFlush = false;
bits = 0;
nBits = 0;
bitReadCursor = 0;
escapingEnabled = false;
escapeBufferSize = 0;
buffer.reserve(64*1024*1024);
}
void BitStream::appendByte(uint8_t x) {
if (escapingEnabled) {
if (x <= 3 && escapeBufferSize == 2 && escapeBuffer[0] == 0 && escapeBuffer[1] == 0) {
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(3);
buffer.push_back(x);
escapeBufferSize = 0;
}else if (escapeBufferSize == 2) {
buffer.push_back(escapeBuffer[0]);
escapeBuffer[0] = escapeBuffer[1];
escapeBuffer[1] = x;
} else {
escapeBuffer[escapeBufferSize++] = x;
}
}else {
buffer.push_back(x);
}
}
void BitStream::appendBytes(const uint8_t*bytes, uint32_t nBytes) {
if (escapingEnabled) {
for (uint32_t i = 0; i < nBytes; ++i) {
appendByte(bytes[i]);
}
}else {
buffer.insert(buffer.end(), bytes, bytes + nBytes);
}
}
void BitStream::clear() {
buffer.clear();
}
void BitStream::flushToWriter(int streamId, CompressedWriter &w) {
if (!buffer.empty()) {
w.Write(streamId, &buffer[0], buffer.size());
}
buffer.clear();
}
void BitStream::emitBits(uint32_t bits, uint32_t nBits) {
// fprintf(stderr, "emit %d\n", nBits);
bitsWrittenSinceFlush = true;
if (nBits > 16) {
assert(false &&"Must have nBits < 16");
}
if (bits >= (1U << nBits)) {
assert(false &&"bits is out of range for nBits");
}
BitStream &b = *this;
nBits += uint32_t(b.nBits);
bits <<= 32 - nBits;
bits |= b.bits;
while (nBits >= 8) {
uint8_t bb = uint8_t(bits >> 24);
b.appendByte(bb);
bits <<= 8;
nBits -= 8;
}
//fprintf(stderr, "Leftovers %d bits %x\n", nBits, bits)
b.bits = bits;
b.nBits = uint8_t(nBits);
}
void BitStream::padToByte() {
for (int i = nBits; (i & 0x07) != 0; ++i) {
emitBit(0);
}
}
std::pair<uint32_t, H264Error> BitStream::scanBits(uint32_t nBits) {
// fprintf(stderr, "scan %d\n", nBits);
BitStream &b = *this;
if (nBits > 16) {
assert(false &&"Must have nBits < 16");
}
if (nBits == 0) {
return uint32E(0, H264ErrorNil); // don't read off the array since it may be empty or at its end
}
uint32_t byteAddress = b.bitReadCursor / 8;
if (int(byteAddress) >= int(b.buffer.size())) {
return uint32E(0, ERR_BOUND);
}
uint32_t bitAddress = b.bitReadCursor - byteAddress*8;
uint32_t retval = 0;
uint32_t curByte = b.buffer[byteAddress] & ((1 << (8 - bitAddress)) - 1);
retval |= uint32_t(curByte);
uint8_t remainingBitsInByte = 8 - bitAddress;
//fmt.Printf("Retval %x[%d].%d so far, Remaining bits %d\n", retval, byteAddress,bitAddress,nBits)
if (remainingBitsInByte >= nBits) {
retval >>= remainingBitsInByte - nBits;
//fmt.Printf("Returning early after single byte read\n")
b.bitReadCursor += nBits;
return uint32E(retval, H264ErrorNil);
}
if (int(byteAddress) >= int(b.buffer.size())) {
return uint32E(0, ERR_BOUND);
}
b.bitReadCursor += remainingBitsInByte;
nBits -= remainingBitsInByte;
if (nBits > 8) {
b.bitReadCursor += 8;
byteAddress += 1;
retval <<= 8;
retval |= uint32_t(b.buffer[byteAddress]);
nBits -= 8;
}
if (nBits > 8) {
assert(false &&"unreachable: we should have only 16 bits to grab");
}
//fmt.Printf("Pref Final things are %x going to read %x after shifting %d\n", retval, b.buffer[byteAddress + 1], nBits)
if (byteAddress+1 >= b.buffer.size()) {
return uint32E(0, ERR_BOUND);
}
retval <<= nBits;
retval |= uint32_t(b.buffer[byteAddress+1] >> (8 - nBits));
b.bitReadCursor += nBits;
//fprintf(stderr, "Final value %x\n", retval)
return uint32E(retval, H264ErrorNil);
}
void BitStream::pop() {
BitStream &b = *this;
if (b.nBits > 0 && b.nBits < 8) {
if (b.buffer.empty()) {
assert(false && "popping from empty buffer");
return;
}
uint32_t poppedByte = 0;
poppedByte = uint32_t(b.buffer.back());
b.buffer.pop_back();
poppedByte <<= b.nBits;
b.bits |= poppedByte;
b.nBits += 8;
}
if (b.nBits >= 8) {
b.nBits -= 8;
b.bits >>= 8;
} else {
b.buffer.pop_back();
}
}
uint32_t BitStream::len()const {
return uint32_t(buffer.size()) + uint32_t(nBits/8);
}
void BitStream::flushBits() {
if (bitsWrittenSinceFlush) {
//emitBits(1, 1);
}
while (nBits > 0) {
emitBits(0, 1);
}
bitsWrittenSinceFlush = false;
}
DynProb ArithmeticCodedInput::TEST_PROB;
DynProb ArithmeticCodedOutput::TEST_PROB;
void ArithmeticCodedOutput::flushToWriter(int streamId, CompressedWriter &w) {
vpx_stop_encode(&writer);
#ifdef BILLING
static int total = 0;
fprintf(stderr, "%d :: %d [%s]\n", streamId, writer.pos, billEnumToName(streamId));
total += writer.pos;
if (streamId == PIP_PREV_PRED_TAG || streamId == PIP_NZC_TAG) {
fprintf(stderr, "TOTAL written %d\n", total);
}
#endif
if (!buffer.empty()) {
w.Write(streamId, &buffer[0], writer.pos);
}
buffer.clear();
}
std::vector<uint8_t> streamLenToBE(uint32_t streamLen) {
uint8_t retval[5] = {uint8_t(streamLen >> 24), uint8_t((streamLen >> 16) & 0xff),
uint8_t((streamLen >> 8) & 0xff), uint8_t(streamLen & 0xff), 0};
return std::vector<uint8_t>(retval, retval + 4);
}
uint32_t bufferBEToStreamLength(uint8_t *buf) {
uint32_t vectorLength = 0;
for (int i = 0; i < 4; i++) { // read in the huffvector length
vectorLength <<= 8;
vectorLength |= uint32_t(buf[i]);
}
return vectorLength;
}
void CompressionStream::flushToWriter(CompressedWriter&w) {
def().padToByte();
def().flushToWriter(DEFAULT_STREAM, w);
for (std::map<int32_t, ArithmeticCodedOutput>::iterator i = taggedStreams.begin(), ie = taggedStreams.end();
i != ie;
++i) {
i->second.flushToWriter(i->first, w);
}
}
ArithmeticCodedInput& InputCompressionStream::tag(int32_t tag) {
bool mustReadData = taggedStreams.find(tag) == taggedStreams.end();
ArithmeticCodedInput &bs = taggedStreams[tag];
if (filenamePrefix.empty()) {
fprintf(stderr, "Attempting to read %d without input file set\n", tag);
assert(!filenamePrefix.empty());
} else if (mustReadData) {
std::ostringstream os;
os << filenamePrefix << "." << tag;
std::string thisfilename = os.str();
FILE *fp = fopen(thisfilename.c_str(), "rb");
int nread = 0;
if (fp) {
long datalen = -1;
if (fseek(fp, 0, SEEK_END) != -1) {
datalen = ftell(fp);
rewind(fp);
}
if (datalen > 0) {
bs.buffer.resize(datalen);
nread = fread(&(bs.buffer[0]), datalen, 1, fp);
}
fclose(fp);
}
if (nread == 0) {
fprintf(stderr, "Failed to read from file %s\n", thisfilename.c_str());
assert(false && "failed to open input");
}
bs.init();
}
return bs;
}
|
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
#include "error_code.h"
#include "macroblock_model.h"
#include "compression_stream.h"
#include <sstream>
using namespace WelsDec;
void warnme() {
fprintf(stderr, "DOING 431\n");
}
#define H264ErrorNil ERR_NONE
namespace {
static CompressionStream css;
static InputCompressionStream icss;
}
CompressionStream &oMovie() {
return css;
}
InputCompressionStream &iMovie() {
return icss;
}
CompressionStream::CompressionStream() {
isRecoding = false;
pModel = new MacroblockModel;
}
CompressionStream::~CompressionStream() {
delete pModel;
}
BitStream::BitStream() {
bitsWrittenSinceFlush = false;
bits = 0;
nBits = 0;
bitReadCursor = 0;
escapingEnabled = false;
escapeBufferSize = 0;
buffer.reserve(64*1024*1024);
}
void BitStream::appendByte(uint8_t x) {
if (escapingEnabled) {
if (x <= 3 && escapeBufferSize == 2 && escapeBuffer[0] == 0 && escapeBuffer[1] == 0) {
buffer.push_back(0);
buffer.push_back(0);
buffer.push_back(3);
buffer.push_back(x);
escapeBufferSize = 0;
}else if (escapeBufferSize == 2) {
buffer.push_back(escapeBuffer[0]);
escapeBuffer[0] = escapeBuffer[1];
escapeBuffer[1] = x;
} else {
escapeBuffer[escapeBufferSize++] = x;
}
}else {
buffer.push_back(x);
}
}
void BitStream::appendBytes(const uint8_t*bytes, uint32_t nBytes) {
if (escapingEnabled) {
for (uint32_t i = 0; i < nBytes; ++i) {
appendByte(bytes[i]);
}
}else {
buffer.insert(buffer.end(), bytes, bytes + nBytes);
}
}
void BitStream::clear() {
buffer.clear();
}
void BitStream::flushToWriter(int streamId, CompressedWriter &w) {
if (!buffer.empty()) {
w.Write(streamId, &buffer[0], buffer.size());
}
buffer.clear();
}
void BitStream::emitBits(uint32_t bits, uint32_t nBits) {
// fprintf(stderr, "emit %d\n", nBits);
bitsWrittenSinceFlush = true;
if (nBits > 16) {
assert(false &&"Must have nBits < 16");
}
if (bits >= (1U << nBits)) {
assert(false &&"bits is out of range for nBits");
}
BitStream &b = *this;
nBits += uint32_t(b.nBits);
bits <<= 32 - nBits;
bits |= b.bits;
while (nBits >= 8) {
uint8_t bb = uint8_t(bits >> 24);
b.appendByte(bb);
bits <<= 8;
nBits -= 8;
}
//fprintf(stderr, "Leftovers %d bits %x\n", nBits, bits)
b.bits = bits;
b.nBits = uint8_t(nBits);
}
void BitStream::padToByte() {
for (int i = nBits; (i & 0x07) != 0; ++i) {
emitBit(0);
}
}
std::pair<uint32_t, H264Error> BitStream::scanBits(uint32_t nBits) {
// fprintf(stderr, "scan %d\n", nBits);
BitStream &b = *this;
if (nBits > 16) {
assert(false &&"Must have nBits < 16");
}
if (nBits == 0) {
return uint32E(0, H264ErrorNil); // don't read off the array since it may be empty or at its end
}
uint32_t byteAddress = b.bitReadCursor / 8;
if (int(byteAddress) >= int(b.buffer.size())) {
return uint32E(0, ERR_BOUND);
}
uint32_t bitAddress = b.bitReadCursor - byteAddress*8;
uint32_t retval = 0;
uint32_t curByte = b.buffer[byteAddress] & ((1 << (8 - bitAddress)) - 1);
retval |= uint32_t(curByte);
uint8_t remainingBitsInByte = 8 - bitAddress;
//fmt.Printf("Retval %x[%d].%d so far, Remaining bits %d\n", retval, byteAddress,bitAddress,nBits)
if (remainingBitsInByte >= nBits) {
retval >>= remainingBitsInByte - nBits;
//fmt.Printf("Returning early after single byte read\n")
b.bitReadCursor += nBits;
return uint32E(retval, H264ErrorNil);
}
if (int(byteAddress) >= int(b.buffer.size())) {
return uint32E(0, ERR_BOUND);
}
b.bitReadCursor += remainingBitsInByte;
nBits -= remainingBitsInByte;
if (nBits > 8) {
b.bitReadCursor += 8;
byteAddress += 1;
retval <<= 8;
retval |= uint32_t(b.buffer[byteAddress]);
nBits -= 8;
}
if (nBits > 8) {
assert(false &&"unreachable: we should have only 16 bits to grab");
}
//fmt.Printf("Pref Final things are %x going to read %x after shifting %d\n", retval, b.buffer[byteAddress + 1], nBits)
if (byteAddress+1 >= b.buffer.size()) {
return uint32E(0, ERR_BOUND);
}
retval <<= nBits;
retval |= uint32_t(b.buffer[byteAddress+1] >> (8 - nBits));
b.bitReadCursor += nBits;
//fprintf(stderr, "Final value %x\n", retval)
return uint32E(retval, H264ErrorNil);
}
void BitStream::pop() {
BitStream &b = *this;
if (b.nBits > 0 && b.nBits < 8) {
if (b.buffer.empty()) {
assert(false && "popping from empty buffer");
return;
}
uint32_t poppedByte = 0;
poppedByte = uint32_t(b.buffer.back());
b.buffer.pop_back();
poppedByte <<= b.nBits;
b.bits |= poppedByte;
b.nBits += 8;
}
if (b.nBits >= 8) {
b.nBits -= 8;
b.bits >>= 8;
} else {
b.buffer.pop_back();
}
}
uint32_t BitStream::len()const {
return uint32_t(buffer.size()) + uint32_t(nBits/8);
}
void BitStream::flushBits() {
if (bitsWrittenSinceFlush) {
//emitBits(1, 1);
}
while (nBits > 0) {
emitBits(0, 1);
}
bitsWrittenSinceFlush = false;
}
DynProb ArithmeticCodedInput::TEST_PROB;
DynProb ArithmeticCodedOutput::TEST_PROB;
static int compressed_total = 0;
void ArithmeticCodedOutput::flushToWriter(int streamId, CompressedWriter &w) {
vpx_stop_encode(&writer);
#ifdef BILLING
fprintf(stderr, "%d :: %d [%s]\n", streamId, writer.pos, billEnumToName(streamId));
compressed_total += writer.pos;
if (streamId == PIP_PREV_PRED_TAG || streamId == PIP_NZC_TAG) {
fprintf(stderr, "TOTAL written %d\n", compressed_total);
}
#endif
if (!buffer.empty()) {
w.Write(streamId, &buffer[0], writer.pos);
}
buffer.clear();
}
std::vector<uint8_t> streamLenToBE(uint32_t streamLen) {
uint8_t retval[5] = {uint8_t(streamLen >> 24), uint8_t((streamLen >> 16) & 0xff),
uint8_t((streamLen >> 8) & 0xff), uint8_t(streamLen & 0xff), 0};
return std::vector<uint8_t>(retval, retval + 4);
}
uint32_t bufferBEToStreamLength(uint8_t *buf) {
uint32_t vectorLength = 0;
for (int i = 0; i < 4; i++) { // read in the huffvector length
vectorLength <<= 8;
vectorLength |= uint32_t(buf[i]);
}
return vectorLength;
}
void CompressionStream::flushToWriter(CompressedWriter&w) {
def().padToByte();
#ifdef BILLING
if (!isRecoding) {
static int total = 0;
fprintf(stderr, "0 :: %d [boilerplate]\n", def().buffer.size());
compressed_total += def().buffer.size();
}
#endif
def().flushToWriter(DEFAULT_STREAM, w);
for (std::map<int32_t, ArithmeticCodedOutput>::iterator i = taggedStreams.begin(), ie = taggedStreams.end();
i != ie;
++i) {
i->second.flushToWriter(i->first, w);
}
}
ArithmeticCodedInput& InputCompressionStream::tag(int32_t tag) {
bool mustReadData = taggedStreams.find(tag) == taggedStreams.end();
ArithmeticCodedInput &bs = taggedStreams[tag];
if (filenamePrefix.empty()) {
fprintf(stderr, "Attempting to read %d without input file set\n", tag);
assert(!filenamePrefix.empty());
} else if (mustReadData) {
std::ostringstream os;
os << filenamePrefix << "." << tag;
std::string thisfilename = os.str();
FILE *fp = fopen(thisfilename.c_str(), "rb");
int nread = 0;
if (fp) {
long datalen = -1;
if (fseek(fp, 0, SEEK_END) != -1) {
datalen = ftell(fp);
rewind(fp);
}
if (datalen > 0) {
bs.buffer.resize(datalen);
nread = fread(&(bs.buffer[0]), datalen, 1, fp);
}
fclose(fp);
}
if (nread == 0) {
fprintf(stderr, "Failed to read from file %s\n", thisfilename.c_str());
assert(false && "failed to open input");
}
bs.init();
}
return bs;
}
|
make billing more accurate
|
make billing more accurate
|
C++
|
bsd-2-clause
|
bowlofstew/losslessh264,kevinzhang1986/losslessh264,abhishekgahlot/losslessh264,xiangshuai/losslessh264,SunGuo/losslessh264,lioonline/losslessh264,itplanes/losslessh264,zyhh/losslessh264,bitwing/losslessh264,sunfei/losslessh264,alihalabyah/losslessh264,erillfire/wusunyasuo,alihalabyah/losslessh264,jasonzhong/losslessh264,SunGuo/losslessh264,froggatt/losslessh264,PeterBLITZ/losslessh264,zyhh/losslessh264,LaurenLuoYun/losslessh264,danielrh/losslessh264,WuYaoWang/losslessh264,sunfei/losslessh264,subailong/losslessh264,zyhh/losslessh264,hioop/losslessh264,itplanes/losslessh264,erillfire/wusunyasuo,zyhh/losslessh264,bitwing/losslessh264,aquar25/losslessh264,hgl888/losslessh264,Ghimtim/losslessh264,LaurenLuoYun/losslessh264,WuYaoWang/losslessh264,common2015/losslessh264,lioonline/losslessh264,hj3938/losslessh264,heavenlw/losslessh264,krsjoseph/losslessh264,TonySheh/losslessh264,TonySheh/losslessh264,froggatt/losslessh264,eastlhu/losslessh264,LaurenLuoYun/losslessh264,hioop/losslessh264,hgl888/losslessh264,hj3938/losslessh264,legendtkl/losslessh264,aquar25/losslessh264,noname007/losslessh264,aquar25/losslessh264,hcxyzlm/losslessh264,WuYaoWang/losslessh264,hcxyzlm/losslessh264,Ghimtim/losslessh264,hj3938/losslessh264,aquar25/losslessh264,yurenyong123/losslessh264,PeterBLITZ/losslessh264,WuYaoWang/losslessh264,hgl888/losslessh264,dahebolangkuan/losslessh264,yurenyong123/losslessh264,jasonzhong/losslessh264,treble37/losslessh264,hcxyzlm/losslessh264,subailong/losslessh264,lioonline/losslessh264,hanchl/losslessh264,dahebolangkuan/losslessh264,maxming2333/losslessh264,PeterBLITZ/losslessh264,dahebolangkuan/losslessh264,subailong/losslessh264,SunGuo/losslessh264,hgl888/losslessh264,subailong/losslessh264,lioonline/losslessh264,common2015/losslessh264,kevinzhang1986/losslessh264,zyhh/losslessh264,erillfire/wusunyasuo,erillfire/wusunyasuo,joncampbell123/losslessh264,hj3938/losslessh264,xiangshuai/losslessh264,hcxyzlm/losslessh264,danielrh/losslessh264,jasonzhong/losslessh264,alihalabyah/losslessh264,treble37/losslessh264,noname007/losslessh264,danielrh/losslessh264,jasonzhong/losslessh264,maxming2333/losslessh264,froggatt/losslessh264,joncampbell123/losslessh264,maxming2333/losslessh264,hcxyzlm/losslessh264,noname007/losslessh264,yurenyong123/losslessh264,legendtkl/losslessh264,bowlofstew/losslessh264,mazalet/losslessh264,maxming2333/losslessh264,heavenlw/losslessh264,hioop/losslessh264,kevinzhang1986/losslessh264,LaurenLuoYun/losslessh264,common2015/losslessh264,heavenlw/losslessh264,itplanes/losslessh264,mazalet/losslessh264,itplanes/losslessh264,krsjoseph/losslessh264,xiangshuai/losslessh264,krsjoseph/losslessh264,krsjoseph/losslessh264,bitwing/losslessh264,eastlhu/losslessh264,dahebolangkuan/losslessh264,froggatt/losslessh264,common2015/losslessh264,hgl888/losslessh264,WuYaoWang/losslessh264,PeterBLITZ/losslessh264,alihalabyah/losslessh264,bowlofstew/losslessh264,kevinzhang1986/losslessh264,LaurenLuoYun/losslessh264,subailong/losslessh264,TonySheh/losslessh264,hj3938/losslessh264,treble37/losslessh264,TonySheh/losslessh264,yurenyong123/losslessh264,jlhbaseball15/losslessh264,TonySheh/losslessh264,PeterBLITZ/losslessh264,xiangshuai/losslessh264,abhishekgahlot/losslessh264,noname007/losslessh264,mazalet/losslessh264,hgl888/losslessh264,aquar25/losslessh264,bowlofstew/losslessh264,bitwing/losslessh264,itplanes/losslessh264,common2015/losslessh264,yurenyong123/losslessh264,mazalet/losslessh264,LaurenLuoYun/losslessh264,subailong/losslessh264,xiangshuai/losslessh264,xiangshuai/losslessh264,maxming2333/losslessh264,WuYaoWang/losslessh264,Ghimtim/losslessh264,treble37/losslessh264,jlhbaseball15/losslessh264,hioop/losslessh264,hioop/losslessh264,hcxyzlm/losslessh264,heavenlw/losslessh264,heavenlw/losslessh264,bitwing/losslessh264,mazalet/losslessh264,LaurenLuoYun/losslessh264,sunfei/losslessh264,sunfei/losslessh264,eastlhu/losslessh264,danielrh/losslessh264,treble37/losslessh264,jasonzhong/losslessh264,zyhh/losslessh264,joncampbell123/losslessh264,sunfei/losslessh264,TonySheh/losslessh264,Ghimtim/losslessh264,mazalet/losslessh264,jlhbaseball15/losslessh264,danielrh/losslessh264,common2015/losslessh264,hanchl/losslessh264,kevinzhang1986/losslessh264,joncampbell123/losslessh264,legendtkl/losslessh264,krsjoseph/losslessh264,dahebolangkuan/losslessh264,alihalabyah/losslessh264,jasonzhong/losslessh264,TonySheh/losslessh264,froggatt/losslessh264,legendtkl/losslessh264,lioonline/losslessh264,hanchl/losslessh264,legendtkl/losslessh264,legendtkl/losslessh264,SunGuo/losslessh264,noname007/losslessh264,dahebolangkuan/losslessh264,hj3938/losslessh264,PeterBLITZ/losslessh264,abhishekgahlot/losslessh264,hanchl/losslessh264,maxming2333/losslessh264,bitwing/losslessh264,xiangshuai/losslessh264,legendtkl/losslessh264,abhishekgahlot/losslessh264,Ghimtim/losslessh264,dahebolangkuan/losslessh264,mazalet/losslessh264,hj3938/losslessh264,alihalabyah/losslessh264,zyhh/losslessh264,joncampbell123/losslessh264,eastlhu/losslessh264,erillfire/wusunyasuo,aquar25/losslessh264,krsjoseph/losslessh264,alihalabyah/losslessh264,erillfire/wusunyasuo,hcxyzlm/losslessh264,jasonzhong/losslessh264,abhishekgahlot/losslessh264,aquar25/losslessh264,yurenyong123/losslessh264,hioop/losslessh264,eastlhu/losslessh264,hioop/losslessh264,jlhbaseball15/losslessh264,noname007/losslessh264,Ghimtim/losslessh264,hanchl/losslessh264,froggatt/losslessh264,bowlofstew/losslessh264,SunGuo/losslessh264,treble37/losslessh264,kevinzhang1986/losslessh264,SunGuo/losslessh264,treble37/losslessh264,jlhbaseball15/losslessh264,bitwing/losslessh264,bowlofstew/losslessh264,erillfire/wusunyasuo,abhishekgahlot/losslessh264,heavenlw/losslessh264,maxming2333/losslessh264,froggatt/losslessh264,hgl888/losslessh264,jlhbaseball15/losslessh264,hanchl/losslessh264,danielrh/losslessh264,lioonline/losslessh264,kevinzhang1986/losslessh264,hanchl/losslessh264,krsjoseph/losslessh264,SunGuo/losslessh264,jlhbaseball15/losslessh264,joncampbell123/losslessh264,danielrh/losslessh264,common2015/losslessh264,itplanes/losslessh264,WuYaoWang/losslessh264,sunfei/losslessh264,sunfei/losslessh264,yurenyong123/losslessh264,subailong/losslessh264,abhishekgahlot/losslessh264,itplanes/losslessh264,eastlhu/losslessh264,Ghimtim/losslessh264,PeterBLITZ/losslessh264,heavenlw/losslessh264,eastlhu/losslessh264,joncampbell123/losslessh264,lioonline/losslessh264,noname007/losslessh264,bowlofstew/losslessh264
|
67ceae8385ff88231aed7db22f27b236809732d0
|
unittest/progress_test.cc
|
unittest/progress_test.cc
|
///////////////////////////////////////////////////////////////////////
// File: apiexample_test.cc
// Description: Progress reporting API Test for Tesseract.
// Author: Jaroslaw Kubik
//
// 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.
///////////////////////////////////////////////////////////////////////
// expects clone of tessdata_fast repo in ../../tessdata_fast
#include "include_gunit.h"
#include "gmock/gmock.h"
#include "baseapi.h"
#include "ocrclass.h"
#include "leptonica/allheaders.h"
#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <limits.h>
#include <time.h>
namespace {
class QuickTest : public testing::Test {
protected:
virtual void SetUp() {
start_time_ = time(nullptr);
}
virtual void TearDown() {
const time_t end_time = time(nullptr);
EXPECT_TRUE(end_time - start_time_ <=25) << "The test took too long - " << ::testing::PrintToString(end_time - start_time_);
}
time_t start_time_;
};
class ClassicMockProgressSink {
public:
MOCK_METHOD1(classicProgress, bool( int ) );
MOCK_METHOD1(cancel, bool( int ));
ETEXT_DESC monitor;
ClassicMockProgressSink()
{
monitor.progress_callback = []( int progress, int, int, int, int ) ->bool {
return instance->classicProgress( progress );
};
monitor.cancel = []( void* ths, int words ) -> bool {
((ClassicMockProgressSink*)ths)->cancel( words );
};
monitor.cancel_this = this;
instance = this;
}
static ClassicMockProgressSink* instance;
};
ClassicMockProgressSink* ClassicMockProgressSink::instance = nullptr;
class NewMockProgressSink : public ClassicMockProgressSink {
public:
MOCK_METHOD1(progress, bool( int ) );
NewMockProgressSink()
{
monitor.progress_callback2 = [](ETEXT_DESC* ths, int, int, int, int ) -> bool {
return ((NewMockProgressSink*)ths->cancel_this)->progress( ths->progress );
};
}
};
void ClassicProgressTester(const char* imgname, const char* tessdatadir, const char* lang) {
using ::testing::_;
using ::testing::AllOf;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::Gt;
using ::testing::Le;
using ::testing::Return;
using ::testing::SaveArg;
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
ASSERT_FALSE(api->Init(tessdatadir, lang)) << "Could not initialize tesseract.";
Pix *image = pixRead(imgname);
ASSERT_TRUE(image != nullptr) << "Failed to read test image.";
api->SetImage(image);
ClassicMockProgressSink progressSink;
int currentProgress = -1;
EXPECT_CALL( progressSink, classicProgress(AllOf(Gt(currentProgress),Le(100))) )
.Times(AtLeast(5))
.WillRepeatedly( DoAll(SaveArg<0>(¤tProgress),
Return(false) ));
EXPECT_CALL( progressSink, cancel(_) )
.Times(AtLeast(5))
.WillRepeatedly(Return(false));
EXPECT_EQ( api->Recognize( &progressSink.monitor ), false );
EXPECT_GE( currentProgress, 50 ) << "The reported progress did not reach 50%";
api->End();
pixDestroy(&image);
}
void NewProgressTester(const char* imgname, const char* tessdatadir, const char* lang) {
using ::testing::_;
using ::testing::AllOf;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::Gt;
using ::testing::Le;
using ::testing::Return;
using ::testing::SaveArg;
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
ASSERT_FALSE(api->Init(tessdatadir, lang)) << "Could not initialize tesseract.";
Pix *image = pixRead(imgname);
ASSERT_TRUE(image != nullptr) << "Failed to read test image.";
api->SetImage(image);
NewMockProgressSink progressSink;
int currentProgress = -1;
EXPECT_CALL( progressSink, classicProgress(_) )
.Times(0);
EXPECT_CALL( progressSink, progress(AllOf(Gt(currentProgress),Le(100))) )
.Times(AtLeast(5))
.WillRepeatedly( DoAll(SaveArg<0>(¤tProgress),
Return(false) ));
EXPECT_CALL( progressSink, cancel(_) )
.Times(AtLeast(5))
.WillRepeatedly(Return(false));
EXPECT_EQ( api->Recognize( &progressSink.monitor ), false );
EXPECT_GE( currentProgress, 50 ) << "The reported progress did not reach 50%";
api->End();
pixDestroy(&image);
}
TEST(QuickTest, ClassicProgressReporitng) {
ClassicProgressTester(TESTING_DIR "/phototest.tif",
TESSDATA_DIR "_fast", "eng");
}
TEST(QuickTest, NewProgressReporitng) {
NewProgressTester(TESTING_DIR "/phototest.tif",
TESSDATA_DIR "_fast", "eng");
}
} // namespace
|
///////////////////////////////////////////////////////////////////////
// File: apiexample_test.cc
// Description: Progress reporting API Test for Tesseract.
// Author: Jaroslaw Kubik
//
// 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.
///////////////////////////////////////////////////////////////////////
// expects clone of tessdata_fast repo in ../../tessdata_fast
#include "include_gunit.h"
#include "gmock/gmock.h"
#include "baseapi.h"
#include "ocrclass.h"
#include "leptonica/allheaders.h"
#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <limits.h>
#include <time.h>
namespace {
class QuickTest : public testing::Test {
protected:
virtual void SetUp() {
start_time_ = time(nullptr);
}
virtual void TearDown() {
const time_t end_time = time(nullptr);
EXPECT_TRUE(end_time - start_time_ <=25) << "The test took too long - " << ::testing::PrintToString(end_time - start_time_);
}
time_t start_time_;
};
class ClassicMockProgressSink {
public:
MOCK_METHOD1(classicProgress, bool( int ) );
MOCK_METHOD1(cancel, bool( int ));
ETEXT_DESC monitor;
ClassicMockProgressSink()
{
monitor.progress_callback = []( int progress, int, int, int, int ) ->bool {
return instance->classicProgress( progress );
};
monitor.cancel = []( void* ths, int words ) -> bool {
((ClassicMockProgressSink*)ths)->cancel( words );
};
monitor.cancel_this = this;
instance = this;
}
static ClassicMockProgressSink* instance;
};
ClassicMockProgressSink* ClassicMockProgressSink::instance = nullptr;
class NewMockProgressSink : public ClassicMockProgressSink {
public:
MOCK_METHOD1(progress, bool( int ) );
NewMockProgressSink()
{
monitor.progress_callback2 = [](ETEXT_DESC* ths, int, int, int, int ) -> bool {
return ((NewMockProgressSink*)ths->cancel_this)->progress( ths->progress );
};
}
};
void ClassicProgressTester(const char* imgname, const char* tessdatadir, const char* lang) {
using ::testing::_;
using ::testing::AllOf;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::Gt;
using ::testing::Le;
using ::testing::Return;
using ::testing::SaveArg;
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
ASSERT_FALSE(api->Init(tessdatadir, lang)) << "Could not initialize tesseract.";
Pix *image = pixRead(imgname);
ASSERT_TRUE(image != nullptr) << "Failed to read test image.";
api->SetImage(image);
ClassicMockProgressSink progressSink;
int currentProgress = -1;
EXPECT_CALL( progressSink, classicProgress(AllOf(Gt<int&>(currentProgress),Le(100))) )
.Times(AtLeast(5))
.WillRepeatedly( DoAll(SaveArg<0>(¤tProgress),
Return(false) ));
EXPECT_CALL( progressSink, cancel(_) )
.Times(AtLeast(5))
.WillRepeatedly(Return(false));
EXPECT_EQ( api->Recognize( &progressSink.monitor ), false );
EXPECT_GE( currentProgress, 50 ) << "The reported progress did not reach 50%";
api->End();
pixDestroy(&image);
}
void NewProgressTester(const char* imgname, const char* tessdatadir, const char* lang) {
using ::testing::_;
using ::testing::AllOf;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::Gt;
using ::testing::Le;
using ::testing::Return;
using ::testing::SaveArg;
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
ASSERT_FALSE(api->Init(tessdatadir, lang)) << "Could not initialize tesseract.";
Pix *image = pixRead(imgname);
ASSERT_TRUE(image != nullptr) << "Failed to read test image.";
api->SetImage(image);
NewMockProgressSink progressSink;
int currentProgress = -1;
EXPECT_CALL( progressSink, classicProgress(_) )
.Times(0);
EXPECT_CALL( progressSink, progress(AllOf(Gt<int&>(currentProgress),Le(100))) )
.Times(AtLeast(5))
.WillRepeatedly( DoAll(SaveArg<0>(¤tProgress),
Return(false) ));
EXPECT_CALL( progressSink, cancel(_) )
.Times(AtLeast(5))
.WillRepeatedly(Return(false));
EXPECT_EQ( api->Recognize( &progressSink.monitor ), false );
EXPECT_GE( currentProgress, 50 ) << "The reported progress did not reach 50%";
api->End();
pixDestroy(&image);
}
TEST(QuickTest, ClassicProgressReporitng) {
ClassicProgressTester(TESTING_DIR "/phototest.tif",
TESSDATA_DIR "_fast", "eng");
}
TEST(QuickTest, NewProgressReporitng) {
NewProgressTester(TESTING_DIR "/phototest.tif",
TESSDATA_DIR "_fast", "eng");
}
} // namespace
|
Fix the progres increase test
|
Fix the progres increase test
The progress increase test must compare the input value against
the variable that contains a previous value, not against it's
initial value.
|
C++
|
apache-2.0
|
amitdo/tesseract,stweil/tesseract,tesseract-ocr/tesseract,amitdo/tesseract,UB-Mannheim/tesseract,jbarlow83/tesseract,jbarlow83/tesseract,stweil/tesseract,jbarlow83/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,jbarlow83/tesseract,UB-Mannheim/tesseract,tesseract-ocr/tesseract,stweil/tesseract,tesseract-ocr/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,amitdo/tesseract,stweil/tesseract,stweil/tesseract,jbarlow83/tesseract,tesseract-ocr/tesseract,amitdo/tesseract
|
29afbdba61614d61fdb803b27478e32ea35edc5f
|
src/compositor/hardware_integration/wayland_egl/waylandeglintegration.cpp
|
src/compositor/hardware_integration/wayland_egl/waylandeglintegration.cpp
|
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "waylandeglintegration.h"
#include "wayland_wrapper/wlcompositor.h"
#include "wayland_wrapper/wlsurface.h"
#include "compositor_api/waylandsurface.h"
#include <qpa/qplatformnativeinterface.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLContext>
#include <qpa/qplatformscreen.h>
#include <QtGui/QWindow>
#include <QtCore/QWeakPointer>
#include <QDebug>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
GraphicsHardwareIntegration * GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor)
{
return new WaylandEglIntegration(compositor);
}
#ifndef EGL_WL_bind_wayland_display
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
#endif
#ifndef EGL_KHR_image
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#endif
#ifndef GL_OES_EGL_image
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
#endif
class WaylandEglIntegrationPrivate
{
public:
WaylandEglIntegrationPrivate()
: egl_display(EGL_NO_DISPLAY)
, valid(false)
, flipperConnected(false)
, egl_bind_wayland_display(0)
, egl_unbind_wayland_display(0)
, egl_create_image(0)
, egl_destroy_image(0)
, gl_egl_image_target_texture_2d(0)
{ }
EGLDisplay egl_display;
bool valid;
bool flipperConnected;
#ifdef EGL_WL_request_client_buffer_format
QWeakPointer<WaylandSurface> directRenderSurface;
#endif
PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;
PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;
PFNEGLCREATEIMAGEKHRPROC egl_create_image;
PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;
};
WaylandEglIntegration::WaylandEglIntegration(WaylandCompositor *compositor)
: GraphicsHardwareIntegration(compositor)
, d_ptr(new WaylandEglIntegrationPrivate)
{
}
void WaylandEglIntegration::initializeHardware(Wayland::Display *waylandDisplay)
{
Q_D(WaylandEglIntegration);
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
if (nativeInterface) {
d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window());
if (d->egl_display) {
const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);
if (extensionString && strstr(extensionString, "EGL_WL_bind_wayland_display"))
{
d->egl_bind_wayland_display =
reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglBindWaylandDisplayWL"));
d->egl_unbind_wayland_display =
reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglUnbindWaylandDisplayWL"));
d->egl_create_image =
reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
d->egl_destroy_image =
reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
d->gl_egl_image_target_texture_2d =
reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));
if (d->egl_bind_wayland_display
&& d->egl_unbind_wayland_display
&& d->egl_create_image
&& d->egl_destroy_image
&& d->gl_egl_image_target_texture_2d) {
if (d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle())) {
d->valid = true;
}
}
}
}
if (!d->valid)
qWarning("Failed to initialize egl display\n");
}
}
GLuint WaylandEglIntegration::createTextureFromBuffer(wl_buffer *buffer, QOpenGLContext *context)
{
Q_D(WaylandEglIntegration);
if (!d->valid) {
qWarning("createTextureFromBuffer() failed\n");
return 0;
}
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
//#####jl: fix to use functions pointer
EGLContext egl_context = nativeInterface->nativeResourceForContext("EglContext", context);
EGLImageKHR image = d->egl_create_image(d->egl_display, egl_context,
EGL_WAYLAND_BUFFER_WL,
buffer, NULL);
GLuint textureId;
glGenTextures(1,&textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
d->egl_destroy_image(d->egl_display, image);
return textureId;
}
bool WaylandEglIntegration::isYInverted(struct wl_buffer *buffer) const
{
#ifdef EGL_WL_request_client_buffer_format
return eglGetBufferYInvertedWL(buffer);
#else
return GraphicsHardwareIntegration::isYInverted(buffer);
#endif
}
bool WaylandEglIntegration::setDirectRenderSurface(WaylandSurface *surface)
{
Q_D(WaylandEglIntegration);
QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());
QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;
if (flipper && !d->flipperConnected) {
QObject::connect(flipper, SIGNAL(bufferReleased(void*)), m_compositor->handle(), SLOT(releaseBuffer(void*)));
d->flipperConnected = true;
}
#ifdef EGL_WL_request_client_buffer_format
int buffer_format = surface ? EGL_SCANOUT_FORMAT_WL : EGL_RENDER_FORMAT_WL;
struct wl_client *client = 0;
if (surface) {
client = surface->handle()->base()->resource.client;
} else {
WaylandSurface *oldSurface = d->directRenderSurface.data();
if (oldSurface)
client = oldSurface->handle()->base()->resource.client;
}
if (client)
eglRequestClientBufferFormatWL(d->egl_display, client, buffer_format);
d->directRenderSurface = surface;
#else
Q_UNUSED(surface);
#endif
return flipper;
}
void *WaylandEglIntegration::lockNativeBuffer(struct wl_buffer *buffer, QOpenGLContext *context) const
{
Q_D(const WaylandEglIntegration);
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
//#####jl: fix to use functions pointer
EGLContext egl_context = nativeInterface->nativeResourceForContext("EglContext", context);
EGLImageKHR image = d->egl_create_image(d->egl_display, egl_context,
EGL_WAYLAND_BUFFER_WL,
buffer, NULL);
return image;
}
void WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const
{
Q_D(const WaylandEglIntegration);
EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);
d->egl_destroy_image(d->egl_display, image);
}
|
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "waylandeglintegration.h"
#include "wayland_wrapper/wlcompositor.h"
#include "wayland_wrapper/wlsurface.h"
#include "compositor_api/waylandsurface.h"
#include <qpa/qplatformnativeinterface.h>
#include <QtGui/QGuiApplication>
#include <QtGui/QOpenGLContext>
#include <qpa/qplatformscreen.h>
#include <QtGui/QWindow>
#include <QtCore/QPointer>
#include <QDebug>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
GraphicsHardwareIntegration * GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor)
{
return new WaylandEglIntegration(compositor);
}
#ifndef EGL_WL_bind_wayland_display
typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWL) (EGLDisplay dpy, struct wl_display *display);
#endif
#ifndef EGL_KHR_image
typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image);
#endif
#ifndef GL_OES_EGL_image
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image);
typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image);
#endif
class WaylandEglIntegrationPrivate
{
public:
WaylandEglIntegrationPrivate()
: egl_display(EGL_NO_DISPLAY)
, valid(false)
, flipperConnected(false)
, egl_bind_wayland_display(0)
, egl_unbind_wayland_display(0)
, egl_create_image(0)
, egl_destroy_image(0)
, gl_egl_image_target_texture_2d(0)
{ }
EGLDisplay egl_display;
bool valid;
bool flipperConnected;
#ifdef EGL_WL_request_client_buffer_format
QPointer<WaylandSurface> directRenderSurface;
#endif
PFNEGLBINDWAYLANDDISPLAYWL egl_bind_wayland_display;
PFNEGLUNBINDWAYLANDDISPLAYWL egl_unbind_wayland_display;
PFNEGLCREATEIMAGEKHRPROC egl_create_image;
PFNEGLDESTROYIMAGEKHRPROC egl_destroy_image;
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gl_egl_image_target_texture_2d;
};
WaylandEglIntegration::WaylandEglIntegration(WaylandCompositor *compositor)
: GraphicsHardwareIntegration(compositor)
, d_ptr(new WaylandEglIntegrationPrivate)
{
}
void WaylandEglIntegration::initializeHardware(Wayland::Display *waylandDisplay)
{
Q_D(WaylandEglIntegration);
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
if (nativeInterface) {
d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window());
if (d->egl_display) {
const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS);
if (extensionString && strstr(extensionString, "EGL_WL_bind_wayland_display"))
{
d->egl_bind_wayland_display =
reinterpret_cast<PFNEGLBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglBindWaylandDisplayWL"));
d->egl_unbind_wayland_display =
reinterpret_cast<PFNEGLUNBINDWAYLANDDISPLAYWL>(eglGetProcAddress("eglUnbindWaylandDisplayWL"));
d->egl_create_image =
reinterpret_cast<PFNEGLCREATEIMAGEKHRPROC>(eglGetProcAddress("eglCreateImageKHR"));
d->egl_destroy_image =
reinterpret_cast<PFNEGLDESTROYIMAGEKHRPROC>(eglGetProcAddress("eglDestroyImageKHR"));
d->gl_egl_image_target_texture_2d =
reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));
if (d->egl_bind_wayland_display
&& d->egl_unbind_wayland_display
&& d->egl_create_image
&& d->egl_destroy_image
&& d->gl_egl_image_target_texture_2d) {
if (d->egl_bind_wayland_display(d->egl_display, waylandDisplay->handle())) {
d->valid = true;
}
}
}
}
if (!d->valid)
qWarning("Failed to initialize egl display\n");
}
}
GLuint WaylandEglIntegration::createTextureFromBuffer(wl_buffer *buffer, QOpenGLContext *context)
{
Q_D(WaylandEglIntegration);
if (!d->valid) {
qWarning("createTextureFromBuffer() failed\n");
return 0;
}
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
//#####jl: fix to use functions pointer
EGLContext egl_context = nativeInterface->nativeResourceForContext("EglContext", context);
EGLImageKHR image = d->egl_create_image(d->egl_display, egl_context,
EGL_WAYLAND_BUFFER_WL,
buffer, NULL);
GLuint textureId;
glGenTextures(1,&textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
d->gl_egl_image_target_texture_2d(GL_TEXTURE_2D, image);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
d->egl_destroy_image(d->egl_display, image);
return textureId;
}
bool WaylandEglIntegration::isYInverted(struct wl_buffer *buffer) const
{
#ifdef EGL_WL_request_client_buffer_format
return eglGetBufferYInvertedWL(buffer);
#else
return GraphicsHardwareIntegration::isYInverted(buffer);
#endif
}
bool WaylandEglIntegration::setDirectRenderSurface(WaylandSurface *surface)
{
Q_D(WaylandEglIntegration);
QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window());
QPlatformScreenPageFlipper *flipper = screen ? screen->pageFlipper() : 0;
if (flipper && !d->flipperConnected) {
QObject::connect(flipper, SIGNAL(bufferReleased(void*)), m_compositor->handle(), SLOT(releaseBuffer(void*)));
d->flipperConnected = true;
}
#ifdef EGL_WL_request_client_buffer_format
int buffer_format = surface ? EGL_SCANOUT_FORMAT_WL : EGL_RENDER_FORMAT_WL;
struct wl_client *client = 0;
if (surface) {
client = surface->handle()->base()->resource.client;
} else {
WaylandSurface *oldSurface = d->directRenderSurface.data();
if (oldSurface)
client = oldSurface->handle()->base()->resource.client;
}
if (client)
eglRequestClientBufferFormatWL(d->egl_display, client, buffer_format);
d->directRenderSurface = surface;
#else
Q_UNUSED(surface);
#endif
return flipper;
}
void *WaylandEglIntegration::lockNativeBuffer(struct wl_buffer *buffer, QOpenGLContext *context) const
{
Q_D(const WaylandEglIntegration);
QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface();
//#####jl: fix to use functions pointer
EGLContext egl_context = nativeInterface->nativeResourceForContext("EglContext", context);
EGLImageKHR image = d->egl_create_image(d->egl_display, egl_context,
EGL_WAYLAND_BUFFER_WL,
buffer, NULL);
return image;
}
void WaylandEglIntegration::unlockNativeBuffer(void *native_buffer, QOpenGLContext *) const
{
Q_D(const WaylandEglIntegration);
EGLImageKHR image = static_cast<EGLImageKHR>(native_buffer);
d->egl_destroy_image(d->egl_display, image);
}
|
Use QPointer instead of QWeakPointer for tracking QObjects.
|
Use QPointer instead of QWeakPointer for tracking QObjects.
Change-Id: I842906ffcc37e6649d947cef3a0d9ea942b14d05
Reviewed-by: Thiago Macieira <[email protected]>
|
C++
|
lgpl-2.1
|
locusf/qtwayland-1,locusf/qtwayland-1,Tofee/qtwayland,locusf/qtwayland-1,ntanibata/qtwayland,ntanibata/qtwayland,Tofee/qtwayland,ntanibata/qtwayland,locusf/qtwayland-1,Tofee/qtwayland
|
35193d5c54380be9c820e8f20583f77c83ff7ab7
|
chrome/browser/intents/cws_intents_registry.cc
|
chrome/browser/intents/cws_intents_registry.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/intents/cws_intents_registry.h"
#include "base/callback.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/intents/api_key.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/net/url_util.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
namespace {
// URL for CWS intents API.
const char kCWSIntentServiceURL[] =
"https://www.googleapis.com/chromewebstore/v1.1b/items/intent";
} // namespace
// Internal object representing all data associated with a single query.
struct CWSIntentsRegistry::IntentsQuery {
IntentsQuery();
~IntentsQuery();
// Underlying URL request query.
scoped_ptr<content::URLFetcher> url_fetcher;
// The callback - invoked on completed retrieval.
ResultsCallback callback;
};
CWSIntentsRegistry::IntentsQuery::IntentsQuery() {
}
CWSIntentsRegistry::IntentsQuery::~IntentsQuery() {
}
CWSIntentsRegistry::IntentExtensionInfo::IntentExtensionInfo()
: num_ratings(0),
average_rating(0) {
}
CWSIntentsRegistry::IntentExtensionInfo::~IntentExtensionInfo() {
}
CWSIntentsRegistry::CWSIntentsRegistry(net::URLRequestContextGetter* context)
: request_context_(context) {
}
CWSIntentsRegistry::~CWSIntentsRegistry() {
// Cancel all pending queries, since we can't handle them any more.
STLDeleteValues(&queries_);
}
void CWSIntentsRegistry::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK(source);
URLFetcherHandle handle = reinterpret_cast<URLFetcherHandle>(source);
QueryMap::iterator it = queries_.find(handle);
DCHECK(it != queries_.end());
scoped_ptr<IntentsQuery> query(it->second);
DCHECK(query.get() != NULL);
queries_.erase(it);
std::string response;
source->GetResponseAsString(&response);
// TODO(groby): Do we really only accept 200, or any 2xx codes?
if (source->GetResponseCode() != 200)
return;
std::string error;
scoped_ptr<Value> parsed_response;
JSONStringValueSerializer serializer(response);
parsed_response.reset(serializer.Deserialize(NULL, &error));
if (parsed_response.get() == NULL)
return;
DictionaryValue* response_dict;
parsed_response->GetAsDictionary(&response_dict);
if (!response_dict)
return;
ListValue* items;
if (!response_dict->GetList("items", &items))
return;
IntentExtensionList intents;
for (ListValue::const_iterator iter(items->begin());
iter != items->end(); ++iter) {
DictionaryValue* item = static_cast<DictionaryValue*>(*iter);
// All fields are mandatory - skip this result if we can't find a field.
IntentExtensionInfo info;
if (!item->GetString("id", &info.id))
continue;
if (!item->GetInteger("num_ratings", &info.num_ratings))
continue;
if (!item->GetDouble("average_rating", &info.average_rating))
continue;
if (!item->GetString("manifest", &info.manifest))
continue;
std::string manifest_utf8 = UTF16ToUTF8(info.manifest);
JSONStringValueSerializer manifest_serializer(manifest_utf8);
scoped_ptr<Value> manifest_value;
manifest_value.reset(manifest_serializer.Deserialize(NULL, &error));
if (manifest_value.get() == NULL)
continue;
DictionaryValue* manifest_dict;
manifest_value->GetAsDictionary(&manifest_dict);
if (!manifest_dict->GetString("name", &info.name))
continue;
string16 url_string;
if (!item->GetString("icon_url", &url_string))
continue;
info.icon_url = GURL(url_string);
intents.push_back(info);
}
if (!query->callback.is_null())
query->callback.Run(intents);
}
void CWSIntentsRegistry::GetIntentServices(const string16& action,
const string16& mimetype,
const ResultsCallback& cb) {
scoped_ptr<IntentsQuery> query(new IntentsQuery);
query->callback = cb;
query->url_fetcher.reset(content::URLFetcher::Create(
0, BuildQueryURL(action,mimetype), content::URLFetcher::GET, this));
if (query->url_fetcher.get() == NULL)
return;
query->url_fetcher->SetRequestContext(request_context_);
query->url_fetcher->SetLoadFlags(
net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES);
URLFetcherHandle handle = reinterpret_cast<URLFetcherHandle>(
query->url_fetcher.get());
queries_[handle] = query.release();
queries_[handle]->url_fetcher->Start();
}
// static
GURL CWSIntentsRegistry::BuildQueryURL(const string16& action,
const string16& type) {
GURL request(kCWSIntentServiceURL);
request = chrome_common_net::AppendQueryParameter(request, "intent",
UTF16ToUTF8(action));
request = chrome_common_net::AppendQueryParameter(request, "mime_types",
UTF16ToUTF8(type));
if (web_intents::kApiKey[0]) {
request = chrome_common_net::AppendQueryParameter(request, "key",
web_intents::kApiKey);
}
return request;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/intents/cws_intents_registry.h"
#include "base/callback.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/scoped_ptr.h"
#include "base/stl_util.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/intents/api_key.h"
#include "chrome/browser/net/chrome_url_request_context.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/common/net/url_util.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
namespace {
// URL for CWS intents API.
const char kCWSIntentServiceURL[] =
"https://www.googleapis.com/chromewebstore/v1.1b/items/intent";
} // namespace
// Internal object representing all data associated with a single query.
struct CWSIntentsRegistry::IntentsQuery {
IntentsQuery();
~IntentsQuery();
// Underlying URL request query.
scoped_ptr<content::URLFetcher> url_fetcher;
// The callback - invoked on completed retrieval.
ResultsCallback callback;
};
CWSIntentsRegistry::IntentsQuery::IntentsQuery() {
}
CWSIntentsRegistry::IntentsQuery::~IntentsQuery() {
}
CWSIntentsRegistry::IntentExtensionInfo::IntentExtensionInfo()
: num_ratings(0),
average_rating(0) {
}
CWSIntentsRegistry::IntentExtensionInfo::~IntentExtensionInfo() {
}
CWSIntentsRegistry::CWSIntentsRegistry(net::URLRequestContextGetter* context)
: request_context_(context) {
}
CWSIntentsRegistry::~CWSIntentsRegistry() {
// Cancel all pending queries, since we can't handle them any more.
STLDeleteValues(&queries_);
}
void CWSIntentsRegistry::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK(source);
URLFetcherHandle handle = reinterpret_cast<URLFetcherHandle>(source);
QueryMap::iterator it = queries_.find(handle);
DCHECK(it != queries_.end());
scoped_ptr<IntentsQuery> query(it->second);
DCHECK(query.get() != NULL);
queries_.erase(it);
std::string response;
source->GetResponseAsString(&response);
// TODO(groby): Do we really only accept 200, or any 2xx codes?
if (source->GetResponseCode() != 200)
return;
std::string error;
scoped_ptr<Value> parsed_response;
JSONStringValueSerializer serializer(response);
parsed_response.reset(serializer.Deserialize(NULL, &error));
if (parsed_response.get() == NULL)
return;
DictionaryValue* response_dict = NULL;
if (!parsed_response->GetAsDictionary(&response_dict) || !response_dict)
return;
ListValue* items;
if (!response_dict->GetList("items", &items))
return;
IntentExtensionList intents;
for (ListValue::const_iterator iter(items->begin());
iter != items->end(); ++iter) {
DictionaryValue* item = static_cast<DictionaryValue*>(*iter);
// All fields are mandatory - skip this result if we can't find a field.
IntentExtensionInfo info;
if (!item->GetString("id", &info.id))
continue;
if (!item->GetInteger("num_ratings", &info.num_ratings))
continue;
if (!item->GetDouble("average_rating", &info.average_rating))
continue;
if (!item->GetString("manifest", &info.manifest))
continue;
std::string manifest_utf8 = UTF16ToUTF8(info.manifest);
JSONStringValueSerializer manifest_serializer(manifest_utf8);
scoped_ptr<Value> manifest_value;
manifest_value.reset(manifest_serializer.Deserialize(NULL, &error));
if (manifest_value.get() == NULL)
continue;
DictionaryValue* manifest_dict;
manifest_value->GetAsDictionary(&manifest_dict);
if (!manifest_dict->GetString("name", &info.name))
continue;
string16 url_string;
if (!item->GetString("icon_url", &url_string))
continue;
info.icon_url = GURL(url_string);
intents.push_back(info);
}
if (!query->callback.is_null())
query->callback.Run(intents);
}
void CWSIntentsRegistry::GetIntentServices(const string16& action,
const string16& mimetype,
const ResultsCallback& cb) {
scoped_ptr<IntentsQuery> query(new IntentsQuery);
query->callback = cb;
query->url_fetcher.reset(content::URLFetcher::Create(
0, BuildQueryURL(action,mimetype), content::URLFetcher::GET, this));
if (query->url_fetcher.get() == NULL)
return;
query->url_fetcher->SetRequestContext(request_context_);
query->url_fetcher->SetLoadFlags(
net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES);
URLFetcherHandle handle = reinterpret_cast<URLFetcherHandle>(
query->url_fetcher.get());
queries_[handle] = query.release();
queries_[handle]->url_fetcher->Start();
}
// static
GURL CWSIntentsRegistry::BuildQueryURL(const string16& action,
const string16& type) {
GURL request(kCWSIntentServiceURL);
request = chrome_common_net::AppendQueryParameter(request, "intent",
UTF16ToUTF8(action));
request = chrome_common_net::AppendQueryParameter(request, "mime_types",
UTF16ToUTF8(type));
if (web_intents::kApiKey[0]) {
request = chrome_common_net::AppendQueryParameter(request, "key",
web_intents::kApiKey);
}
return request;
}
|
Check the return value of GetAsDictionary().
|
Coverity: Check the return value of GetAsDictionary().
CID_COUNT=1
CID=103995
BUG=none
TEST=none
R=groby
Review URL: https://chromiumcodereview.appspot.com/10387103
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@136919 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
ltilve/chromium,dushu1203/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,robclark/chromium,M4sse/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,keishi/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,zcbenz/cefode-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,Fireblend/chromium-crosswalk,robclark/chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,robclark/chromium,anirudhSK/chromium,robclark/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,robclark/chromium,timopulkkinen/BubbleFish,keishi/chromium,Just-D/chromium-1,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,Just-D/chromium-1,anirudhSK/chromium,markYoungH/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,ltilve/chromium,hgl888/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,keishi/chromium,ondra-novak/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,anirudhSK/chromium,timopulkkinen/BubbleFish,ltilve/chromium,pozdnyakov/chromium-crosswalk,keishi/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,robclark/chromium,M4sse/chromium.src,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,robclark/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,Just-D/chromium-1,markYoungH/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,dushu1203/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,Just-D/chromium-1,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,ltilve/chromium,keishi/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,timopulkkinen/BubbleFish,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,jaruba/chromium.src,dednal/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,littlstar/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,robclark/chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,dushu1203/chromium.src,robclark/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,chuan9/chromium-crosswalk,keishi/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,timopulkkinen/BubbleFish,Just-D/chromium-1,chuan9/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,ltilve/chromium
|
66e437031fab7d461eca47dec31e561d42768711
|
chrome/renderer/media/cast_session_delegate.cc
|
chrome/renderer/media/cast_session_delegate.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/media/cast_session_delegate.h"
#include "base/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/renderer/media/cast_threads.h"
#include "chrome/renderer/media/cast_transport_sender_ipc.h"
#include "content/public/renderer/render_thread.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/log_serializer.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/logging/proto/raw_events.pb.h"
#include "media/cast/logging/raw_event_subscriber_bundle.h"
#include "media/cast/net/cast_transport_config.h"
#include "media/cast/net/cast_transport_sender.h"
using media::cast::AudioSenderConfig;
using media::cast::CastEnvironment;
using media::cast::CastSender;
using media::cast::VideoSenderConfig;
static base::LazyInstance<CastThreads> g_cast_threads =
LAZY_INSTANCE_INITIALIZER;
CastSessionDelegateBase::CastSessionDelegateBase()
: io_task_runner_(
content::RenderThread::Get()->GetIOMessageLoopProxy()),
weak_factory_(this) {
DCHECK(io_task_runner_.get());
}
CastSessionDelegateBase::~CastSessionDelegateBase() {
DCHECK(io_task_runner_->BelongsToCurrentThread());
}
void CastSessionDelegateBase::StartUDP(
const net::IPEndPoint& local_endpoint,
const net::IPEndPoint& remote_endpoint,
scoped_ptr<base::DictionaryValue> options,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
// CastSender uses the renderer's IO thread as the main thread. This reduces
// thread hopping for incoming video frames and outgoing network packets.
// TODO(hubbe): Create cast environment in ctor instead.
cast_environment_ = new CastEnvironment(
scoped_ptr<base::TickClock>(new base::DefaultTickClock()).Pass(),
base::ThreadTaskRunnerHandle::Get(),
g_cast_threads.Get().GetAudioEncodeMessageLoopProxy(),
g_cast_threads.Get().GetVideoEncodeMessageLoopProxy());
// Rationale for using unretained: The callback cannot be called after the
// destruction of CastTransportSenderIPC, and they both share the same thread.
cast_transport_.reset(new CastTransportSenderIPC(
local_endpoint,
remote_endpoint,
options.Pass(),
base::Bind(&CastSessionDelegateBase::ReceivePacket,
base::Unretained(this)),
base::Bind(&CastSessionDelegateBase::StatusNotificationCB,
base::Unretained(this), error_callback),
base::Bind(&CastSessionDelegateBase::LogRawEvents,
base::Unretained(this))));
}
void CastSessionDelegateBase::StatusNotificationCB(
const ErrorCallback& error_callback,
media::cast::CastTransportStatus status) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
std::string error_message;
switch (status) {
case media::cast::TRANSPORT_AUDIO_UNINITIALIZED:
case media::cast::TRANSPORT_VIDEO_UNINITIALIZED:
case media::cast::TRANSPORT_AUDIO_INITIALIZED:
case media::cast::TRANSPORT_VIDEO_INITIALIZED:
return; // Not errors, do nothing.
case media::cast::TRANSPORT_INVALID_CRYPTO_CONFIG:
error_callback.Run("Invalid encrypt/decrypt configuration.");
break;
case media::cast::TRANSPORT_SOCKET_ERROR:
error_callback.Run("Socket error.");
break;
}
}
CastSessionDelegate::CastSessionDelegate()
: weak_factory_(this) {
DCHECK(io_task_runner_.get());
}
CastSessionDelegate::~CastSessionDelegate() {
DCHECK(io_task_runner_->BelongsToCurrentThread());
}
void CastSessionDelegate::StartAudio(
const AudioSenderConfig& config,
const AudioFrameInputAvailableCallback& callback,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!cast_transport_ || !cast_sender_) {
error_callback.Run("Destination not set.");
return;
}
audio_frame_input_available_callback_ = callback;
cast_sender_->InitializeAudio(
config,
base::Bind(&CastSessionDelegate::OnOperationalStatusChange,
weak_factory_.GetWeakPtr(), true, error_callback));
}
void CastSessionDelegate::StartVideo(
const VideoSenderConfig& config,
const VideoFrameInputAvailableCallback& callback,
const ErrorCallback& error_callback,
const media::cast::CreateVideoEncodeAcceleratorCallback& create_vea_cb,
const media::cast::CreateVideoEncodeMemoryCallback&
create_video_encode_mem_cb) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!cast_transport_ || !cast_sender_) {
error_callback.Run("Destination not set.");
return;
}
video_frame_input_available_callback_ = callback;
cast_sender_->InitializeVideo(
config,
base::Bind(&CastSessionDelegate::OnOperationalStatusChange,
weak_factory_.GetWeakPtr(), false, error_callback),
create_vea_cb,
create_video_encode_mem_cb);
}
void CastSessionDelegate::StartUDP(
const net::IPEndPoint& local_endpoint,
const net::IPEndPoint& remote_endpoint,
scoped_ptr<base::DictionaryValue> options,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
CastSessionDelegateBase::StartUDP(local_endpoint,
remote_endpoint,
options.Pass(),
error_callback);
event_subscribers_.reset(
new media::cast::RawEventSubscriberBundle(cast_environment_));
cast_sender_ = CastSender::Create(cast_environment_, cast_transport_.get());
}
void CastSessionDelegate::ToggleLogging(bool is_audio, bool enable) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get())
return;
if (enable)
event_subscribers_->AddEventSubscribers(is_audio);
else
event_subscribers_->RemoveEventSubscribers(is_audio);
}
void CastSessionDelegate::GetEventLogsAndReset(
bool is_audio,
const std::string& extra_data,
const EventLogsCallback& callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get()) {
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
media::cast::EncodingEventSubscriber* subscriber =
event_subscribers_->GetEncodingEventSubscriber(is_audio);
if (!subscriber) {
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
media::cast::proto::LogMetadata metadata;
media::cast::FrameEventList frame_events;
media::cast::PacketEventList packet_events;
subscriber->GetEventsAndReset(&metadata, &frame_events, &packet_events);
if (!extra_data.empty())
metadata.set_extra_data(extra_data);
media::cast::proto::GeneralDescription* gen_desc =
metadata.mutable_general_description();
chrome::VersionInfo version_info;
gen_desc->set_product(version_info.Name());
gen_desc->set_product_version(version_info.Version());
gen_desc->set_os(version_info.OSType());
scoped_ptr<char[]> serialized_log(new char[media::cast::kMaxSerializedBytes]);
int output_bytes;
bool success = media::cast::SerializeEvents(metadata,
frame_events,
packet_events,
true,
media::cast::kMaxSerializedBytes,
serialized_log.get(),
&output_bytes);
if (!success) {
DVLOG(2) << "Failed to serialize event log.";
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
DVLOG(2) << "Serialized log length: " << output_bytes;
scoped_ptr<base::BinaryValue> blob(
new base::BinaryValue(serialized_log.Pass(), output_bytes));
callback.Run(blob.Pass());
}
void CastSessionDelegate::GetStatsAndReset(bool is_audio,
const StatsCallback& callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get()) {
callback.Run(make_scoped_ptr(new base::DictionaryValue).Pass());
return;
}
media::cast::StatsEventSubscriber* subscriber =
event_subscribers_->GetStatsEventSubscriber(is_audio);
if (!subscriber) {
callback.Run(make_scoped_ptr(new base::DictionaryValue).Pass());
return;
}
scoped_ptr<base::DictionaryValue> stats = subscriber->GetStats();
subscriber->Reset();
callback.Run(stats.Pass());
}
void CastSessionDelegate::OnOperationalStatusChange(
bool is_for_audio,
const ErrorCallback& error_callback,
media::cast::OperationalStatus status) {
DCHECK(cast_sender_);
switch (status) {
case media::cast::STATUS_UNINITIALIZED:
case media::cast::STATUS_CODEC_REINIT_PENDING:
// Not an error.
// TODO(miu): As an optimization, signal the client to pause sending more
// frames until the state becomes STATUS_INITIALIZED again.
break;
case media::cast::STATUS_INITIALIZED:
// Once initialized, run the "frame input available" callback to allow the
// client to begin sending frames. If STATUS_INITIALIZED is encountered
// again, do nothing since this is only an indication that the codec has
// successfully re-initialized.
if (is_for_audio) {
if (!audio_frame_input_available_callback_.is_null()) {
base::ResetAndReturn(&audio_frame_input_available_callback_).Run(
cast_sender_->audio_frame_input());
}
} else {
if (!video_frame_input_available_callback_.is_null()) {
base::ResetAndReturn(&video_frame_input_available_callback_).Run(
cast_sender_->video_frame_input());
}
}
break;
case media::cast::STATUS_INVALID_CONFIGURATION:
error_callback.Run(base::StringPrintf("Invalid %s configuration.",
is_for_audio ? "audio" : "video"));
break;
case media::cast::STATUS_UNSUPPORTED_CODEC:
error_callback.Run(base::StringPrintf("%s codec not supported.",
is_for_audio ? "Audio" : "Video"));
break;
case media::cast::STATUS_CODEC_INIT_FAILED:
error_callback.Run(base::StringPrintf("%s codec initialization failed.",
is_for_audio ? "Audio" : "Video"));
break;
case media::cast::STATUS_CODEC_RUNTIME_ERROR:
error_callback.Run(base::StringPrintf("%s codec runtime error.",
is_for_audio ? "Audio" : "Video"));
break;
}
}
void CastSessionDelegate::ReceivePacket(
scoped_ptr<media::cast::Packet> packet) {
// Do nothing (frees packet)
}
void CastSessionDelegate::LogRawEvents(
const std::vector<media::cast::PacketEvent>& packet_events,
const std::vector<media::cast::FrameEvent>& frame_events) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
for (std::vector<media::cast::PacketEvent>::const_iterator it =
packet_events.begin();
it != packet_events.end();
++it) {
cast_environment_->Logging()->InsertPacketEvent(it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id,
it->packet_id,
it->max_packet_id,
it->size);
}
for (std::vector<media::cast::FrameEvent>::const_iterator it =
frame_events.begin();
it != frame_events.end();
++it) {
if (it->type == media::cast::FRAME_PLAYOUT) {
cast_environment_->Logging()->InsertFrameEventWithDelay(
it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id,
it->delay_delta);
} else {
cast_environment_->Logging()->InsertFrameEvent(
it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id);
}
}
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/media/cast_session_delegate.h"
#include "base/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/stringprintf.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/renderer/media/cast_threads.h"
#include "chrome/renderer/media/cast_transport_sender_ipc.h"
#include "content/public/renderer/render_thread.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_sender.h"
#include "media/cast/logging/log_serializer.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/logging/proto/raw_events.pb.h"
#include "media/cast/logging/raw_event_subscriber_bundle.h"
#include "media/cast/net/cast_transport_config.h"
#include "media/cast/net/cast_transport_sender.h"
using media::cast::AudioSenderConfig;
using media::cast::CastEnvironment;
using media::cast::CastSender;
using media::cast::VideoSenderConfig;
static base::LazyInstance<CastThreads> g_cast_threads =
LAZY_INSTANCE_INITIALIZER;
CastSessionDelegateBase::CastSessionDelegateBase()
: io_task_runner_(
content::RenderThread::Get()->GetIOMessageLoopProxy()),
weak_factory_(this) {
DCHECK(io_task_runner_.get());
#if defined(OS_WIN)
// Note that this also increases the accuracy of PostDelayTask,
// which is is very helpful to cast.
if (!base::Time::ActivateHighResolutionTimer(true)) {
LOG(WARNING) << "Failed to activate high resolution timers for cast.";
}
#endif
}
CastSessionDelegateBase::~CastSessionDelegateBase() {
DCHECK(io_task_runner_->BelongsToCurrentThread());
#if defined(OS_WIN)
base::Time::ActivateHighResolutionTimer(false);
#endif
}
void CastSessionDelegateBase::StartUDP(
const net::IPEndPoint& local_endpoint,
const net::IPEndPoint& remote_endpoint,
scoped_ptr<base::DictionaryValue> options,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
// CastSender uses the renderer's IO thread as the main thread. This reduces
// thread hopping for incoming video frames and outgoing network packets.
// TODO(hubbe): Create cast environment in ctor instead.
cast_environment_ = new CastEnvironment(
scoped_ptr<base::TickClock>(new base::DefaultTickClock()).Pass(),
base::ThreadTaskRunnerHandle::Get(),
g_cast_threads.Get().GetAudioEncodeMessageLoopProxy(),
g_cast_threads.Get().GetVideoEncodeMessageLoopProxy());
// Rationale for using unretained: The callback cannot be called after the
// destruction of CastTransportSenderIPC, and they both share the same thread.
cast_transport_.reset(new CastTransportSenderIPC(
local_endpoint,
remote_endpoint,
options.Pass(),
base::Bind(&CastSessionDelegateBase::ReceivePacket,
base::Unretained(this)),
base::Bind(&CastSessionDelegateBase::StatusNotificationCB,
base::Unretained(this), error_callback),
base::Bind(&CastSessionDelegateBase::LogRawEvents,
base::Unretained(this))));
}
void CastSessionDelegateBase::StatusNotificationCB(
const ErrorCallback& error_callback,
media::cast::CastTransportStatus status) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
std::string error_message;
switch (status) {
case media::cast::TRANSPORT_AUDIO_UNINITIALIZED:
case media::cast::TRANSPORT_VIDEO_UNINITIALIZED:
case media::cast::TRANSPORT_AUDIO_INITIALIZED:
case media::cast::TRANSPORT_VIDEO_INITIALIZED:
return; // Not errors, do nothing.
case media::cast::TRANSPORT_INVALID_CRYPTO_CONFIG:
error_callback.Run("Invalid encrypt/decrypt configuration.");
break;
case media::cast::TRANSPORT_SOCKET_ERROR:
error_callback.Run("Socket error.");
break;
}
}
CastSessionDelegate::CastSessionDelegate()
: weak_factory_(this) {
DCHECK(io_task_runner_.get());
}
CastSessionDelegate::~CastSessionDelegate() {
DCHECK(io_task_runner_->BelongsToCurrentThread());
}
void CastSessionDelegate::StartAudio(
const AudioSenderConfig& config,
const AudioFrameInputAvailableCallback& callback,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!cast_transport_ || !cast_sender_) {
error_callback.Run("Destination not set.");
return;
}
audio_frame_input_available_callback_ = callback;
cast_sender_->InitializeAudio(
config,
base::Bind(&CastSessionDelegate::OnOperationalStatusChange,
weak_factory_.GetWeakPtr(), true, error_callback));
}
void CastSessionDelegate::StartVideo(
const VideoSenderConfig& config,
const VideoFrameInputAvailableCallback& callback,
const ErrorCallback& error_callback,
const media::cast::CreateVideoEncodeAcceleratorCallback& create_vea_cb,
const media::cast::CreateVideoEncodeMemoryCallback&
create_video_encode_mem_cb) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!cast_transport_ || !cast_sender_) {
error_callback.Run("Destination not set.");
return;
}
video_frame_input_available_callback_ = callback;
cast_sender_->InitializeVideo(
config,
base::Bind(&CastSessionDelegate::OnOperationalStatusChange,
weak_factory_.GetWeakPtr(), false, error_callback),
create_vea_cb,
create_video_encode_mem_cb);
}
void CastSessionDelegate::StartUDP(
const net::IPEndPoint& local_endpoint,
const net::IPEndPoint& remote_endpoint,
scoped_ptr<base::DictionaryValue> options,
const ErrorCallback& error_callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
CastSessionDelegateBase::StartUDP(local_endpoint,
remote_endpoint,
options.Pass(),
error_callback);
event_subscribers_.reset(
new media::cast::RawEventSubscriberBundle(cast_environment_));
cast_sender_ = CastSender::Create(cast_environment_, cast_transport_.get());
}
void CastSessionDelegate::ToggleLogging(bool is_audio, bool enable) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get())
return;
if (enable)
event_subscribers_->AddEventSubscribers(is_audio);
else
event_subscribers_->RemoveEventSubscribers(is_audio);
}
void CastSessionDelegate::GetEventLogsAndReset(
bool is_audio,
const std::string& extra_data,
const EventLogsCallback& callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get()) {
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
media::cast::EncodingEventSubscriber* subscriber =
event_subscribers_->GetEncodingEventSubscriber(is_audio);
if (!subscriber) {
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
media::cast::proto::LogMetadata metadata;
media::cast::FrameEventList frame_events;
media::cast::PacketEventList packet_events;
subscriber->GetEventsAndReset(&metadata, &frame_events, &packet_events);
if (!extra_data.empty())
metadata.set_extra_data(extra_data);
media::cast::proto::GeneralDescription* gen_desc =
metadata.mutable_general_description();
chrome::VersionInfo version_info;
gen_desc->set_product(version_info.Name());
gen_desc->set_product_version(version_info.Version());
gen_desc->set_os(version_info.OSType());
scoped_ptr<char[]> serialized_log(new char[media::cast::kMaxSerializedBytes]);
int output_bytes;
bool success = media::cast::SerializeEvents(metadata,
frame_events,
packet_events,
true,
media::cast::kMaxSerializedBytes,
serialized_log.get(),
&output_bytes);
if (!success) {
DVLOG(2) << "Failed to serialize event log.";
callback.Run(make_scoped_ptr(new base::BinaryValue).Pass());
return;
}
DVLOG(2) << "Serialized log length: " << output_bytes;
scoped_ptr<base::BinaryValue> blob(
new base::BinaryValue(serialized_log.Pass(), output_bytes));
callback.Run(blob.Pass());
}
void CastSessionDelegate::GetStatsAndReset(bool is_audio,
const StatsCallback& callback) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
if (!event_subscribers_.get()) {
callback.Run(make_scoped_ptr(new base::DictionaryValue).Pass());
return;
}
media::cast::StatsEventSubscriber* subscriber =
event_subscribers_->GetStatsEventSubscriber(is_audio);
if (!subscriber) {
callback.Run(make_scoped_ptr(new base::DictionaryValue).Pass());
return;
}
scoped_ptr<base::DictionaryValue> stats = subscriber->GetStats();
subscriber->Reset();
callback.Run(stats.Pass());
}
void CastSessionDelegate::OnOperationalStatusChange(
bool is_for_audio,
const ErrorCallback& error_callback,
media::cast::OperationalStatus status) {
DCHECK(cast_sender_);
switch (status) {
case media::cast::STATUS_UNINITIALIZED:
case media::cast::STATUS_CODEC_REINIT_PENDING:
// Not an error.
// TODO(miu): As an optimization, signal the client to pause sending more
// frames until the state becomes STATUS_INITIALIZED again.
break;
case media::cast::STATUS_INITIALIZED:
// Once initialized, run the "frame input available" callback to allow the
// client to begin sending frames. If STATUS_INITIALIZED is encountered
// again, do nothing since this is only an indication that the codec has
// successfully re-initialized.
if (is_for_audio) {
if (!audio_frame_input_available_callback_.is_null()) {
base::ResetAndReturn(&audio_frame_input_available_callback_).Run(
cast_sender_->audio_frame_input());
}
} else {
if (!video_frame_input_available_callback_.is_null()) {
base::ResetAndReturn(&video_frame_input_available_callback_).Run(
cast_sender_->video_frame_input());
}
}
break;
case media::cast::STATUS_INVALID_CONFIGURATION:
error_callback.Run(base::StringPrintf("Invalid %s configuration.",
is_for_audio ? "audio" : "video"));
break;
case media::cast::STATUS_UNSUPPORTED_CODEC:
error_callback.Run(base::StringPrintf("%s codec not supported.",
is_for_audio ? "Audio" : "Video"));
break;
case media::cast::STATUS_CODEC_INIT_FAILED:
error_callback.Run(base::StringPrintf("%s codec initialization failed.",
is_for_audio ? "Audio" : "Video"));
break;
case media::cast::STATUS_CODEC_RUNTIME_ERROR:
error_callback.Run(base::StringPrintf("%s codec runtime error.",
is_for_audio ? "Audio" : "Video"));
break;
}
}
void CastSessionDelegate::ReceivePacket(
scoped_ptr<media::cast::Packet> packet) {
// Do nothing (frees packet)
}
void CastSessionDelegate::LogRawEvents(
const std::vector<media::cast::PacketEvent>& packet_events,
const std::vector<media::cast::FrameEvent>& frame_events) {
DCHECK(io_task_runner_->BelongsToCurrentThread());
for (std::vector<media::cast::PacketEvent>::const_iterator it =
packet_events.begin();
it != packet_events.end();
++it) {
cast_environment_->Logging()->InsertPacketEvent(it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id,
it->packet_id,
it->max_packet_id,
it->size);
}
for (std::vector<media::cast::FrameEvent>::const_iterator it =
frame_events.begin();
it != frame_events.end();
++it) {
if (it->type == media::cast::FRAME_PLAYOUT) {
cast_environment_->Logging()->InsertFrameEventWithDelay(
it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id,
it->delay_delta);
} else {
cast_environment_->Logging()->InsertFrameEvent(
it->timestamp,
it->type,
it->media_type,
it->rtp_timestamp,
it->frame_id);
}
}
}
|
Enable high-resolution timers while casting.
|
Cast: Enable high-resolution timers while casting.
Review URL: https://codereview.chromium.org/1126873002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#328870}
|
C++
|
bsd-3-clause
|
chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk
|
83d607c8ad432bb3f9625b8be635c984881b776e
|
MC.cpp
|
MC.cpp
|
/*
* MC.cpp
* Simulation of 2-D Rods By GCMC with SUS, No energy
* Author: Yuding Ai
* Date: 2015.10.19
* *************************** MC implementation ********************************
* This simulation follows Successive Umbrella sampling without energy.
* ******************************************************************************
*
*/
#include "MC.h"
MC::MC(long int ST, int LEN,int C, int R, double Z)
{
VRodlist.clear(); // the list storage the Vertical Rods;
HRodlist.clear(); // the list storage the Horizantal Rods;
r = R;
c = C;
length = LEN;
step = ST; // now the step stands for the steps in each SUS window
z = Z;
nh=nv=dh=dv=ah=av=0;
}
vector<HR> MC::getVRodlist()
{
return VRodlist;
}
vector<HR> MC::getHRodlist()
{
return HRodlist;
}
double MC::getTho() const
{
double tho;
tho = double(length*(av+ah-dv-dh))/double(r*c);
return tho;
}
double MC::getQ() const
{
double Q;
Q = (nv - nh)/(nv + nh);
return Q;
}
double MC::getAaccp() const
{
double A;
A = z*(double(r*c))/(double(av+ah-dv-dh+1.0)*double(length));
return A;
}
double MC::getDaccp() const
{
double D;
D = (double(av+ah-dv-dh)*double(length))/(z*(double(r*c)));
return D;
}
double MC::getNh() const
{
return nh;
}
double MC::getNv() const
{
return nv;
}
void MC::Add(Cells &s,double &prob,double &proba)
{
int x,y,o; // pick a random position and orientation for the HR to be added;
x = rand()%c;
y = rand()%r;
o = rand()%1;// change it to 1 for lattice gas case
if(s.getSquare(x,y).isEmpty()) // if it's open, try to do Addition;
{
HR rod(x,y,length,o);
//======================== Vertical ===============================
if(o == 0)
{
int counter = 0;
for (int j = 0; j < length-1; j++)
{
// check if the vertical space is wide open
if(s.getSquare(x,(y+j+1)%r).isOccupied())
{
counter++;
}
}
if(counter == 0)
{
if(prob <= proba)
{
// Do addition;
// push the new rod into the Rodlist;
VRodlist.push_back(rod);
av++;
nv++;// accumulate the # of ver rod;
// update new N, E and new config;
for (int i = 0; i < length; i++)
{
s.getSquare(x,(y+i)%r).setStatus(1);
}
}
}
}
else
{
//======================= Horizontal ============================
int counter = 0;
for (int j = 0; j< length-1 ; j++)
{
// check if the horizontal space is wide open
if(s.getSquare((x+1+j)%c,y).isOccupied())
{
counter++;
}
}
if (counter == 0)
{
if(prob <= proba)
{
//Do addition;
//push the new rod into the Rodlist;
HRodlist.push_back(rod);
ah++;
nh++;// accumulate the # of hor rod;
// update new N, E and new config;
for (int i = 0; i < length; i++)
{
s.getSquare((x+i)%c,y).setStatus(1);
}
}
}
}
}
}
void MC::Del(Cells &s,double &prob,double &probd,double &size)
{
//Do Del;
if(nv+nh > 0)// make sure there are rod;
{
int indx; // pick a random index from the Rodlist;
indx = rand()%int(nv+nh);
//remove Rodlist[indx];
int x,y;// the position of the target on the cells;
if(prob <= probd)
{
if (indx < nv) // vertical
{
x = VRodlist[indx].getX();
y = VRodlist[indx].getY();
// --------------------- it's a vertical rod -----------------------
for(int i = 0; i<VRodlist[indx].getLength(); i++)
{
// update the new config of cells
s.getSquare(x,(y+i)%r).setStatus(0);
}
// remove the target rod from the vector Rodlist;
VRodlist.erase(VRodlist.begin() + indx);
nv--;// substract the # of ver rod;
dv++;
}
else
{
x = HRodlist[indx - nv].getX();
y = HRodlist[indx - nv].getY();
// --------------------- it's a Horizontal rod -----------------------
for(int i = 0; i<HRodlist[indx-nv].getLength(); i++)
{
// update the new config of cells
s.getSquare((x+i)%c,y).setStatus(0);
}
// remove the target rod from the vector Rodlist;
HRodlist.erase(HRodlist.begin() + indx - nv);
nh--;// substract the # of hor rod;
dh++;
}
}
}
}
array<double,10000> MC::MCSUS()
{
Cells s(c,r); // setting the lattice;
//========================================================== declare instance variables ============================================================= //
stringstream sh;
sh.precision(20);
double addordel; // the prob to decide either add or del;
double probd,proba; // the acceptance prob of addition and deletion;
double prob; // the prob to decide either accept add/del;
double aaccp,daccp; // the acceptance probabilities:
double V = double(r*c); // the total lattice size
double K = double(length); //
array<double,10000> WF;
srand(time(NULL));
long int i = 0; // counter for each window
double w = 1.0; // a counter that keep track of the index of window
double fu,fl; // occurrence counter
//================================Start my MC simulation=================================
while (w <= V/K) // while loop terminate until finish the last window; window[V/K]
{
i = 0; // initialize my step counter;
fl = fu = 0; // initialize my occurrence counter;
while(i < step )
// Simulation for each window with "step" amount of step
{
i++;
// generate a random probability to decide either add or del;
addordel = rand()%2;
double size = nv+nh;
prob = ((double) rand() / (RAND_MAX));
aaccp = (z*V)/((size+1.0)*K)*(exp(WF[int(size+1)] - WF[int(size)]));
daccp = (size*K)/(z*V)*(exp(WF[int(size-1)] - WF[int(size)]));
probd = min(1.0,daccp);
proba = min(1.0,aaccp);
// ===========================Addition ===================================
if(addordel == 0)
{
if (nh+nv < w ) // only try to add if the size is below the upper window
{
//try to Do Addition;
Add(s,prob,proba);
}
}
// ============================Deletion=============================
else
{
if (nh+nv > w - 1) // only try to delete if the size is above the lower window size
{
//Do deletion;
Del(s,prob,probd,size);
}
}
if (nv + nh == w) // only update the fu when addition succeessfully.
{
fu++; // if at the upper window, update fu
}
else if (nv + nh == w-1 ) // only update the fu when deletion succeessfully.
{
fl++;//if at the lower window, update fl
}
}
// ======================= if fu and fl != 0 Update the upper window side ================================
if (fu!=0 && fl != 0)
{
WF[w] = WF[w] + log(fu/fl);
// "linearly extrapolate" for WF[w+1] by using W[w] and WF[w-1]
WF[w+1] = WF[w];
cout << fl<<" "<<fu <<" " <<nv <<" "<<WF[w+1]<<endl;
// ======================= Print out the data into terminal =============================================
cout <<"Window: "<< w <<" : "<<"W("<<w<<" : lower) = "<< WF[w-1]<<" "<<"W("<<w<<" : Upper) = "<< WF[w] << endl;
// initial config determine the intial value of fu and fl
w++; // switch into the next window
}
// else reset fu and fl and repeat the simulation
}
for(int i = 0; i< V/K+1; i++)
{
sh<<WF[i]<<endl;
}
ofstream myfile ("SUSWeight_function.txt");
myfile.precision(20);
string data2 = sh.str();
myfile << data2;
myfile.close();
return WF;
}
void MC::plot(const vector<HR>& VRodlist, const vector<HR>& HRodlist)
{
stringstream stv,sth;
for (int i = 0; i < VRodlist.size(); i++)
{
stv<< VRodlist[i].getX() << " "<< VRodlist[i].getY()<<endl;
}
ofstream myfilev ("2dplotv.txt");
string datav = stv.str();
myfilev << datav;
myfilev.close();
for (int j = 0; j < HRodlist.size(); j++)
{
sth<< HRodlist[j].getX() << " "<< HRodlist[j].getY() <<endl;
}
ofstream myfileh ("2dploth.txt");
string datah = sth.str();
myfileh << datah;
myfileh.close();
}
|
/*
* MC.cpp
* Simulation of 2-D Rods By GCMC with SUS, No energy
* Author: Yuding Ai
* Date: 2015.10.19
* *************************** MC implementation ********************************
* This simulation follows Successive Umbrella sampling without energy.
* ******************************************************************************
*
*/
#include "MC.h"
MC::MC(long int ST, int LEN,int C, int R, double Z)
{
VRodlist.clear(); // the list storage the Vertical Rods;
HRodlist.clear(); // the list storage the Horizantal Rods;
r = R;
c = C;
length = LEN;
step = ST; // now the step stands for the steps in each SUS window
z = Z;
nh=nv=dh=dv=ah=av=0;
}
vector<HR> MC::getVRodlist()
{
return VRodlist;
}
vector<HR> MC::getHRodlist()
{
return HRodlist;
}
double MC::getTho() const
{
double tho;
tho = double(length*(av+ah-dv-dh))/double(r*c);
return tho;
}
double MC::getQ() const
{
double Q;
Q = (nv - nh)/(nv + nh);
return Q;
}
double MC::getAaccp() const
{
double A;
A = z*(double(r*c))/(double(av+ah-dv-dh+1.0)*double(length));
return A;
}
double MC::getDaccp() const
{
double D;
D = (double(av+ah-dv-dh)*double(length))/(z*(double(r*c)));
return D;
}
double MC::getNh() const
{
return nh;
}
double MC::getNv() const
{
return nv;
}
void MC::Add(Cells &s,double &prob,double &proba)
{
int x,y,o; // pick a random position and orientation for the HR to be added;
x = rand()%c;
y = rand()%r;
o = rand()%1;// change it to 1 for lattice gas case
if(s.getSquare(x,y).isEmpty()) // if it's open, try to do Addition;
{
HR rod(x,y,length,o);
//======================== Vertical ===============================
if(o == 0)
{
int counter = 0;
for (int j = 0; j < length-1; j++)
{
// check if the vertical space is wide open
if(s.getSquare(x,(y+j+1)%r).isOccupied())
{
counter++;
}
}
if(counter == 0)
{
if(prob <= proba)
{
// Do addition;
// push the new rod into the Rodlist;
VRodlist.push_back(rod);
av++;
nv++;// accumulate the # of ver rod;
// update new N, E and new config;
for (int i = 0; i < length; i++)
{
s.getSquare(x,(y+i)%r).setStatus(1);
}
}
}
}
else
{
//======================= Horizontal ============================
int counter = 0;
for (int j = 0; j< length-1 ; j++)
{
// check if the horizontal space is wide open
if(s.getSquare((x+1+j)%c,y).isOccupied())
{
counter++;
}
}
if (counter == 0)
{
if(prob <= proba)
{
//Do addition;
//push the new rod into the Rodlist;
HRodlist.push_back(rod);
ah++;
nh++;// accumulate the # of hor rod;
// update new N, E and new config;
for (int i = 0; i < length; i++)
{
s.getSquare((x+i)%c,y).setStatus(1);
}
}
}
}
}
}
void MC::Del(Cells &s,double &prob,double &probd,double &size)
{
//Do Del;
if(nv+nh > 0)// make sure there are rod;
{
int indx; // pick a random index from the Rodlist;
indx = rand()%int(nv+nh);
//remove Rodlist[indx];
int x,y;// the position of the target on the cells;
if(prob <= probd)
{
if (indx < nv) // vertical
{
x = VRodlist[indx].getX();
y = VRodlist[indx].getY();
// --------------------- it's a vertical rod -----------------------
for(int i = 0; i<VRodlist[indx].getLength(); i++)
{
// update the new config of cells
s.getSquare(x,(y+i)%r).setStatus(0);
}
// remove the target rod from the vector Rodlist;
VRodlist.erase(VRodlist.begin() + indx);
nv--;// substract the # of ver rod;
dv++;
}
else
{
x = HRodlist[indx - nv].getX();
y = HRodlist[indx - nv].getY();
// --------------------- it's a Horizontal rod -----------------------
for(int i = 0; i<HRodlist[indx-nv].getLength(); i++)
{
// update the new config of cells
s.getSquare((x+i)%c,y).setStatus(0);
}
// remove the target rod from the vector Rodlist;
HRodlist.erase(HRodlist.begin() + indx - nv);
nh--;// substract the # of hor rod;
dh++;
}
}
}
}
array<double,10000> MC::MCSUS()
{
Cells s(c,r); // setting the lattice;
//========================================================== declare instance variables ============================================================= //
stringstream sh;
sh.precision(20);
double addordel; // the prob to decide either add or del;
double probd,proba; // the acceptance prob of addition and deletion;
double prob; // the prob to decide either accept add/del;
double aaccp,daccp; // the acceptance probabilities:
double V = double(r*c); // the total lattice size
double K = double(length); //
array<double,10000> WF;
srand(time(NULL));
long int i = 0; // counter for each window
double w = 1.0; // a counter that keep track of the index of window
double fu,fl; // occurrence counter
//================================Start my MC simulation=================================
while (w <= V/K) // while loop terminate until finish the last window; window[V/K]
{
i = 0; // initialize my step counter;
fl = fu = 0; // initialize my occurrence counter;
while(i < step )
// Simulation for each window with "step" amount of step
{
i++;
// generate a random probability to decide either add or del;
addordel = rand()%2;
double size = nv+nh;
prob = ((double) rand() / (RAND_MAX));
aaccp = (z*V)/((size+1.0)*K)*(exp(WF[int(size+1)] - WF[int(size)]));
daccp = (size*K)/(z*V)*(exp(WF[int(size-1)] - WF[int(size)]));
probd = min(1.0,daccp);
proba = min(1.0,aaccp);
// ===========================Addition ===================================
if(addordel == 0)
{
if (nh+nv < w ) // only try to add if the size is below the upper window
{
//try to Do Addition;
Add(s,prob,proba);
}
}
// ============================Deletion=============================
else
{
if (nh+nv > w - 1) // only try to delete if the size is above the lower window size
{
//Do deletion;
Del(s,prob,probd,size);
}
}
if (nv + nh == w) // only update the fu when addition succeessfully.
{
fu++; // if at the upper window, update fu
}
else if (nv + nh == w-1 ) // only update the fu when deletion succeessfully.
{
fl++;//if at the lower window, update fl
}
}
// ======================= if fu and fl != 0 Update the upper window side ================================
if (fu!=0 && fl != 0)
{
WF[w] = WF[w] + log(fu/fl);
// "linearly extrapolate" for WF[w+1] by using W[w] and WF[w-1]
WF[w+1] = WF[w];
// cout << fl<<" "<<fu <<" " <<nv <<" "<<WF[w+1]<<endl;
// ======================= Print out the data into terminal =============================================
cout <<"Window: "<< w <<" : "<<"W("<<w<<" : lower) = "<< WF[w-1]<<" "<<"W("<<w<<" : Upper) = "<< WF[w] << endl;
// initial config determine the intial value of fu and fl
w++; // switch into the next window
}
// else reset fu and fl and repeat the simulation
}
for(int i = 0; i< V/K+1; i++)
{
sh<<WF[i]<<endl;
}
ofstream myfile ("SUSWeight_function.txt");
myfile.precision(20);
string data2 = sh.str();
myfile << data2;
myfile.close();
return WF;
}
void MC::plot(const vector<HR>& VRodlist, const vector<HR>& HRodlist)
{
stringstream stv,sth;
for (int i = 0; i < VRodlist.size(); i++)
{
stv<< VRodlist[i].getX() << " "<< VRodlist[i].getY()<<endl;
}
ofstream myfilev ("2dplotv.txt");
string datav = stv.str();
myfilev << datav;
myfilev.close();
for (int j = 0; j < HRodlist.size(); j++)
{
sth<< HRodlist[j].getX() << " "<< HRodlist[j].getY() <<endl;
}
ofstream myfileh ("2dploth.txt");
string datah = sth.str();
myfileh << datah;
myfileh.close();
}
|
edit comment
|
edit comment
|
C++
|
mit
|
Aieener/SUS_2D,Aieener/SUS_2D
|
3dd106dab9436179745f820727a2e8dec5341838
|
app.cc
|
app.cc
|
#include "app.h"
#include "linsys.h"
#include "utils.h"
#include <PCU.h>
namespace pe {
App::App(AppInput& in) :
mesh(in.mesh),
polynomialOrder(in.polynomialOrder),
integrationOrder(in.integrationOrder),
u(in.u),
rhs(in.rhs),
out(in.out)
{
print("sovling poisson's equation!");
}
void App::run()
{
pre();
assemble();
linsys->solve();
post();
}
}
|
#include "app.h"
#include "linsys.h"
#include "utils.h"
#include <PCU.h>
namespace pe {
App::App(AppInput& in) :
mesh(in.mesh),
polynomialOrder(in.polynomialOrder),
integrationOrder(in.integrationOrder),
u(in.u),
rhs(in.rhs),
out(in.out)
{
print("solvifying poisson's equation!");
}
void App::run()
{
pre();
assemble();
linsys->solve();
post();
}
}
|
fix typo
|
fix typo
|
C++
|
bsd-3-clause
|
bgranzow/pe,bgranzow/pe
|
ba479885812992b99fb65d329323e317aefe1fc9
|
fx.cpp
|
fx.cpp
|
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include "fx.h"
int Fxstream::checkFormat(boost::iostreams::filtering_istream& in, std::istream& file, read_type& t, bool gzip, bool bzip2) {
try {
#ifdef HAVE_LIBZ
if(gzip) {
in.push(boost::iostreams::gzip_decompressor());
}
#endif
#ifdef HAVE_LIBBZ2
else if (bzip2) {
in.push(boost::iostreams::bzip2_decompressor());
}
#endif
in.push(file);
char c = in.peek();
if(c == '>') {
//std::cerr << "looks like a fasta file"<<std::endl;
t = FASTA;
} else if( c == '@') {
//std::cerr << "looks like a fastq file"<<std::endl;
t = FASTQ;
} else {
fprintf(stderr, "bad character found: %c\n", c);
return 1;
}
}
catch(const boost::iostreams::gzip_error& e) {
fprintf(stderr, "%s\n", e.what() );
} catch(const boost::iostreams::bzip2_error& e) {
fprintf(stderr, "%s\n", e.what() );
}
return 0;
}
int Fxstream::open(const char * file1, const char * file2, bool interleaved, bool gzip, bool bzip2) {
std::cerr << file1 <<" "<<interleaved <<" " << gzip << " "<< bzip2<<std::endl;
in1.open(file1, std::ios_base::in | std::ios_base::binary);
//std::ifstream file(argv[1], std::ios_base::in | std::ios_base::binary);
if(!in1.good()) {
fprintf(stderr, "failed to open file for mate1\n");
return 1;
} else if(checkFormat(f1, in1, t1, gzip, bzip2)) {
fprintf(stderr, "The file %s does not look like either fasta or fastq\n", file1);
return 1;
}
if(file2 != NULL && interleaved) {
fprintf(stderr, "A second file cannot be given if the interleaved flag is set\n");
return 1;
} else if (file2 != NULL) {
in2.open(file2, std::ios_base::in | std::ios_base::binary);
if(!in2.good()) {
fprintf(stderr, "failed to open file for mate2\n");
return 1;
} else {
if(checkFormat(f2, in2, t2, gzip, bzip2)) {
fprintf(stderr, "The file %s does not look like either fasta or fastq\n", file2);
return 1;
}
if( t1 != t2) {
fprintf(stderr, "both files must be either fasta or fastq\n");
return 1;
}
}
}
this->interleaved = interleaved;
return 0;
}
int Fxstream::close() {
in1.close();
if(in2.is_open()) {
in2.close();
}
return 0;
}
int Fxstream::readFastaRecord(Fx& read, std::istream& input) {
// assume that we enter this funcion always pointing at the next
// start of a fasta record. The first line will therefore be the
// header line
if(input.fail()) {
fprintf(stderr, "Internal Logic error: %s %d\n", __FILE__, __LINE__);
return 2;
} else if(input.eof()) {
return 0;
}
input.get();
input >> read.name; // first word from the current line
std::getline(input, read.comment);
// peek the begining of the next line. it should not be the '>' char
// if this is a valid fasta file
if(input.peek() == '>') {
fprintf(stderr, "malformed fasta record\n");
return 3;
}
do {
std::string tmp;
std::getline(input, tmp);
read.seq += tmp;
} while (input.good() && input.peek() != '>');
read.len = static_cast<int>(read.seq.size());
return 0;
}
int Fxstream::readFastqRecord(Fx& read, std::istream& input) {
// assume that we enter this funcion always pointing at the next
// start of a fastq record. The first line will therefore be the
// header line
if(!input.good()) {
return 1;
}
// waste the '@' char
input.get();
input >> read.name; // first word from the current line
std::getline(input, read.comment);
// seq line
std::getline(input, read.seq);
read.len = static_cast<int>(read.seq.size());
// waste line
std::string tmp;
std::getline(input, tmp);
// quality line
std::getline(input, read.qual);
return 0;
}
//TODO: BSD grep has support for zip, bzip2 and xz files out of the box
//http://svnweb.freebsd.org/base/head/usr.bin/grep/file.c?view=markup
int Fxstream::read( Fx& read1, Fx& read2) {
if(f1.eof()) {
return 1;
}
if(t1 == FASTA) {
if(readFastaRecord(read1, f1)) {
return 1;
}
if(this->interleaved) {
if(readFastaRecord(read2, f1)) {
return 1;
}
} else if(in2.is_open() && in2.good()) {
if(readFastaRecord(read2, f2)) {
return 1;
}
}
} else if( t1 == FASTQ) {
if(readFastqRecord(read1, f1)) {
return 1;
}
if(this->interleaved) {
if(readFastqRecord(read2, f1)) {
return 1;
}
} else if(in2.is_open() && in2.good()) {
if(readFastqRecord(read2, f2)) {
return 1;
}
}
} else {
// this should never happen as this kind of error should be caught previously
fprintf(stderr, "Internal logic error occurred: %s %d\n", __FILE__, __LINE__);
return 1;
}
return 0;
}
int Fxstream::read(ReadPair& pair) {
return this->read(pair.first, pair.second);
}
#ifdef TEST_FXREAD_MAIN
int main(int argc, char * argv[]) {
Fxstream stream;
int state;
if(argc == 3) {
state = stream.open(argv[1], argv[2], false);
} else if(argc == 2) {
state = stream.open(argv[1], NULL, false);
}
if(state != 0) {
fprintf(stderr, "Failed to open the stream\n");
stream.close();
return 1;
}
ReadPair pair;
//Fx read1, read2;
while(stream.read(pair.first, pair.second) == 0) {
//std::cout << read1 << read2;
std::cout << pair;
pair.clear();
//read1.clear();
//read2.clear();
}
stream.close();
return 0;
}
#endif
|
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdio>
#include "fx.h"
int Fxstream::checkFormat(boost::iostreams::filtering_istream& in, std::istream& file, read_type& t, bool gzip, bool bzip2) {
try {
#ifdef HAVE_LIBZ
if(gzip) {
in.push(boost::iostreams::gzip_decompressor());
}
#endif
#ifdef HAVE_LIBBZ2
else if (bzip2) {
in.push(boost::iostreams::bzip2_decompressor());
}
#endif
in.push(file);
char c = in.peek();
if(c == '>') {
//std::cerr << "looks like a fasta file"<<std::endl;
t = FASTA;
} else if( c == '@') {
//std::cerr << "looks like a fastq file"<<std::endl;
t = FASTQ;
} else {
fprintf(stderr, "bad character found: %c\n", c);
return 1;
}
}
catch(const boost::iostreams::gzip_error& e) {
fprintf(stderr, "%s\n", e.what() );
} catch(const boost::iostreams::bzip2_error& e) {
fprintf(stderr, "%s\n", e.what() );
}
return 0;
}
int Fxstream::open(const char * file1, const char * file2, bool interleaved, bool gzip, bool bzip2) {
in1.open(file1, std::ios_base::in | std::ios_base::binary);
//std::ifstream file(argv[1], std::ios_base::in | std::ios_base::binary);
if(!in1.good()) {
fprintf(stderr, "failed to open file for mate1\n");
return 1;
} else if(checkFormat(f1, in1, t1, gzip, bzip2)) {
fprintf(stderr, "The file %s does not look like either fasta or fastq\n", file1);
return 1;
}
if(file2 != NULL && interleaved) {
fprintf(stderr, "A second file cannot be given if the interleaved flag is set\n");
return 1;
} else if (file2 != NULL) {
in2.open(file2, std::ios_base::in | std::ios_base::binary);
if(!in2.good()) {
fprintf(stderr, "failed to open file for mate2\n");
return 1;
} else {
if(checkFormat(f2, in2, t2, gzip, bzip2)) {
fprintf(stderr, "The file %s does not look like either fasta or fastq\n", file2);
return 1;
}
if( t1 != t2) {
fprintf(stderr, "both files must be either fasta or fastq\n");
return 1;
}
}
}
this->interleaved = interleaved;
return 0;
}
int Fxstream::close() {
in1.close();
if(in2.is_open()) {
in2.close();
}
return 0;
}
int Fxstream::readFastaRecord(Fx& read, std::istream& input) {
// assume that we enter this funcion always pointing at the next
// start of a fasta record. The first line will therefore be the
// header line
if(input.fail()) {
fprintf(stderr, "Internal Logic error: %s %d\n", __FILE__, __LINE__);
return 2;
} else if(input.eof()) {
return 0;
}
input.get();
input >> read.name; // first word from the current line
std::getline(input, read.comment);
// peek the begining of the next line. it should not be the '>' char
// if this is a valid fasta file
if(input.peek() == '>') {
fprintf(stderr, "malformed fasta record\n");
return 3;
}
do {
std::string tmp;
std::getline(input, tmp);
read.seq += tmp;
} while (input.good() && input.peek() != '>');
read.len = static_cast<int>(read.seq.size());
return 0;
}
int Fxstream::readFastqRecord(Fx& read, std::istream& input) {
// assume that we enter this funcion always pointing at the next
// start of a fastq record. The first line will therefore be the
// header line
if(!input.good()) {
return 1;
}
// waste the '@' char
input.get();
input >> read.name; // first word from the current line
std::getline(input, read.comment);
// seq line
std::getline(input, read.seq);
read.len = static_cast<int>(read.seq.size());
// waste line
std::string tmp;
std::getline(input, tmp);
// quality line
std::getline(input, read.qual);
return 0;
}
//TODO: BSD grep has support for zip, bzip2 and xz files out of the box
//http://svnweb.freebsd.org/base/head/usr.bin/grep/file.c?view=markup
int Fxstream::read( Fx& read1, Fx& read2) {
if(f1.eof()) {
return 1;
}
if(t1 == FASTA) {
if(readFastaRecord(read1, f1)) {
return 1;
}
if(this->interleaved) {
if(readFastaRecord(read2, f1)) {
return 1;
}
} else if(in2.is_open() && in2.good()) {
if(readFastaRecord(read2, f2)) {
return 1;
}
}
} else if( t1 == FASTQ) {
if(readFastqRecord(read1, f1)) {
return 1;
}
if(this->interleaved) {
if(readFastqRecord(read2, f1)) {
return 1;
}
} else if(in2.is_open() && in2.good()) {
if(readFastqRecord(read2, f2)) {
return 1;
}
}
} else {
// this should never happen as this kind of error should be caught previously
fprintf(stderr, "Internal logic error occurred: %s %d\n", __FILE__, __LINE__);
return 1;
}
return 0;
}
int Fxstream::read(ReadPair& pair) {
return this->read(pair.first, pair.second);
}
#ifdef TEST_FXREAD_MAIN
int main(int argc, char * argv[]) {
Fxstream stream;
int state;
if(argc == 3) {
state = stream.open(argv[1], argv[2], false);
} else if(argc == 2) {
state = stream.open(argv[1], NULL, false);
}
if(state != 0) {
fprintf(stderr, "Failed to open the stream\n");
stream.close();
return 1;
}
ReadPair pair;
//Fx read1, read2;
while(stream.read(pair.first, pair.second) == 0) {
//std::cout << read1 << read2;
std::cout << pair;
pair.clear();
//read1.clear();
//read2.clear();
}
stream.close();
return 0;
}
#endif
|
remove rouge print statement
|
remove rouge print statement
|
C++
|
mit
|
jameslz/fxtract,ctSkennerton/fxtract,jameslz/fxtract,ctSkennerton/fxtract,ctSkennerton/fxtract,jameslz/fxtract
|
668e9bc40c7e5e3cb477acf62e9ba6ccc0914835
|
chrome/browser/devtools/tethering_adb_filter.cc
|
chrome/browser/devtools/tethering_adb_filter.cc
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/devtools/tethering_adb_filter.h"
#include <map>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/devtools/adb_client_socket.h"
#include "net/base/address_list.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/socket/tcp_client_socket.h"
namespace {
const int kBufferSize = 16 * 1024;
static const char kMethodAttribute[] = "method";
static const char kParamsAttribute[] = "params";
static const char kPortAttribute[] = "port";
static const char kLocationAttribute[] = "location";
static const char kConnectionIdAttribute[] = "connectionId";
static const char kTetheringAccepted[] = "Tethering.accepted";
static const char kTetheringBind[] = "Tethering.bind";
static const char kTetheringUnbind[] = "Tethering.unbind";
class SocketTunnel {
public:
SocketTunnel(const std::string& location)
: location_(location) {
}
void Start(int result, net::StreamSocket* socket) {
if (result < 0) {
SelfDestruct();
return;
}
remote_socket_.reset(socket);
std::vector<std::string> tokens;
Tokenize(location_, ":", &tokens);
int port = 0;
if (tokens.size() != 2 || !base::StringToInt(tokens[1], &port)) {
SelfDestruct();
return;
}
net::IPAddressNumber ip_number;
if (!net::ParseIPLiteralToNumber(tokens[0], &ip_number)) {
SelfDestruct();
return;
}
net::AddressList address_list =
net::AddressList::CreateFromIPAddress(ip_number, port);
host_socket_.reset(new net::TCPClientSocket(address_list, NULL,
net::NetLog::Source()));
result = host_socket_->Connect(base::Bind(&SocketTunnel::OnConnected,
base::Unretained(this)));
if (result != net::ERR_IO_PENDING)
OnConnected(result);
}
~SocketTunnel() {
}
private:
void OnConnected(int result) {
if (result < 0) {
SelfDestruct();
return;
}
Pump(host_socket_.get(), remote_socket_.get());
Pump(remote_socket_.get(), host_socket_.get());
}
void Pump(net::StreamSocket* from, net::StreamSocket* to) {
scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer(kBufferSize);
int result = from->Read(buffer, kBufferSize,
base::Bind(&SocketTunnel::OnRead, base::Unretained(this), from, to,
buffer));
if (result != net::ERR_IO_PENDING)
OnRead(from, to, buffer, result);
}
void OnRead(net::StreamSocket* from,
net::StreamSocket* to,
scoped_refptr<net::IOBuffer> buffer,
int result) {
if (result <= 0) {
SelfDestruct();
return;
}
to->Write(buffer, result, base::Bind(&SocketTunnel::OnWritten,
base::Unretained(this)));
Pump(from, to);
}
void OnWritten(int result) {
if (result < 0)
SelfDestruct();
}
void SelfDestruct() {
if (host_socket_)
host_socket_->Disconnect();
if (remote_socket_)
remote_socket_->Disconnect();
delete this;
}
std::string location_;
scoped_ptr<net::StreamSocket> remote_socket_;
scoped_ptr<net::StreamSocket> host_socket_;
};
} // namespace
TetheringAdbFilter::TetheringAdbFilter(int adb_port, const std::string& serial)
: adb_port_(adb_port),
serial_(serial) {
}
TetheringAdbFilter::~TetheringAdbFilter() {
}
bool TetheringAdbFilter::ProcessIncomingMessage(const std::string& message) {
// Only parse messages that might be Tethering.accepted event.
if (message.length() > 100 ||
message.find(kTetheringAccepted) == std::string::npos)
return false;
scoped_ptr<base::Value> value(base::JSONReader::Read(message));
DictionaryValue* dvalue;
if (!value || !value->GetAsDictionary(&dvalue))
return false;
std::string method;
if (!dvalue->GetString(kMethodAttribute, &method) ||
method != kTetheringAccepted) {
return false;
}
DictionaryValue* params = NULL;
dvalue->GetDictionary(kParamsAttribute, ¶ms);
if (!params)
return false;
int port;
std::string connection_id;
if (!params->GetInteger(kPortAttribute, &port) ||
!params->GetString(kConnectionIdAttribute, &connection_id))
return false;
std::map<int, std::string>::iterator it = requested_ports_.find(port);
if (it == requested_ports_.end())
return false;
std::string location = it->second;
SocketTunnel* tunnel = new SocketTunnel(location);
AdbClientSocket::TransportQuery(
adb_port_, serial_, connection_id,
base::Bind(&SocketTunnel::Start, base::Unretained(tunnel)));
return true;
}
void TetheringAdbFilter::ProcessOutgoingMessage(const std::string& message) {
if (message.length() > 100)
return;
if (message.find(kTetheringBind) == std::string::npos &&
message.find(kTetheringUnbind) == std::string::npos)
return;
scoped_ptr<base::Value> value(base::JSONReader::Read(message));
DictionaryValue* dvalue;
if (!value || !value->GetAsDictionary(&dvalue))
return;
std::string method;
if (!dvalue->GetString(kMethodAttribute, &method))
return;
DictionaryValue* params = NULL;
dvalue->GetDictionary(kParamsAttribute, ¶ms);
if (!params)
return;
int port;
if (!params->GetInteger(kPortAttribute, &port))
return;
std::string location;
if (!params->GetString(kLocationAttribute, &location))
return;
if (method == kTetheringBind)
requested_ports_[port] = location;
else
requested_ports_.erase(port);
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/devtools/tethering_adb_filter.h"
#include <map>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/devtools/adb_client_socket.h"
#include "net/base/address_list.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/dns/host_resolver.h"
#include "net/socket/tcp_client_socket.h"
namespace {
const int kBufferSize = 16 * 1024;
static const char kMethodAttribute[] = "method";
static const char kParamsAttribute[] = "params";
static const char kPortAttribute[] = "port";
static const char kLocationAttribute[] = "location";
static const char kConnectionIdAttribute[] = "connectionId";
static const char kTetheringAccepted[] = "Tethering.accepted";
static const char kTetheringBind[] = "Tethering.bind";
static const char kTetheringUnbind[] = "Tethering.unbind";
class SocketTunnel {
public:
explicit SocketTunnel(const std::string& location)
: location_(location) {
}
void Start(int result, net::StreamSocket* socket) {
if (result < 0) {
SelfDestruct();
return;
}
remote_socket_.reset(socket);
std::vector<std::string> tokens;
Tokenize(location_, ":", &tokens);
int port = 0;
if (tokens.size() != 2 || !base::StringToInt(tokens[1], &port)) {
SelfDestruct();
return;
}
host_resolver_ = net::HostResolver::CreateDefaultResolver(NULL);
net::HostResolver::RequestInfo request_info(
net::HostPortPair(tokens[0], port));
result = host_resolver_->Resolve(
request_info, &address_list_,
base::Bind(&SocketTunnel::OnResolved, base::Unretained(this)),
NULL, net::BoundNetLog());
if (result != net::ERR_IO_PENDING)
OnResolved(result);
}
private:
void OnResolved(int result) {
if (result < 0) {
SelfDestruct();
return;
}
host_socket_.reset(new net::TCPClientSocket(address_list_, NULL,
net::NetLog::Source()));
result = host_socket_->Connect(base::Bind(&SocketTunnel::OnConnected,
base::Unretained(this)));
if (result != net::ERR_IO_PENDING)
OnConnected(result);
}
~SocketTunnel() {
}
void OnConnected(int result) {
if (result < 0) {
SelfDestruct();
return;
}
Pump(host_socket_.get(), remote_socket_.get());
Pump(remote_socket_.get(), host_socket_.get());
}
void Pump(net::StreamSocket* from, net::StreamSocket* to) {
scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer(kBufferSize);
int result = from->Read(buffer, kBufferSize,
base::Bind(&SocketTunnel::OnRead, base::Unretained(this), from, to,
buffer));
if (result != net::ERR_IO_PENDING)
OnRead(from, to, buffer, result);
}
void OnRead(net::StreamSocket* from,
net::StreamSocket* to,
scoped_refptr<net::IOBuffer> buffer,
int result) {
if (result <= 0) {
SelfDestruct();
return;
}
to->Write(buffer, result, base::Bind(&SocketTunnel::OnWritten,
base::Unretained(this)));
Pump(from, to);
}
void OnWritten(int result) {
if (result < 0)
SelfDestruct();
}
void SelfDestruct() {
if (host_socket_)
host_socket_->Disconnect();
if (remote_socket_)
remote_socket_->Disconnect();
delete this;
}
std::string location_;
scoped_ptr<net::StreamSocket> remote_socket_;
scoped_ptr<net::StreamSocket> host_socket_;
scoped_ptr<net::HostResolver> host_resolver_;
net::AddressList address_list_;
};
} // namespace
TetheringAdbFilter::TetheringAdbFilter(int adb_port, const std::string& serial)
: adb_port_(adb_port),
serial_(serial) {
}
TetheringAdbFilter::~TetheringAdbFilter() {
}
bool TetheringAdbFilter::ProcessIncomingMessage(const std::string& message) {
// Only parse messages that might be Tethering.accepted event.
if (message.length() > 100 ||
message.find(kTetheringAccepted) == std::string::npos)
return false;
scoped_ptr<base::Value> value(base::JSONReader::Read(message));
DictionaryValue* dvalue;
if (!value || !value->GetAsDictionary(&dvalue))
return false;
std::string method;
if (!dvalue->GetString(kMethodAttribute, &method) ||
method != kTetheringAccepted) {
return false;
}
DictionaryValue* params = NULL;
dvalue->GetDictionary(kParamsAttribute, ¶ms);
if (!params)
return false;
int port;
std::string connection_id;
if (!params->GetInteger(kPortAttribute, &port) ||
!params->GetString(kConnectionIdAttribute, &connection_id))
return false;
std::map<int, std::string>::iterator it = requested_ports_.find(port);
if (it == requested_ports_.end())
return false;
std::string location = it->second;
SocketTunnel* tunnel = new SocketTunnel(location);
AdbClientSocket::TransportQuery(
adb_port_, serial_, connection_id,
base::Bind(&SocketTunnel::Start, base::Unretained(tunnel)));
return true;
}
void TetheringAdbFilter::ProcessOutgoingMessage(const std::string& message) {
if (message.length() > 100)
return;
if (message.find(kTetheringBind) == std::string::npos &&
message.find(kTetheringUnbind) == std::string::npos)
return;
scoped_ptr<base::Value> value(base::JSONReader::Read(message));
DictionaryValue* dvalue;
if (!value || !value->GetAsDictionary(&dvalue))
return;
std::string method;
if (!dvalue->GetString(kMethodAttribute, &method))
return;
DictionaryValue* params = NULL;
dvalue->GetDictionary(kParamsAttribute, ¶ms);
if (!params)
return;
int port;
if (!params->GetInteger(kPortAttribute, &port))
return;
std::string location;
if (!params->GetString(kLocationAttribute, &location))
return;
if (method == kTetheringBind)
requested_ports_[port] = location;
else
requested_ports_.erase(port);
}
|
add host resolver to the reversed port forwarder.
|
DevTools: add host resolver to the reversed port forwarder.
Review URL: https://chromiumcodereview.appspot.com/13890019
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@196444 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,Just-D/chromium-1,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,ondra-novak/chromium.src,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,jaruba/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,jaruba/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,ltilve/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,dednal/chromium.src,jaruba/chromium.src,ltilve/chromium,ltilve/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,jaruba/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,dednal/chromium.src,jaruba/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,axinging/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,ltilve/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,Just-D/chromium-1,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,anirudhSK/chromium,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,mogoweb/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,anirudhSK/chromium,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk
|
03d2e5e32329a69dc5e5553f6853ba34616d1de1
|
chrome/browser/renderer_host/backing_store_x.cc
|
chrome/browser/renderer_host/backing_store_x.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/backing_store.h"
#include <stdlib.h>
#include <utility>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "chrome/common/transport_dib.h"
#include "chrome/common/x11_util.h"
#include "chrome/common/x11_util_internal.h"
// X Backing Stores:
//
// Unlike Windows, where the backing store is kept in heap memory, we keep our
// backing store in the X server, as a pixmap. Thus expose events just require
// instructing the X server to copy from the backing store to the window.
//
// The backing store is in the same format as the visual which our main window
// is using. Bitmaps from the renderer are uploaded to the X server, either via
// shared memory or over the wire, and XRENDER is used to convert them to the
// correct format for the backing store.
BackingStore::BackingStore(const gfx::Size& size,
Display* display,
int depth,
void* visual,
Drawable root_window,
bool use_render,
bool use_shared_memory)
: size_(size),
display_(display),
use_shared_memory_(use_shared_memory),
use_render_(use_render),
visual_depth_(depth),
root_window_(root_window) {
const int width = size.width();
const int height = size.height();
COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN, assumes_little_endian);
pixmap_ = XCreatePixmap(display_, root_window, width, height, depth);
if (use_render_) {
picture_ = XRenderCreatePicture(
display_, pixmap_,
x11_util::GetRenderVisualFormat(display_, static_cast<Visual*>(visual)),
0, NULL);
} else {
picture_ = 0;
pixmap_bpp_ = x11_util::BitsPerPixelForPixmapDepth(display, depth);
}
pixmap_gc_ = XCreateGC(display_, pixmap_, 0, NULL);
}
BackingStore::BackingStore(const gfx::Size& size)
: size_(size),
display_(NULL),
use_shared_memory_(false),
use_render_(false),
visual_depth_(-1),
root_window_(0) {
}
BackingStore::~BackingStore() {
// In unit tests, display_ may be NULL.
if (!display_)
return;
XRenderFreePicture(display_, picture_);
XFreePixmap(display_, pixmap_);
XFreeGC(display_, static_cast<GC>(pixmap_gc_));
}
void BackingStore::PaintRectWithoutXrender(TransportDIB* bitmap,
const gfx::Rect &bitmap_rect) {
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Pixmap pixmap = XCreatePixmap(display_, root_window_, width, height,
visual_depth_);
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
if (pixmap_bpp_ == 32) {
// If the X server depth is already 32-bits, then our job is easy.
image.depth = visual_depth_;
image.bits_per_pixel = 32;
image.bytes_per_line = width * 4;
image.data = static_cast<char*>(bitmap->memory());
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
} else if (pixmap_bpp_ == 24) {
// In this case we just need to strip the alpha channel out of each
// pixel. This is the case which covers VNC servers since they don't
// support Xrender but typically have 24-bit visuals.
//
// It's possible to use some fancy SSE tricks here, but since this is the
// slow path anyway, we do it slowly.
uint8_t* bitmap24 = static_cast<uint8_t*>(malloc(3 * width * height));
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
bitmap24[0] = (pixel >> 16) & 0xff;
bitmap24[1] = (pixel >> 8) & 0xff;
bitmap24[2] = pixel & 0xff;
bitmap24 += 3;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 24;
image.bytes_per_line = width * 3;
image.data = reinterpret_cast<char*>(bitmap24);
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(bitmap24);
} else {
CHECK(false) << "Sorry, we don't support your visual depth without "
"Xrender support (depth:" << visual_depth_
<< " bpp:" << pixmap_bpp_ << ")";
}
XCopyArea(display_, pixmap /* source */, pixmap_ /* target */,
static_cast<GC>(pixmap_gc_),
0, 0 /* source x, y */, bitmap_rect.width(), bitmap_rect.height(),
bitmap_rect.x(), bitmap_rect.y() /* dest x, y */);
XFreePixmap(display_, pixmap);
}
void BackingStore::PaintRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect) {
if (!display_)
return;
if (!use_render_)
return PaintRectWithoutXrender(bitmap, bitmap_rect);
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Picture picture;
Pixmap pixmap;
if (use_shared_memory_) {
const XID shmseg = bitmap->MapToX(display_);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmseg = shmseg;
// The NULL in the following is the |data| pointer: this is an artifact of
// Xlib trying to be helpful, rather than just exposing the X protocol. It
// assumes that we have the shared memory segment mapped into our memory,
// which we don't, and it's trying to calculate an offset by taking the
// difference between the |data| pointer and the address of the mapping in
// |shminfo|. Since both are NULL, the offset will be calculated to be 0,
// which is correct for us.
pixmap = XShmCreatePixmap(display_, root_window_, NULL, &shminfo, width,
height, 32);
} else {
// No shared memory support, we have to copy the bitmap contents to the X
// server. Xlib wraps the underlying PutImage call behind several layers of
// functions which try to convert the image into the format which the X
// server expects. The following values hopefully disable all conversions.
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.depth = 32;
image.bits_per_pixel = 32;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.bytes_per_line = width * 4;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
image.data = static_cast<char*>(bitmap->memory());
pixmap = XCreatePixmap(display_, root_window_, width, height, 32);
GC gc = XCreateGC(display_, pixmap, 0, NULL);
XPutImage(display_, pixmap, gc, &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
XFreeGC(display_, gc);
}
picture = x11_util::CreatePictureFromSkiaPixmap(display_, pixmap);
XRenderComposite(display_, PictOpSrc, picture /* source */, 0 /* mask */,
picture_ /* dest */, 0, 0 /* source x, y */,
0, 0 /* mask x, y */,
bitmap_rect.x(), bitmap_rect.y() /* target x, y */,
width, height);
// In the case of shared memory, we wait for the composite to complete so that
// we are sure that the X server has finished reading.
if (use_shared_memory_)
XSync(display_, False);
XRenderFreePicture(display_, picture);
XFreePixmap(display_, pixmap);
}
void BackingStore::ScrollRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
if (!display_)
return;
// We only support scrolling in one direction at a time.
DCHECK(dx == 0 || dy == 0);
if (dy) {
// Positive values of |dy| scroll up
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
0, std::max(0, -dy) /* source x, y */,
size_.width(), size_.height() - abs(dy),
0, std::max(0, dy) /* dest x, y */);
} else if (dx) {
// Positive values of |dx| scroll right
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
std::max(0, -dx), 0 /* source x, y */,
size_.width() - abs(dx), size_.height(),
std::max(0, dx), 0 /* dest x, y */);
}
PaintRect(process, bitmap, bitmap_rect);
}
void BackingStore::ShowRect(const gfx::Rect& rect, XID target) {
XCopyArea(display_, pixmap_, target, static_cast<GC>(pixmap_gc_),
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x(), rect.y());
}
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/backing_store.h"
#include <stdlib.h>
#include <utility>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "chrome/common/transport_dib.h"
#include "chrome/common/x11_util.h"
#include "chrome/common/x11_util_internal.h"
// X Backing Stores:
//
// Unlike Windows, where the backing store is kept in heap memory, we keep our
// backing store in the X server, as a pixmap. Thus expose events just require
// instructing the X server to copy from the backing store to the window.
//
// The backing store is in the same format as the visual which our main window
// is using. Bitmaps from the renderer are uploaded to the X server, either via
// shared memory or over the wire, and XRENDER is used to convert them to the
// correct format for the backing store.
BackingStore::BackingStore(const gfx::Size& size,
Display* display,
int depth,
void* visual,
Drawable root_window,
bool use_render,
bool use_shared_memory)
: size_(size),
display_(display),
use_shared_memory_(use_shared_memory),
use_render_(use_render),
visual_depth_(depth),
root_window_(root_window) {
const int width = size.width();
const int height = size.height();
COMPILE_ASSERT(__BYTE_ORDER == __LITTLE_ENDIAN, assumes_little_endian);
pixmap_ = XCreatePixmap(display_, root_window, width, height, depth);
if (use_render_) {
picture_ = XRenderCreatePicture(
display_, pixmap_,
x11_util::GetRenderVisualFormat(display_, static_cast<Visual*>(visual)),
0, NULL);
} else {
picture_ = 0;
pixmap_bpp_ = x11_util::BitsPerPixelForPixmapDepth(display, depth);
}
pixmap_gc_ = XCreateGC(display_, pixmap_, 0, NULL);
}
BackingStore::BackingStore(const gfx::Size& size)
: size_(size),
display_(NULL),
use_shared_memory_(false),
use_render_(false),
visual_depth_(-1),
root_window_(0) {
}
BackingStore::~BackingStore() {
// In unit tests, display_ may be NULL.
if (!display_)
return;
XRenderFreePicture(display_, picture_);
XFreePixmap(display_, pixmap_);
XFreeGC(display_, static_cast<GC>(pixmap_gc_));
}
void BackingStore::PaintRectWithoutXrender(TransportDIB* bitmap,
const gfx::Rect &bitmap_rect) {
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Pixmap pixmap = XCreatePixmap(display_, root_window_, width, height,
visual_depth_);
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
if (pixmap_bpp_ == 32) {
// If the X server depth is already 32-bits, then our job is easy.
image.depth = visual_depth_;
image.bits_per_pixel = 32;
image.bytes_per_line = width * 4;
image.data = static_cast<char*>(bitmap->memory());
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
} else if (pixmap_bpp_ == 24) {
// In this case we just need to strip the alpha channel out of each
// pixel. This is the case which covers VNC servers since they don't
// support Xrender but typically have 24-bit visuals.
//
// It's possible to use some fancy SSE tricks here, but since this is the
// slow path anyway, we do it slowly.
uint8_t* bitmap24 = static_cast<uint8_t*>(malloc(3 * width * height));
const uint32_t* bitmap_in = static_cast<const uint32_t*>(bitmap->memory());
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
const uint32_t pixel = *(bitmap_in++);
bitmap24[0] = (pixel >> 16) & 0xff;
bitmap24[1] = (pixel >> 8) & 0xff;
bitmap24[2] = pixel & 0xff;
bitmap24 += 3;
}
}
image.depth = visual_depth_;
image.bits_per_pixel = 24;
image.bytes_per_line = width * 3;
image.data = reinterpret_cast<char*>(bitmap24);
XPutImage(display_, pixmap, static_cast<GC>(pixmap_gc_), &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
free(bitmap24);
} else {
CHECK(false) << "Sorry, we don't support your visual depth without "
"Xrender support (depth:" << visual_depth_
<< " bpp:" << pixmap_bpp_ << ")";
}
XCopyArea(display_, pixmap /* source */, pixmap_ /* target */,
static_cast<GC>(pixmap_gc_),
0, 0 /* source x, y */, bitmap_rect.width(), bitmap_rect.height(),
bitmap_rect.x(), bitmap_rect.y() /* dest x, y */);
XFreePixmap(display_, pixmap);
}
void BackingStore::PaintRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect) {
if (!display_)
return;
if (!use_render_)
return PaintRectWithoutXrender(bitmap, bitmap_rect);
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Picture picture;
Pixmap pixmap;
if (use_shared_memory_) {
const XID shmseg = bitmap->MapToX(display_);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmseg = shmseg;
// The NULL in the following is the |data| pointer: this is an artifact of
// Xlib trying to be helpful, rather than just exposing the X protocol. It
// assumes that we have the shared memory segment mapped into our memory,
// which we don't, and it's trying to calculate an offset by taking the
// difference between the |data| pointer and the address of the mapping in
// |shminfo|. Since both are NULL, the offset will be calculated to be 0,
// which is correct for us.
pixmap = XShmCreatePixmap(display_, root_window_, NULL, &shminfo, width,
height, 32);
} else {
// No shared memory support, we have to copy the bitmap contents to the X
// server. Xlib wraps the underlying PutImage call behind several layers of
// functions which try to convert the image into the format which the X
// server expects. The following values hopefully disable all conversions.
XImage image;
memset(&image, 0, sizeof(image));
image.width = width;
image.height = height;
image.depth = 32;
image.bits_per_pixel = 32;
image.format = ZPixmap;
image.byte_order = LSBFirst;
image.bitmap_unit = 8;
image.bitmap_bit_order = LSBFirst;
image.bytes_per_line = width * 4;
image.red_mask = 0xff;
image.green_mask = 0xff00;
image.blue_mask = 0xff0000;
image.data = static_cast<char*>(bitmap->memory());
pixmap = XCreatePixmap(display_, root_window_, width, height, 32);
GC gc = XCreateGC(display_, pixmap, 0, NULL);
XPutImage(display_, pixmap, gc, &image,
0, 0 /* source x, y */, 0, 0 /* dest x, y */,
width, height);
XFreeGC(display_, gc);
}
picture = x11_util::CreatePictureFromSkiaPixmap(display_, pixmap);
XRenderComposite(display_, PictOpSrc, picture /* source */, 0 /* mask */,
picture_ /* dest */, 0, 0 /* source x, y */,
0, 0 /* mask x, y */,
bitmap_rect.x(), bitmap_rect.y() /* target x, y */,
width, height);
// In the case of shared memory, we wait for the composite to complete so that
// we are sure that the X server has finished reading.
if (use_shared_memory_)
XSync(display_, False);
XRenderFreePicture(display_, picture);
XFreePixmap(display_, pixmap);
}
void BackingStore::ScrollRect(base::ProcessHandle process,
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect,
int dx, int dy,
const gfx::Rect& clip_rect,
const gfx::Size& view_size) {
if (!display_)
return;
// We only support scrolling in one direction at a time.
DCHECK(dx == 0 || dy == 0);
if (dy) {
// Positive values of |dy| scroll up
if (abs(dy) >= clip_rect.height())
return;
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
clip_rect.x() /* source x */,
std::max(clip_rect.y(), clip_rect.y() - dy),
clip_rect.width(),
clip_rect.height() - abs(dy),
clip_rect.x() /* dest x */,
std::max(clip_rect.y(), clip_rect.y() + dy) /* dest y */);
} else if (dx) {
// Positive values of |dx| scroll right
if (abs(dx) >= clip_rect.width())
return;
XCopyArea(display_, pixmap_, pixmap_, static_cast<GC>(pixmap_gc_),
std::max(clip_rect.x(), clip_rect.x() - dx),
clip_rect.y() /* source y */,
clip_rect.width() - abs(dx),
clip_rect.height(),
std::max(clip_rect.x(), clip_rect.x() + dx) /* dest x */,
clip_rect.y() /* dest x */);
}
PaintRect(process, bitmap, bitmap_rect);
}
void BackingStore::ShowRect(const gfx::Rect& rect, XID target) {
XCopyArea(display_, pixmap_, target, static_cast<GC>(pixmap_gc_),
rect.x(), rect.y(), rect.width(), rect.height(),
rect.x(), rect.y());
}
|
fix scrolling
|
Linux: fix scrolling
I had assuming that we always scroll the whole window; I was wrong.
This patch fixes issues with 'ghost' scrollbars appearing when the
window looses focus and with huge misrendering when scrolling iframes.
Review URL: http://codereview.chromium.org/42357
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@12012 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
1e66d8a989911a70d201fa62997eb740b526c995
|
chrome/browser/tab_contents/navigation_entry.cc
|
chrome/browser/tab_contents/navigation_entry.cc
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/common/gfx/text_elider.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/resource_bundle.h"
// Use this to get a new unique ID for a NavigationEntry during construction.
// The returned ID is guaranteed to be nonzero (which is the "no ID" indicator).
static int GetUniqueID() {
static int unique_id_counter = 0;
return ++unique_id_counter;
}
NavigationEntry::SSLStatus::SSLStatus()
: security_style_(SECURITY_STYLE_UNKNOWN),
cert_id_(0),
cert_status_(0),
security_bits_(-1),
content_status_(NORMAL_CONTENT) {
}
NavigationEntry::FaviconStatus::FaviconStatus() : valid_(false) {
ResourceBundle &rb = ResourceBundle::GetSharedInstance();
bitmap_ = *rb.GetBitmapNamed(IDR_DEFAULT_FAVICON);
}
NavigationEntry::NavigationEntry(TabContentsType type)
: unique_id_(GetUniqueID()),
tab_type_(type),
site_instance_(NULL),
page_type_(NORMAL_PAGE),
page_id_(-1),
transition_type_(PageTransition::LINK),
has_post_data_(false),
restored_(false) {
}
NavigationEntry::NavigationEntry(TabContentsType type,
SiteInstance* instance,
int page_id,
const GURL& url,
const GURL& referrer,
const string16& title,
PageTransition::Type transition_type)
: unique_id_(GetUniqueID()),
tab_type_(type),
site_instance_(instance),
page_type_(NORMAL_PAGE),
url_(url),
referrer_(referrer),
title_(title),
page_id_(page_id),
transition_type_(transition_type),
has_post_data_(false),
restored_(false) {
}
const string16& NavigationEntry::GetTitleForDisplay(
const NavigationController* navigation_controller) {
// Most pages have real titles. Don't even bother caching anything if this is
// the case.
if (!title_.empty())
return title_;
// More complicated cases will use the URLs as the title. This result we will
// cache since it's more complicated to compute.
if (!cached_display_title_.empty())
return cached_display_title_;
// Use the display URL first if any, and fall back on using the real URL.
std::wstring languages;
if (navigation_controller) {
languages = navigation_controller->profile()->GetPrefs()->GetString(
prefs::kAcceptLanguages);
}
if (!display_url_.is_empty()) {
cached_display_title_ = WideToUTF16Hack(gfx::GetCleanStringFromUrl(
display_url_, languages, NULL, NULL));
} else if (!url_.is_empty()) {
cached_display_title_ = WideToUTF16Hack(gfx::GetCleanStringFromUrl(
display_url_, languages, NULL, NULL));
}
return cached_display_title_;
}
bool NavigationEntry::IsViewSourceMode() const {
return display_url_.SchemeIs(chrome::kViewSourceScheme);
}
|
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/tab_contents/navigation_entry.h"
#include "chrome/browser/tab_contents/navigation_controller.h"
#include "chrome/common/gfx/text_elider.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/resource_bundle.h"
// Use this to get a new unique ID for a NavigationEntry during construction.
// The returned ID is guaranteed to be nonzero (which is the "no ID" indicator).
static int GetUniqueID() {
static int unique_id_counter = 0;
return ++unique_id_counter;
}
NavigationEntry::SSLStatus::SSLStatus()
: security_style_(SECURITY_STYLE_UNKNOWN),
cert_id_(0),
cert_status_(0),
security_bits_(-1),
content_status_(NORMAL_CONTENT) {
}
NavigationEntry::FaviconStatus::FaviconStatus() : valid_(false) {
ResourceBundle &rb = ResourceBundle::GetSharedInstance();
bitmap_ = *rb.GetBitmapNamed(IDR_DEFAULT_FAVICON);
}
NavigationEntry::NavigationEntry(TabContentsType type)
: unique_id_(GetUniqueID()),
tab_type_(type),
site_instance_(NULL),
page_type_(NORMAL_PAGE),
page_id_(-1),
transition_type_(PageTransition::LINK),
has_post_data_(false),
restored_(false) {
}
NavigationEntry::NavigationEntry(TabContentsType type,
SiteInstance* instance,
int page_id,
const GURL& url,
const GURL& referrer,
const string16& title,
PageTransition::Type transition_type)
: unique_id_(GetUniqueID()),
tab_type_(type),
site_instance_(instance),
page_type_(NORMAL_PAGE),
url_(url),
referrer_(referrer),
title_(title),
page_id_(page_id),
transition_type_(transition_type),
has_post_data_(false),
restored_(false) {
}
const string16& NavigationEntry::GetTitleForDisplay(
const NavigationController* navigation_controller) {
// Most pages have real titles. Don't even bother caching anything if this is
// the case.
if (!title_.empty())
return title_;
// More complicated cases will use the URLs as the title. This result we will
// cache since it's more complicated to compute.
if (!cached_display_title_.empty())
return cached_display_title_;
// Use the display URL first if any, and fall back on using the real URL.
std::wstring languages;
if (navigation_controller) {
languages = navigation_controller->profile()->GetPrefs()->GetString(
prefs::kAcceptLanguages);
}
if (!display_url_.is_empty()) {
cached_display_title_ = WideToUTF16Hack(gfx::GetCleanStringFromUrl(
display_url_, languages, NULL, NULL));
} else if (!url_.is_empty()) {
cached_display_title_ = WideToUTF16Hack(gfx::GetCleanStringFromUrl(
url_, languages, NULL, NULL));
}
return cached_display_title_;
}
bool NavigationEntry::IsViewSourceMode() const {
return display_url_.SchemeIs(chrome::kViewSourceScheme);
}
|
Fix stupid typo causing the navigation entry unit tests to fail. Review URL: http://codereview.chromium.org/39117
|
Fix stupid typo causing the navigation entry unit tests to fail.
Review URL: http://codereview.chromium.org/39117
git-svn-id: http://src.chromium.org/svn/trunk/src@10877 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: ec9e4a61f1afb874c336fbebb4e26f0e49cb571b
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
70f95f9b42ead1d72fc87954f22e9c81c20a5134
|
chrome/renderer/loadtimes_extension_bindings.cc
|
chrome/renderer/loadtimes_extension_bindings.cc
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/loadtimes_extension_bindings.h"
#include <math.h>
#include "base/time.h"
#include "chrome/renderer/navigation_state.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"
using WebKit::WebDataSource;
using WebKit::WebFrame;
using WebKit::WebNavigationType;
// Values for CSI "tran" property
const int kTransitionLink = 0;
const int kTransitionForwardBack = 6;
const int kTransitionOther = 15;
const int kTransitionReload = 16;
namespace extensions_v8 {
static const char* const kLoadTimesExtensionName = "v8/LoadTimes";
class LoadTimesExtensionWrapper : public v8::Extension {
public:
// Creates an extension which adds a new function, chromium.GetLoadTimes()
// This function returns an object containing the following members:
// requestTime: The time the request to load the page was received
// loadTime: The time the renderer started the load process
// finishDocumentLoadTime: The time the document itself was loaded
// (this is before the onload() method is fired)
// finishLoadTime: The time all loading is done, after the onload()
// method and all resources
// navigationType: A string describing what user action initiated the load
LoadTimesExtensionWrapper() :
v8::Extension(kLoadTimesExtensionName,
"var chrome;"
"if (!chrome)"
" chrome = {};"
"chrome.loadTimes = function() {"
" native function GetLoadTimes();"
" return GetLoadTimes();"
"};"
"chrome.csi = function() {"
" native function GetCSI();"
" return GetCSI();"
"}") {}
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetLoadTimes"))) {
return v8::FunctionTemplate::New(GetLoadTimes);
} else if (name->Equals(v8::String::New("GetCSI"))) {
return v8::FunctionTemplate::New(GetCSI);
}
return v8::Handle<v8::FunctionTemplate>();
}
static const char* GetNavigationType(WebNavigationType nav_type) {
switch (nav_type) {
case WebKit::WebNavigationTypeLinkClicked:
return "LinkClicked";
case WebKit::WebNavigationTypeFormSubmitted:
return "FormSubmitted";
case WebKit::WebNavigationTypeBackForward:
return "BackForward";
case WebKit::WebNavigationTypeReload:
return "Reload";
case WebKit::WebNavigationTypeFormResubmitted:
return "Resubmitted";
case WebKit::WebNavigationTypeOther:
return "Other";
}
return "";
}
static int GetCSITransitionType(WebNavigationType nav_type) {
switch (nav_type) {
case WebKit::WebNavigationTypeLinkClicked:
case WebKit::WebNavigationTypeFormSubmitted:
case WebKit::WebNavigationTypeFormResubmitted:
return kTransitionLink;
case WebKit::WebNavigationTypeBackForward:
return kTransitionForwardBack;
case WebKit::WebNavigationTypeReload:
return kTransitionReload;
case WebKit::WebNavigationTypeOther:
return kTransitionOther;
}
return kTransitionOther;
}
static v8::Handle<v8::Value> GetLoadTimes(const v8::Arguments& args) {
WebFrame* frame = WebFrame::frameForEnteredContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
NavigationState* navigation_state =
NavigationState::FromDataSource(data_source);
v8::Local<v8::Object> load_times = v8::Object::New();
load_times->Set(
v8::String::New("requestTime"),
v8::Number::New(navigation_state->request_time().ToDoubleT()));
load_times->Set(
v8::String::New("startLoadTime"),
v8::Number::New(navigation_state->start_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("commitLoadTime"),
v8::Number::New(navigation_state->commit_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("finishDocumentLoadTime"),
v8::Number::New(
navigation_state->finish_document_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("finishLoadTime"),
v8::Number::New(navigation_state->finish_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("firstPaintTime"),
v8::Number::New(navigation_state->first_paint_time().ToDoubleT()));
load_times->Set(
v8::String::New("firstPaintAfterLoadTime"),
v8::Number::New(
navigation_state->first_paint_after_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("navigationType"),
v8::String::New(GetNavigationType(data_source->navigationType())));
load_times->Set(
v8::String::New("wasFetchedViaSpdy"),
v8::Boolean::New(navigation_state->was_fetched_via_spdy()));
return load_times;
}
}
return v8::Null();
}
static v8::Handle<v8::Value> GetCSI(const v8::Arguments& args) {
WebFrame* frame = WebFrame::frameForEnteredContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
NavigationState* navigation_state =
NavigationState::FromDataSource(data_source);
v8::Local<v8::Object> csi = v8::Object::New();
base::Time now = base::Time::Now();
base::Time start = navigation_state->request_time().is_null() ?
navigation_state->start_load_time() :
navigation_state->request_time();
base::Time onload = navigation_state->finish_document_load_time();
base::TimeDelta page = now - start;
csi->Set(
v8::String::New("startE"),
v8::Number::New(floor(start.ToDoubleT() * 1000)));
csi->Set(
v8::String::New("onloadT"),
v8::Number::New(floor(onload.ToDoubleT() * 1000)));
csi->Set(
v8::String::New("pageT"),
v8::Number::New(page.InMillisecondsF()));
csi->Set(
v8::String::New("tran"),
v8::Number::New(
GetCSITransitionType(data_source->navigationType())));
return csi;
}
}
return v8::Null();
}
};
v8::Extension* LoadTimesExtension::Get() {
return new LoadTimesExtensionWrapper();
}
} // namespace extensions_v8
|
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/renderer/loadtimes_extension_bindings.h"
#include <math.h>
#include "base/time.h"
#include "chrome/renderer/navigation_state.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"
using WebKit::WebDataSource;
using WebKit::WebFrame;
using WebKit::WebNavigationType;
// Values for CSI "tran" property
const int kTransitionLink = 0;
const int kTransitionForwardBack = 6;
const int kTransitionOther = 15;
const int kTransitionReload = 16;
namespace extensions_v8 {
static const char* const kLoadTimesExtensionName = "v8/LoadTimes";
class LoadTimesExtensionWrapper : public v8::Extension {
public:
// Creates an extension which adds a new function, chromium.GetLoadTimes()
// This function returns an object containing the following members:
// requestTime: The time the request to load the page was received
// loadTime: The time the renderer started the load process
// finishDocumentLoadTime: The time the document itself was loaded
// (this is before the onload() method is fired)
// finishLoadTime: The time all loading is done, after the onload()
// method and all resources
// navigationType: A string describing what user action initiated the load
LoadTimesExtensionWrapper() :
v8::Extension(kLoadTimesExtensionName,
"var chrome;"
"if (!chrome)"
" chrome = {};"
"chrome.loadTimes = function() {"
" native function GetLoadTimes();"
" return GetLoadTimes();"
"};"
"chrome.csi = function() {"
" native function GetCSI();"
" return GetCSI();"
"}") {}
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetLoadTimes"))) {
return v8::FunctionTemplate::New(GetLoadTimes);
} else if (name->Equals(v8::String::New("GetCSI"))) {
return v8::FunctionTemplate::New(GetCSI);
}
return v8::Handle<v8::FunctionTemplate>();
}
static const char* GetNavigationType(WebNavigationType nav_type) {
switch (nav_type) {
case WebKit::WebNavigationTypeLinkClicked:
return "LinkClicked";
case WebKit::WebNavigationTypeFormSubmitted:
return "FormSubmitted";
case WebKit::WebNavigationTypeBackForward:
return "BackForward";
case WebKit::WebNavigationTypeReload:
return "Reload";
case WebKit::WebNavigationTypeFormResubmitted:
return "Resubmitted";
case WebKit::WebNavigationTypeOther:
return "Other";
}
return "";
}
static int GetCSITransitionType(WebNavigationType nav_type) {
switch (nav_type) {
case WebKit::WebNavigationTypeLinkClicked:
case WebKit::WebNavigationTypeFormSubmitted:
case WebKit::WebNavigationTypeFormResubmitted:
return kTransitionLink;
case WebKit::WebNavigationTypeBackForward:
return kTransitionForwardBack;
case WebKit::WebNavigationTypeReload:
return kTransitionReload;
case WebKit::WebNavigationTypeOther:
return kTransitionOther;
}
return kTransitionOther;
}
static v8::Handle<v8::Value> GetLoadTimes(const v8::Arguments& args) {
WebFrame* frame = WebFrame::frameForCurrentContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
NavigationState* navigation_state =
NavigationState::FromDataSource(data_source);
v8::Local<v8::Object> load_times = v8::Object::New();
load_times->Set(
v8::String::New("requestTime"),
v8::Number::New(navigation_state->request_time().ToDoubleT()));
load_times->Set(
v8::String::New("startLoadTime"),
v8::Number::New(navigation_state->start_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("commitLoadTime"),
v8::Number::New(navigation_state->commit_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("finishDocumentLoadTime"),
v8::Number::New(
navigation_state->finish_document_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("finishLoadTime"),
v8::Number::New(navigation_state->finish_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("firstPaintTime"),
v8::Number::New(navigation_state->first_paint_time().ToDoubleT()));
load_times->Set(
v8::String::New("firstPaintAfterLoadTime"),
v8::Number::New(
navigation_state->first_paint_after_load_time().ToDoubleT()));
load_times->Set(
v8::String::New("navigationType"),
v8::String::New(GetNavigationType(data_source->navigationType())));
load_times->Set(
v8::String::New("wasFetchedViaSpdy"),
v8::Boolean::New(navigation_state->was_fetched_via_spdy()));
return load_times;
}
}
return v8::Null();
}
static v8::Handle<v8::Value> GetCSI(const v8::Arguments& args) {
WebFrame* frame = WebFrame::frameForCurrentContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
NavigationState* navigation_state =
NavigationState::FromDataSource(data_source);
v8::Local<v8::Object> csi = v8::Object::New();
base::Time now = base::Time::Now();
base::Time start = navigation_state->request_time().is_null() ?
navigation_state->start_load_time() :
navigation_state->request_time();
base::Time onload = navigation_state->finish_document_load_time();
base::TimeDelta page = now - start;
csi->Set(
v8::String::New("startE"),
v8::Number::New(floor(start.ToDoubleT() * 1000)));
csi->Set(
v8::String::New("onloadT"),
v8::Number::New(floor(onload.ToDoubleT() * 1000)));
csi->Set(
v8::String::New("pageT"),
v8::Number::New(page.InMillisecondsF()));
csi->Set(
v8::String::New("tran"),
v8::Number::New(
GetCSITransitionType(data_source->navigationType())));
return csi;
}
}
return v8::Null();
}
};
v8::Extension* LoadTimesExtension::Get() {
return new LoadTimesExtensionWrapper();
}
} // namespace extensions_v8
|
Change the javascript context used by the loadtimes extension. It should be using the CurrentContext, not the EnteredContext so that it grabs the right object based on the frame being called.
|
Change the javascript context used by the loadtimes extension. It should be
using the CurrentContext, not the EnteredContext so that it grabs the right
object based on the frame being called.
The security of this object is not in question - access to the window itself
is already protected from XSS access.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/593003
git-svn-id: http://src.chromium.org/svn/trunk/src@38426 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: 2705b1ce1e0bcfd798828b49e4507c88231dd4ae
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
400a1514a7742c50f1fd68f21d4eba4b048e268c
|
src/dlvhex/BoostComponentFinder.cpp
|
src/dlvhex/BoostComponentFinder.cpp
|
/* -*- C++ -*- */
/**
* @file BoostComponentFinder.cpp
* @author Roman Schindlauer
* @date Wed Jan 25 14:34:20 CET 2006
*
* @brief Strategy class for finding SCCs and WCCs from a given program graph, using
* the Boost Graph Library.
*
*
*/
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include "dlvhex/BoostComponentFinder.h"
#include "dlvhex/globals.h"
#include "dlvhex/helper.h"
void
BoostComponentFinder::makeEdges(const std::vector<AtomNode*>& nodes,
Edges& edges) const
{
for (std::vector<AtomNode*>::const_iterator node = nodes.begin();
node != nodes.end();
++node)
{
ComponentFinder::Vertex v1 = (*node)->getId();
//
// considering all types of dependencies
//
for (std::vector<Dependency>::const_iterator d = (*node)->getSucceeding().begin();
d != (*node)->getSucceeding().end();
++d)
{
ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId();
//
// making edge from v2 to v1, because the direction is not relevant
// for finding WCCs and SCCs and this is the "traditional" direction
// for lp-dependency (head->body), and we want these arrows in the
// graphviz output (see below)!
//
edges.push_back(ComponentFinder::Edge(v2, v1));
}
}
}
void
BoostComponentFinder::selectNodes(const Vertices& vertices,
const std::vector<AtomNode*>& nodes,
std::vector<AtomNode*>& newnodes) const
{
newnodes.clear();
for (ComponentFinder::Vertices::const_iterator vi = vertices.begin();
vi != vertices.end();
++vi)
{
//
// TODO: this is too expensive - all the vertices-stuff should actually be done
// in boost, it could handle all these properties internally.
// there shouldn't be any mapping and searching here!
//
std::vector<AtomNode*>::const_iterator an;
for (an = nodes.begin(); an != nodes.end(); ++an)
{
if ((*an)->getId() == *vi)
break;
}
if (an != nodes.end())
{
newnodes.push_back(*an);
}
}
}
void
BoostComponentFinder::findWeakComponents(const std::vector<AtomNode*>& nodes,
std::vector<std::vector<AtomNode*> >& wccs)
{
/*
std::map<int, Vertex> vmap;
Edges contedges;
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
}
*/
ComponentFinder::Edges edges;
makeEdges(nodes, edges);
using namespace boost;
{
typedef adjacency_list <listS, vecS, undirectedS> Graph;
Graph G;
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
add_edge((*ei).first, (*ei).second, G);
}
std::vector<int> component(num_vertices(G));
int num = connected_components(G, &component[0]);
// std::cout << "Total number of components: " << num << std::endl;
std::vector<AtomNode*> wcc;
for (int cn = 0; cn < num; ++cn)
{
Vertices thiscomponent;
for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
{
if (component[i] == cn)
{
thiscomponent.push_back(Vertex(i));
}
}
//
// hack - remove all single noded-components, as long as we don't know
// how to use boost with non-contiguous vertices!
//
if (thiscomponent.size() > 1)
{
//.push_back(thiscomponent);
wcc.clear();
selectNodes(thiscomponent, nodes, wcc);
wccs.push_back(wcc);
}
}
// for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
// std::cout << "Vertex " << i <<" is in component " << component[i] << std::endl;
// std::cout << std::endl;
}
}
void
BoostComponentFinder::findStrongComponents(const std::vector<AtomNode*>& nodes,
std::vector<std::vector<AtomNode*> >& sccs)
{
ComponentFinder::Edges edges;
makeEdges(nodes, edges);
//
// create a label table for the graphviz output
//
std::string nms[nodes.size()];
for (int y = 0; y < nodes.size(); ++y)
{
std::stringstream out;
out.str("");
nodes[y]->getAtom()->print(out,0);
std::string at(out.str());
helper::escapeQuotes(at);
nms[y] = at.c_str();
}
using namespace boost;
{
typedef adjacency_list <vecS, vecS, directedS> Graph;
Graph G(0);
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
add_edge((*ei).first, (*ei).second, G);
}
std::vector<int> component(num_vertices(G));
int num = strong_components(G, &component[0]);
//std::cout << "Total number of components: " << num << std::endl;
std::vector<AtomNode*> scc;
for (int cn = 0; cn < num; ++cn)
{
Vertices thiscomponent;
for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
{
if (component[i] == cn)
thiscomponent.push_back(Vertex(i));
}
//
// boost adds also single components as strong components. we avoid that
// for now (25-01-06), because having so many sccs will mean to call dlv
// a lot, which might cost a lot. better to put an effort into the
// graphprocessor strategy of finding big wccs on the fly.
// TODO: try the other way by using a different boostcomponentfinder with
// a different graphprocessor!
//
//
// only add components with more than one vertex:
//
if (thiscomponent.size() > 1)
{
//components.push_back(thiscomponent);
scc.clear();
selectNodes(thiscomponent, nodes, scc);
sccs.push_back(scc);
}
}
if (global::optionVerbose)
{
std::ofstream out;
out.open(global::lpfilename.c_str());
write_graphviz(out, G, make_label_writer(nms));
out.close();
std::cout << "Graph written to " << global::lpfilename << std::endl;
}
}
}
|
/* -*- C++ -*- */
/**
* @file BoostComponentFinder.cpp
* @author Roman Schindlauer
* @date Wed Jan 25 14:34:20 CET 2006
*
* @brief Strategy class for finding SCCs and WCCs from a given program graph, using
* the Boost Graph Library.
*
*
*/
#include <sstream>
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/graph/strong_components.hpp>
#include <boost/graph/graphviz.hpp>
#include "dlvhex/BoostComponentFinder.h"
#include "dlvhex/globals.h"
#include "dlvhex/helper.h"
void
BoostComponentFinder::makeEdges(const std::vector<AtomNode*>& nodes,
Edges& edges) const
{
for (std::vector<AtomNode*>::const_iterator node = nodes.begin();
node != nodes.end();
++node)
{
ComponentFinder::Vertex v1 = (*node)->getId();
//
// considering all types of dependencies
//
for (std::vector<Dependency>::const_iterator d = (*node)->getSucceeding().begin();
d != (*node)->getSucceeding().end();
++d)
{
ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId();
//
// making edge from v2 to v1, because the direction is not relevant
// for finding WCCs and SCCs and this is the "traditional" direction
// for lp-dependency (head->body), and we want these arrows in the
// graphviz output (see below)!
//
edges.push_back(ComponentFinder::Edge(v2, v1));
}
}
}
void
BoostComponentFinder::selectNodes(const Vertices& vertices,
const std::vector<AtomNode*>& nodes,
std::vector<AtomNode*>& newnodes) const
{
newnodes.clear();
for (ComponentFinder::Vertices::const_iterator vi = vertices.begin();
vi != vertices.end();
++vi)
{
//
// TODO: this is too expensive - all the vertices-stuff should actually be done
// in boost, it could handle all these properties internally.
// there shouldn't be any mapping and searching here!
//
std::vector<AtomNode*>::const_iterator an;
for (an = nodes.begin(); an != nodes.end(); ++an)
{
if ((*an)->getId() == *vi)
break;
}
if (an != nodes.end())
{
newnodes.push_back(*an);
}
}
}
void
BoostComponentFinder::findWeakComponents(const std::vector<AtomNode*>& nodes,
std::vector<std::vector<AtomNode*> >& wccs)
{
/*
std::map<int, Vertex> vmap;
Edges contedges;
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
}
*/
ComponentFinder::Edges edges;
makeEdges(nodes, edges);
using namespace boost;
{
typedef adjacency_list <listS, vecS, undirectedS> Graph;
Graph G;
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
add_edge((*ei).first, (*ei).second, G);
}
std::vector<int> component(num_vertices(G));
int num = connected_components(G, &component[0]);
// std::cout << "Total number of components: " << num << std::endl;
std::vector<AtomNode*> wcc;
for (int cn = 0; cn < num; ++cn)
{
Vertices thiscomponent;
for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
{
if (component[i] == cn)
{
thiscomponent.push_back(Vertex(i));
}
}
//
// hack - remove all single noded-components, as long as we don't know
// how to use boost with non-contiguous vertices!
//
if (thiscomponent.size() > 1)
{
//.push_back(thiscomponent);
wcc.clear();
selectNodes(thiscomponent, nodes, wcc);
wccs.push_back(wcc);
}
}
// for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
// std::cout << "Vertex " << i <<" is in component " << component[i] << std::endl;
// std::cout << std::endl;
}
}
void
BoostComponentFinder::findStrongComponents(const std::vector<AtomNode*>& nodes,
std::vector<std::vector<AtomNode*> >& sccs)
{
ComponentFinder::Edges edges;
makeEdges(nodes, edges);
//
// create a label table for the graphviz output
//
std::string nms[nodes.size()];
for (int y = 0; y < nodes.size(); ++y)
{
std::stringstream out;
out.str("");
nodes[y]->getAtom()->print(out,0);
std::string at(out.str());
helper::escapeQuotes(at);
nms[y] = at.c_str();
}
using namespace boost;
{
typedef adjacency_list <vecS, vecS, directedS> Graph;
Graph G(0);
for (Edges::const_iterator ei = edges.begin();
ei != edges.end();
++ei)
{
add_edge((*ei).first, (*ei).second, G);
}
std::vector<int> component(num_vertices(G));
int num = strong_components(G, &component[0]);
//std::cout << "Total number of components: " << num << std::endl;
std::vector<AtomNode*> scc;
for (int cn = 0; cn < num; ++cn)
{
Vertices thiscomponent;
for (std::vector<int>::size_type i = 0; i != component.size(); ++i)
{
if (component[i] == cn)
thiscomponent.push_back(Vertex(i));
}
//
// boost adds also single components as strong components. we avoid that
// for now (25-01-06), because having so many sccs will mean to call dlv
// a lot, which might cost a lot. better to put an effort into the
// graphprocessor strategy of finding big wccs on the fly.
// TODO: try the other way by using a different boostcomponentfinder with
// a different graphprocessor!
//
//
// only add components with more than one vertex:
//
if (thiscomponent.size() > 1)
{
//components.push_back(thiscomponent);
scc.clear();
selectNodes(thiscomponent, nodes, scc);
sccs.push_back(scc);
}
}
if (global::optionVerbose)
{
std::ofstream out;
out.open(global::lpfilename.c_str());
write_graphviz(out, G, make_label_writer(nms));
out.close();
std::cout << "Graph written to " << global::lpfilename << std::endl;
}
}
}
|
Include sstream, or std::stringstream is unknown (maybe some installed library headers don't include this header file on gluck.kr.tuwien.ac.at).
|
Include sstream, or std::stringstream is unknown (maybe some installed
library headers don't include this header file on gluck.kr.tuwien.ac.at).
|
C++
|
lgpl-2.1
|
hexhex/core,hexhex/core,hexhex/core,hexhex/core
|
144ef1c50f3b6cf6b2e2256eabaa552dd63e5d97
|
API-Samples/enable_validation_with_callback/enable_validation_with_callback.cpp
|
API-Samples/enable_validation_with_callback/enable_validation_with_callback.cpp
|
/*
* Vulkan Samples
*
* Copyright (C) 2015-2016 Valve Corporation
* Copyright (C) 2015-2016 LunarG, 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.
*/
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
Show how to enable validation layers and provide callback
*/
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <util_init.hpp>
VKAPI_ATTR VkBool32 VKAPI_CALL
dbgFunc(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType,
uint64_t srcObject, size_t location, int32_t msgCode,
const char *pLayerPrefix, const char *pMsg, void *pUserData) {
std::ostringstream message;
if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
message << "ERROR: ";
} else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
message << "WARNING: ";
} else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
message << "PERFORMANCE WARNING: ";
} else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
message << "INFO: ";
} else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
message << "DEBUG: ";
}
message << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg;
#ifdef _WIN32
MessageBox(NULL, message.str().c_str(), "Alert", MB_OK);
#else
std::cout << message.str() << std::endl;
#endif
/*
* false indicates that layer should not bail-out of an
* API call that had validation failures. This may mean that the
* app dies inside the driver due to invalid parameter(s).
* That's what would happen without validation layers, so we'll
* keep that behavior here.
*/
return false;
}
int sample_main(int argc, char *argv[]) {
struct sample_info info = {};
init_global_layer_properties(info);
/* VULKAN_KEY_START */
/* Use standard_validation meta layer that enables all
* recommended validation layers
*/
info.instance_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
if (!demo_check_layers(info.instance_layer_properties,
info.instance_layer_names)) {
/* If standard validation is not present, search instead for the
* individual layers that make it up, in the correct order.
*/
info.instance_layer_names.clear();
info.instance_layer_names.push_back("VK_LAYER_GOOGLE_threading");
info.instance_layer_names.push_back(
"VK_LAYER_LUNARG_parameter_validation");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_core_validation");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_device_limits");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_image");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_swapchain");
info.instance_layer_names.push_back("VK_LAYER_GOOGLE_unique_objects");
if (!demo_check_layers(info.instance_layer_properties,
info.instance_layer_names)) {
exit(1);
}
}
/* Enable debug callback extension */
info.instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = NULL;
app_info.pApplicationName = "vulkansamples_enable_validation_with_callback";
app_info.applicationVersion = 1;
app_info.pEngineName = "Vulkan Samples";
app_info.engineVersion = 1;
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo inst_info = {};
inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
inst_info.pNext = NULL;
inst_info.flags = 0;
inst_info.pApplicationInfo = &app_info;
inst_info.enabledLayerCount = info.instance_layer_names.size();
inst_info.ppEnabledLayerNames = info.instance_layer_names.size()
? info.instance_layer_names.data()
: NULL;
inst_info.enabledExtensionCount = info.instance_extension_names.size();
inst_info.ppEnabledExtensionNames = info.instance_extension_names.data();
VkResult res = vkCreateInstance(&inst_info, NULL, &info.inst);
assert(res == VK_SUCCESS);
init_enumerate_device(info);
init_device_layer_properties(info);
/* Use standard_validation meta layer that enables all
* recommended validation layers
* Instance layers and Device layers are independent so
* must enable validation layers for both to see everything.
*/
info.device_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
if (!demo_check_layers(info.device_layer_properties,
info.device_layer_names)) {
/* If standard validation is not present, search instead for the
* individual layers that make it up, in the correct order.
*/
info.device_layer_names.clear();
info.device_layer_names.push_back("VK_LAYER_GOOGLE_threading");
info.device_layer_names.push_back(
"VK_LAYER_LUNARG_parameter_validation");
info.device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker");
info.device_layer_names.push_back("VK_LAYER_LUNARG_core_validation");
info.device_layer_names.push_back("VK_LAYER_LUNARG_device_limits");
info.device_layer_names.push_back("VK_LAYER_LUNARG_image");
info.device_layer_names.push_back("VK_LAYER_LUNARG_swapchain");
info.device_layer_names.push_back("VK_LAYER_GOOGLE_unique_objects");
if (!demo_check_layers(info.device_layer_properties,
info.device_layer_names)) {
exit(1);
}
}
float queue_priorities[1] = { 0.0 };
VkDeviceQueueCreateInfo queue_info = {};
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
NULL);
assert(info.queue_count >= 1);
info.queue_props.resize(info.queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
info.queue_props.data());
assert(info.queue_count >= 1);
bool found = false;
for (unsigned int i = 0; i < info.queue_count; i++) {
if (info.queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
queue_info.queueFamilyIndex = i;
found = true;
break;
}
}
assert(found);
assert(info.queue_count >= 1);
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = queue_priorities;
VkDeviceCreateInfo device_info = {};
device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_info.pNext = NULL;
device_info.queueCreateInfoCount = 1;
device_info.pQueueCreateInfos = &queue_info;
device_info.enabledLayerCount = info.device_layer_names.size();
device_info.ppEnabledLayerNames =
device_info.enabledLayerCount ? info.device_layer_names.data() : NULL;
device_info.enabledExtensionCount = info.device_extension_names.size();
device_info.ppEnabledExtensionNames =
device_info.enabledExtensionCount ? info.device_extension_names.data()
: NULL;
device_info.pEnabledFeatures = NULL;
res = vkCreateDevice(info.gpus[0], &device_info, NULL, &info.device);
assert(res == VK_SUCCESS);
VkDebugReportCallbackEXT debug_report_callback;
info.dbgCreateDebugReportCallback =
(PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkCreateDebugReportCallbackEXT");
if (!info.dbgCreateDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkCreateDebugReportCallbackEXT function." << std::endl;
exit(1);
}
info.dbgDestroyDebugReportCallback =
(PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkDestroyDebugReportCallbackEXT");
if (!info.dbgDestroyDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkDestroyDebugReportCallbackEXT function." << std::endl;
exit(1);
}
VkDebugReportCallbackCreateInfoEXT create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
create_info.pNext = NULL;
create_info.flags =
VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
create_info.pfnCallback = dbgFunc;
create_info.pUserData = NULL;
res = info.dbgCreateDebugReportCallback(info.inst, &create_info, NULL,
&debug_report_callback);
switch (res) {
case VK_SUCCESS:
break;
case VK_ERROR_OUT_OF_HOST_MEMORY:
std::cout << "dbgCreateDebugReportCallback: out of host memory\n"
<< std::endl;
exit(1);
break;
default:
std::cout << "dbgCreateDebugReportCallback: unknown failure\n"
<< std::endl;
exit(1);
break;
}
/* Create a command pool */
VkCommandPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = info.graphics_queue_family_index;
cmd_pool_info.flags = 0;
res =
vkCreateCommandPool(info.device, &cmd_pool_info, NULL, &info.cmd_pool);
assert(res == VK_SUCCESS);
/*
* Destroying the device before destroying the command pool above
* will trigger a validation error.
*/
std::cout << "calling vkDestroyDevice before destroying command pool\n";
std::cout << "this should result in an error\n";
vkDestroyDevice(info.device, NULL);
/* Clean up callback */
info.dbgDestroyDebugReportCallback(info.inst, debug_report_callback, NULL);
/* VULKAN_KEY_END */
vkDestroyInstance(info.inst, NULL);
return 0;
}
|
/*
* Vulkan Samples
*
* Copyright (C) 2015-2016 Valve Corporation
* Copyright (C) 2015-2016 LunarG, 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.
*/
/*
VULKAN_SAMPLE_SHORT_DESCRIPTION
Show how to enable validation layers and provide callback
*/
#include <iostream>
#include <cassert>
#include <cstdlib>
#include <util_init.hpp>
VKAPI_ATTR VkBool32 VKAPI_CALL
dbgFunc(VkDebugReportFlagsEXT msgFlags, VkDebugReportObjectTypeEXT objType,
uint64_t srcObject, size_t location, int32_t msgCode,
const char *pLayerPrefix, const char *pMsg, void *pUserData) {
std::ostringstream message;
if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
message << "ERROR: ";
} else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
message << "WARNING: ";
} else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
message << "PERFORMANCE WARNING: ";
} else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
message << "INFO: ";
} else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
message << "DEBUG: ";
}
message << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg;
std::cout << message.str() << std::endl;
/*
* false indicates that layer should not bail-out of an
* API call that had validation failures. This may mean that the
* app dies inside the driver due to invalid parameter(s).
* That's what would happen without validation layers, so we'll
* keep that behavior here.
*/
return false;
}
int sample_main(int argc, char *argv[]) {
struct sample_info info = {};
init_global_layer_properties(info);
/* VULKAN_KEY_START */
/* Use standard_validation meta layer that enables all
* recommended validation layers
*/
info.instance_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
if (!demo_check_layers(info.instance_layer_properties,
info.instance_layer_names)) {
/* If standard validation is not present, search instead for the
* individual layers that make it up, in the correct order.
*/
info.instance_layer_names.clear();
info.instance_layer_names.push_back("VK_LAYER_GOOGLE_threading");
info.instance_layer_names.push_back(
"VK_LAYER_LUNARG_parameter_validation");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_object_tracker");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_core_validation");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_device_limits");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_image");
info.instance_layer_names.push_back("VK_LAYER_LUNARG_swapchain");
info.instance_layer_names.push_back("VK_LAYER_GOOGLE_unique_objects");
if (!demo_check_layers(info.instance_layer_properties,
info.instance_layer_names)) {
exit(1);
}
}
/* Enable debug callback extension */
info.instance_extension_names.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = NULL;
app_info.pApplicationName = "vulkansamples_enable_validation_with_callback";
app_info.applicationVersion = 1;
app_info.pEngineName = "Vulkan Samples";
app_info.engineVersion = 1;
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo inst_info = {};
inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
inst_info.pNext = NULL;
inst_info.flags = 0;
inst_info.pApplicationInfo = &app_info;
inst_info.enabledLayerCount = info.instance_layer_names.size();
inst_info.ppEnabledLayerNames = info.instance_layer_names.size()
? info.instance_layer_names.data()
: NULL;
inst_info.enabledExtensionCount = info.instance_extension_names.size();
inst_info.ppEnabledExtensionNames = info.instance_extension_names.data();
VkResult res = vkCreateInstance(&inst_info, NULL, &info.inst);
assert(res == VK_SUCCESS);
init_enumerate_device(info);
init_device_layer_properties(info);
/* Use standard_validation meta layer that enables all
* recommended validation layers
* Instance layers and Device layers are independent so
* must enable validation layers for both to see everything.
*/
info.device_layer_names.push_back("VK_LAYER_LUNARG_standard_validation");
if (!demo_check_layers(info.device_layer_properties,
info.device_layer_names)) {
/* If standard validation is not present, search instead for the
* individual layers that make it up, in the correct order.
*/
info.device_layer_names.clear();
info.device_layer_names.push_back("VK_LAYER_GOOGLE_threading");
info.device_layer_names.push_back(
"VK_LAYER_LUNARG_parameter_validation");
info.device_layer_names.push_back("VK_LAYER_LUNARG_object_tracker");
info.device_layer_names.push_back("VK_LAYER_LUNARG_core_validation");
info.device_layer_names.push_back("VK_LAYER_LUNARG_device_limits");
info.device_layer_names.push_back("VK_LAYER_LUNARG_image");
info.device_layer_names.push_back("VK_LAYER_LUNARG_swapchain");
info.device_layer_names.push_back("VK_LAYER_GOOGLE_unique_objects");
if (!demo_check_layers(info.device_layer_properties,
info.device_layer_names)) {
exit(1);
}
}
float queue_priorities[1] = { 0.0 };
VkDeviceQueueCreateInfo queue_info = {};
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
NULL);
assert(info.queue_count >= 1);
info.queue_props.resize(info.queue_count);
vkGetPhysicalDeviceQueueFamilyProperties(info.gpus[0], &info.queue_count,
info.queue_props.data());
assert(info.queue_count >= 1);
bool found = false;
for (unsigned int i = 0; i < info.queue_count; i++) {
if (info.queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
queue_info.queueFamilyIndex = i;
found = true;
break;
}
}
assert(found);
assert(info.queue_count >= 1);
queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_info.pNext = NULL;
queue_info.queueCount = 1;
queue_info.pQueuePriorities = queue_priorities;
VkDeviceCreateInfo device_info = {};
device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
device_info.pNext = NULL;
device_info.queueCreateInfoCount = 1;
device_info.pQueueCreateInfos = &queue_info;
device_info.enabledLayerCount = info.device_layer_names.size();
device_info.ppEnabledLayerNames =
device_info.enabledLayerCount ? info.device_layer_names.data() : NULL;
device_info.enabledExtensionCount = info.device_extension_names.size();
device_info.ppEnabledExtensionNames =
device_info.enabledExtensionCount ? info.device_extension_names.data()
: NULL;
device_info.pEnabledFeatures = NULL;
res = vkCreateDevice(info.gpus[0], &device_info, NULL, &info.device);
assert(res == VK_SUCCESS);
VkDebugReportCallbackEXT debug_report_callback;
info.dbgCreateDebugReportCallback =
(PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkCreateDebugReportCallbackEXT");
if (!info.dbgCreateDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkCreateDebugReportCallbackEXT function." << std::endl;
exit(1);
}
info.dbgDestroyDebugReportCallback =
(PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
info.inst, "vkDestroyDebugReportCallbackEXT");
if (!info.dbgDestroyDebugReportCallback) {
std::cout << "GetInstanceProcAddr: Unable to find "
"vkDestroyDebugReportCallbackEXT function." << std::endl;
exit(1);
}
VkDebugReportCallbackCreateInfoEXT create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
create_info.pNext = NULL;
create_info.flags =
VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
create_info.pfnCallback = dbgFunc;
create_info.pUserData = NULL;
res = info.dbgCreateDebugReportCallback(info.inst, &create_info, NULL,
&debug_report_callback);
switch (res) {
case VK_SUCCESS:
break;
case VK_ERROR_OUT_OF_HOST_MEMORY:
std::cout << "dbgCreateDebugReportCallback: out of host memory\n"
<< std::endl;
exit(1);
break;
default:
std::cout << "dbgCreateDebugReportCallback: unknown failure\n"
<< std::endl;
exit(1);
break;
}
/* Create a command pool */
VkCommandPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = info.graphics_queue_family_index;
cmd_pool_info.flags = 0;
res =
vkCreateCommandPool(info.device, &cmd_pool_info, NULL, &info.cmd_pool);
assert(res == VK_SUCCESS);
/*
* Destroying the device before destroying the command pool above
* will trigger a validation error.
*/
std::cout << "calling vkDestroyDevice before destroying command pool\n";
std::cout << "this should result in an error\n";
vkDestroyDevice(info.device, NULL);
/* Clean up callback */
info.dbgDestroyDebugReportCallback(info.inst, debug_report_callback, NULL);
/* VULKAN_KEY_END */
vkDestroyInstance(info.inst, NULL);
return 0;
}
|
Disable message popups
|
samples: Disable message popups
|
C++
|
apache-2.0
|
Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples
|
1ecff85fdebf59a9ab9d372ff6b8101e607e8cb6
|
Source/qigroups.cpp
|
Source/qigroups.cpp
|
/*
* qigroups.cpp
*
* Copyright (c) 2016 Tobias Wood.
*
* 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/.
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include "itkTileImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkDivideImageFilter.h"
#include "Filters/MeanImageFilter.h"
#include "QI/Types.h"
#include "QI/Util.h"
#include "QI/Option.h"
const std::string usage{
"Usage is: qigroups [options] output_file\n\
\n\
A utility for setting up merged 4D files for use with FSL randomise etc.\n\
The list of files to be merged is read from stdin, one per line.\n\
A list of groups must be passed in with the --groups option. This\n\
file should contain a single number per line, indicating the group each\n\
matching line of stdin corresponds to. Group 0 is ignore.\n"
};
int main(int argc, char **argv) {
Eigen::initParallel();
QI::OptionList opts(usage);
QI::Switch sort('s',"sort","Sort merged file (and design matrix) in ascending group order", opts);
QI::Switch pdiffs('F',"fracdiffs","Output fractional group mean diffs", opts);
QI::Switch diffs('D',"diffs","Output group mean diffs", opts);
QI::Switch means('m',"means","Output group means", opts);
QI::Option<std::string> covars_path("",'C',"covars","Path to covariates file (added to design matrix)", opts);
QI::Option<std::string> ftests_path("",'f',"ftests","Generate and save F-tests", opts);
QI::Option<std::string> contrasts_path("",'c',"contrasts","Generate and save contrasts", opts);
QI::Option<std::string> design_path("",'d',"design","Path to save design matrix", opts);
QI::Option<std::string> output_path("",'o',"out","Path for output merged file", opts);
QI::Option<std::string> group_path("",'g',"groups","File to read group numbers from", opts);
QI::Switch verbose('v',"verbose","Print more information", opts);
QI::Help help(opts);
std::vector<std::string> file_paths = opts.parse(argc, argv);
if (!group_path.set()) {
std::cerr << opts << std::endl;
std::cerr << "Group file must be set with --groups option" << std::endl;
return EXIT_FAILURE;
}
std::ifstream group_file(*group_path);
if (!group_file) {
std::cerr << "Group file: " << *group_path << " does not exist" << std::endl;
return EXIT_FAILURE;
}
if (*verbose) std::cout << "Reading group file" << std::endl;
std::vector<int> group_list;
int temp;
while (group_file >> temp) {
group_list.push_back(temp);
}
int n_groups = *std::max_element(group_list.begin(), group_list.end());
int n_images = std::count_if(group_list.begin(), group_list.end(), [](int i){return i > 0;}); // Count non-zero elements
if (file_paths.size() != group_list.size()) {
std::cerr << "Group list size and number of files do not match." << std::endl;
return EXIT_FAILURE;
}
std::vector<std::vector<QI::VolumeF::Pointer>> groups(n_groups);
if (*verbose) std::cout << "Number of groups: " << n_groups << std::endl;
if (*verbose) std::cout << "Number of images: " << n_images << std::endl;
itk::FixedArray<unsigned int, 4> layout;
layout[0] = layout[1] = layout[2] = 1;
layout[3] = n_images;
auto tiler = itk::TileImageFilter<QI::VolumeF, QI::SeriesF>::New();
tiler->SetLayout(layout);
std::ofstream design_file;
if (design_path.set()) {
if (*verbose) std::cout << "Design matrix will be saved to: " << *design_path << std::endl;
design_file = std::ofstream(*design_path);
}
std::vector<std::vector<std::vector<double>>> covars(n_groups);
std::ifstream covars_file;
if (covars_path.set()) {
covars_file = std::ifstream(*covars_path);
}
int out_index = 0;
for (int i = 0; i < group_list.size(); i++) {
const int group = group_list.at(i);
if (group > 0) { // Ignore entries with a 0
if (*verbose) std::cout << "File: " << file_paths.at(i) << " Group: " << group << std::flush;
QI::VolumeF::Pointer ptr = QI::ReadImage(file_paths.at(i));
groups.at(group - 1).push_back(ptr);
std::vector<double> covar;
if (covars_path.set()) {
std::string covar_line;
std::getline(covars_file, covar_line);
std::stringstream css(covar_line);
double c;
while (css >> c) {
covar.push_back(c);
}
covars.at(group - 1).push_back(covar);
if (*verbose) std::cout << ", read covariates.";
}
if (*verbose) std::cout << std::endl;
if (!*sort) {
tiler->SetInput(out_index, ptr);
out_index++;
if (design_path.set()) {
for (int g = 1; g <= n_groups; g++) {
if (g == group) {
design_file << "1\t";
} else {
design_file << "0\t";
}
}
if (covars_path.set()) {
for (auto& c : covar) {
design_file << c << "\t";
}
}
design_file << std::endl;
}
}
} else {
if (*verbose) std::cout << "Ignoring file: " << file_paths.at(i) << std::endl;
}
}
if (*sort) {
if (*verbose) std::cout << "Sorting." << std::endl;
for (int g = 0; g < n_groups; g++) {
for (int i = 0; i < groups.at(g).size(); i++) {
tiler->SetInput(out_index, groups.at(g).at(i));
out_index++;
if (design_path.set()) {
for (int g2 = 0; g2 < n_groups; g2++) {
if (g2 == g) {
design_file << "1\t";
} else {
design_file << "0\t";
}
}
if (covars_path.set()) {
for (auto& c : covars.at(g).at(i)) {
design_file << c << "\t";
}
}
design_file << std::endl;
}
}
}
}
int n_covars = covars_path.set() ? covars.front().front().size() : 0;
if (contrasts_path.set()) {
if (*verbose) std::cout << "Generating contrasts" << std::endl;
std::ofstream con_file(*contrasts_path);
for (int g = 0; g < n_groups; g++) {
for (int g2 = 0; g2 < n_groups; g2++) {
if (g2 == g) {
con_file << "1\t";
} else if (g2 == ((g+1) % (n_groups))) {
con_file << "-1\t";
} else {
con_file << "0\t";
}
}
for (int c = 0; c < n_covars; c++) {
con_file << "0\t";
}
con_file << std::endl;
}
for (int c = 0; c < 2*n_covars; c++) {
for (int g = 0; g < n_groups; g++) {
con_file << "0\t";
}
for (int c2 = 0; c2 < n_covars; c2++) {
if ((c/2) == c2) {
con_file << ((c % 2 == 0) ? "1\t" : "-1\t");
} else {
con_file << "0\t";
}
}
con_file << std::endl;
}
}
if (ftests_path.set()) {
if (*verbose) std::cout << "Generating F-tests" << std::endl;
std::ofstream fts_file(*ftests_path);
if (n_groups > 2) { // Main effect of model
for (int g = 0; g < (n_groups - 1); g++) {
fts_file << "1\t";
}
fts_file << "0\t";
for (int c = 0; c < 2*n_covars; c++) {
fts_file << "0\t";
}
fts_file << std::endl;
}
for (int g = 0; g < n_groups; g++) { // Individual group comparisons
for (int g2 = 0; g2 < n_groups; g2++) {
fts_file << ((g2 == g) ? "1\t" : "0\t");
}
for (int c = 0; c < 2*n_covars; c++) {
fts_file << "0\t";
}
fts_file << std::endl;
}
}
if (*means | *diffs | *pdiffs) {
std::vector<QI::VolumeF::Pointer> mean_imgs(n_groups, ITK_NULLPTR);
for (int g = 0; g < n_groups; g++) {
auto mean = itk::MeanImageFilter<QI::VolumeF>::New();
for (int i = 0; i < groups.at(g).size(); i++) {
mean->SetInput(i, groups.at(g).at(i));
}
mean->Update();
mean_imgs.at(g) = mean->GetOutput();
mean_imgs.at(g)->DisconnectPipeline();
if (*means) {
if (*verbose) std::cout << "Writing mean " << std::to_string(g+1) << std::endl;
QI::WriteImage(mean_imgs.at(g), QI::StripExt(*output_path) + "_mean" + std::to_string(g+1) + ".nii");
}
if ((*diffs || *pdiffs) && g > 0) {
auto diff = itk::SubtractImageFilter<QI::VolumeF, QI::VolumeF>::New();
diff->SetInput1(mean_imgs.at(g));
for (int g2 = 0; g2 < g; g2++) {
diff->SetInput2(mean_imgs.at(g2));
diff->Update();
if (*diffs) {
if (*verbose) std::cout << "Writing difference " << std::to_string(g+1) << " - " << std::to_string(g2+1) << std::endl;
QI::WriteImage(diff->GetOutput(), QI::StripExt(*output_path) + "_diff" + std::to_string(g+1) + "_" + std::to_string(g2+1) + ".nii");
}
if (*pdiffs) {
auto frac = itk::DivideImageFilter<QI::VolumeF, QI::VolumeF, QI::VolumeF>::New();
frac->SetInput1(diff->GetOutput());
frac->SetInput2(mean_imgs.at(g));
frac->Update();
if (*verbose) std::cout << "Writing fractional difference " << std::to_string(g+1) << " - " << std::to_string(g2+1) << std::endl;
QI::WriteImage(frac->GetOutput(), QI::StripExt(*output_path) + "_fdiff" + std::to_string(g+1) + "_" + std::to_string(g2 + 1) + ".nii");
}
}
}
}
}
if (*verbose) std::cout << "Writing merged file: " << *output_path << std::endl;
tiler->UpdateLargestPossibleRegion();
QI::WriteImage<QI::SeriesF>(tiler->GetOutput(), *output_path);
return EXIT_SUCCESS;
}
|
/*
* qigroups.cpp
*
* Copyright (c) 2016 Tobias Wood.
*
* 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/.
*
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include "itkTileImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkDivideImageFilter.h"
#include "Filters/MeanImageFilter.h"
#include "QI/Types.h"
#include "QI/Util.h"
#include "QI/Option.h"
const std::string usage{
"Usage is: qigroups [options] output_file\n\
\n\
A utility for setting up merged 4D files for use with FSL randomise etc.\n\
The list of files to be merged is read from stdin, one per line.\n\
A list of groups must be passed in with the --groups option. This\n\
file should contain a single number per line, indicating the group each\n\
matching line of stdin corresponds to. Group 0 is ignore.\n"
};
int main(int argc, char **argv) {
Eigen::initParallel();
QI::OptionList opts(usage);
QI::Switch sort('s',"sort","Sort merged file (and design matrix) in ascending group order", opts);
QI::Switch pdiffs('F',"fracdiffs","Output fractional group mean diffs", opts);
QI::Switch diffs('D',"diffs","Output group mean diffs", opts);
QI::Switch means('m',"means","Output group means", opts);
QI::Option<std::string> covars_path("",'C',"covars","Path to covariates file (added to design matrix)", opts);
QI::Option<std::string> ftests_path("",'f',"ftests","Generate and save F-tests", opts);
QI::Option<std::string> contrasts_path("",'c',"contrasts","Generate and save contrasts", opts);
QI::Option<std::string> design_path("",'d',"design","Path to save design matrix", opts);
QI::Option<std::string> output_path("",'o',"out","Path for output merged file", opts);
QI::Option<std::string> group_path("",'g',"groups","File to read group numbers from", opts);
QI::Switch verbose('v',"verbose","Print more information", opts);
QI::Help help(opts);
std::vector<std::string> file_paths = opts.parse(argc, argv);
if (!group_path.set()) {
std::cerr << opts << std::endl;
std::cerr << "Group file must be set with --groups option" << std::endl;
return EXIT_FAILURE;
}
std::ifstream group_file(*group_path);
if (!group_file) {
std::cerr << "Group file: " << *group_path << " does not exist" << std::endl;
return EXIT_FAILURE;
}
if (*verbose) std::cout << "Reading group file" << std::endl;
std::vector<int> group_list;
int temp;
while (group_file >> temp) {
group_list.push_back(temp);
}
int n_groups = *std::max_element(group_list.begin(), group_list.end());
int n_images = std::count_if(group_list.begin(), group_list.end(), [](int i){return i > 0;}); // Count non-zero elements
if (file_paths.size() != group_list.size()) {
std::cerr << "Group list size and number of files do not match." << std::endl;
return EXIT_FAILURE;
}
std::vector<std::vector<QI::VolumeF::Pointer>> groups(n_groups);
if (*verbose) std::cout << "Number of groups: " << n_groups << std::endl;
if (*verbose) std::cout << "Number of images: " << n_images << std::endl;
itk::FixedArray<unsigned int, 4> layout;
layout[0] = layout[1] = layout[2] = 1;
layout[3] = n_images;
auto tiler = itk::TileImageFilter<QI::VolumeF, QI::SeriesF>::New();
tiler->SetLayout(layout);
std::ofstream design_file;
if (design_path.set()) {
if (*verbose) std::cout << "Design matrix will be saved to: " << *design_path << std::endl;
design_file = std::ofstream(*design_path);
}
std::vector<std::vector<std::vector<double>>> covars(n_groups);
std::ifstream covars_file;
if (covars_path.set()) {
covars_file = std::ifstream(*covars_path);
}
int out_index = 0;
for (int i = 0; i < group_list.size(); i++) {
const int group = group_list.at(i);
if (group > 0) { // Ignore entries with a 0
if (*verbose) std::cout << "File: " << file_paths.at(i) << " Group: " << group << std::flush;
QI::VolumeF::Pointer ptr = QI::ReadImage(file_paths.at(i));
groups.at(group - 1).push_back(ptr);
std::vector<double> covar;
if (covars_path.set()) {
std::string covar_line;
std::getline(covars_file, covar_line);
std::stringstream css(covar_line);
double c;
while (css >> c) {
covar.push_back(c);
}
covars.at(group - 1).push_back(covar);
if (*verbose) std::cout << ", read covariates.";
}
if (*verbose) std::cout << std::endl;
if (!*sort) {
tiler->SetInput(out_index, ptr);
out_index++;
if (design_path.set()) {
for (int g = 1; g <= n_groups; g++) {
if (g == group) {
design_file << "1\t";
} else {
design_file << "0\t";
}
}
if (covars_path.set()) {
for (auto& c : covar) {
design_file << c << "\t";
}
}
design_file << std::endl;
}
}
} else {
if (*verbose) std::cout << "Ignoring file: " << file_paths.at(i) << std::endl;
}
}
if (*sort) {
if (*verbose) std::cout << "Sorting." << std::endl;
for (int g = 0; g < n_groups; g++) {
for (int i = 0; i < groups.at(g).size(); i++) {
tiler->SetInput(out_index, groups.at(g).at(i));
out_index++;
if (design_path.set()) {
for (int g2 = 0; g2 < n_groups; g2++) {
if (g2 == g) {
design_file << "1\t";
} else {
design_file << "0\t";
}
}
if (covars_path.set()) {
for (auto& c : covars.at(g).at(i)) {
design_file << c << "\t";
}
}
design_file << std::endl;
}
}
}
}
int n_covars = covars_path.set() ? covars.front().front().size() : 0;
if (contrasts_path.set()) {
if (*verbose) std::cout << "Generating contrasts" << std::endl;
std::ofstream con_file(*contrasts_path);
for (int g = 0; g < n_groups; g++) {
for (int g2 = 0; g2 < n_groups; g2++) {
if (g2 == g) {
con_file << "1\t";
} else if (g2 == ((g+1) % (n_groups))) {
con_file << "-1\t";
} else {
con_file << "0\t";
}
}
for (int c = 0; c < n_covars; c++) {
con_file << "0\t";
}
con_file << std::endl;
}
for (int c = 0; c < 2*n_covars; c++) {
for (int g = 0; g < n_groups; g++) {
con_file << "0\t";
}
for (int c2 = 0; c2 < n_covars; c2++) {
if ((c/2) == c2) {
con_file << ((c % 2 == 0) ? "1\t" : "-1\t");
} else {
con_file << "0\t";
}
}
con_file << std::endl;
}
}
if (ftests_path.set()) {
if (*verbose) std::cout << "Generating F-tests" << std::endl;
std::ofstream fts_file(*ftests_path);
for (int g = 0; g < n_groups; g++) { // Individual group comparisons
for (int g2 = 0; g2 < n_groups; g2++) {
fts_file << ((g2 == g) ? "1\t" : "0\t");
}
for (int c = 0; c < 2*n_covars; c++) {
fts_file << "0\t";
}
fts_file << std::endl;
}
if (n_groups > 2) { // Main effect
for (int g = 0; g < (n_groups - 1); g++) {
fts_file << "1\t";
}
fts_file << "0\t";
for (int c = 0; c < 2*n_covars; c++) {
fts_file << "0\t";
}
fts_file << std::endl;
}
}
if (*means | *diffs | *pdiffs) {
std::vector<QI::VolumeF::Pointer> mean_imgs(n_groups, ITK_NULLPTR);
for (int g = 0; g < n_groups; g++) {
auto mean = itk::MeanImageFilter<QI::VolumeF>::New();
for (int i = 0; i < groups.at(g).size(); i++) {
mean->SetInput(i, groups.at(g).at(i));
}
mean->Update();
mean_imgs.at(g) = mean->GetOutput();
mean_imgs.at(g)->DisconnectPipeline();
if (*means) {
if (*verbose) std::cout << "Writing mean " << std::to_string(g+1) << std::endl;
QI::WriteImage(mean_imgs.at(g), QI::StripExt(*output_path) + "_mean" + std::to_string(g+1) + ".nii");
}
if ((*diffs || *pdiffs) && g > 0) {
auto diff = itk::SubtractImageFilter<QI::VolumeF, QI::VolumeF>::New();
diff->SetInput1(mean_imgs.at(g));
for (int g2 = 0; g2 < g; g2++) {
diff->SetInput2(mean_imgs.at(g2));
diff->Update();
if (*diffs) {
if (*verbose) std::cout << "Writing difference " << std::to_string(g+1) << " - " << std::to_string(g2+1) << std::endl;
QI::WriteImage(diff->GetOutput(), QI::StripExt(*output_path) + "_diff" + std::to_string(g+1) + "_" + std::to_string(g2+1) + ".nii");
}
if (*pdiffs) {
auto frac = itk::DivideImageFilter<QI::VolumeF, QI::VolumeF, QI::VolumeF>::New();
frac->SetInput1(diff->GetOutput());
frac->SetInput2(mean_imgs.at(g));
frac->Update();
if (*verbose) std::cout << "Writing fractional difference " << std::to_string(g+1) << " - " << std::to_string(g2+1) << std::endl;
QI::WriteImage(frac->GetOutput(), QI::StripExt(*output_path) + "_fdiff" + std::to_string(g+1) + "_" + std::to_string(g2 + 1) + ".nii");
}
}
}
}
}
if (*verbose) std::cout << "Writing merged file: " << *output_path << std::endl;
tiler->UpdateLargestPossibleRegion();
QI::WriteImage<QI::SeriesF>(tiler->GetOutput(), *output_path);
return EXIT_SUCCESS;
}
|
Put group F-Tests first so T & F stats match
|
BUG: Put group F-Tests first so T & F stats match
|
C++
|
mpl-2.0
|
spinicist/QUIT,spinicist/QUIT,spinicist/QUIT,spinicist/QUIT
|
85aef798095ea6b0c9d44e659e15a24b041fea2b
|
src/ee/ads/internal/AsyncHelper.inl
|
src/ee/ads/internal/AsyncHelper.inl
|
#include <ee/coroutine/LambdaAwaiter.hpp>
#include <ee/coroutine/Task.hpp>
namespace ee {
namespace ads {
#define Self AsyncHelper
template <class T>
bool Self<T>::isProcessing() const {
return processing_;
}
template <class T>
Task<T> Self<T>::process(const Processor& processor) {
if (processing_) {
// Waiting.
} else {
awaiter_ = std::make_unique<LambdaAwaiter<T>>(
[this, processor](auto&& resolve) {
processing_ = true;
resolve_ = [this, resolve](T result) {
processing_ = false;
awaiter_.reset();
resolve_ = nullptr;
resolve(result);
};
processor();
});
}
auto result = co_await(*awaiter_);
co_return result;
}
template <class T>
void Self<T>::resolve(T result) {
resolve_(result);
}
#undef Self
} // namespace ads
} // namespace ee
|
#include <ee/coroutine/LambdaAwaiter.hpp>
#include <ee/coroutine/Task.hpp>
namespace ee {
namespace ads {
#define Self AsyncHelper
template <class T>
bool Self<T>::isProcessing() const {
return processing_;
}
template <class T>
Task<T> Self<T>::process(const Processor& processor) {
if (processing_) {
// Waiting.
} else {
awaiter_ = std::make_unique<LambdaAwaiter<T>>(
[this, processor](auto&& resolve) {
processing_ = true;
resolve_ = [this, resolve](T result) {
resolve(result);
resolve_ = nullptr;
awaiter_.reset();
processing_ = false;
};
processor();
});
}
auto result = co_await(*awaiter_);
co_return result;
}
template <class T>
void Self<T>::resolve(T result) {
resolve_(result);
}
#undef Self
} // namespace ads
} // namespace ee
|
Fix sanitizer.
|
Fix sanitizer.
|
C++
|
mit
|
Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x,Senspark/ee-x
|
71feb0516d6b98ae346d8c9659aee76a78c3a437
|
src/entt/graph/adjacency_matrix.hpp
|
src/entt/graph/adjacency_matrix.hpp
|
#ifndef ENTT_GRAPH_ADJACENCY_MATRIX_HPP
#define ENTT_GRAPH_ADJACENCY_MATRIX_HPP
#include <cstddef>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/iterator.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename It>
class edge_iterator {
using size_type = std::size_t;
public:
using value_type = std::pair<size_type, size_type>;
using pointer = input_iterator_pointer<value_type>;
using reference = value_type;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
constexpr edge_iterator() noexcept
: it{},
vert{},
pos{},
last{},
offset{} {}
constexpr edge_iterator(It base, const size_type vertices, const size_type from, const size_type to, const size_type step) noexcept
: it{std::move(base)},
vert{vertices},
pos{from},
last{to},
offset{step} {
for(; pos != last && !it[pos]; pos += offset) {}
}
constexpr edge_iterator &operator++() noexcept {
for(pos += offset; pos != last && !it[pos]; pos += offset) {}
return *this;
}
constexpr edge_iterator operator++(int) noexcept {
edge_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] constexpr reference operator*() const noexcept {
return *operator->();
}
[[nodiscard]] constexpr pointer operator->() const noexcept {
return std::make_pair<size_type>(pos / vert, pos % vert);
}
template<typename Type>
friend constexpr bool operator==(const edge_iterator<Type> &, const edge_iterator<Type> &) noexcept;
private:
It it;
size_type vert;
size_type pos;
size_type last;
size_type offset{};
};
template<typename Container>
[[nodiscard]] inline constexpr bool operator==(const edge_iterator<Container> &lhs, const edge_iterator<Container> &rhs) noexcept {
return lhs.pos == rhs.pos;
}
template<typename Container>
[[nodiscard]] inline constexpr bool operator!=(const edge_iterator<Container> &lhs, const edge_iterator<Container> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace internal
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Basic implementation of a directed adjacency matrix.
* @tparam Category Either a directed or undirected category tag.
* @tparam Allocator Type of allocator used to manage memory and elements.
*/
template<typename Category, typename Allocator>
class adjacency_matrix {
using alloc_traits = std::allocator_traits<Allocator>;
static_assert(std::is_base_of_v<directed_tag, Category>, "Invalid graph category");
static_assert(std::is_same_v<typename alloc_traits::value_type, std::size_t>, "Invalid value type");
using container_type = std::vector<std::size_t, typename alloc_traits::template rebind_alloc<std::size_t>>;
public:
/*! @brief Allocator type. */
using allocator_type = Allocator;
/*! @brief Unsigned integer type. */
using size_type = std::size_t;
/*! @brief Vertex type. */
using vertex_type = size_type;
/*! @brief Edge type. */
using edge_type = std::pair<vertex_type, vertex_type>;
/*! @brief Vertex iterator type. */
using vertex_iterator = iota_iterator<vertex_type>;
/*! @brief Edge iterator type. */
using edge_iterator = internal::edge_iterator<typename container_type::const_iterator>;
/*! @brief Out edge iterator type. */
using out_edge_iterator = edge_iterator;
/*! @brief In edge iterator type. */
using in_edge_iterator = edge_iterator;
/*! @brief Graph category tag. */
using graph_category = Category;
/*! @brief Default constructor. */
adjacency_matrix() noexcept(noexcept(allocator_type{}))
: adjacency_matrix{0u} {}
/**
* @brief Constructs an empty container with a given allocator.
* @param allocator The allocator to use.
*/
explicit adjacency_matrix(const allocator_type &allocator) noexcept
: adjacency_matrix{0u, allocator} {}
/**
* @brief Constructs an empty container with a given allocator and user
* supplied number of vertices.
* @param vertices Number of vertices.
* @param allocator The allocator to use.
*/
adjacency_matrix(const size_type vertices, const allocator_type &allocator = allocator_type{})
: matrix(vertices * vertices),
vert{vertices} {}
/**
* @brief Copy constructor.
* @param other The instance to copy from.
*/
adjacency_matrix(const adjacency_matrix &other)
: adjacency_matrix{other, other.get_allocator()} {}
/**
* @brief Allocator-extended copy constructor.
* @param other The instance to copy from.
* @param allocator The allocator to use.
*/
adjacency_matrix(const adjacency_matrix &other, const allocator_type &allocator)
: matrix{other.matrix, allocator},
vert{other.vert} {}
/**
* @brief Move constructor.
* @param other The instance to move from.
*/
adjacency_matrix(adjacency_matrix &&other) noexcept
: adjacency_matrix{std::move(other), other.get_allocator()} {}
/**
* @brief Allocator-extended move constructor.
* @param other The instance to move from.
* @param allocator The allocator to use.
*/
adjacency_matrix(adjacency_matrix &&other, const allocator_type &allocator)
: matrix{std::move(other.matrix), allocator},
vert{std::exchange(other.vert, 0u)} {}
/**
* @brief Default copy assignment operator.
* @param other The instance to copy from.
* @return This container.
*/
adjacency_matrix &operator=(const adjacency_matrix &other) {
matrix = other.matrix;
vert = other.vert;
return *this;
}
/**
* @brief Default move assignment operator.
* @param other The instance to move from.
* @return This container.
*/
adjacency_matrix &operator=(adjacency_matrix &&other) noexcept {
matrix = std::move(other.matrix);
vert = std::exchange(other.vert, 0u);
return *this;
}
/**
* @brief Returns the associated allocator.
* @return The associated allocator.
*/
[[nodiscard]] constexpr allocator_type get_allocator() const noexcept {
return matrix.get_allocator();
}
/*! @brief Clears the adjacency matrix. */
void clear() noexcept {
matrix.clear();
vert = {};
}
/**
* @brief Exchanges the contents with those of a given adjacency matrix.
* @param other Adjacency matrix to exchange the content with.
*/
void swap(adjacency_matrix &other) {
using std::swap;
swap(matrix, other.matrix);
swap(vert, other.vert);
}
/**
* @brief Returns the number of vertices.
* @return The number of vertices.
*/
[[nodiscard]] size_type size() const noexcept {
return vert;
}
/**
* @brief Returns an iterable object to visit all vertices of a matrix.
* @return An iterable object to visit all vertices of a matrix.
*/
[[nodiscard]] iterable_adaptor<vertex_iterator> vertices() const noexcept {
return {0u, vert};
}
/**
* @brief Returns an iterable object to visit all edges of a matrix.
* @return An iterable object to visit all edges of a matrix.
*/
[[nodiscard]] iterable_adaptor<edge_iterator> edges() const noexcept {
const auto it = matrix.cbegin();
const auto sz = matrix.size();
return {{it, vert, 0u, sz, 1u}, {it, vert, sz, sz, 1u}};
}
/**
* @brief Returns an iterable object to visit all out edges of a vertex.
* @param vertex The vertex of which to return all out edges.
* @return An iterable object to visit all out edges of a vertex.
*/
[[nodiscard]] iterable_adaptor<out_edge_iterator> out_edges(const vertex_type vertex) const noexcept {
const auto it = matrix.cbegin();
const auto from = vertex * vert;
const auto to = vertex * vert + vert;
return {{it, vert, from, to, 1u}, {it, vert, to, to, 1u}};
}
/**
* @brief Returns an iterable object to visit all in edges of a vertex.
* @param vertex The vertex of which to return all in edges.
* @return An iterable object to visit all in edges of a vertex.
*/
[[nodiscard]] iterable_adaptor<in_edge_iterator> in_edges(const vertex_type vertex) const noexcept {
const auto it = matrix.cbegin();
const auto from = vertex;
const auto to = vert * (vert - 1u) + vertex;
return {{it, vert, from, to, vert}, {it, vert, to, to, vert}};
}
/**
* @brief Resizes an adjacency matrix.
* @param vertices The new number of vertices.
*/
void resize(const size_type vertices) {
adjacency_matrix other{vertices, get_allocator()};
for(auto [lhs, rhs]: edges()) {
other.insert(lhs, rhs);
}
other.swap(*this);
}
/**
* @brief Inserts an edge into the adjacency matrix, if it does not exist.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return A pair consisting of an iterator to the inserted element (or to
* the element that prevented the insertion) and a bool denoting whether the
* insertion took place.
*/
std::pair<edge_iterator, bool> insert(const vertex_type lhs, const vertex_type rhs) {
const auto pos = lhs * vert + rhs;
if constexpr(std::is_same_v<graph_category, undirected_tag>) {
const auto rev = rhs * vert + lhs;
ENTT_ASSERT(matrix[pos] == matrix[rev], "Something went really wrong");
matrix[rev] = 1u;
}
const auto inserted = !std::exchange(matrix[pos], 1u);
return {edge_iterator{matrix.cbegin(), vert, pos, matrix.size(), 1u}, inserted};
}
/**
* @brief Removes the edge associated with a pair of given vertices.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return Number of elements removed (either 0 or 1).
*/
size_type erase(const vertex_type lhs, const vertex_type rhs) {
const auto pos = lhs * vert + rhs;
if constexpr(std::is_same_v<graph_category, undirected_tag>) {
const auto rev = rhs * vert + lhs;
ENTT_ASSERT(matrix[pos] == matrix[rev], "Something went really wrong");
matrix[rev] = 0u;
}
return std::exchange(matrix[pos], 0u);
}
/**
* @brief Checks if an adjacency matrix contains a given edge.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return True if there is such an edge, false otherwise.
*/
[[nodiscard]] bool contains(const vertex_type lhs, const vertex_type rhs) const {
const auto pos = lhs * vert + rhs;
return pos < matrix.size() && matrix[pos];
}
private:
container_type matrix;
size_type vert;
};
} // namespace entt
#endif
|
#ifndef ENTT_GRAPH_ADJACENCY_MATRIX_HPP
#define ENTT_GRAPH_ADJACENCY_MATRIX_HPP
#include <cstddef>
#include <iterator>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/iterator.hpp"
#include "fwd.hpp"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename It>
class edge_iterator {
using size_type = std::size_t;
public:
using value_type = std::pair<size_type, size_type>;
using pointer = input_iterator_pointer<value_type>;
using reference = value_type;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
constexpr edge_iterator() noexcept
: it{},
vert{},
pos{},
last{},
offset{} {}
constexpr edge_iterator(It base, const size_type vertices, const size_type from, const size_type to, const size_type step) noexcept
: it{std::move(base)},
vert{vertices},
pos{from},
last{to},
offset{step} {
for(; pos != last && !it[pos]; pos += offset) {}
}
constexpr edge_iterator &operator++() noexcept {
for(pos += offset; pos != last && !it[pos]; pos += offset) {}
return *this;
}
constexpr edge_iterator operator++(int) noexcept {
edge_iterator orig = *this;
return ++(*this), orig;
}
[[nodiscard]] constexpr reference operator*() const noexcept {
return *operator->();
}
[[nodiscard]] constexpr pointer operator->() const noexcept {
return std::make_pair<size_type>(pos / vert, pos % vert);
}
template<typename Type>
friend constexpr bool operator==(const edge_iterator<Type> &, const edge_iterator<Type> &) noexcept;
private:
It it;
size_type vert;
size_type pos;
size_type last;
size_type offset{};
};
template<typename Container>
[[nodiscard]] inline constexpr bool operator==(const edge_iterator<Container> &lhs, const edge_iterator<Container> &rhs) noexcept {
return lhs.pos == rhs.pos;
}
template<typename Container>
[[nodiscard]] inline constexpr bool operator!=(const edge_iterator<Container> &lhs, const edge_iterator<Container> &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace internal
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Basic implementation of a directed adjacency matrix.
* @tparam Category Either a directed or undirected category tag.
* @tparam Allocator Type of allocator used to manage memory and elements.
*/
template<typename Category, typename Allocator>
class adjacency_matrix {
using alloc_traits = std::allocator_traits<Allocator>;
static_assert(std::is_base_of_v<directed_tag, Category>, "Invalid graph category");
static_assert(std::is_same_v<typename alloc_traits::value_type, std::size_t>, "Invalid value type");
using container_type = std::vector<std::size_t, typename alloc_traits::template rebind_alloc<std::size_t>>;
public:
/*! @brief Allocator type. */
using allocator_type = Allocator;
/*! @brief Unsigned integer type. */
using size_type = std::size_t;
/*! @brief Vertex type. */
using vertex_type = size_type;
/*! @brief Edge type. */
using edge_type = std::pair<vertex_type, vertex_type>;
/*! @brief Vertex iterator type. */
using vertex_iterator = iota_iterator<vertex_type>;
/*! @brief Edge iterator type. */
using edge_iterator = internal::edge_iterator<typename container_type::const_iterator>;
/*! @brief Out edge iterator type. */
using out_edge_iterator = edge_iterator;
/*! @brief In edge iterator type. */
using in_edge_iterator = edge_iterator;
/*! @brief Graph category tag. */
using graph_category = Category;
/*! @brief Default constructor. */
adjacency_matrix() noexcept(noexcept(allocator_type{}))
: adjacency_matrix{0u} {}
/**
* @brief Constructs an empty container with a given allocator.
* @param allocator The allocator to use.
*/
explicit adjacency_matrix(const allocator_type &allocator) noexcept
: adjacency_matrix{0u, allocator} {}
/**
* @brief Constructs an empty container with a given allocator and user
* supplied number of vertices.
* @param vertices Number of vertices.
* @param allocator The allocator to use.
*/
adjacency_matrix(const size_type vertices, const allocator_type &allocator = allocator_type{})
: matrix{vertices * vertices, allocator},
vert{vertices} {}
/**
* @brief Copy constructor.
* @param other The instance to copy from.
*/
adjacency_matrix(const adjacency_matrix &other)
: adjacency_matrix{other, other.get_allocator()} {}
/**
* @brief Allocator-extended copy constructor.
* @param other The instance to copy from.
* @param allocator The allocator to use.
*/
adjacency_matrix(const adjacency_matrix &other, const allocator_type &allocator)
: matrix{other.matrix, allocator},
vert{other.vert} {}
/**
* @brief Move constructor.
* @param other The instance to move from.
*/
adjacency_matrix(adjacency_matrix &&other) noexcept
: adjacency_matrix{std::move(other), other.get_allocator()} {}
/**
* @brief Allocator-extended move constructor.
* @param other The instance to move from.
* @param allocator The allocator to use.
*/
adjacency_matrix(adjacency_matrix &&other, const allocator_type &allocator)
: matrix{std::move(other.matrix), allocator},
vert{std::exchange(other.vert, 0u)} {}
/**
* @brief Default copy assignment operator.
* @param other The instance to copy from.
* @return This container.
*/
adjacency_matrix &operator=(const adjacency_matrix &other) {
matrix = other.matrix;
vert = other.vert;
return *this;
}
/**
* @brief Default move assignment operator.
* @param other The instance to move from.
* @return This container.
*/
adjacency_matrix &operator=(adjacency_matrix &&other) noexcept {
matrix = std::move(other.matrix);
vert = std::exchange(other.vert, 0u);
return *this;
}
/**
* @brief Returns the associated allocator.
* @return The associated allocator.
*/
[[nodiscard]] constexpr allocator_type get_allocator() const noexcept {
return matrix.get_allocator();
}
/*! @brief Clears the adjacency matrix. */
void clear() noexcept {
matrix.clear();
vert = {};
}
/**
* @brief Exchanges the contents with those of a given adjacency matrix.
* @param other Adjacency matrix to exchange the content with.
*/
void swap(adjacency_matrix &other) {
using std::swap;
swap(matrix, other.matrix);
swap(vert, other.vert);
}
/**
* @brief Returns the number of vertices.
* @return The number of vertices.
*/
[[nodiscard]] size_type size() const noexcept {
return vert;
}
/**
* @brief Returns an iterable object to visit all vertices of a matrix.
* @return An iterable object to visit all vertices of a matrix.
*/
[[nodiscard]] iterable_adaptor<vertex_iterator> vertices() const noexcept {
return {0u, vert};
}
/**
* @brief Returns an iterable object to visit all edges of a matrix.
* @return An iterable object to visit all edges of a matrix.
*/
[[nodiscard]] iterable_adaptor<edge_iterator> edges() const noexcept {
const auto it = matrix.cbegin();
const auto sz = matrix.size();
return {{it, vert, 0u, sz, 1u}, {it, vert, sz, sz, 1u}};
}
/**
* @brief Returns an iterable object to visit all out edges of a vertex.
* @param vertex The vertex of which to return all out edges.
* @return An iterable object to visit all out edges of a vertex.
*/
[[nodiscard]] iterable_adaptor<out_edge_iterator> out_edges(const vertex_type vertex) const noexcept {
const auto it = matrix.cbegin();
const auto from = vertex * vert;
const auto to = vertex * vert + vert;
return {{it, vert, from, to, 1u}, {it, vert, to, to, 1u}};
}
/**
* @brief Returns an iterable object to visit all in edges of a vertex.
* @param vertex The vertex of which to return all in edges.
* @return An iterable object to visit all in edges of a vertex.
*/
[[nodiscard]] iterable_adaptor<in_edge_iterator> in_edges(const vertex_type vertex) const noexcept {
const auto it = matrix.cbegin();
const auto from = vertex;
const auto to = vert * (vert - 1u) + vertex;
return {{it, vert, from, to, vert}, {it, vert, to, to, vert}};
}
/**
* @brief Resizes an adjacency matrix.
* @param vertices The new number of vertices.
*/
void resize(const size_type vertices) {
adjacency_matrix other{vertices, get_allocator()};
for(auto [lhs, rhs]: edges()) {
other.insert(lhs, rhs);
}
other.swap(*this);
}
/**
* @brief Inserts an edge into the adjacency matrix, if it does not exist.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return A pair consisting of an iterator to the inserted element (or to
* the element that prevented the insertion) and a bool denoting whether the
* insertion took place.
*/
std::pair<edge_iterator, bool> insert(const vertex_type lhs, const vertex_type rhs) {
const auto pos = lhs * vert + rhs;
if constexpr(std::is_same_v<graph_category, undirected_tag>) {
const auto rev = rhs * vert + lhs;
ENTT_ASSERT(matrix[pos] == matrix[rev], "Something went really wrong");
matrix[rev] = 1u;
}
const auto inserted = !std::exchange(matrix[pos], 1u);
return {edge_iterator{matrix.cbegin(), vert, pos, matrix.size(), 1u}, inserted};
}
/**
* @brief Removes the edge associated with a pair of given vertices.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return Number of elements removed (either 0 or 1).
*/
size_type erase(const vertex_type lhs, const vertex_type rhs) {
const auto pos = lhs * vert + rhs;
if constexpr(std::is_same_v<graph_category, undirected_tag>) {
const auto rev = rhs * vert + lhs;
ENTT_ASSERT(matrix[pos] == matrix[rev], "Something went really wrong");
matrix[rev] = 0u;
}
return std::exchange(matrix[pos], 0u);
}
/**
* @brief Checks if an adjacency matrix contains a given edge.
* @param lhs The left hand vertex of the edge.
* @param rhs The right hand vertex of the edge.
* @return True if there is such an edge, false otherwise.
*/
[[nodiscard]] bool contains(const vertex_type lhs, const vertex_type rhs) const {
const auto pos = lhs * vert + rhs;
return pos < matrix.size() && matrix[pos];
}
private:
container_type matrix;
size_type vert;
};
} // namespace entt
#endif
|
update allocator aware constructor (#909)
|
adjacency_matrix: update allocator aware constructor (#909)
|
C++
|
mit
|
skypjack/entt,skypjack/entt,skypjack/entt,skypjack/entt
|
04a21f8be1d8a6ca9dd45afeb1b4eed96aeb4302
|
src/examples/contactlistwidgets.cpp
|
src/examples/contactlistwidgets.cpp
|
/*
Persons Model Example
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QApplication>
#include <QTreeView>
#include <QHeaderView>
#include <QStyledItemDelegate>
#include <QSortFilterProxyModel>
#include <qpainter.h>
#include <personsmodel.h>
#include <personsmodelfeature.h>
using namespace KPeople;
class ContactDelegate : public QStyledItemDelegate
{
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
QStyledItemDelegate::paint(painter, option, index);
QRect infoRect(QPoint(option.rect.center().x(), option.rect.top()), option.rect.bottomRight());
if (index.parent().isValid()) {
painter->drawText(infoRect, index.data(PersonsModel::PresenceTypeRole).toString());
} else {
painter->drawText(infoRect, QString::number(index.model()->rowCount(index)));
}
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTreeView view;
view.setItemDelegate(new ContactDelegate);
PersonsModel *model = new PersonsModel(&view);
// QList<PersonsModelFeature> features;
// features << PersonsModelFeature::emailModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::avatarModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::imModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::fullNameModelFeature(PersonsModelFeature::Optional);
// model->startQuery(features);
QSortFilterProxyModel *sortFilter = new QSortFilterProxyModel(&view);
sortFilter->setDynamicSortFilter(true);
sortFilter->setSourceModel(model);
view.setModel(sortFilter);
view.setSortingEnabled(true);
view.show();
app.exec();
}
|
/*
Persons Model Example
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QApplication>
#include <QTreeView>
#include <QHeaderView>
#include <QStyledItemDelegate>
#include <QSortFilterProxyModel>
#include <qpainter.h>
#include <personsmodel.h>
#include <personsmodelfeature.h>
using namespace KPeople;
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTreeView view;
PersonsModel *model = new PersonsModel(&view);
// QList<PersonsModelFeature> features;
// features << PersonsModelFeature::emailModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::avatarModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::imModelFeature(PersonsModelFeature::Optional)
// << PersonsModelFeature::fullNameModelFeature(PersonsModelFeature::Optional);
// model->startQuery(features);
QSortFilterProxyModel *sortFilter = new QSortFilterProxyModel(&view);
sortFilter->setDynamicSortFilter(true);
sortFilter->setSourceModel(model);
view.setModel(sortFilter);
view.setSortingEnabled(true);
view.show();
app.exec();
}
|
Remove broken style delegate on example demo
|
Remove broken style delegate on example demo
|
C++
|
lgpl-2.1
|
detrout/libkpeople-debian,detrout/libkpeople-debian,detrout/libkpeople-debian
|
0292e4e3d3d72f817c7c3aa9e755636befb208fb
|
modules/cdm_boost.hpp
|
modules/cdm_boost.hpp
|
#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP
#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>
//Boost is so large that the output of cp exceeds the 4 MB log limit of travis
//which aborts the build job then.
//On Windows, the console is so slow (especially in Virtualbox) that we want
//to avoid the megabytes of output from the Boost build process.
//TODO: Buffer the output in memory and save it somewhere if something fails.
#if defined(CDM_TESTS_RUNNING_ON_TRAVIS_CI) || defined(_WIN32)
# define CDM_AVOID_CONSOLE_OUTPUT 1
#else
# define CDM_AVOID_CONSOLE_OUTPUT 0
#endif
namespace cdm
{
struct boost_paths
{
Si::absolute_path root;
};
inline boost_paths install_boost(
Si::absolute_path const &source,
Si::absolute_path const &temporary,
Si::absolute_path const &install_root,
Si::absolute_path const &cmake_exe,
unsigned make_parallelism,
Si::Sink<char, Si::success>::interface &output)
{
boost::ignore_unused_variable_warning(cmake_exe);
Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
if (!Si::file_exists(module_in_cache, Si::throw_))
{
Si::absolute_path const copy_of_boost = temporary / Si::relative_path("src");
Si::copy_recursively(
source,
copy_of_boost,
#if CDM_AVOID_CONSOLE_OUTPUT
nullptr
#else
&output
#endif
, Si::throw_);
Si::create_directories(module_in_cache, Si::throw_);
{
std::vector<Si::os_string> arguments;
#ifdef _MSC_VER
Si::absolute_path const exe = copy_of_boost / "bootstrap.bat";
#else
Si::absolute_path const exe = *Si::absolute_path::create("/usr/bin/env");
arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
#endif
int const rc = Si::run_process(exe, arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("bootstrap failed");
}
}
{
#if CDM_AVOID_CONSOLE_OUTPUT
auto null_output = Si::Sink<char, Si::success>::erase(Si::null_sink<char, Si::success>());
#endif
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
{
Si::os_string const install_argument = SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache);
arguments.push_back(install_argument);
}
#ifdef _MSC_VER
arguments.push_back(SILICIUM_SYSTEM_LITERAL("toolset=msvc-12.0"));
#endif
arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
int const rc = Si::run_process(copy_of_boost / "b2"
#ifdef _WIN32
".exe"
#endif
, arguments, copy_of_boost,
#if CDM_AVOID_CONSOLE_OUTPUT
null_output
#else
output
#endif
).get();
if (rc != 0)
{
throw std::runtime_error("b2 failed");
}
}
}
boost_paths result;
result.root = module_in_cache;
return result;
}
}
#endif
|
#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP
#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>
//Boost is so large that the output of cp exceeds the 4 MB log limit of travis
//which aborts the build job then.
//On Windows, the console is so slow (especially in Virtualbox) that we want
//to avoid the megabytes of output from the Boost build process.
//TODO: Buffer the output in memory and save it somewhere if something fails.
#if defined(CDM_TESTS_RUNNING_ON_TRAVIS_CI) || defined(_WIN32)
# define CDM_AVOID_CONSOLE_OUTPUT 1
#else
# define CDM_AVOID_CONSOLE_OUTPUT 0
#endif
namespace cdm
{
struct boost_paths
{
Si::absolute_path root;
};
inline boost_paths install_boost(
Si::absolute_path const &source,
Si::absolute_path const &temporary,
Si::absolute_path const &install_root,
Si::absolute_path const &cmake_exe,
unsigned make_parallelism,
Si::Sink<char, Si::success>::interface &output)
{
boost::ignore_unused_variable_warning(cmake_exe);
Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
if (!Si::file_exists(module_in_cache, Si::throw_))
{
Si::absolute_path const copy_of_boost = temporary / Si::relative_path("src");
Si::copy_recursively(
source,
copy_of_boost,
#if CDM_AVOID_CONSOLE_OUTPUT
nullptr
#else
&output
#endif
, Si::throw_);
Si::create_directories(module_in_cache, Si::throw_);
{
std::vector<Si::os_string> arguments;
#ifdef _MSC_VER
Si::absolute_path const exe = copy_of_boost / "bootstrap.bat";
#else
Si::absolute_path const exe = *Si::absolute_path::create("/usr/bin/env");
arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
#endif
int const rc = Si::run_process(exe, arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("bootstrap failed");
}
}
{
#if CDM_AVOID_CONSOLE_OUTPUT
auto null_output = Si::Sink<char, Si::success>::erase(Si::null_sink<char, Si::success>());
#endif
std::vector<Si::os_string> arguments;
arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
{
Si::os_string const install_argument = SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache);
arguments.push_back(install_argument);
}
arguments.push_back(SILICIUM_SYSTEM_LITERAL("link=static"));
#ifdef _MSC_VER
arguments.push_back(SILICIUM_SYSTEM_LITERAL("toolset=msvc-12.0"));
#endif
arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
int const rc = Si::run_process(copy_of_boost / "b2"
#ifdef _WIN32
".exe"
#endif
, arguments, copy_of_boost,
#if CDM_AVOID_CONSOLE_OUTPUT
null_output
#else
output
#endif
).get();
if (rc != 0)
{
throw std::runtime_error("b2 failed");
}
}
}
boost_paths result;
result.root = module_in_cache;
return result;
}
}
#endif
|
build Boost as static libs for now
|
build Boost as static libs for now
|
C++
|
mit
|
TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm
|
1b1a0a91b34f195ef8ff4a345b97184058ce2631
|
modules/cdm_boost.hpp
|
modules/cdm_boost.hpp
|
#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP
#include <ventura/file_operations.hpp>
#include <ventura/run_process.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <boost/lexical_cast.hpp>
namespace cdm
{
struct boost_paths
{
ventura::absolute_path root;
};
inline boost_paths install_boost(ventura::absolute_path const &source, ventura::absolute_path const &temporary,
ventura::absolute_path const &install_root, unsigned make_parallelism,
Si::Sink<char, Si::success>::interface &output)
{
ventura::absolute_path const module_in_cache = install_root / "boost";
if (!ventura::file_exists(module_in_cache, Si::throw_))
{
ventura::absolute_path const copy_of_boost = temporary / "src";
ventura::copy_recursively(source, copy_of_boost, &output, Si::throw_);
ventura::create_directories(module_in_cache, Si::throw_);
{
std::vector<Si::os_string> arguments;
#ifdef _MSC_VER
ventura::absolute_path const exe = copy_of_boost / "bootstrap.bat";
#else
ventura::absolute_path const exe = *ventura::absolute_path::create("/usr/bin/env");
arguments.emplace_back(SILICIUM_OS_STR("bash"));
arguments.emplace_back(to_os_string(copy_of_boost / "bootstrap.sh"));
#endif
int const rc = ventura::run_process(exe, arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("bootstrap failed");
}
}
{
std::vector<Si::os_string> arguments;
arguments.emplace_back(SILICIUM_OS_STR("install"));
{
Si::os_string const install_argument = SILICIUM_OS_STR("--prefix=") + to_os_string(module_in_cache);
arguments.emplace_back(install_argument);
}
arguments.emplace_back(SILICIUM_OS_STR("link=static"));
#ifdef _MSC_VER
arguments.emplace_back(SILICIUM_OS_STR("toolset=msvc-12.0"));
#endif
#if CDM_TESTS_RUNNING_ON_TRAVIS_CI
boost::ignore_unused_variable_warning(make_parallelism);
#else
// GCC 4.6 crashes when compiling Boost.Log on travis probably due
// to lack of RAM.
// Thus we do not parallelize the build on travis so that the
// compiler can use all of the memory available to the machine.
arguments.emplace_back(SILICIUM_OS_STR("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
#endif
int const rc = ventura::run_process(copy_of_boost / "b2"
#ifdef _WIN32
".exe"
#endif
,
arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("b2 failed");
}
}
}
boost_paths result;
result.root = module_in_cache;
return result;
}
}
#endif
|
#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP
#include <ventura/file_operations.hpp>
#include <ventura/run_process.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <boost/lexical_cast.hpp>
namespace cdm
{
struct boost_paths
{
ventura::absolute_path root;
};
inline boost_paths install_boost(ventura::absolute_path const &source, ventura::absolute_path const &temporary,
ventura::absolute_path const &install_root, unsigned make_parallelism,
Si::Sink<char, Si::success>::interface &output)
{
ventura::absolute_path const module_in_cache = install_root / "boost";
if (!ventura::file_exists(module_in_cache, Si::throw_))
{
ventura::absolute_path const copy_of_boost = temporary / "src";
ventura::copy_recursively(source, copy_of_boost, &output, Si::throw_);
ventura::create_directories(module_in_cache, Si::throw_);
{
std::vector<Si::os_string> arguments;
#ifdef _MSC_VER
ventura::absolute_path const exe = copy_of_boost / "bootstrap.bat";
#else
ventura::absolute_path const exe = *ventura::absolute_path::create("/usr/bin/env");
arguments.emplace_back(SILICIUM_OS_STR("bash"));
arguments.emplace_back(to_os_string(copy_of_boost / "bootstrap.sh"));
#endif
int const rc = ventura::run_process(exe, arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("bootstrap failed");
}
}
{
std::vector<Si::os_string> arguments;
arguments.emplace_back(SILICIUM_OS_STR("install"));
{
Si::os_string const install_argument = SILICIUM_OS_STR("--prefix=") + to_os_string(module_in_cache);
arguments.emplace_back(install_argument);
}
arguments.emplace_back(SILICIUM_OS_STR("link=static"));
#ifdef _MSC_VER
arguments.emplace_back(SILICIUM_OS_STR("toolset=msvc-12.0"));
#endif
#if CDM_TESTS_RUNNING_ON_TRAVIS_CI
// GCC 4.6 crashes when compiling Boost.Log on travis probably due
// to lack of RAM.
// Thus we do not parallelize the build on travis so that the
// compiler can use all of the memory available to the machine.
boost::ignore_unused_variable_warning(make_parallelism);
#else
arguments.emplace_back(SILICIUM_OS_STR("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
#endif
int const rc = ventura::run_process(copy_of_boost / "b2"
#ifdef _WIN32
".exe"
#endif
,
arguments, copy_of_boost, output).get();
if (rc != 0)
{
throw std::runtime_error("b2 failed");
}
}
}
boost_paths result;
result.root = module_in_cache;
return result;
}
}
#endif
|
move a comment to the intended location
|
move a comment to the intended location
|
C++
|
mit
|
TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm,TyRoXx/cdm
|
ad2f94bcc6f0280cd6f7eae1b71f01d576f33cce
|
src/highlevel_feature_extractor.cpp
|
src/highlevel_feature_extractor.cpp
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "highlevel_feature_extractor.h"
#include <rcsc/common/server_param.h>
using namespace rcsc;
HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,
int num_opponents,
bool playing_offense) :
FeatureExtractor(num_teammates, num_opponents, playing_offense)
{
assert(numTeammates >= 0);
assert(numOpponents >= 0);
numFeatures = num_basic_features + features_per_teammate * numTeammates
+ features_per_opponent * numOpponents;
feature_vec.resize(numFeatures);
}
HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}
const std::vector<float>& HighLevelFeatureExtractor::ExtractFeatures(
const WorldModel& wm) {
featIndx = 0;
const ServerParam& SP = ServerParam::i();
const SelfObject& self = wm.self();
const Vector2D& self_pos = self.pos();
const float self_ang = self.body().radian();
const PlayerCont& teammates = wm.teammates();
const PlayerCont& opponents = wm.opponents();
float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()
+ SP.pitchHalfWidth() * SP.pitchHalfWidth());
// features about self pos
// Allow the agent to go 10% over the playfield in any direction
float tolerance_x = .1 * SP.pitchHalfLength();
float tolerance_y = .1 * SP.pitchHalfWidth();
// figure up min, max x, y
float min_x = 0; // Depends on offense vs defense
float max_x = 0;
if (playingOffense) {
min_x = -tolerance_x;
max_x = SP.pitchHalfLength() + tolerance_x;
} else {
min_x = -SP.pitchHalfLength()-tolerance_x;
max_x = tolerance_x;
}
float min_y = -SP.pitchHalfWidth() - tolerance_y;
float max_y = SP.pitchHalfWidth() + tolerance_y;
// Feature[0]: X-postion
// Feature[1]: Y-position
if (self.posValid()) {
addNormFeature(self_pos.x, min_x, max_x);
addNormFeature(self_pos.y, min_y, max_y);
} else {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Feature[2]: Self Angle
addNormFeature(self_ang, -M_PI, M_PI); // Check for validity?
float r;
float th;
// Features about the ball
const BallObject& ball = wm.ball();
if (ball.rposValid()) {
Vector2D ball_pos = ball.pos();
angleDistToPoint(self_pos, ball_pos, th, r);
// Feature[3] and [4]: (x,y) postition of the ball
addNormFeature(ball_pos.x, min_x, max_x);
addNormFeature(ball_pos.y, min_y, max_y);
} else {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Feature[5]: Able to kick
addNormFeature(self.isKickable(), false, true);
// Features about distance to goal center
Vector2D goalCenter(SP.pitchHalfLength(), 0);
if (!playingOffense) {
goalCenter.assign(-SP.pitchHalfLength(), 0);
}
angleDistToPoint(self_pos, goalCenter, th, r);
// Feature[6]: Goal Center Distance
addNormFeature(r, 0, maxR);
// Feature[7]: Angle to goal center
addNormFeature(th, -M_PI, M_PI);
// Feature[8]: largest open goal angle
addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);
// Feature[9]: Dist to our closest opp
if (numOpponents > 0) {
calcClosestOpp(wm, self_pos, th, r);
addNormFeature(r, 0, maxR);
} else {
addFeature(FEAT_INVALID);
}
// Features[9 - 9+T]: teammate's open angle to goal
int detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestGoalAngle(wm, teammate.pos()), 0, M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features[9+T - 9+2T]: teammates' dists to closest opps
if (numOpponents > 0) {
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
calcClosestOpp(wm, teammate.pos(), th, r);
addNormFeature(r, 0, maxR);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
} else { // If no opponents, add invalid features
for (int i=0; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
}
// Features [9+2T - 9+3T]: open angle to teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()),0,M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features [9+3T - 9+6T]: x, y, unum of teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
if (playingOffense) {
addNormFeature(teammate.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(teammate.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(teammate.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(teammate.unum());
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Features [9+6T - 9+6T+3O]: x, y, unum of opponents
int detected_opponents = 0;
for (PlayerCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) {
const PlayerObject& opponent = *it;
if (valid(opponent) && detected_opponents < numOpponents) {
if (playingOffense) {
addNormFeature(opponent.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(opponent.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(opponent.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(opponent.unum());
detected_opponents++;
}
}
// Add zero features for any missing opponents
for (int i=detected_opponents; i<numOpponents; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
assert(featIndx == numFeatures);
// checkFeatures();
return feature_vec;
}
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "highlevel_feature_extractor.h"
#include <rcsc/common/server_param.h>
using namespace rcsc;
HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,
int num_opponents,
bool playing_offense) :
FeatureExtractor(num_teammates, num_opponents, playing_offense)
{
assert(numTeammates >= 0);
assert(numOpponents >= 0);
numFeatures = num_basic_features + features_per_teammate * numTeammates
+ features_per_opponent * numOpponents;
feature_vec.resize(numFeatures);
}
HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}
const std::vector<float>& HighLevelFeatureExtractor::ExtractFeatures(
const WorldModel& wm) {
featIndx = 0;
const ServerParam& SP = ServerParam::i();
const SelfObject& self = wm.self();
const Vector2D& self_pos = self.pos();
const float self_ang = self.body().radian();
const PlayerCont& teammates = wm.teammates();
const PlayerCont& opponents = wm.opponents();
float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()
+ SP.pitchHalfWidth() * SP.pitchHalfWidth());
// features about self pos
// Allow the agent to go 10% over the playfield in any direction
float tolerance_x = .1 * SP.pitchHalfLength();
float tolerance_y = .1 * SP.pitchHalfWidth();
// figure up min, max x, y
float min_x = 0; // Depends on offense vs defense
float max_x = 0;
if (playingOffense) {
min_x = -tolerance_x;
max_x = SP.pitchHalfLength() + tolerance_x;
} else {
min_x = -SP.pitchHalfLength()-tolerance_x;
max_x = tolerance_x;
}
float min_y = -SP.pitchHalfWidth() - tolerance_y;
float max_y = SP.pitchHalfWidth() + tolerance_y;
// Feature[0]: X-postion
// Feature[1]: Y-position
if (valid(self)) {
addNormFeature(self_pos.x, min_x, max_x);
addNormFeature(self_pos.y, min_y, max_y);
} else {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Feature[2]: Self Angle
addNormFeature(self_ang, -M_PI, M_PI); // Check for validity?
float r;
float th;
// Features about the ball
const BallObject& ball = wm.ball();
if (ball.rposValid()) {
Vector2D ball_pos = ball.pos();
angleDistToPoint(self_pos, ball_pos, th, r);
// Feature[3] and [4]: (x,y) postition of the ball
addNormFeature(ball_pos.x, min_x, max_x);
addNormFeature(ball_pos.y, min_y, max_y);
} else {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Feature[5]: Able to kick
addNormFeature(self.isKickable(), false, true);
// Features about distance to goal center
Vector2D goalCenter(SP.pitchHalfLength(), 0);
if (!playingOffense) {
goalCenter.assign(-SP.pitchHalfLength(), 0);
}
angleDistToPoint(self_pos, goalCenter, th, r);
// Feature[6]: Goal Center Distance
addNormFeature(r, 0, maxR);
// Feature[7]: Angle to goal center
addNormFeature(th, -M_PI, M_PI);
// Feature[8]: largest open goal angle
addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);
// Feature[9]: Dist to our closest opp
if (numOpponents > 0) {
calcClosestOpp(wm, self_pos, th, r);
addNormFeature(r, 0, maxR);
} else {
addFeature(FEAT_INVALID);
}
// Features[9 - 9+T]: teammate's open angle to goal
int detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestGoalAngle(wm, teammate.pos()), 0, M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features[9+T - 9+2T]: teammates' dists to closest opps
if (numOpponents > 0) {
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
calcClosestOpp(wm, teammate.pos(), th, r);
addNormFeature(r, 0, maxR);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
} else { // If no opponents, add invalid features
for (int i=0; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
}
// Features [9+2T - 9+3T]: open angle to teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()),0,M_PI);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features [9+3T - 9+6T]: x, y, unum of teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
if (playingOffense) {
addNormFeature(teammate.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(teammate.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(teammate.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(teammate.unum());
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
// Features [9+6T - 9+6T+3O]: x, y, unum of opponents
int detected_opponents = 0;
for (PlayerCont::const_iterator it = opponents.begin(); it != opponents.end(); ++it) {
const PlayerObject& opponent = *it;
if (valid(opponent) && detected_opponents < numOpponents) {
if (playingOffense) {
addNormFeature(opponent.pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(opponent.pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
addNormFeature(opponent.pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);
addFeature(opponent.unum());
detected_opponents++;
}
}
// Add zero features for any missing opponents
for (int i=detected_opponents; i<numOpponents; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
assert(featIndx == numFeatures);
// checkFeatures();
return feature_vec;
}
|
Revert "Staging further changes vs invalid feature errors" - compatibility worries Will experiment with low-level features while consulting re errors
|
Revert "Staging further changes vs invalid feature errors" - compatibility worries
Will experiment with low-level features while consulting re errors
This reverts commit 461ee7df8d281078f2f13c912e18409dc2d59a8e.
modified: src/highlevel_feature_extractor.cpp
|
C++
|
mit
|
LARG/HFO,mhauskn/HFO,LARG/HFO,LARG/HFO,mhauskn/HFO,mhauskn/HFO
|
77ba1cc62d4e11269c6d4d14daed96f2e4abd97d
|
src/io/register_loader_saver_xg.cpp
|
src/io/register_loader_saver_xg.cpp
|
/**
* \file register_loader_saver_xg.cpp
* Defines IO for an XG index from stream files.
*/
#include <vg/io/registry.hpp>
#include "register_loader_saver_xg.hpp"
#include "handle.hpp"
#include "xg.hpp"
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_xg() {
// Convert the XG SerializableHandleGraph magic number to a string
xg::XG empty;
// Make sure it is in network byte order
uint32_t new_magic_number = htonl(empty.get_magic_number());
// Load all 4 characters of it into a string
string new_magic((char*)&new_magic_number, 4);
// Register to load with either old or new SerializableHandleGraph-managed
// XG magic number sequences, in addition to the tag.
Registry::register_bare_loader_saver_with_magics<xg::XG, PathPositionHandleGraph, PathHandleGraph, HandleGraph>("XG",
{"XG", new_magic}, [](istream& input) -> void* {
// Allocate an XG
xg::XG* index = new xg::XG();
// Load it
index->deserialize(input);
// Return it so the caller owns it.
return (void*) index;
}, [](const void* index_void, ostream& output) {
// Cast to XG and serialize to the stream.
assert(index_void != nullptr);
((const xg::XG*) index_void)->serialize(output);
});
}
}
}
|
/**
* \file register_loader_saver_xg.cpp
* Defines IO for an XG index from stream files.
*/
#include <arpa/inet.h>
#include <vg/io/registry.hpp>
#include "register_loader_saver_xg.hpp"
#include "handle.hpp"
#include "xg.hpp"
namespace vg {
namespace io {
using namespace std;
using namespace vg::io;
void register_loader_saver_xg() {
// Convert the XG SerializableHandleGraph magic number to a string
xg::XG empty;
// Make sure it is in network byte order
uint32_t new_magic_number = htonl(empty.get_magic_number());
// Load all 4 characters of it into a string
string new_magic((char*)&new_magic_number, 4);
// Register to load with either old or new SerializableHandleGraph-managed
// XG magic number sequences, in addition to the tag.
Registry::register_bare_loader_saver_with_magics<xg::XG, PathPositionHandleGraph, PathHandleGraph, HandleGraph>("XG",
{"XG", new_magic}, [](istream& input) -> void* {
// Allocate an XG
xg::XG* index = new xg::XG();
// Load it
index->deserialize(input);
// Return it so the caller owns it.
return (void*) index;
}, [](const void* index_void, ostream& output) {
// Cast to XG and serialize to the stream.
assert(index_void != nullptr);
((const xg::XG*) index_void)->serialize(output);
});
}
}
}
|
add missing include in xg loader saver
|
add missing include in xg loader saver
|
C++
|
mit
|
ekg/vg,ekg/vg,ekg/vg
|
53cc8c3abc2efdfe6e2be30a6a1ca0e8c594fde0
|
EnvironmentModule/EC_WaterPlane.cpp
|
EnvironmentModule/EC_WaterPlane.cpp
|
// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_OgrePlaceable.h"
#include "IAttribute.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")
#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include "MemoryLeakCheck.h"
namespace Environment
{
EC_WaterPlane::EC_WaterPlane(IModule *module)
: IComponent(module->GetFramework()),
xSizeAttr_(this, "x-size", 5000),
ySizeAttr_(this, "y-size", 5000),
depthAttr_(this, "Depth", 20),
positionAttr_(this, "Position", Vector3df()),
rotationAttr_(this, "Rotation", Quaternion()),
scaleUfactorAttr_(this, "U factor", 0.0002f),
scaleVfactorAttr_(this, "V factor", 0.0002f),
xSegmentsAttr_(this, "Segments x direction", 10),
ySegmentsAttr_(this, "Segments y direction", 10),
materialNameAttr_(this, "Material", QString("Ocean")),
fogColorAttr_(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
fogStartAttr_(this, "Fog start distance", 100.f),
fogEndAttr_(this, "Fog end distance", 2000.f),
fogModeAttr_(this, "Fog mode", 3),
entity_(0),
node_(0),
attached_(false)
{
static AttributeMetadata metadata;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
metadata.enums[Ogre::FOG_NONE] = "NoFog";
metadata.enums[Ogre::FOG_EXP] = "Exponentially";
metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
metadata.enums[Ogre::FOG_LINEAR] = "Linearly";
metadataInitialized = true;
}
fogModeAttr_.SetMetadata(&metadata);
renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
if(!renderer_.expired())
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_ = scene_mgr->createSceneNode();
}
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));
lastXsize_ = xSizeAttr_.Get();
lastYsize_ = ySizeAttr_.Get();
CreateWaterPlane();
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(AttachEntity()));
// If there exist placeable copy its position for default position and rotation.
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ( placeable != 0)
{
Vector3df vec = placeable->GetPosition();
positionAttr_.Set(vec,AttributeChange::Local);
Quaternion rot =placeable->GetOrientation();
rotationAttr_.Set(rot, AttributeChange::Local);
ComponentChanged(AttributeChange::Local);
}
}
EC_WaterPlane::~EC_WaterPlane()
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
RemoveWaterPlane();
if (node_ != 0)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroySceneNode(node_);
node_ = 0;
}
}
bool EC_WaterPlane::IsUnderWater()
{
// Check that is camera inside of defined waterplane.
///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.
if ( entity_ == 0)
return false;
Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
Ogre::Vector3 posCamera = camera->getDerivedPosition();
Ogre::Vector3 pos;
if (node_ != 0)
pos = node_->_getDerivedPosition();
else
return false;
int xSize = xSizeAttr_.Get(), ySize = ySizeAttr_.Get(), depth = depthAttr_.Get();
int x = posCamera.x, y = posCamera.y, z = posCamera.z;
// HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
int tmpMax = pos.x + 0.25*xSize;
int tmpMin = pos.x - 0.25*xSize;
if ( x >= tmpMin && x <= tmpMax )
{
tmpMax = pos.y + 0.25*ySize;
tmpMin = pos.y - 0.25*ySize;
if ( y >= tmpMin && y <= tmpMax)
{
tmpMax = pos.z;
tmpMin = pos.z - depth;
if ( z >= tmpMin && z <= tmpMax)
{
return true;
}
else
return false;
}
else
return false;
}
return false;
}
void EC_WaterPlane::CreateWaterPlane()
{
// Create waterplane
if (renderer_.lock() != 0)
{
Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
assert(sceneMgr);
if (node_ != 0)
{
int xSize = xSizeAttr_.Get();
int ySize = ySizeAttr_.Get();
float uTile = scaleUfactorAttr_.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
float vTile = scaleVfactorAttr_.Get() * ySize;
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr_.Get(), ySegmentsAttr_.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);
entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
entity_->setMaterialName(materialNameAttr_.Get().toStdString().c_str());
entity_->setCastShadows(false);
// Tries to attach entity, if there is not EC_OgrePlaceable availible, it will not attach object
AttachEntity();
}
}
}
void EC_WaterPlane::RemoveWaterPlane()
{
// Remove waterplane
if (renderer_.expired() || !entity_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = 0;
Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());
}
Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
{
Color col = fogColorAttr_.Get();
return Ogre::ColourValue(col.r, col.g, col.b, col.a);
}
void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
{
ChangeWaterPlane(attribute);
}
void EC_WaterPlane::SetPosition()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && !attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
Vector3df vec = positionAttr_.Get();
//node_->setPosition(vec.x, vec.y, vec.z);
node_->_setDerivedPosition(Ogre::Vector3(vec.x, vec.y, vec.z));
}
void EC_WaterPlane::SetOrientation()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
// Set orientation
Quaternion rot = rotationAttr_.Get();
node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
}
void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
{
std::string name = attribute->GetNameString();
if ( ( name == xSizeAttr_.GetNameString()
|| name == ySizeAttr_.GetNameString()
|| name == scaleUfactorAttr_.GetNameString()
|| name == scaleVfactorAttr_.GetNameString() ) &&
( lastXsize_ != xSizeAttr_.Get() || lastYsize_ != ySizeAttr_.Get() ) )
{
RemoveWaterPlane();
CreateWaterPlane();
lastXsize_ = xSizeAttr_.Get();
lastYsize_ = ySizeAttr_.Get();
}
else if ( name == positionAttr_.GetNameString() )
{
// Change position
SetPosition();
}
else if ( name == rotationAttr_.GetNameString() )
{
// Change rotation
// Is there placeable component? If not use given rotation
//if ( dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get()) == 0 )
//{
SetOrientation();
//}
}
else if ( name == depthAttr_.GetNameString() )
{
// Change depth
// Currently do nothing..
}
else if ( name == materialNameAttr_.GetNameString())
{
//Change material
if ( entity_ != 0)
{
entity_->setMaterialName(materialNameAttr_.Get().toStdString().c_str());
}
}
}
ComponentPtr EC_WaterPlane::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
return comp;
comp = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
return comp;
}
void EC_WaterPlane::AttachEntity()
{
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ((!entity_) || (!placeable) || attached_)
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(node_);
node_->attachObject(entity_);
attached_ = true;
}
void EC_WaterPlane::DetachEntity()
{
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ((!attached_) || (!entity_) || (!placeable))
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node_->detachObject(entity_);
node->removeChild(node_);
attached_ = false;
}
}
|
// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_WaterPlane.h"
#include "EC_OgrePlaceable.h"
#include "IAttribute.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_WaterPlane")
#include <Ogre.h>
#include <OgreQuaternion.h>
#include <OgreColourValue.h>
#include "MemoryLeakCheck.h"
namespace Environment
{
EC_WaterPlane::EC_WaterPlane(IModule *module)
: IComponent(module->GetFramework()),
xSizeAttr_(this, "x-size", 5000),
ySizeAttr_(this, "y-size", 5000),
depthAttr_(this, "Depth", 20),
positionAttr_(this, "Position", Vector3df()),
rotationAttr_(this, "Rotation", Quaternion()),
scaleUfactorAttr_(this, "U factor", 0.0002f),
scaleVfactorAttr_(this, "V factor", 0.0002f),
xSegmentsAttr_(this, "Segments x direction", 10),
ySegmentsAttr_(this, "Segments y direction", 10),
materialNameAttr_(this, "Material", QString("Ocean")),
fogColorAttr_(this, "Fog color", Color(0.2f,0.4f,0.35f,1.0f)),
fogStartAttr_(this, "Fog start distance", 100.f),
fogEndAttr_(this, "Fog end distance", 2000.f),
fogModeAttr_(this, "Fog mode", 3),
entity_(0),
node_(0),
attached_(false)
{
static AttributeMetadata metadata;
static bool metadataInitialized = false;
if(!metadataInitialized)
{
metadata.enums[Ogre::FOG_NONE] = "NoFog";
metadata.enums[Ogre::FOG_EXP] = "Exponentially";
metadata.enums[Ogre::FOG_EXP2] = "ExponentiallySquare";
metadata.enums[Ogre::FOG_LINEAR] = "Linearly";
metadataInitialized = true;
}
fogModeAttr_.SetMetadata(&metadata);
renderer_ = framework_->GetServiceManager()->GetService<OgreRenderer::Renderer>();
if(!renderer_.expired())
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_ = scene_mgr->createSceneNode();
}
QObject::connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)),
SLOT(AttributeUpdated(IAttribute*, AttributeChange::Type)));
lastXsize_ = xSizeAttr_.Get();
lastYsize_ = ySizeAttr_.Get();
CreateWaterPlane();
QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(AttachEntity()));
// If there exist placeable copy its position for default position and rotation.
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ( placeable != 0)
{
Vector3df vec = placeable->GetPosition();
positionAttr_.Set(vec,AttributeChange::Local);
Quaternion rot =placeable->GetOrientation();
rotationAttr_.Set(rot, AttributeChange::Local);
ComponentChanged(AttributeChange::Local);
}
}
EC_WaterPlane::~EC_WaterPlane()
{
if (renderer_.expired())
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
RemoveWaterPlane();
if (node_ != 0)
{
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroySceneNode(node_);
node_ = 0;
}
}
bool EC_WaterPlane::IsUnderWater()
{
// Check that is camera inside of defined waterplane.
///todo this cannot be done this way, mesh orientation etc. must take care. Now we just assume that plane does not have orientation.
if ( entity_ == 0)
return false;
Ogre::Camera *camera = renderer_.lock()->GetCurrentCamera();
Ogre::Vector3 posCamera = camera->getDerivedPosition();
Ogre::Vector3 pos;
if (node_ != 0)
pos = node_->_getDerivedPosition();
else
return false;
int xSize = xSizeAttr_.Get(), ySize = ySizeAttr_.Get(), depth = depthAttr_.Get();
int x = posCamera.x, y = posCamera.y, z = posCamera.z;
// HACK this is strange, i thought that it should be 0.5 but some reason, visually it looks like that you can travel really "outside" from water.
int tmpMax = pos.x + 0.25*xSize;
int tmpMin = pos.x - 0.25*xSize;
if ( x >= tmpMin && x <= tmpMax )
{
tmpMax = pos.y + 0.25*ySize;
tmpMin = pos.y - 0.25*ySize;
if ( y >= tmpMin && y <= tmpMax)
{
tmpMax = pos.z;
tmpMin = pos.z - depth;
if ( z >= tmpMin && z <= tmpMax)
{
return true;
}
else
return false;
}
else
return false;
}
return false;
}
void EC_WaterPlane::CreateWaterPlane()
{
// Create waterplane
if (renderer_.lock() != 0)
{
Ogre::SceneManager *sceneMgr = renderer_.lock()->GetSceneManager();
assert(sceneMgr);
if (node_ != 0)
{
int xSize = xSizeAttr_.Get();
int ySize = ySizeAttr_.Get();
float uTile = scaleUfactorAttr_.Get() * xSize; /// Default x-size 5000 --> uTile 1.0
float vTile = scaleVfactorAttr_.Get() * ySize;
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createPlane(name_.toStdString().c_str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::Plane(Ogre::Vector3::UNIT_Z, 0),xSize, ySize, xSegmentsAttr_.Get(), ySegmentsAttr_.Get(), true, 1, uTile, vTile, Ogre::Vector3::UNIT_X);
entity_ = sceneMgr->createEntity(renderer_.lock()->GetUniqueObjectName(), name_.toStdString().c_str());
entity_->setMaterialName(materialNameAttr_.Get().toStdString().c_str());
entity_->setCastShadows(false);
// Tries to attach entity, if there is not EC_OgrePlaceable availible, it will not attach object
AttachEntity();
}
}
}
void EC_WaterPlane::RemoveWaterPlane()
{
// Remove waterplane
if (renderer_.expired() || !entity_)
return;
OgreRenderer::RendererPtr renderer = renderer_.lock();
DetachEntity();
Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
scene_mgr->destroyEntity(entity_);
entity_ = 0;
Ogre::MeshManager::getSingleton().remove(name_.toStdString().c_str());
}
Ogre::ColourValue EC_WaterPlane::GetFogColorAsOgreValue() const
{
Color col = fogColorAttr_.Get();
return Ogre::ColourValue(col.r, col.g, col.b, col.a);
}
void EC_WaterPlane::AttributeUpdated(IAttribute* attribute, AttributeChange::Type change)
{
ChangeWaterPlane(attribute);
}
void EC_WaterPlane::SetPosition()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && !attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
Vector3df vec = positionAttr_.Get();
//node_->setPosition(vec.x, vec.y, vec.z);
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Vector3 current_pos = node_->_getDerivedPosition();
Ogre::Vector3 tmp(vec.x,vec.y,vec.z);
tmp = current_pos + tmp;
node_->setPosition(tmp);
#else
node_->_setDerivedPosition(Ogre::Vector3(vec.x, vec.y, vec.z));
#endif
}
void EC_WaterPlane::SetOrientation()
{
// Is attached?
if ( entity_ != 0 && !entity_->isAttached() && attached_ )
{
Ogre::SceneManager* scene_mgr = renderer_.lock()->GetSceneManager();
node_->attachObject(entity_);
attached_ = true;
scene_mgr->getRootSceneNode()->addChild(node_);
node_->setVisible(true);
}
// Set orientation
Quaternion rot = rotationAttr_.Get();
#if OGRE_VERSION_MINOR <= 6 && OGRE_VERSION_MAJOR <= 1
Ogre::Quaternion current_rot = node_->_getDerivedOrientation();
Ogre::Quaternion tmp(rot.w, rot.x, rot.y, rot.z);
Ogre::Quaternion rota = current_rot + tmp;
node_->setOrientation(rota);
#else
node_->_setDerivedOrientation(Ogre::Quaternion(rot.w, rot.x, rot.y, rot.z));
#endif
}
void EC_WaterPlane::ChangeWaterPlane(IAttribute* attribute)
{
std::string name = attribute->GetNameString();
if ( ( name == xSizeAttr_.GetNameString()
|| name == ySizeAttr_.GetNameString()
|| name == scaleUfactorAttr_.GetNameString()
|| name == scaleVfactorAttr_.GetNameString() ) &&
( lastXsize_ != xSizeAttr_.Get() || lastYsize_ != ySizeAttr_.Get() ) )
{
RemoveWaterPlane();
CreateWaterPlane();
lastXsize_ = xSizeAttr_.Get();
lastYsize_ = ySizeAttr_.Get();
}
else if ( name == positionAttr_.GetNameString() )
{
// Change position
SetPosition();
}
else if ( name == rotationAttr_.GetNameString() )
{
// Change rotation
// Is there placeable component? If not use given rotation
//if ( dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get()) == 0 )
//{
SetOrientation();
//}
}
else if ( name == depthAttr_.GetNameString() )
{
// Change depth
// Currently do nothing..
}
else if ( name == materialNameAttr_.GetNameString())
{
//Change material
if ( entity_ != 0)
{
entity_->setMaterialName(materialNameAttr_.Get().toStdString().c_str());
}
}
}
ComponentPtr EC_WaterPlane::FindPlaceable() const
{
assert(framework_);
ComponentPtr comp;
if(!GetParentEntity())
return comp;
comp = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
return comp;
}
void EC_WaterPlane::AttachEntity()
{
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ((!entity_) || (!placeable) || attached_)
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node->addChild(node_);
node_->attachObject(entity_);
attached_ = true;
}
void EC_WaterPlane::DetachEntity()
{
OgreRenderer::EC_OgrePlaceable* placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable*>(FindPlaceable().get());
if ((!attached_) || (!entity_) || (!placeable))
return;
Ogre::SceneNode* node = placeable->GetSceneNode();
node_->detachObject(entity_);
node->removeChild(node_);
attached_ = false;
}
}
|
Fix for linux build.
|
Fix for linux build.
|
C++
|
apache-2.0
|
BogusCurry/tundra,pharos3d/tundra,antont/tundra,pharos3d/tundra,antont/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,jesterKing/naali,realXtend/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,jesterKing/naali,BogusCurry/tundra,antont/tundra,BogusCurry/tundra,pharos3d/tundra,antont/tundra,jesterKing/naali,realXtend/tundra,antont/tundra,jesterKing/naali,pharos3d/tundra,realXtend/tundra,realXtend/tundra,AlphaStaxLLC/tundra,jesterKing/naali,AlphaStaxLLC/tundra,antont/tundra,jesterKing/naali,jesterKing/naali,BogusCurry/tundra,antont/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,realXtend/tundra,realXtend/tundra
|
a1cab6d1d81e2e1aa485b75b09da9bdca925d54a
|
examples/apptest/example_apptest.cc
|
examples/apptest/example_apptest.cc
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "examples/apptest/example_service.mojom.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/application/application_test_base.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/environment/logging.h"
#include "mojo/public/cpp/system/macros.h"
namespace mojo {
namespace {
// Exemplifies ApplicationTestBase's application testing pattern.
class ExampleApplicationTest : public test::ApplicationTestBase {
public:
ExampleApplicationTest() : ApplicationTestBase() {}
~ExampleApplicationTest() override {}
protected:
// ApplicationTestBase:
void SetUp() override {
ApplicationTestBase::SetUp();
application_impl()->ConnectToService("mojo:example_service",
&example_service_);
}
ExampleServicePtr example_service_;
private:
MOJO_DISALLOW_COPY_AND_ASSIGN(ExampleApplicationTest);
};
struct PongCallback {
explicit PongCallback(uint16_t* pong_value) : pong_value(pong_value) {}
void Run(uint16_t value) const { *pong_value = value; }
uint16_t* pong_value;
};
TEST_F(ExampleApplicationTest, PingServiceToPong) {
uint16_t pong_value = 0u;
example_service_->Ping(1u, PongCallback(&pong_value));
EXPECT_TRUE(example_service_.WaitForIncomingMethodCall());
// Test making a call and receiving the reply.
EXPECT_EQ(1u, pong_value);
}
TEST_F(ExampleApplicationTest, CheckCommandLineArg) {
// Ensure the test runner passes along this example command line argument.
ASSERT_TRUE(application_impl()->HasArg("--example_apptest_arg"));
}
} // namespace
} // namespace mojo
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "examples/apptest/example_service.mojom.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/application/application_test_base.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/environment/logging.h"
#include "mojo/public/cpp/system/macros.h"
namespace mojo {
namespace {
// Exemplifies ApplicationTestBase's application testing pattern.
class ExampleApplicationTest : public test::ApplicationTestBase {
public:
ExampleApplicationTest() : ApplicationTestBase() {}
~ExampleApplicationTest() override {}
protected:
// ApplicationTestBase:
void SetUp() override {
ApplicationTestBase::SetUp();
application_impl()->ConnectToService("mojo:example_service",
&example_service_);
}
ExampleServicePtr example_service_;
private:
MOJO_DISALLOW_COPY_AND_ASSIGN(ExampleApplicationTest);
};
TEST_F(ExampleApplicationTest, PingServiceToPong) {
uint16_t pong_value = 0u;
example_service_->Ping(1u,
[&pong_value](uint16_t value) { pong_value = value; });
EXPECT_TRUE(example_service_.WaitForIncomingMethodCall());
// Test making a call and receiving the reply.
EXPECT_EQ(1u, pong_value);
}
TEST_F(ExampleApplicationTest, CheckCommandLineArg) {
// Ensure the test runner passes along this example command line argument.
ASSERT_TRUE(application_impl()->HasArg("--example_apptest_arg"));
}
} // namespace
} // namespace mojo
|
Use lambda instead of explicit struct in example_apptest
|
Use lambda instead of explicit struct in example_apptest
[email protected]
Review URL: https://codereview.chromium.org/910963002
|
C++
|
bsd-3-clause
|
afandria/mojo,collinjackson/mojo,afandria/mojo,afandria/mojo,afandria/mojo,chinmaygarde/mojo,chinmaygarde/mojo,chinmaygarde/mojo,collinjackson/mojo,jianglu/mojo,collinjackson/mojo,jianglu/mojo,jianglu/mojo,afandria/mojo,collinjackson/mojo,chinmaygarde/mojo,chinmaygarde/mojo,afandria/mojo,collinjackson/mojo,chinmaygarde/mojo,jianglu/mojo,afandria/mojo,jianglu/mojo,chinmaygarde/mojo,jianglu/mojo,jianglu/mojo,chinmaygarde/mojo,afandria/mojo,jianglu/mojo,collinjackson/mojo,collinjackson/mojo,chinmaygarde/mojo,collinjackson/mojo,collinjackson/mojo
|
5785ae5e8f7609abdce3cfbc0a0e13e71099fade
|
net/TcpConnection.cpp
|
net/TcpConnection.cpp
|
#include <simcode/net/TcpConnection.h>
#include <simcode/base/logger.h>
using namespace simcode;
using namespace net;
static const int DEF_HIGHWATERSIZE = 64*1024*1024;
TcpConnection::TcpConnection(EventLoop* loop, int connfd, const SockAddr& peerAddr, uint64_t id__):
loop_(loop),
socket_(connfd),
peerAddr_(peerAddr),
localAddr_(SockAddr(socket_.getLocalAddr())),
highWaterSize_(DEF_HIGHWATERSIZE),
isClosed_(false),
id_(id__),
read_able_(1)
{
socket_.setKeepAlive(true);
}
TcpConnection::~TcpConnection()
{
if (!isClosed_)
loop_->removeInLoop(socket_.sockfd());
}
void TcpConnection::run()
{
channel_.reset(new EventChannel(loop_, socket_.sockfd(), simex::bind(&TcpConnection::eventHandle, this, _1)));
channel_->tie(shared_from_this());
channel_->enableReading();
loop_->runInLoop(channel_);
}
void TcpConnection::eventHandle(EventChannel* ec)
{
if (channel_->isReading())
{
handleRead();
}
if (channel_->isWriting())
{
handleWrite();
}
else
{
//handle error
}
}
void TcpConnection::handleRead()
{
if (read_able_ == 0)
{
channel_->disableReading();
return;
}
// saved an ioctl()/FIONREAD call to tell how much to read
int fd = socket_.sockfd();
const size_t writable = 65536;
char tmpbuf[65536];
char extrabuf[65536];
struct iovec vec[2];
vec[0].iov_base = tmpbuf;
vec[0].iov_len = sizeof tmpbuf;
vec[1].iov_base = extrabuf;
vec[1].iov_len = sizeof extrabuf;
// when there is enough space in this buffer, don't read into extrabuf.
// when extrabuf is used, we read 128k-1 bytes at most.
const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1;
const ssize_t n = ::readv(fd, vec, iovcnt);
if (n < 0)
{
errcode_ = errno;
LOG_ERROR("read error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
this->close();
return;
}
else if (n == 0)
{
this->close();
return;
}
else if (static_cast<size_t>(n) <= writable)
{
readBuf_.append(tmpbuf, n);
}
else
{
readBuf_.append(tmpbuf, sizeof tmpbuf);
readBuf_.append(extrabuf, sizeof extrabuf);
}
messageCallback_(shared_from_this(), &readBuf_);
}
void TcpConnection::handleWrite()
{
// if (isClosed_) return;
if (writeBuf_.readableBytes() == 0)
{
ScopeLock lock(mutex_);
writeBuf_.changeIndex();
}
if (writeBuf_.readableBytes() != 0)
{
int fd = socket_.sockfd();
ssize_t n;
n = ::write(fd, writeBuf_.peek(), writeBuf_.readableBytes());
if (n > 0)
{
if (n < writeBuf_.readableBytes())
{
}
else
{
if (writeCompleteCallback_) writeCompleteCallback_(shared_from_this());
}
}
else
{
n = 0;
int e = errno;
errcode_ = e;
channel_->disableWriting();
if (errno != EWOULDBLOCK)
{
LOG_TRACE("write error|errmsg=%s|port=%d", strerror(errno), peerAddr().port());
if (errno == EPIPE || errno == ECONNRESET) // FIXME: any others?
{
//shutdown();
this->close();
return;
}
}
}
writeBuf_.seek(n);
if (writeBuf_.readableBytes() == 0)
{
writeBuf_.mutableReadBuf()->clear();
writeBuf_.resetSeek();
ScopeLock lock(mutex_);
if (writeBuf_.mutableWriteBuf()->empty())
{
channel_->disableWriting();
}
else
{
writeBuf_.changeIndex();
}
}
}
}
void TcpConnection::send(const char* data, size_t len)
{
if (!isClosed_)
{
ScopeLock lock(mutex_);
writeBuf_.append(data, len);
//HighWater
if (writeBuf_.mutableWriteBuf()->size() > highWaterSize_)
{
if (!highWaterCallback_)
{
writeBuf_.mutableWriteBuf()->clear();
return;
}
else
{
highWaterCallback_(shared_from_this(), &writeBuf_);
return;
}
}
channel_->enableWriting();
}
//handleWrite();
}
void TcpConnection::sendString(const std::string& data)
{
if (!isClosed_)
{
ScopeLock lock(mutex_);
writeBuf_.append(data);
if (writeBuf_.mutableWriteBuf()->size() > highWaterSize_)
{
if (!highWaterCallback_)
{
writeBuf_.mutableWriteBuf()->clear();
return;
}
else
{
highWaterCallback_(shared_from_this(), &writeBuf_);
return;
}
}
channel_->enableWriting();
}
}
void TcpConnection::close()
{
if (isClosed_) return;
isClosed_ = true;
//shutdown();
loop_->removeInLoop(socket_.sockfd());
onClose();
//if (closeCallback_) loop_->addTask(simex::bind(&TcpConnection::onClose, this));
}
void TcpConnection::onClose()
{
if (closeCallback_)
closeCallback_(shared_from_this());
}
|
#include <simcode/net/TcpConnection.h>
#include <simcode/base/logger.h>
using namespace simcode;
using namespace net;
static const int DEF_HIGHWATERSIZE = 64*1024*1024;
TcpConnection::TcpConnection(EventLoop* loop, int connfd, const SockAddr& peerAddr, uint64_t id__):
loop_(loop),
socket_(connfd),
peerAddr_(peerAddr),
localAddr_(SockAddr(socket_.getLocalAddr())),
highWaterSize_(DEF_HIGHWATERSIZE),
isClosed_(false),
id_(id__),
read_able_(1)
{
socket_.setKeepAlive(true);
}
TcpConnection::~TcpConnection()
{
if (!isClosed_)
loop_->removeInLoop(socket_.sockfd());
}
void TcpConnection::run()
{
channel_.reset(new EventChannel(loop_, socket_.sockfd(), simex::bind(&TcpConnection::eventHandle, this, _1)));
channel_->tie(shared_from_this());
channel_->enableReading();
loop_->runInLoop(channel_);
}
void TcpConnection::eventHandle(EventChannel* ec)
{
if (channel_->isReading())
{
handleRead();
}
if (channel_->isWriting())
{
handleWrite();
}
else
{
//handle error
}
}
void TcpConnection::handleRead()
{
if (read_able_ == 0)
{
channel_->disableReading();
return;
}
// saved an ioctl()/FIONREAD call to tell how much to read
int fd = socket_.sockfd();
const size_t writable = 65536;
char tmpbuf[65536];
char extrabuf[65536];
struct iovec vec[2];
vec[0].iov_base = tmpbuf;
vec[0].iov_len = sizeof tmpbuf;
vec[1].iov_base = extrabuf;
vec[1].iov_len = sizeof extrabuf;
// when there is enough space in this buffer, don't read into extrabuf.
// when extrabuf is used, we read 128k-1 bytes at most.
const int iovcnt = (writable < sizeof extrabuf) ? 2 : 1;
const ssize_t n = ::readv(fd, vec, iovcnt);
if (n < 0)
{
errcode_ = errno;
LOG_ERROR("read error|errno=%d|errmsg=%s", errcode_, strerror(errcode_));
//this->close();
return;
}
else if (n == 0)
{
this->close();
return;
}
else if (static_cast<size_t>(n) <= writable)
{
readBuf_.append(tmpbuf, n);
}
else
{
readBuf_.append(tmpbuf, sizeof tmpbuf);
readBuf_.append(extrabuf, sizeof extrabuf);
}
messageCallback_(shared_from_this(), &readBuf_);
}
void TcpConnection::handleWrite()
{
// if (isClosed_) return;
if (writeBuf_.readableBytes() == 0)
{
ScopeLock lock(mutex_);
writeBuf_.changeIndex();
}
if (writeBuf_.readableBytes() != 0)
{
int fd = socket_.sockfd();
ssize_t n;
n = ::write(fd, writeBuf_.peek(), writeBuf_.readableBytes());
if (n > 0)
{
if (n < writeBuf_.readableBytes())
{
}
else
{
if (writeCompleteCallback_) writeCompleteCallback_(shared_from_this());
}
}
else
{
n = 0;
int e = errno;
errcode_ = e;
channel_->disableWriting();
if (errno != EWOULDBLOCK)
{
LOG_TRACE("write error|errmsg=%s|port=%d", strerror(errno), peerAddr().port());
if (errno == EPIPE || errno == ECONNRESET) // FIXME: any others?
{
//shutdown();
this->close();
return;
}
}
}
writeBuf_.seek(n);
if (writeBuf_.readableBytes() == 0)
{
writeBuf_.mutableReadBuf()->clear();
writeBuf_.resetSeek();
ScopeLock lock(mutex_);
if (writeBuf_.mutableWriteBuf()->empty())
{
channel_->disableWriting();
}
else
{
writeBuf_.changeIndex();
}
}
}
}
void TcpConnection::send(const char* data, size_t len)
{
if (!isClosed_)
{
ScopeLock lock(mutex_);
writeBuf_.append(data, len);
//HighWater
if (writeBuf_.mutableWriteBuf()->size() > highWaterSize_)
{
if (!highWaterCallback_)
{
writeBuf_.mutableWriteBuf()->clear();
return;
}
else
{
highWaterCallback_(shared_from_this(), &writeBuf_);
return;
}
}
channel_->enableWriting();
}
//handleWrite();
}
void TcpConnection::sendString(const std::string& data)
{
if (!isClosed_)
{
ScopeLock lock(mutex_);
writeBuf_.append(data);
if (writeBuf_.mutableWriteBuf()->size() > highWaterSize_)
{
if (!highWaterCallback_)
{
writeBuf_.mutableWriteBuf()->clear();
return;
}
else
{
highWaterCallback_(shared_from_this(), &writeBuf_);
return;
}
}
channel_->enableWriting();
}
}
void TcpConnection::close()
{
if (isClosed_) return;
isClosed_ = true;
//shutdown();
loop_->removeInLoop(socket_.sockfd());
onClose();
//if (closeCallback_) loop_->addTask(simex::bind(&TcpConnection::onClose, this));
}
void TcpConnection::onClose()
{
if (closeCallback_)
closeCallback_(shared_from_this());
}
|
remove close from handRead when readn<0
|
remove close from handRead when readn<0
|
C++
|
mit
|
jettyu/simcode,jettyu/simcode,jettyu/simcode
|
6889b9bd39b3ed7059815fabd49d42d2e9261617
|
src/lineFollowing/lineFollowing.cpp
|
src/lineFollowing/lineFollowing.cpp
|
/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
printf("Hello, this is Caleb\n");
VideoCapture cap("videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
}
|
/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
// printf("Hello, this is Caleb\n");
VideoCapture cap("videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
namedWindow("linesH", CV_WINDOW_NORMAL);
Mat edges;
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
|
test code
|
test code
Former-commit-id: 96b6310f25f8545cb0ad445cb39e8d30b6e971b5 [formerly 7ebc8f3d7084e6400df328b380cf7145d83a3283]
Former-commit-id: 0a4c31c258c996d7f7dbb19a862845fb71c316e9
|
C++
|
bsd-3-clause
|
tourdrone/cvdrone,tourdrone/cvdrone
|
d21d74f3b145c71f4ae6944155ae71af58eb30f2
|
include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.hxx
|
include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.hxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkBlockMatchingOptimizingInterpolationDisplacementCalculator_hxx
#define itkBlockMatchingOptimizingInterpolationDisplacementCalculator_hxx
#include "itkImageRegionConstIteratorWithIndex.h"
namespace itk
{
namespace BlockMatching
{
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationDisplacementCalculator()
{
m_CostFunction = OptimizingInterpolationCostFunction::New();
// @todo sensible default optimizer and interpolator
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
void
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::SetMetricImagePixel(
const PointType & centerPoint,
const IndexType & displacementIndex,
MetricImageType * metricImage)
{
Superclass::SetMetricImagePixel(centerPoint, displacementIndex, metricImage);
// Find index of the maximum value.
PixelType max = NumericTraits<PixelType>::min();
IndexType maxIndex;
maxIndex.Fill(0);
const typename MetricImageType::RegionType region = metricImage->GetBufferedRegion();
itk::ImageRegionConstIteratorWithIndex<MetricImageType> it(metricImage, region);
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
if (it.Get() > max)
{
max = it.Get();
maxIndex = it.GetIndex();
}
}
// If the maxIndex is on the edge of the image we don't try interpolation.
bool onEdge = false;
IndexType metricIndex = region.GetIndex();
const typename MetricImageType::SizeType metricSize = region.GetSize();
for (unsigned int i = 0; i < ImageDimension; ++i)
{
if (maxIndex[i] == metricIndex[i] ||
maxIndex[i] == metricIndex[i] + static_cast<typename IndexType::IndexValueType>(metricSize[i]))
{
onEdge = true;
break;
}
}
PointType maxPoint;
if (onEdge)
{
metricImage->TransformIndexToPhysicalPoint(maxIndex, maxPoint);
}
else
{
typename OptimizingInterpolationCostFunction::ParametersType parameters(ImageDimension);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
parameters[i] = static_cast<typename OptimizingInterpolationCostFunction::ParametersValueType>(maxIndex[i]);
}
m_Optimizer->SetInitialPosition(parameters);
// Is this the right offset?
for (unsigned int i = 0; i < ImageDimension; i++)
parameters[i] += 0.1;
m_CostFunction->Initialize(parameters);
m_CostFunction->GetInterpolator()->SetInputImage(metricImage);
m_Optimizer->StartOptimization();
parameters = m_Optimizer->GetCurrentPosition();
ContinuousIndexType continuousIndex;
for (unsigned int i = 0; i < ImageDimension; i++)
{
continuousIndex[i] = parameters[i];
}
metricImage->TransformContinuousIndexToPhysicalPoint(continuousIndex, maxPoint);
}
this->m_DisplacementImage->SetPixel(displacementIndex, maxPoint - centerPoint);
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction ::OptimizingInterpolationCostFunction()
{
// This is needed to compile :S
this->m_ContinuousIndexPtr = this->m_ContinuousIndex.GetDataPointer();
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
typename OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::MeasureType
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::GetValue(const ParametersType & parameters) const
{
for (unsigned int i = 0; i < ImageDimension; i++)
{
m_ContinuousIndexPtr[i] = parameters[i];
}
MeasureType measure = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
return measure;
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
void
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::GetDerivative(const ParametersType & parameters,
DerivativeType & derivative) const
{
MeasureType value;
MeasureType centerValue;
TCoordRep delta;
for (unsigned int i = 0; i < ImageDimension; ++i)
{
m_ContinuousIndexPtr[i] = parameters[i];
}
centerValue = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
const static double acceptibleValue = 100 * NumericTraits<double>::epsilon();
delta = parameters[i] - m_PreviousParameters[i];
if (std::abs(delta) > acceptibleValue)
{
m_ContinuousIndexPtr[i] += delta;
value = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
derivative[i] = (value - centerValue) / delta;
}
else
{
derivative[i] = 0.0;
}
m_ContinuousIndexPtr[i] = parameters[i];
}
for (unsigned int i = 0; i < ImageDimension; ++i)
{
m_PreviousParametersPtr[i] = parameters[i];
}
}
} // end namespace BlockMatching
} // end namespace itk
#endif
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkBlockMatchingOptimizingInterpolationDisplacementCalculator_hxx
#define itkBlockMatchingOptimizingInterpolationDisplacementCalculator_hxx
#include "itkImageRegionConstIteratorWithIndex.h"
namespace itk
{
namespace BlockMatching
{
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationDisplacementCalculator()
{
m_CostFunction = OptimizingInterpolationCostFunction::New();
// @todo sensible default optimizer and interpolator
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
void
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::SetMetricImagePixel(
const PointType & centerPoint,
const IndexType & displacementIndex,
MetricImageType * metricImage)
{
Superclass::SetMetricImagePixel(centerPoint, displacementIndex, metricImage);
// Find index of the maximum value.
PixelType max = NumericTraits<PixelType>::min();
IndexType maxIndex;
maxIndex.Fill(0);
const typename MetricImageType::RegionType region = metricImage->GetBufferedRegion();
itk::ImageRegionConstIteratorWithIndex<MetricImageType> it(metricImage, region);
for (it.GoToBegin(); !it.IsAtEnd(); ++it)
{
if (it.Get() > max)
{
max = it.Get();
maxIndex = it.GetIndex();
}
}
// If the maxIndex is on the edge of the image we don't try interpolation.
bool onEdge = false;
IndexType metricIndex = region.GetIndex();
const typename MetricImageType::SizeType metricSize = region.GetSize();
for (unsigned int i = 0; i < ImageDimension; ++i)
{
if (maxIndex[i] == metricIndex[i] ||
maxIndex[i] == metricIndex[i] + static_cast<typename IndexType::IndexValueType>(metricSize[i]))
{
onEdge = true;
break;
}
}
PointType maxPoint;
if (onEdge)
{
metricImage->TransformIndexToPhysicalPoint(maxIndex, maxPoint);
}
else
{
typename OptimizingInterpolationCostFunction::ParametersType parameters(ImageDimension);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
parameters[i] = static_cast<typename OptimizingInterpolationCostFunction::ParametersValueType>(maxIndex[i]);
}
m_Optimizer->SetInitialPosition(parameters);
// Is this the right offset?
for (unsigned int i = 0; i < ImageDimension; i++)
parameters[i] += 0.1;
m_CostFunction->Initialize(parameters);
const_cast<InterpolatorType*>(m_CostFunction->GetInterpolator())->SetInputImage(metricImage);
m_Optimizer->StartOptimization();
parameters = m_Optimizer->GetCurrentPosition();
ContinuousIndexType continuousIndex;
for (unsigned int i = 0; i < ImageDimension; i++)
{
continuousIndex[i] = parameters[i];
}
metricImage->TransformContinuousIndexToPhysicalPoint(continuousIndex, maxPoint);
}
this->m_DisplacementImage->SetPixel(displacementIndex, maxPoint - centerPoint);
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction ::OptimizingInterpolationCostFunction()
{
// This is needed to compile :S
this->m_ContinuousIndexPtr = this->m_ContinuousIndex.GetDataPointer();
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
typename OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::MeasureType
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::GetValue(const ParametersType & parameters) const
{
for (unsigned int i = 0; i < ImageDimension; i++)
{
m_ContinuousIndexPtr[i] = parameters[i];
}
MeasureType measure = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
return measure;
}
template <class TMetricImage, class TDisplacementImage, class TCoordRep>
void
OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::
OptimizingInterpolationCostFunction::GetDerivative(const ParametersType & parameters,
DerivativeType & derivative) const
{
MeasureType value;
MeasureType centerValue;
TCoordRep delta;
for (unsigned int i = 0; i < ImageDimension; ++i)
{
m_ContinuousIndexPtr[i] = parameters[i];
}
centerValue = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
for (unsigned int i = 0; i < ImageDimension; ++i)
{
const static double acceptibleValue = 100 * NumericTraits<double>::epsilon();
delta = parameters[i] - m_PreviousParameters[i];
if (std::abs(delta) > acceptibleValue)
{
m_ContinuousIndexPtr[i] += delta;
value = -1 * m_Interpolator->EvaluateAtContinuousIndex(m_ContinuousIndex);
derivative[i] = (value - centerValue) / delta;
}
else
{
derivative[i] = 0.0;
}
m_ContinuousIndexPtr[i] = parameters[i];
}
for (unsigned int i = 0; i < ImageDimension; ++i)
{
m_PreviousParametersPtr[i] = parameters[i];
}
}
} // end namespace BlockMatching
} // end namespace itk
#endif
|
Fix -fpermissive error in OptimizingInterpolationDisplacementCalculator
|
COMP: Fix -fpermissive error in OptimizingInterpolationDisplacementCalculator
This commit fixes the following error reported when building
SlicerITKUltrasound extension againg Slicer 4.13 and ITK 5.3:
In file included from /path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.h:202,
from /path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingDisplacementPipeline.h:39,
from /path/to/SlicerITKUltrasound/GenerateDisplacementFromFrames/GenerateDisplacementFromFrames.cxx:25:
/path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.hxx: In instantiation of ‘void itk::BlockMatching::OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::SetMetricImagePixel(const PointType&, const IndexType&, itk::BlockMatching::OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::MetricImageType*) [with TMetricImage = itk::Image<float, 2>; TDisplacementImage = itk::Image<itk::Vector<float, 2>, 2>; TCoordRep = double; itk::BlockMatching::OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::PointType = itk::Point<double, 2>; itk::BlockMatching::OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::IndexType = itk::Index<2>; itk::BlockMatching::OptimizingInterpolationDisplacementCalculator<TMetricImage, TDisplacementImage, TCoordRep>::MetricImageType = itk::Image<float, 2>]’:
/path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.hxx:41:1: required from here
/path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingOptimizingInterpolationDisplacementCalculator.hxx:95:5: error: passing ‘const InterpolatorType’ {aka ‘const itk::InterpolateImageFunction<itk::Image<float, 2>, double>’} as ‘this’ argument discards qualifiers [-fpermissive]
95 | m_CostFunction->GetInterpolator()->SetInputImage(metricImage);
| ^~~~~~~~~~~~~~
In file included from /path/to/Slicer-Release/ITK/Modules/Core/ImageFunction/include/itkImageFunction.h:229,
from /path/to/Slicer-Release/ITK/Modules/Core/ImageFunction/include/itkInterpolateImageFunction.h:21,
from /path/to/Slicer-Release/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.h:23,
from /path/to/SlicerITKUltrasound-Release/ITKUltrasound/include/itkBlockMatchingDisplacementPipeline.h:26,
from /path/to/SlicerITKUltrasound/GenerateDisplacementFromFrames/GenerateDisplacementFromFrames.cxx:25:
/path/to/Slicer-Release/ITK/Modules/Core/ImageFunction/include/itkImageFunction.hxx:57:1: note: in call to ‘void itk::ImageFunction<TInputImage, TOutput, TCoordRep>::SetInputImage(const InputImageType*) [with TInputImage = itk::Image<float, 2>; TOutput = double; TCoordRep = double; itk::ImageFunction<TInputImage, TOutput, TCoordRep>::InputImageType = itk::Image<float, 2>]’
57 | ImageFunction<TInputImage, TOutput, TCoordRep>::SetInputImage(const InputImageType * ptr)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
C++
|
apache-2.0
|
KitwareMedical/ITKUltrasound,KitwareMedical/ITKUltrasound,KitwareMedical/ITKUltrasound
|
50629c1d76780dc0c37c24b1dedb7794f4aa5447
|
src/mlpack/methods/det/dt_utils.cpp
|
src/mlpack/methods/det/dt_utils.cpp
|
/**
* @file dt_utils.cpp
* @author Parikshit Ram ([email protected])
*
* This file implements functions to perform different tasks with the Density
* Tree class.
*/
#include "dt_utils.hpp"
using namespace mlpack;
using namespace det;
void mlpack::det::PrintLeafMembership(DTree* dtree,
const arma::mat& data,
const arma::Mat<size_t>& labels,
const size_t numClasses,
const std::string leafClassMembershipFile)
{
// Tag the leaves with numbers.
int numLeaves = dtree->TagTree();
arma::Mat<size_t> table(numLeaves, (numClasses + 1));
table.zeros();
for (size_t i = 0; i < data.n_cols; i++)
{
const arma::vec testPoint = data.unsafe_col(i);
const int leafTag = dtree->FindBucket(testPoint);
const size_t label = labels[i];
table(leafTag, label) += 1;
}
if (leafClassMembershipFile == "")
{
Log::Info << "Leaf membership; row represents leaf id, column represents "
<< "class id; value represents number of points in leaf in class."
<< std::endl << table;
}
else
{
// Create a stream for the file.
std::ofstream outfile(leafClassMembershipFile.c_str());
if (outfile.good())
{
outfile << table;
Log::Info << "Leaf membership printed to '" << leafClassMembershipFile
<< "'." << std::endl;
}
else
{
Log::Warn << "Can't open '" << leafClassMembershipFile << "' to write "
<< "leaf membership to." << std::endl;
}
outfile.close();
}
return;
}
void mlpack::det::PrintVariableImportance(const DTree* dtree,
const std::string viFile)
{
arma::vec imps;
dtree->ComputeVariableImportance(imps);
double max = 0.0;
for (size_t i = 0; i < imps.n_elem; ++i)
if (imps[i] > max)
max = imps[i];
Log::Info << "Maximum variable importance: " << max << "." << std::endl;
if (viFile == "")
{
Log::Info << "Variable importance: " << std::endl << imps.t() << std::endl;
}
else
{
std::ofstream outfile(viFile.c_str());
if (outfile.good())
{
outfile << imps;
Log::Info << "Variable importance printed to '" << viFile << "'."
<< std::endl;
}
else
{
Log::Warn << "Can't open '" << viFile << "' to write variable importance "
<< "to." << std::endl;
}
outfile.close();
}
}
// This function trains the optimal decision tree using the given number of
// folds.
DTree* mlpack::det::Trainer(arma::mat& dataset,
const size_t folds,
const bool useVolumeReg,
const size_t maxLeafSize,
const size_t minLeafSize,
const std::string unprunedTreeOutput)
{
// Initialize the tree.
DTree dtree(dataset);
// Prepare to grow the tree...
arma::Col<size_t> oldFromNew(dataset.n_cols);
for (size_t i = 0; i < oldFromNew.n_elem; i++)
oldFromNew[i] = i;
// Save the dataset since it would be modified while growing the tree.
arma::mat newDataset(dataset);
// Growing the tree
double oldAlpha = 0.0;
double alpha = dtree.Grow(newDataset, oldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
Log::Info << dtree.SubtreeLeaves() << " leaf nodes in the tree using full "
<< "dataset; minimum alpha: " << alpha << "." << std::endl;
// Compute densities for the training points in the full tree, if we were
// asked for this.
if (unprunedTreeOutput != "")
{
std::ofstream outfile(unprunedTreeOutput.c_str());
if (outfile.good())
{
for (size_t i = 0; i < dataset.n_cols; ++i)
{
arma::vec testPoint = dataset.unsafe_col(i);
outfile << dtree.ComputeValue(testPoint) << std::endl;
}
}
else
{
Log::Warn << "Can't open '" << unprunedTreeOutput << "' to write computed"
<< " densities to." << std::endl;
}
outfile.close();
}
// Sequentially prune and save the alpha values and the values of c_t^2 * r_t.
std::vector<std::pair<double, double> > prunedSequence;
while (dtree.SubtreeLeaves() > 1)
{
std::pair<double, double> treeSeq(oldAlpha,
dtree.SubtreeLeavesLogNegError());
prunedSequence.push_back(treeSeq);
oldAlpha = alpha;
alpha = dtree.PruneAndUpdate(oldAlpha, dataset.n_cols, useVolumeReg);
// Some sanity checks. It seems that on some datasets, the error does not
// increase as the tree is pruned but instead stays the same---hence the
// "<=" in the final assert.
Log::Assert((alpha < std::numeric_limits<double>::max()) ||
(dtree.SubtreeLeaves() == 1));
Log::Assert(alpha > oldAlpha);
Log::Assert(dtree.SubtreeLeavesLogNegError() <= treeSeq.second);
}
std::pair<double, double> treeSeq(oldAlpha,
dtree.SubtreeLeavesLogNegError());
prunedSequence.push_back(treeSeq);
Log::Info << prunedSequence.size() << " trees in the sequence; maximum alpha:"
<< " " << oldAlpha << "." << std::endl;
arma::mat cvData(dataset);
size_t testSize = dataset.n_cols / folds;
arma::vec regularizationConstants(prunedSequence.size());
regularizationConstants.fill(0.0);
Timer::Start("cross_validation");
// Go through each fold.
#pragma omp parallel for default(none) \
shared(testSize, cvData, prunedSequence, regularizationConstants, dataset)
for (size_t fold = 0; fold < folds; fold++)
{
// Break up data into train and test sets.
size_t start = fold * testSize;
size_t end = std::min((fold + 1) * testSize, (size_t) cvData.n_cols);
arma::mat test = cvData.cols(start, end - 1);
arma::mat train(cvData.n_rows, cvData.n_cols - test.n_cols);
if (start == 0 && end < cvData.n_cols)
{
train.cols(0, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1);
}
else if (start > 0 && end == cvData.n_cols)
{
train.cols(0, train.n_cols - 1) = cvData.cols(0, start - 1);
}
else
{
train.cols(0, start - 1) = cvData.cols(0, start - 1);
train.cols(start, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1);
}
// Initialize the tree.
DTree cvDTree(train);
// Getting ready to grow the tree...
arma::Col<size_t> cvOldFromNew(train.n_cols);
for (size_t i = 0; i < cvOldFromNew.n_elem; i++)
cvOldFromNew[i] = i;
// Grow the tree.
cvDTree.Grow(train, cvOldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
// Sequentially prune with all the values of available alphas and adding
// values for test values. Don't enter this loop if there are less than two
// trees in the pruned sequence.
arma::vec cvRegularizationConstants(prunedSequence.size());
cvRegularizationConstants.fill(0.0);
for (size_t i = 0;
i < ((prunedSequence.size() < 2) ? 0 : prunedSequence.size() - 2); ++i)
{
// Compute test values for this state of the tree.
double cvVal = 0.0;
for (size_t j = 0; j < test.n_cols; j++)
{
arma::vec testPoint = test.unsafe_col(j);
cvVal += cvDTree.ComputeValue(testPoint);
}
// Update the cv regularization constant.
cvRegularizationConstants[i] += 2.0 * cvVal / (double) dataset.n_cols;
// Determine the new alpha value and prune accordingly.
double cvOldAlpha = 0.5 * (prunedSequence[i + 1].first +
prunedSequence[i + 2].first);
cvDTree.PruneAndUpdate(cvOldAlpha, train.n_cols, useVolumeReg);
}
// Compute test values for this state of the tree.
double cvVal = 0.0;
for (size_t i = 0; i < test.n_cols; ++i)
{
arma::vec testPoint = test.unsafe_col(i);
cvVal += cvDTree.ComputeValue(testPoint);
}
if (prunedSequence.size() > 2)
cvRegularizationConstants[prunedSequence.size() - 2] += 2.0 * cvVal /
(double) dataset.n_cols;
#pragma omp critical
regularizationConstants += cvRegularizationConstants;
}
Timer::Stop("cross_validation");
double optimalAlpha = -1.0;
long double cvBestError = -std::numeric_limits<long double>::max();
for (size_t i = 0; i < prunedSequence.size() - 1; ++i)
{
// We can no longer work in the log-space for this because we have no
// guarantee the quantity will be positive.
long double thisError = -std::exp((long double) prunedSequence[i].second) +
(long double) regularizationConstants[i];
if (thisError > cvBestError)
{
cvBestError = thisError;
optimalAlpha = prunedSequence[i].first;
}
}
Log::Info << "Optimal alpha: " << optimalAlpha << "." << std::endl;
// Initialize the tree.
DTree* dtreeOpt = new DTree(dataset);
// Getting ready to grow the tree...
for (size_t i = 0; i < oldFromNew.n_elem; i++)
oldFromNew[i] = i;
// Save the dataset since it would be modified while growing the tree.
newDataset = dataset;
// Grow the tree.
oldAlpha = -DBL_MAX;
alpha = dtreeOpt->Grow(newDataset, oldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
// Prune with optimal alpha.
while ((oldAlpha < optimalAlpha) && (dtreeOpt->SubtreeLeaves() > 1))
{
oldAlpha = alpha;
alpha = dtreeOpt->PruneAndUpdate(oldAlpha, newDataset.n_cols, useVolumeReg);
// Some sanity checks.
Log::Assert((alpha < std::numeric_limits<double>::max()) ||
(dtreeOpt->SubtreeLeaves() == 1));
Log::Assert(alpha > oldAlpha);
}
Log::Info << dtreeOpt->SubtreeLeaves() << " leaf nodes in the optimally "
<< "pruned tree; optimal alpha: " << oldAlpha << "." << std::endl;
return dtreeOpt;
}
|
/**
* @file dt_utils.cpp
* @author Parikshit Ram ([email protected])
*
* This file implements functions to perform different tasks with the Density
* Tree class.
*/
#include "dt_utils.hpp"
using namespace mlpack;
using namespace det;
void mlpack::det::PrintLeafMembership(DTree* dtree,
const arma::mat& data,
const arma::Mat<size_t>& labels,
const size_t numClasses,
const std::string leafClassMembershipFile)
{
// Tag the leaves with numbers.
int numLeaves = dtree->TagTree();
arma::Mat<size_t> table(numLeaves, (numClasses + 1));
table.zeros();
for (size_t i = 0; i < data.n_cols; i++)
{
const arma::vec testPoint = data.unsafe_col(i);
const int leafTag = dtree->FindBucket(testPoint);
const size_t label = labels[i];
table(leafTag, label) += 1;
}
if (leafClassMembershipFile == "")
{
Log::Info << "Leaf membership; row represents leaf id, column represents "
<< "class id; value represents number of points in leaf in class."
<< std::endl << table;
}
else
{
// Create a stream for the file.
std::ofstream outfile(leafClassMembershipFile.c_str());
if (outfile.good())
{
outfile << table;
Log::Info << "Leaf membership printed to '" << leafClassMembershipFile
<< "'." << std::endl;
}
else
{
Log::Warn << "Can't open '" << leafClassMembershipFile << "' to write "
<< "leaf membership to." << std::endl;
}
outfile.close();
}
return;
}
void mlpack::det::PrintVariableImportance(const DTree* dtree,
const std::string viFile)
{
arma::vec imps;
dtree->ComputeVariableImportance(imps);
double max = 0.0;
for (size_t i = 0; i < imps.n_elem; ++i)
if (imps[i] > max)
max = imps[i];
Log::Info << "Maximum variable importance: " << max << "." << std::endl;
if (viFile == "")
{
Log::Info << "Variable importance: " << std::endl << imps.t() << std::endl;
}
else
{
std::ofstream outfile(viFile.c_str());
if (outfile.good())
{
outfile << imps;
Log::Info << "Variable importance printed to '" << viFile << "'."
<< std::endl;
}
else
{
Log::Warn << "Can't open '" << viFile << "' to write variable importance "
<< "to." << std::endl;
}
outfile.close();
}
}
// This function trains the optimal decision tree using the given number of
// folds.
DTree* mlpack::det::Trainer(arma::mat& dataset,
const size_t folds,
const bool useVolumeReg,
const size_t maxLeafSize,
const size_t minLeafSize,
const std::string unprunedTreeOutput)
{
// Initialize the tree.
DTree dtree(dataset);
// Prepare to grow the tree...
arma::Col<size_t> oldFromNew(dataset.n_cols);
for (size_t i = 0; i < oldFromNew.n_elem; i++)
oldFromNew[i] = i;
// Save the dataset since it would be modified while growing the tree.
arma::mat newDataset(dataset);
// Growing the tree
double oldAlpha = 0.0;
double alpha = dtree.Grow(newDataset, oldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
Log::Info << dtree.SubtreeLeaves() << " leaf nodes in the tree using full "
<< "dataset; minimum alpha: " << alpha << "." << std::endl;
// Compute densities for the training points in the full tree, if we were
// asked for this.
if (unprunedTreeOutput != "")
{
std::ofstream outfile(unprunedTreeOutput.c_str());
if (outfile.good())
{
for (size_t i = 0; i < dataset.n_cols; ++i)
{
arma::vec testPoint = dataset.unsafe_col(i);
outfile << dtree.ComputeValue(testPoint) << std::endl;
}
}
else
{
Log::Warn << "Can't open '" << unprunedTreeOutput << "' to write computed"
<< " densities to." << std::endl;
}
outfile.close();
}
// Sequentially prune and save the alpha values and the values of c_t^2 * r_t.
std::vector<std::pair<double, double> > prunedSequence;
while (dtree.SubtreeLeaves() > 1)
{
std::pair<double, double> treeSeq(oldAlpha,
dtree.SubtreeLeavesLogNegError());
prunedSequence.push_back(treeSeq);
oldAlpha = alpha;
alpha = dtree.PruneAndUpdate(oldAlpha, dataset.n_cols, useVolumeReg);
// Some sanity checks. It seems that on some datasets, the error does not
// increase as the tree is pruned but instead stays the same---hence the
// "<=" in the final assert.
Log::Assert((alpha < std::numeric_limits<double>::max()) ||
(dtree.SubtreeLeaves() == 1));
Log::Assert(alpha > oldAlpha);
Log::Assert(dtree.SubtreeLeavesLogNegError() <= treeSeq.second);
}
std::pair<double, double> treeSeq(oldAlpha,
dtree.SubtreeLeavesLogNegError());
prunedSequence.push_back(treeSeq);
Log::Info << prunedSequence.size() << " trees in the sequence; maximum alpha:"
<< " " << oldAlpha << "." << std::endl;
arma::mat cvData(dataset);
size_t testSize = dataset.n_cols / folds;
arma::vec regularizationConstants(prunedSequence.size());
regularizationConstants.fill(0.0);
Timer::Start("cross_validation");
// Go through each fold. On the Visual Studio compiler, we have to use
// intmax_t because size_t is not yet supported by their OpenMP
// implementation.
#ifdef _WIN32
#pragma omp parallel for default(none) \
shared(testSize, cvData, prunedSequence, regularizationConstants, dataset)
for (intmax_t fold = 0; fold < (intmax_t) folds; fold++)
#else
#pragma omp parallel for default(none) \
shared(testSize, cvData, prunedSequence, regularizationConstants, dataset)
for (size_t fold = 0; fold < folds; fold++)
#endif
{
// Break up data into train and test sets.
size_t start = fold * testSize;
size_t end = std::min((fold + 1) * testSize, (size_t) cvData.n_cols);
arma::mat test = cvData.cols(start, end - 1);
arma::mat train(cvData.n_rows, cvData.n_cols - test.n_cols);
if (start == 0 && end < cvData.n_cols)
{
train.cols(0, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1);
}
else if (start > 0 && end == cvData.n_cols)
{
train.cols(0, train.n_cols - 1) = cvData.cols(0, start - 1);
}
else
{
train.cols(0, start - 1) = cvData.cols(0, start - 1);
train.cols(start, train.n_cols - 1) = cvData.cols(end, cvData.n_cols - 1);
}
// Initialize the tree.
DTree cvDTree(train);
// Getting ready to grow the tree...
arma::Col<size_t> cvOldFromNew(train.n_cols);
for (size_t i = 0; i < cvOldFromNew.n_elem; i++)
cvOldFromNew[i] = i;
// Grow the tree.
cvDTree.Grow(train, cvOldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
// Sequentially prune with all the values of available alphas and adding
// values for test values. Don't enter this loop if there are less than two
// trees in the pruned sequence.
arma::vec cvRegularizationConstants(prunedSequence.size());
cvRegularizationConstants.fill(0.0);
for (size_t i = 0;
i < ((prunedSequence.size() < 2) ? 0 : prunedSequence.size() - 2); ++i)
{
// Compute test values for this state of the tree.
double cvVal = 0.0;
for (size_t j = 0; j < test.n_cols; j++)
{
arma::vec testPoint = test.unsafe_col(j);
cvVal += cvDTree.ComputeValue(testPoint);
}
// Update the cv regularization constant.
cvRegularizationConstants[i] += 2.0 * cvVal / (double) dataset.n_cols;
// Determine the new alpha value and prune accordingly.
double cvOldAlpha = 0.5 * (prunedSequence[i + 1].first +
prunedSequence[i + 2].first);
cvDTree.PruneAndUpdate(cvOldAlpha, train.n_cols, useVolumeReg);
}
// Compute test values for this state of the tree.
double cvVal = 0.0;
for (size_t i = 0; i < test.n_cols; ++i)
{
arma::vec testPoint = test.unsafe_col(i);
cvVal += cvDTree.ComputeValue(testPoint);
}
if (prunedSequence.size() > 2)
cvRegularizationConstants[prunedSequence.size() - 2] += 2.0 * cvVal /
(double) dataset.n_cols;
#pragma omp critical
regularizationConstants += cvRegularizationConstants;
}
Timer::Stop("cross_validation");
double optimalAlpha = -1.0;
long double cvBestError = -std::numeric_limits<long double>::max();
for (size_t i = 0; i < prunedSequence.size() - 1; ++i)
{
// We can no longer work in the log-space for this because we have no
// guarantee the quantity will be positive.
long double thisError = -std::exp((long double) prunedSequence[i].second) +
(long double) regularizationConstants[i];
if (thisError > cvBestError)
{
cvBestError = thisError;
optimalAlpha = prunedSequence[i].first;
}
}
Log::Info << "Optimal alpha: " << optimalAlpha << "." << std::endl;
// Initialize the tree.
DTree* dtreeOpt = new DTree(dataset);
// Getting ready to grow the tree...
for (size_t i = 0; i < oldFromNew.n_elem; i++)
oldFromNew[i] = i;
// Save the dataset since it would be modified while growing the tree.
newDataset = dataset;
// Grow the tree.
oldAlpha = -DBL_MAX;
alpha = dtreeOpt->Grow(newDataset, oldFromNew, useVolumeReg, maxLeafSize,
minLeafSize);
// Prune with optimal alpha.
while ((oldAlpha < optimalAlpha) && (dtreeOpt->SubtreeLeaves() > 1))
{
oldAlpha = alpha;
alpha = dtreeOpt->PruneAndUpdate(oldAlpha, newDataset.n_cols, useVolumeReg);
// Some sanity checks.
Log::Assert((alpha < std::numeric_limits<double>::max()) ||
(dtreeOpt->SubtreeLeaves() == 1));
Log::Assert(alpha > oldAlpha);
}
Log::Info << dtreeOpt->SubtreeLeaves() << " leaf nodes in the optimally "
<< "pruned tree; optimal alpha: " << oldAlpha << "." << std::endl;
return dtreeOpt;
}
|
Handle MSVC compiler properly; Visual Studio only supports OpenMP 2.5. OpenMP 3.0 is where unsigned indices are supported.
|
Handle MSVC compiler properly; Visual Studio only supports OpenMP 2.5.
OpenMP 3.0 is where unsigned indices are supported.
See also:
https://github.com/VespucciProject/MLPACK_for_MSVC
http://stackoverflow.com/questions/2820621/why-arent-unsigned-openmp-index-variables-allowed
|
C++
|
bsd-3-clause
|
palashahuja/mlpack,palashahuja/mlpack,darcyliu/mlpack,ajjl/mlpack,ajjl/mlpack,darcyliu/mlpack,darcyliu/mlpack,palashahuja/mlpack,ranjan1990/mlpack,ranjan1990/mlpack,ajjl/mlpack,ranjan1990/mlpack
|
bc5a4395c9428ad98362305208feadc5c272abad
|
src/network/packages/udppackage.cpp
|
src/network/packages/udppackage.cpp
|
#include "../../../include/network/packages/udppackage.h"
#include <netinet/in.h>
#include <string.h>
#include "../../../include/helpers/helper.h"
namespace PCAP {
UDPPackage::UDPPackage(const unsigned char *p, unsigned int l, bool modify)
: IPPackage{p, l, modify} {
m_udp = (struct sniffudp*)(m_package + size_ethernet + 5*4);
m_data = &m_package[size_ethernet + 5 * 4 + sizeof(*m_udp)];
}
unsigned short UDPPackage::getSrcPort() const {
return ntohs(m_udp->m_th_sport);
}
unsigned short UDPPackage::getDstPort() const {
return ntohs(m_udp->m_th_dport);
}
unsigned short UDPPackage::getUDPLength() const {
return ntohs(m_udp->m_length);
}
void UDPPackage::setSrcPort(unsigned short src_port) {
m_udp->m_th_sport = htons(src_port);
}
void UDPPackage::setDstPort(unsigned short dst_port) {
m_udp->m_th_dport = htons(dst_port);
}
void UDPPackage::setUDPLength(unsigned short length) {
m_udp->m_length = htons(length);
}
void UDPPackage::recalculateChecksums() {
PCAPHelper::setIPChecksum(m_ip);
PCAPHelper::setUDPChecksum(m_ip, m_udp, nullptr);
}
const unsigned char* UDPPackage::getData() const {
return m_data;
}
unsigned int UDPPackage::getDataLength() const {
return ntohs(m_udp->m_length) - 8;
}
void UDPPackage::appendData(unsigned char* data, int size) {
memcpy(&m_package[getDataLength()], (char*)data, size);
m_ip->m_ip_len = htons(ntohs(m_ip->m_ip_len) + size);
m_udp->m_length = htons(ntohs(m_udp->m_length) + size);
}
unsigned int UDPPackage::getLength() const {
return sizeof(*m_ethernet) + ntohs(m_ip->m_ip_len);
}
bool operator==(const UDPPackage &lhs, const UDPPackage &rhs) {
return static_cast<const IPPackage&>(lhs) == static_cast<const IPPackage&>(rhs) &&
memcmp(lhs.m_udp, rhs.m_udp, sizeof(sniffudp)) == 0;
}
bool operator!=(const UDPPackage &lhs, const UDPPackage &rhs) {
return !(lhs == rhs);
}
}
|
#include "../../../include/network/packages/udppackage.h"
#include <netinet/in.h>
#include <string.h>
#include "../../../include/helpers/helper.h"
namespace PCAP {
UDPPackage::UDPPackage(const unsigned char *p, unsigned int l, bool modify)
: IPPackage{p, l, modify} {
m_udp = (struct sniffudp*)(m_package + size_ethernet + 5*4);
m_data = &m_package[size_ethernet + 5 * 4 + sizeof(*m_udp)];
}
unsigned short UDPPackage::getSrcPort() const {
return ntohs(m_udp->m_th_sport);
}
unsigned short UDPPackage::getDstPort() const {
return ntohs(m_udp->m_th_dport);
}
unsigned short UDPPackage::getUDPLength() const {
return ntohs(m_udp->m_length);
}
void UDPPackage::setSrcPort(unsigned short src_port) {
m_udp->m_th_sport = htons(src_port);
}
void UDPPackage::setDstPort(unsigned short dst_port) {
m_udp->m_th_dport = htons(dst_port);
}
void UDPPackage::setUDPLength(unsigned short length) {
m_udp->m_length = htons(length);
}
void UDPPackage::recalculateChecksums() {
PCAPHelper::setIPChecksum(m_ip);
PCAPHelper::setUDPChecksum(m_ip, m_udp, m_data);
}
const unsigned char* UDPPackage::getData() const {
return m_data;
}
unsigned int UDPPackage::getDataLength() const {
return ntohs(m_udp->m_length) - 8;
}
void UDPPackage::appendData(unsigned char* data, int size) {
memcpy(&m_package[getDataLength()], (char*)data, size);
m_ip->m_ip_len = htons(ntohs(m_ip->m_ip_len) + size);
m_udp->m_length = htons(ntohs(m_udp->m_length) + size);
}
unsigned int UDPPackage::getLength() const {
return sizeof(*m_ethernet) + ntohs(m_ip->m_ip_len);
}
bool operator==(const UDPPackage &lhs, const UDPPackage &rhs) {
return static_cast<const IPPackage&>(lhs) == static_cast<const IPPackage&>(rhs) &&
memcmp(lhs.m_udp, rhs.m_udp, sizeof(sniffudp)) == 0;
}
bool operator!=(const UDPPackage &lhs, const UDPPackage &rhs) {
return !(lhs == rhs);
}
}
|
Fix segmentation fault
|
Fix segmentation fault
|
C++
|
mit
|
jef42/pcapwrapper,jef42/pcapwrapper
|
407a1de4ae7525536e381388b722779af6e23ce7
|
src/paintown-engine/level/utils.cpp
|
src/paintown-engine/level/utils.cpp
|
#include "utils.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "util/load_exception.h"
#include "util/funcs.h"
#include "globals.h"
#include "util/debug.h"
namespace Level{
using namespace std;
LevelInfo::LevelInfo():
playerPath("players/"),
name("Level set"),
_loadingMessage("Loading Paintown"),
_loadingBackground(Global::titleScreen()),
background(0),
x(-1),
y(-1){
}
LevelInfo::LevelInfo(const LevelInfo & info){
this->levels = info.levels;
this->_loadingMessage = info._loadingMessage;
this->_loadingBackground = info._loadingBackground;
this->playerPath = info.getPlayerPath();
this->name = info.getName();
this->background = info.getBackground();
this->x = info.getPositionX();
this->y = info.getPositionY();
}
LevelInfo & LevelInfo::operator=(const LevelInfo & info){
this->levels = info.levels;
this->_loadingMessage = info._loadingMessage;
this->_loadingBackground = info._loadingBackground;
this->playerPath = info.getPlayerPath();
this->name = info.getName();
this->background = info.getBackground();
this->x = info.getPositionX();
this->y = info.getPositionY();
return *this;
}
void LevelInfo::setLoadingMessage(const std::string & str){
this->_loadingMessage = str;
}
void LevelInfo::setPosition(int x, int y){
this->x = x;
this->y = y;
}
const std::string & LevelInfo::loadingMessage() const {
return this->_loadingMessage;
}
const Filesystem::AbsolutePath & LevelInfo::loadingBackground() const {
return this->_loadingBackground;
}
const std::string & LevelInfo::getPlayerPath() const {
return this->playerPath;
}
void LevelInfo::addLevel(const string & s){
levels.push_back(s);
}
const vector<string> & LevelInfo::getLevels() const {
return levels;
}
void LevelInfo::setPlayerPath(const std::string & s){
this->playerPath = s;
}
void LevelInfo::setName(const std::string & s){
this->name = s;
}
const string & LevelInfo::getName() const {
return name;
}
LevelInfo::~LevelInfo(){
}
LevelInfo readLevel(const Token * level){
LevelInfo info;
try{
const Token * token_name = level->findToken("level-set/name");
const Token * token_levels = level->findToken("level-set/levels");
const Token * token_player = level->findToken("level-set/player-path");
string name;
token_name->view() >> name;
info.setName(name);
TokenView view = token_levels->view();
while (view.hasMore()){
const Token * next = 0;
view >> next;
Global::debug(1) << "Add level " << next->getName() << endl;
info.addLevel(next->getName());
}
} catch (const TokenException & e){
Global::debug( 0 ) << "Error while reading level set: " << e.getTrace() << endl;
}
return info;
}
#if 0
LevelInfo readLevels( const string & filename ){
LevelInfo info;
try{
TokenReader tr( filename );
Token * head = tr.readToken();
readName(&info, head->findToken("level-set/name"));
readLevels(&info, head->findToken("level-set/levels"));
readPlayerPath(&info, head->findToken("level-set/player-path"));
/*
if ( *head == "levels" ){
while (head->hasTokens()){
Token * next;
*head >> next;
/ * old way * /
if (!next->hasTokens()){
Global::debug(1) << "Add level " << next->getName() << endl;
info.addLevel(next->getName());
} else if (*next == "level"){
} else if (*next == "player-path"){
string s;
*next >> s;
Global::debug(1) << "Set player path to " << s << endl;
info.setPlayerPath(s);
}
}
}
*/
return info;
} catch ( const TokenException & lex ){
Global::debug( 0 ) << "Could not load " << filename << ". Reason: " << lex.getReason() << endl;
return info;
}
}
#endif
}
|
#include "utils.h"
#include "util/tokenreader.h"
#include "util/token.h"
#include "util/load_exception.h"
#include "util/funcs.h"
#include "globals.h"
#include "util/debug.h"
namespace Level{
using namespace std;
LevelInfo::LevelInfo():
playerPath("players/"),
name("Level set"),
_loadingMessage("Loading Paintown"),
_loadingBackground(Global::titleScreen()),
background(0),
x(-1),
y(-1){
}
LevelInfo::LevelInfo(const LevelInfo & info){
this->levels = info.levels;
this->_loadingMessage = info._loadingMessage;
this->_loadingBackground = info._loadingBackground;
this->playerPath = info.getPlayerPath();
this->name = info.getName();
this->background = info.getBackground();
this->x = info.getPositionX();
this->y = info.getPositionY();
}
LevelInfo & LevelInfo::operator=(const LevelInfo & info){
this->levels = info.levels;
this->_loadingMessage = info._loadingMessage;
this->_loadingBackground = info._loadingBackground;
this->playerPath = info.getPlayerPath();
this->name = info.getName();
this->background = info.getBackground();
this->x = info.getPositionX();
this->y = info.getPositionY();
return *this;
}
void LevelInfo::setLoadingMessage(const std::string & str){
this->_loadingMessage = str;
}
void LevelInfo::setPosition(int x, int y){
this->x = x;
this->y = y;
}
const std::string & LevelInfo::loadingMessage() const {
return this->_loadingMessage;
}
const Filesystem::AbsolutePath & LevelInfo::loadingBackground() const {
return this->_loadingBackground;
}
const std::string & LevelInfo::getPlayerPath() const {
return this->playerPath;
}
void LevelInfo::addLevel(const string & s){
levels.push_back(s);
}
const vector<string> & LevelInfo::getLevels() const {
return levels;
}
void LevelInfo::setPlayerPath(const std::string & s){
this->playerPath = s;
}
void LevelInfo::setName(const std::string & s){
this->name = s;
}
const string & LevelInfo::getName() const {
return name;
}
LevelInfo::~LevelInfo(){
}
LevelInfo readLevel(const Token * level){
LevelInfo info;
try{
const Token * token_levels = level->findToken("level-set/levels");
const Token * token_player = level->findToken("level-set/player-path");
string name;
if (level->match("level-set/name", name)){
info.setName(name);
}
string playerPath;
if (level->match("level-set/player-path", playerPath)){
info.setPlayerPath(playerPath);
}
TokenView view = token_levels->view();
while (view.hasMore()){
const Token * next = 0;
view >> next;
Global::debug(1) << "Add level " << next->getName() << endl;
info.addLevel(next->getName());
}
} catch (const TokenException & e){
Global::debug( 0 ) << "Error while reading level set: " << e.getTrace() << endl;
}
return info;
}
#if 0
LevelInfo readLevels( const string & filename ){
LevelInfo info;
try{
TokenReader tr( filename );
Token * head = tr.readToken();
readName(&info, head->findToken("level-set/name"));
readLevels(&info, head->findToken("level-set/levels"));
readPlayerPath(&info, head->findToken("level-set/player-path"));
/*
if ( *head == "levels" ){
while (head->hasTokens()){
Token * next;
*head >> next;
/ * old way * /
if (!next->hasTokens()){
Global::debug(1) << "Add level " << next->getName() << endl;
info.addLevel(next->getName());
} else if (*next == "level"){
} else if (*next == "player-path"){
string s;
*next >> s;
Global::debug(1) << "Set player path to " << s << endl;
info.setPlayerPath(s);
}
}
}
*/
return info;
} catch ( const TokenException & lex ){
Global::debug( 0 ) << "Could not load " << filename << ". Reason: " << lex.getReason() << endl;
return info;
}
}
#endif
}
|
set player path
|
[paintown] set player path
|
C++
|
bsd-3-clause
|
scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown,scristopher/paintown
|
c8f114aeb5ee5fcab00e9ab5281c138a8b8958ab
|
src/plugins/default_term_buffer.cpp
|
src/plugins/default_term_buffer.cpp
|
#include "plugin_base.h"
#include "default_term_buffer.h"
#include "default_term_line.h"
#include "default_term_cell.h"
#include "term_selection.h"
#include <vector>
#include <mutex>
class DefaultTermSelection : public virtual PluginBase, public virtual TermSelection {
public:
DefaultTermSelection() :
PluginBase("default_term_buffer_cpp", "default terminal buffer plugin", 1)
, m_RowBegin{0}
, m_ColBegin(0)
, m_RowEnd{0}
, m_ColEnd(0)
{
}
virtual ~DefaultTermSelection() = default;
uint32_t GetRowBegin() const override {
return m_RowBegin;
}
void SetRowBegin(uint32_t rowBegin) override {
m_RowBegin = rowBegin;
}
uint32_t GetColBegin() const override {
return m_ColBegin;
}
void SetColBegin(uint32_t colBegin) override {
m_ColBegin = colBegin;
}
uint32_t GetRowEnd() const override {
return m_RowEnd;
}
void SetRowEnd(uint32_t rowEnd) override {
m_RowEnd = rowEnd;
}
uint32_t GetColEnd() const override {
return m_ColEnd;
}
void SetColEnd(uint32_t colEnd) override {
m_ColEnd = colEnd;
}
private:
uint32_t m_RowBegin, m_ColBegin;
uint32_t m_RowEnd, m_ColEnd;
};
class DefaultTermBuffer : public virtual PluginBase, public virtual TermBuffer {
public:
DefaultTermBuffer() :
PluginBase("default_term_buffer", "default terminal buffer plugin", 0)
, m_ResizeLock{}
, m_Rows(0)
, m_Cols(0)
, m_CurRow(0)
, m_CurCol(0)
, m_ScrollRegionBegin(0)
, m_ScrollRegionEnd(0)
, m_Lines()
, m_DefaultChar(' ')
, m_DefaultForeColorIndex(TermCell::DefaultColorIndex)
, m_DefaultBackColorIndex(TermCell::DefaultColorIndex)
, m_DefaultMode(0)
, m_Selection{new DefaultTermSelection}
{
}
virtual ~DefaultTermBuffer() = default;
MultipleInstancePluginPtr NewInstance() override {
return MultipleInstancePluginPtr{new DefaultTermBuffer()};
}
void Resize(uint32_t row, uint32_t col) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
m_Rows = row;
m_Cols = col;
m_ScrollRegionBegin = 0;
m_ScrollRegionEnd = row - 1;
if (m_CurRow >= m_Rows)
m_CurRow = m_Rows - 1;
if (m_CurCol >= m_Cols)
m_CurCol = m_Cols - 1;
m_Lines.resize(m_Rows);
printf("----Resize buffer: rows=%u, %u, cols=%u,%u\n",
m_Rows, m_CurRow,
m_Cols, m_CurCol);
for (TermLineVector::iterator it = m_Lines.begin(),
it_end = m_Lines.end();
it != it_end;
it++)
{
if (*it)
(*it)->Resize(m_Cols);
}
}
uint32_t GetRows() const override {
return m_Rows;
}
uint32_t GetCols() const override {
return m_Cols;
}
uint32_t GetRow() const override {
return m_CurRow;
}
uint32_t GetCol() const override {
return m_CurCol;
}
void SetRow(uint32_t row) override {
m_CurRow = row;
}
void SetCol(uint32_t col) override {
m_CurCol = col;
}
TermLinePtr GetLine(uint32_t row) override {
if (row < GetRows()) {
auto line = m_Lines[row];
if (!line) {
line = CreateDefaultTermLine(this);
line->Resize(GetCols());
m_Lines[row] = line;
}
return line;
}
printf("row:%u, rows:%u\n", row, GetRows());
return TermLinePtr{};
}
TermCellPtr GetCell(uint32_t row, uint32_t col) override {
TermLinePtr line = GetLine(row);
if (line)
return line->GetCell(col);
return TermCellPtr{};
}
TermLinePtr GetCurLine() override {
return GetLine(GetRow());
}
TermCellPtr GetCurCell() override {
return GetCell(GetRow(), GetCol());
}
uint32_t GetScrollRegionBegin() const override {
return m_ScrollRegionBegin;
}
uint32_t GetScrollRegionEnd() const override {
return m_ScrollRegionEnd;
}
void SetScrollRegionBegin(uint32_t begin) override {
m_ScrollRegionBegin = begin;
}
void SetScrollRegionEnd(uint32_t end) override {
m_ScrollRegionEnd = end;
}
void DeleteLines(uint32_t begin, uint32_t count) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
if (begin + count > m_ScrollRegionEnd)
{
//Reset line directly
for (uint32_t i = begin;i <= m_ScrollRegionEnd; i++)
{
m_Lines[i]->Resize(0);
m_Lines[i]->Resize(GetCols());
}
return;
}
uint32_t end = begin + count;
TermLineVector::iterator b_it = m_Lines.begin() + begin,
e_it = m_Lines.begin() + end;
//Insert First, then delete
for (uint32_t i = begin; i < end; i++)
{
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
m_Lines.insert(e_it, term_line);
}
m_Lines.erase(b_it, e_it);
}
void InsertLines(uint32_t begin, uint32_t count) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
if (begin + count > m_ScrollRegionEnd)
{
//Reset line directly
for (uint32_t i = begin;i <= m_ScrollRegionEnd; i++)
{
m_Lines[i]->Resize(0);
m_Lines[i]->Resize(GetCols());
}
return;
}
TermLineVector::iterator b_it = m_Lines.begin() + m_ScrollRegionEnd - count + 1,
e_it = m_Lines.begin() + m_ScrollRegionEnd + 1;
m_Lines.erase(b_it, e_it);
b_it = m_Lines.begin() + begin;
for (uint32_t i = 0; i < count; i++)
{
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
m_Lines.insert(b_it, term_line);
}
}
void ScrollBuffer(int32_t scroll_offset) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
TermLineVector::iterator b_it = m_Lines.begin(),
e_it = m_Lines.end();
if (m_ScrollRegionBegin < m_ScrollRegionEnd) {
b_it = b_it + m_ScrollRegionBegin;
e_it = m_Lines.begin() + m_ScrollRegionEnd + 1;
}
if (scroll_offset < 0) {
for(int i=0;i < -scroll_offset;i++) {
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
m_Lines.insert(e_it, term_line);
}
m_Lines.erase(b_it, b_it - scroll_offset);
} else if (scroll_offset > 0) {
m_Lines.erase(e_it - scroll_offset, e_it);
for(int i=0;i < scroll_offset;i++) {
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
m_Lines.insert(b_it, term_line);
}
}
}
void MoveCurRow(uint32_t offset, bool move_down, bool scroll_buffer) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
uint32_t begin = 0, end = GetRows() - 1;
if (m_ScrollRegionBegin < m_ScrollRegionEnd) {
begin = m_ScrollRegionBegin;
end = m_ScrollRegionEnd;
}
if (move_down) {
if (m_CurRow + offset <= end) {
m_CurRow += offset;
} else {
m_CurRow = end;
//scroll
if (scroll_buffer)
ScrollBuffer(-1 * (m_CurRow + offset - end));
}
} else {
if (m_CurRow >= offset && (m_CurRow - offset) >= begin) {
m_CurRow -= offset;
} else {
m_CurRow = begin;
//scroll
if (scroll_buffer)
ScrollBuffer(begin + offset - m_CurRow);
}
}
}
void SetCellDefaults(wchar_t c,
uint16_t fore_color_idx,
uint16_t back_color_idx,
uint16_t mode) override {
m_DefaultChar = c;
m_DefaultForeColorIndex = fore_color_idx;
m_DefaultBackColorIndex = back_color_idx;
m_DefaultMode = mode;
}
TermCellPtr CreateCellWithDefaults() override {
TermCellPtr cell = CreateDefaultTermCell(nullptr);
cell->SetChar(m_DefaultChar);
cell->SetForeColorIndex(m_DefaultForeColorIndex);
cell->SetBackColorIndex(m_DefaultBackColorIndex);
cell->SetMode(m_DefaultMode);
return cell;
}
void SetSelection(TermSelectionPtr selection) override {
m_Selection->SetRowBegin(selection->GetRowBegin());
m_Selection->SetRowEnd(selection->GetRowEnd());
m_Selection->SetColBegin(selection->GetColBegin());
m_Selection->SetColEnd(selection->GetColEnd());
}
TermSelectionPtr GetSelection() override {
return m_Selection;
}
void ClearSelection() override {
m_Selection->SetRowBegin(0);
m_Selection->SetRowEnd(0);
m_Selection->SetColBegin(0);
m_Selection->SetColEnd(0);
}
void SetCurCellData(uint32_t ch, bool wide_char, bool insert, TermCellPtr cell_template) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
int new_cell_count = wide_char ? 1 : 2;
if (!insert)
{
if (m_CurCol + new_cell_count > m_Cols) {
MoveCurRow(1, true, false);
m_CurCol = 0;
}
TermCellPtr cell = GetCurCell();
cell->Reset(cell_template);
cell->SetChar((wchar_t)ch);
cell->SetWideChar(wide_char);
m_CurCol++;
if (wide_char) {
cell = GetCurCell();
cell->Reset(cell_template);
cell->SetChar((wchar_t)0);
m_CurCol++;
}
} else {
TermLinePtr line = GetLine(m_CurRow);
TermCellPtr extra_cell = line->InsertCell(m_CurCol);
TermCellPtr cell = line->GetCell(m_CurCol);
cell->Reset(cell_template);
cell->SetChar((wchar_t)ch);
cell->SetWideChar(wide_char);
m_CurCol++;
TermCellPtr extra_cell_2{};
if (wide_char) {
extra_cell_2 = line->InsertCell(m_CurCol);
cell = line->GetCell(m_CurCol);
cell->Reset(cell_template);
cell->SetChar((wchar_t)0);
m_CurCol++;
}
uint32_t saved_row = m_CurRow;
uint32_t saved_col = m_CurCol;
if (extra_cell || extra_cell_2) {
MoveCurRow(1, true, false);
m_CurCol = 0;
if (extra_cell) {
SetCurCellData((uint32_t)extra_cell->GetChar(),
extra_cell->IsWideChar(),
insert,
extra_cell);
}
if (extra_cell_2) {
SetCurCellData((uint32_t)extra_cell_2->GetChar(),
extra_cell_2->IsWideChar(),
insert,
extra_cell_2);
}
}
m_CurRow = saved_row;
m_CurCol = saved_col;
}
}
void LockResize() override {
m_ResizeLock.lock();
}
void UnlockResize() override {
m_ResizeLock.unlock();
}
private:
std::recursive_mutex m_ResizeLock;
uint32_t m_Rows;
uint32_t m_Cols;
uint32_t m_CurRow;
uint32_t m_CurCol;
uint32_t m_ScrollRegionBegin;
uint32_t m_ScrollRegionEnd;
TermLineVector m_Lines;
wchar_t m_DefaultChar;
uint16_t m_DefaultForeColorIndex;
uint16_t m_DefaultBackColorIndex;
uint16_t m_DefaultMode;
TermSelectionPtr m_Selection;
};
TermBufferPtr CreateDefaultTermBuffer() {
return TermBufferPtr { new DefaultTermBuffer() };
}
|
#include "plugin_base.h"
#include "default_term_buffer.h"
#include "default_term_line.h"
#include "default_term_cell.h"
#include "term_selection.h"
#include <vector>
#include <mutex>
class DefaultTermSelection : public virtual PluginBase, public virtual TermSelection {
public:
DefaultTermSelection() :
PluginBase("default_term_buffer_cpp", "default terminal buffer plugin", 1)
, m_RowBegin{0}
, m_ColBegin(0)
, m_RowEnd{0}
, m_ColEnd(0)
{
}
virtual ~DefaultTermSelection() = default;
uint32_t GetRowBegin() const override {
return m_RowBegin;
}
void SetRowBegin(uint32_t rowBegin) override {
m_RowBegin = rowBegin;
}
uint32_t GetColBegin() const override {
return m_ColBegin;
}
void SetColBegin(uint32_t colBegin) override {
m_ColBegin = colBegin;
}
uint32_t GetRowEnd() const override {
return m_RowEnd;
}
void SetRowEnd(uint32_t rowEnd) override {
m_RowEnd = rowEnd;
}
uint32_t GetColEnd() const override {
return m_ColEnd;
}
void SetColEnd(uint32_t colEnd) override {
m_ColEnd = colEnd;
}
private:
uint32_t m_RowBegin, m_ColBegin;
uint32_t m_RowEnd, m_ColEnd;
};
class DefaultTermBuffer : public virtual PluginBase, public virtual TermBuffer {
public:
DefaultTermBuffer() :
PluginBase("default_term_buffer", "default terminal buffer plugin", 0)
, m_ResizeLock{}
, m_Rows(0)
, m_Cols(0)
, m_CurRow(0)
, m_CurCol(0)
, m_ScrollRegionBegin(0)
, m_ScrollRegionEnd(0)
, m_Lines()
, m_DefaultChar(' ')
, m_DefaultForeColorIndex(TermCell::DefaultColorIndex)
, m_DefaultBackColorIndex(TermCell::DefaultColorIndex)
, m_DefaultMode(0)
, m_Selection{new DefaultTermSelection}
{
}
virtual ~DefaultTermBuffer() = default;
MultipleInstancePluginPtr NewInstance() override {
return MultipleInstancePluginPtr{new DefaultTermBuffer()};
}
void Resize(uint32_t row, uint32_t col) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
m_Rows = row;
m_Cols = col;
m_ScrollRegionBegin = 0;
m_ScrollRegionEnd = row - 1;
if (m_CurRow >= m_Rows)
m_CurRow = m_Rows - 1;
if (m_CurCol >= m_Cols)
m_CurCol = m_Cols - 1;
m_Lines.resize(m_Rows);
printf("----Resize buffer: rows=%u, %u, cols=%u,%u\n",
m_Rows, m_CurRow,
m_Cols, m_CurCol);
for (TermLineVector::iterator it = m_Lines.begin(),
it_end = m_Lines.end();
it != it_end;
it++)
{
if (*it)
(*it)->Resize(m_Cols);
}
}
uint32_t GetRows() const override {
return m_Rows;
}
uint32_t GetCols() const override {
return m_Cols;
}
uint32_t GetRow() const override {
return m_CurRow;
}
uint32_t GetCol() const override {
return m_CurCol;
}
void SetRow(uint32_t row) override {
m_CurRow = row;
}
void SetCol(uint32_t col) override {
m_CurCol = col;
}
TermLinePtr GetLine(uint32_t row) override {
if (row < GetRows()) {
auto line = m_Lines[row];
if (!line) {
line = CreateDefaultTermLine(this);
line->Resize(GetCols());
m_Lines[row] = line;
}
return line;
}
printf("row:%u, rows:%u\n", row, GetRows());
return TermLinePtr{};
}
TermCellPtr GetCell(uint32_t row, uint32_t col) override {
TermLinePtr line = GetLine(row);
if (line)
return line->GetCell(col);
return TermCellPtr{};
}
TermLinePtr GetCurLine() override {
return GetLine(GetRow());
}
TermCellPtr GetCurCell() override {
return GetCell(GetRow(), GetCol());
}
uint32_t GetScrollRegionBegin() const override {
return m_ScrollRegionBegin;
}
uint32_t GetScrollRegionEnd() const override {
return m_ScrollRegionEnd;
}
void SetScrollRegionBegin(uint32_t begin) override {
m_ScrollRegionBegin = begin;
}
void SetScrollRegionEnd(uint32_t end) override {
m_ScrollRegionEnd = end;
}
bool __NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(uint32_t & begin,
uint32_t count,
uint32_t & end)
{
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
end = begin + count;
if (m_ScrollRegionBegin < m_ScrollRegionEnd)
{
if (begin < m_ScrollRegionBegin)
begin = m_ScrollRegionBegin;
if (end > m_ScrollRegionEnd)
{
//Reset line directly
for (uint32_t i = begin;i <= m_ScrollRegionEnd; i++)
{
m_Lines[i]->Resize(0);
m_Lines[i]->Resize(GetCols());
}
return true;
}
}
else
{
if (end >= m_Rows)
{
//Reset line directly
for (uint32_t i = begin;i < m_Rows; i++)
{
m_Lines[i]->Resize(0);
m_Lines[i]->Resize(GetCols());
}
return true;
}
}
return false;
}
void DeleteLines(uint32_t begin, uint32_t count) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
uint32_t end = begin + count;
if (__NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(begin,
count,
end))
{
return;
}
if (end <= begin)
return;
TermLineVector tmpVector(end - begin);
//Insert First, then delete
for (uint32_t i = begin; i < end; i++)
{
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
tmpVector.push_back(term_line);
}
TermLineVector::iterator b_it = m_Lines.begin() + begin,
e_it = m_Lines.begin() + end;
m_Lines.insert(e_it, tmpVector.begin(), tmpVector.end());
//recalculate iterator
b_it = m_Lines.begin() + begin;
e_it = m_Lines.begin() + end;
m_Lines.erase(b_it, e_it);
}
void InsertLines(uint32_t begin, uint32_t count) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
uint32_t end = begin + count;
if (__NormalizeBeginEndPositionResetLinesWhenDeleteOrInsert(begin,
count,
end))
{
return;
}
if (end <= begin)
return;
TermLineVector::iterator b_it = m_Lines.begin() + begin,
e_it = m_Lines.begin() + end;
m_Lines.erase(b_it, e_it);
TermLineVector tmpVector(end - begin);
for (uint32_t i = begin; i < end; i++)
{
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
tmpVector.push_back(term_line);
}
b_it = m_Lines.begin() + begin;
m_Lines.insert(b_it, tmpVector.begin(), tmpVector.end());
}
TermLineVector::iterator __GetScrollBeginIt() {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
TermLineVector::iterator _it = m_Lines.begin();
if (m_ScrollRegionBegin < m_ScrollRegionEnd) {
_it = _it + m_ScrollRegionBegin;
}
return _it;
};
TermLineVector::iterator __GetScrollEndIt() {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
TermLineVector::iterator _it = m_Lines.end();
if (m_ScrollRegionBegin < m_ScrollRegionEnd) {
_it = m_Lines.begin() + m_ScrollRegionEnd + 1;
}
return _it;
};
void ScrollBuffer(int32_t scroll_offset) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
if (scroll_offset < 0) {
TermLineVector tmpVector;
for(int i=0;i < -scroll_offset;i++) {
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
tmpVector.push_back(term_line);
}
m_Lines.insert(__GetScrollEndIt(), tmpVector.begin(), tmpVector.end());
TermLineVector::iterator b_it = __GetScrollBeginIt();
m_Lines.erase(b_it, b_it - scroll_offset);
} else if (scroll_offset > 0) {
TermLineVector::iterator e_it = __GetScrollEndIt();
m_Lines.erase(e_it - scroll_offset, e_it);
TermLineVector tmpVector;
for(int i=0;i < scroll_offset;i++) {
auto term_line = CreateDefaultTermLine(this);
term_line->Resize(GetCols());
tmpVector.push_back(term_line);
}
//recalculate
m_Lines.insert(__GetScrollBeginIt(), tmpVector.begin(), tmpVector.end());
}
}
void MoveCurRow(uint32_t offset, bool move_down, bool scroll_buffer) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
uint32_t begin = 0, end = GetRows() - 1;
if (m_ScrollRegionBegin < m_ScrollRegionEnd) {
begin = m_ScrollRegionBegin;
end = m_ScrollRegionEnd;
}
if (move_down) {
if (m_CurRow + offset <= end) {
m_CurRow += offset;
} else {
m_CurRow = end;
//scroll
if (scroll_buffer)
ScrollBuffer(-1 * (m_CurRow + offset - end));
}
} else {
if (m_CurRow >= offset && (m_CurRow - offset) >= begin) {
m_CurRow -= offset;
} else {
m_CurRow = begin;
//scroll
if (scroll_buffer)
ScrollBuffer(begin + offset - m_CurRow);
}
}
}
void SetCellDefaults(wchar_t c,
uint16_t fore_color_idx,
uint16_t back_color_idx,
uint16_t mode) override {
m_DefaultChar = c;
m_DefaultForeColorIndex = fore_color_idx;
m_DefaultBackColorIndex = back_color_idx;
m_DefaultMode = mode;
}
TermCellPtr CreateCellWithDefaults() override {
TermCellPtr cell = CreateDefaultTermCell(nullptr);
cell->SetChar(m_DefaultChar);
cell->SetForeColorIndex(m_DefaultForeColorIndex);
cell->SetBackColorIndex(m_DefaultBackColorIndex);
cell->SetMode(m_DefaultMode);
return cell;
}
void SetSelection(TermSelectionPtr selection) override {
m_Selection->SetRowBegin(selection->GetRowBegin());
m_Selection->SetRowEnd(selection->GetRowEnd());
m_Selection->SetColBegin(selection->GetColBegin());
m_Selection->SetColEnd(selection->GetColEnd());
}
TermSelectionPtr GetSelection() override {
return m_Selection;
}
void ClearSelection() override {
m_Selection->SetRowBegin(0);
m_Selection->SetRowEnd(0);
m_Selection->SetColBegin(0);
m_Selection->SetColEnd(0);
}
void SetCurCellData(uint32_t ch, bool wide_char, bool insert, TermCellPtr cell_template) override {
std::lock_guard<std::recursive_mutex> guard(m_ResizeLock);
int new_cell_count = wide_char ? 1 : 2;
if (!insert)
{
if (m_CurCol + new_cell_count > m_Cols) {
MoveCurRow(1, true, false);
m_CurCol = 0;
}
TermCellPtr cell = GetCurCell();
cell->Reset(cell_template);
cell->SetChar((wchar_t)ch);
cell->SetWideChar(wide_char);
m_CurCol++;
if (wide_char) {
cell = GetCurCell();
cell->Reset(cell_template);
cell->SetChar((wchar_t)0);
m_CurCol++;
}
} else {
TermLinePtr line = GetLine(m_CurRow);
TermCellPtr extra_cell = line->InsertCell(m_CurCol);
TermCellPtr cell = line->GetCell(m_CurCol);
cell->Reset(cell_template);
cell->SetChar((wchar_t)ch);
cell->SetWideChar(wide_char);
m_CurCol++;
TermCellPtr extra_cell_2{};
if (wide_char) {
extra_cell_2 = line->InsertCell(m_CurCol);
cell = line->GetCell(m_CurCol);
cell->Reset(cell_template);
cell->SetChar((wchar_t)0);
m_CurCol++;
}
uint32_t saved_row = m_CurRow;
uint32_t saved_col = m_CurCol;
if (extra_cell || extra_cell_2) {
MoveCurRow(1, true, false);
m_CurCol = 0;
if (extra_cell) {
SetCurCellData((uint32_t)extra_cell->GetChar(),
extra_cell->IsWideChar(),
insert,
extra_cell);
}
if (extra_cell_2) {
SetCurCellData((uint32_t)extra_cell_2->GetChar(),
extra_cell_2->IsWideChar(),
insert,
extra_cell_2);
}
}
m_CurRow = saved_row;
m_CurCol = saved_col;
}
}
void LockResize() override {
m_ResizeLock.lock();
}
void UnlockResize() override {
m_ResizeLock.unlock();
}
private:
std::recursive_mutex m_ResizeLock;
uint32_t m_Rows;
uint32_t m_Cols;
uint32_t m_CurRow;
uint32_t m_CurCol;
uint32_t m_ScrollRegionBegin;
uint32_t m_ScrollRegionEnd;
TermLineVector m_Lines;
wchar_t m_DefaultChar;
uint16_t m_DefaultForeColorIndex;
uint16_t m_DefaultBackColorIndex;
uint16_t m_DefaultMode;
TermSelectionPtr m_Selection;
};
TermBufferPtr CreateDefaultTermBuffer() {
return TermBufferPtr { new DefaultTermBuffer() };
}
|
fix scroll crash, should recalculate iterator after erase/insert
|
fix scroll crash, should recalculate iterator after erase/insert
|
C++
|
mit
|
stonewell/wxglterm,stonewell/wxglterm,stonewell/wxglterm,stonewell/wxglterm
|
1f9f0c355e9fd960bca4716cc1a9e0db1c1332fa
|
source/architecture/ARM/ARMv6-M-ARMv7-M/ARMv6-M-ARMv7-M-Reset_Handler.cpp
|
source/architecture/ARM/ARMv6-M-ARMv7-M/ARMv6-M-ARMv7-M-Reset_Handler.cpp
|
/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-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/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
// weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()
__attribute__ ((weak)) void lowLevelInitialization0()
{
}
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
" ldr r0, =%[lowLevelInitialization0] \n" // call lowLevelInitialization0() (PSP not set,
" blx r0 \n" // CONTROL not modified, memory not initialized)
" \n"
" ldr r0, =__process_stack_end \n" // initialize PSP
" msr psp, r0 \n"
" \n"
" movs r0, %[controlSpselMsk] \n" // thread mode uses PSP and is privileged
" msr control, r0 \n"
" isb \n"
" \n"
" ldr r4, =__data_array_start \n" // initialize data_array (including .data)
" ldr r5, =__data_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" bhs 4f \n"
" ldmia r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" \n" // r3 - end of destination
" b 3f \n"
"2: ldmia r1!, {r0} \n" // inner loop - section initialization
" stmia r2!, {r0} \n"
"3: cmp r2, r3 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" ite lo \n"
" ldmialo r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" bhs 3f \n" // r3 - end of destination
" \n"
"2: cmp r2, r3 \n" // inner loop - section initialization
" ittt lo \n"
" ldrlo r0, [r1], #4 \n"
" strlo r0, [r2], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r3, =__bss_array_start \n" // initialize bss_array (including .bss)
" ldr r4, =__bss_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" bhs 4f \n"
" ldmia r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" \n" // of destination
" b 3f \n"
"2: stmia r1!, {r0} \n" // inner loop - section initialization
"3: cmp r1, r2 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" ite lo \n"
" ldmialo r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" bhs 3f \n" // of destination
" \n"
"2: cmp r1, r2 \n" // inner loop - section initialization
" itt lo \n"
" strlo r0, [r1], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r0, =__libc_init_array \n" // call constructors for global and static objects
" blx r0 \n"
" \n"
" ldr r0, =main \n" // call main()
" blx r0 \n"
" \n"
#if CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
" ldr r0, =__libc_fini_array \n" // call destructors for global and static objects
" blx r0 \n"
#endif // CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
" \n"
" b . \n" // on return - loop till the end of the world
" \n"
".ltorg \n" // force dumping of literal pool
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk),
[lowLevelInitialization0] "i" (lowLevelInitialization0)
);
__builtin_unreachable();
}
} // extern "C"
|
/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2018 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/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
// weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()
__attribute__ ((weak)) void lowLevelInitialization0()
{
}
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
" ldr r0, =%[lowLevelInitialization0] \n" // call lowLevelInitialization0() (PSP not set,
" blx r0 \n" // CONTROL not modified, memory not initialized)
" \n"
" ldr r0, =__process_stack_end \n" // initialize PSP
" msr psp, r0 \n"
" \n"
" movs r0, %[controlSpselMsk] \n" // thread mode uses PSP and is privileged
" msr control, r0 \n"
" isb \n"
" \n"
" ldr r4, =__data_initializers_start \n" // initialize data_initializers (including .data)
" ldr r5, =__data_initializers_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_initializers
" bhs 4f \n"
" ldmia r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" \n" // r3 - end of destination
" b 3f \n"
"2: ldmia r1!, {r0} \n" // inner loop - section initialization
" stmia r2!, {r0} \n"
"3: cmp r2, r3 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_initializers
" ite lo \n"
" ldmialo r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" bhs 3f \n" // r3 - end of destination
" \n"
"2: cmp r2, r3 \n" // inner loop - section initialization
" ittt lo \n"
" ldrlo r0, [r1], #4 \n"
" strlo r0, [r2], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r3, =__bss_initializers_start \n" // initialize bss_initializers (including .bss)
" ldr r4, =__bss_initializers_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_initializers
" bhs 4f \n"
" ldmia r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" \n" // of destination
" b 3f \n"
"2: stmia r1!, {r0} \n" // inner loop - section initialization
"3: cmp r1, r2 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_initializers
" ite lo \n"
" ldmialo r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" bhs 3f \n" // of destination
" \n"
"2: cmp r1, r2 \n" // inner loop - section initialization
" itt lo \n"
" strlo r0, [r1], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r0, =__libc_init_array \n" // call constructors for global and static objects
" blx r0 \n"
" \n"
" ldr r0, =main \n" // call main()
" blx r0 \n"
" \n"
#if CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
" ldr r0, =__libc_fini_array \n" // call destructors for global and static objects
" blx r0 \n"
#endif // CONFIG_STATIC_DESTRUCTORS_ENABLE == 1
" \n"
" b . \n" // on return - loop till the end of the world
" \n"
".ltorg \n" // force dumping of literal pool
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk),
[lowLevelInitialization0] "i" (lowLevelInitialization0)
);
__builtin_unreachable();
}
} // extern "C"
|
Use "__{bss,data}_initializers_{start,end}" in Reset_Handler()
|
Use "__{bss,data}_initializers_{start,end}" in Reset_Handler()
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos
|
4ddc8087d97e4f2a3db995f7161f858ff407ac9f
|
source/chip/STM32/peripherals/STM32-peripheralsLowLevelInitialization.cpp
|
source/chip/STM32/peripherals/STM32-peripheralsLowLevelInitialization.cpp
|
/**
* \file
* \brief chip::peripheralsLowLevelInitialization() implementation for STM32
*
* \author Copyright (C) 2016 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/.
*/
#include "distortos/chip/peripheralsLowLevelInitialization.hpp"
#include "distortos/distortosConfiguration.h"
#ifdef CONFIG_CHIP_STM32_SPIV1
#include "SPIv1/STM32-SPIv1-spiLowLevelInitialization.hpp"
#endif // def CONFIG_CHIP_STM32_SPIV1
#ifdef CONFIG_CHIP_STM32_USARTV1
#include "USARTv1/STM32-USARTv1-usartLowLevelInitialization.hpp"
#endif // def CONFIG_CHIP_STM32_USARTV1
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void peripheralsLowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32_SPIV1
spiLowLevelInitialization();
#endif // CONFIG_CHIP_STM32_SPIV1
#ifdef CONFIG_CHIP_STM32_USARTV1
usartLowLevelInitialization();
#endif // def CONFIG_CHIP_STM32_USARTV1
}
} // namespace chip
} // namespace distortos
|
/**
* \file
* \brief chip::peripheralsLowLevelInitialization() implementation for STM32
*
* \author Copyright (C) 2016 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/.
*/
#include "distortos/chip/peripheralsLowLevelInitialization.hpp"
#include "distortos/distortosConfiguration.h"
#ifdef CONFIG_CHIP_STM32_SPIV1
#include "SPIv1/STM32-SPIv1-spiLowLevelInitialization.hpp"
#endif // def CONFIG_CHIP_STM32_SPIV1
#ifdef CONFIG_CHIP_STM32_USARTV1
#include "USARTv1/STM32-USARTv1-usartLowLevelInitialization.hpp"
#endif // def CONFIG_CHIP_STM32_USARTV1
#ifdef CONFIG_CHIP_STM32_USARTV2
#include "USARTv2/STM32-USARTv2-usartLowLevelInitialization.hpp"
#endif // def CONFIG_CHIP_STM32_USARTV2
namespace distortos
{
namespace chip
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
void peripheralsLowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32_SPIV1
spiLowLevelInitialization();
#endif // CONFIG_CHIP_STM32_SPIV1
#if defined(CONFIG_CHIP_STM32_USARTV1) || defined(CONFIG_CHIP_STM32_USARTV2)
usartLowLevelInitialization();
#endif // defined(CONFIG_CHIP_STM32_USARTV1) || defined(CONFIG_CHIP_STM32_USARTV2)
}
} // namespace chip
} // namespace distortos
|
Initialize STM32's USARTv2 in chip::peripheralsLowLevelInitialization()
|
Initialize STM32's USARTv2 in chip::peripheralsLowLevelInitialization()
|
C++
|
mpl-2.0
|
jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos
|
67350af54463af9775a4c2197c2ec2a71b25f8f4
|
System/predator.cpp
|
System/predator.cpp
|
#include "predator.h"
Predator::Predator() {
component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Predator.qml")));
if(component->status() == component->Ready) {
object = component->create(getEngine()->rootContext());
object->setProperty("parent", QVariant::fromValue(getCanvas()));
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
}
else
qDebug() << component->errorString();
setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));
isPredator = true;
velocity = Vector2(0.5,1);
lastVel = Vector2();
}
Predator::~Predator() {
delete component;
delete object;
}
/**
* @brief Predator logic Calculate the Movement of Vectors relativ to Boids and set them accordingly.
*
* The Vectors are:
* v1: Describes the closest boid and set their velocity according to their position.
* v2: Describes the Velocity of other Boids nearby and matches it.
* v3: Holds Information so that every Predator doesn't collide with the boundaries.
*/
void Predator::update() {
double forceX = 0.0;
double forceY = 0.0;
double force;
Vector2 v1 = Vector2();
Vector2 v2 = Vector2();
Vector2 v3 = Vector2();
Vector2 center = Vector2();
center += neighbours[0].pos;
v1 = center - position;
// Rule3: Match velocity to surrounding Boids
for(int i = 0; i < 3; i++){
v2 = v2 + neighbours[i].vel;
}
v2 = (v2/3)*1.3;
if(position.getX() < PREDATOR_ATTENUATION)
v3.setX(1);
else if(position.getX() >= getCanvasWidth() - PREDATOR_ATTENUATION)
v3.setX(-1);
if(position.getY() < PREDATOR_ATTENUATION)
v3.setY(1);
else if(position.getY() >= getCanvasHeight() - PREDATOR_ATTENUATION)
v3.setY(-1);
if(position.getX() < PREDATOR_ATTENUATION)
forceX = PREDATOR_ATTENUATION - position.getX();
else if(position.getX() >= getCanvasWidth() - PREDATOR_ATTENUATION)
forceX = PREDATOR_ATTENUATION + position.getX() - getCanvasWidth() ;
else if(position.getY() < PREDATOR_ATTENUATION)
forceY = PREDATOR_ATTENUATION - position.getY();
else if(position.getY() >= getCanvasHeight() - PREDATOR_ATTENUATION)
forceY = PREDATOR_ATTENUATION + position.getY() - getCanvasHeight();
force = 3.0 * (forceX + forceY);
velocity = Vector2::lerp(lastVel, velocity + v1.normalize() * 1.3 + v2.normalize() * 1.3 + v3.normalize() * force, 0.016f);
lastVel = velocity;
}
|
#include "predator.h"
Predator::Predator() {
component = new QQmlComponent(getEngine(), QUrl(QStringLiteral("qrc:/Predator.qml")));
if(component->status() == component->Ready) {
object = component->create(getEngine()->rootContext());
object->setProperty("parent", QVariant::fromValue(getCanvas()));
QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
}
else
qDebug() << component->errorString();
setY(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasHeight() - 100));
setX(50 + ((double)rand()/(double)(RAND_MAX)) * (getCanvasWidth() - 100));
isPredator = true;
velocity = Vector2(0.5,1);
lastVel = Vector2();
}
Predator::~Predator() {
delete component;
delete object;
}
/**
* @brief Predator logic Calculate the Movement of Vectors relativ to Boids and set them accordingly.
*
* The Vectors are:
* v1: Describes the closest boid and set their velocity according to their position.
* v2: Describes the Velocity of other Boids nearby and matches it.
* v3: Holds Information so that every Predator doesn't collide with the boundaries.
*/
void Predator::update() {
double forceX = 0.0;
double forceY = 0.0;
double force;
Vector2 v1 = Vector2();
Vector2 v2 = Vector2();
Vector2 v3 = Vector2();
Vector2 center = Vector2();
center += neighbours[0].pos;
if(center != Vector2())
v1 = center - position;
// Rule3: Match velocity to surrounding Boids
for(int i = 0; i < 3; i++){
v2 = v2 + neighbours[i].vel;
}
v2 = (v2/3)*1.3;
if(position.getX() < PREDATOR_ATTENUATION)
v3.setX(1);
else if(position.getX() >= getCanvasWidth() - PREDATOR_ATTENUATION)
v3.setX(-1);
if(position.getY() < PREDATOR_ATTENUATION)
v3.setY(1);
else if(position.getY() >= getCanvasHeight() - PREDATOR_ATTENUATION)
v3.setY(-1);
if(position.getX() < PREDATOR_ATTENUATION)
forceX = PREDATOR_ATTENUATION - position.getX();
else if(position.getX() >= getCanvasWidth() - PREDATOR_ATTENUATION)
forceX = PREDATOR_ATTENUATION + position.getX() - getCanvasWidth() ;
else if(position.getY() < PREDATOR_ATTENUATION)
forceY = PREDATOR_ATTENUATION - position.getY();
else if(position.getY() >= getCanvasHeight() - PREDATOR_ATTENUATION)
forceY = PREDATOR_ATTENUATION + position.getY() - getCanvasHeight();
force = 3.0 * (forceX + forceY);
velocity = Vector2::lerp(lastVel, velocity + v1.normalize() * 1.3 + v2.normalize() * 1.3 + v3.normalize() * force, 0.016f);
lastVel = velocity;
}
|
Fix predator behaviour when no boids were found.
|
Fix predator behaviour when no boids were found.
Signed-off-by: TheSniperFan <[email protected]>
|
C++
|
mit
|
knorko/Multimedior,knorko/Multimedior
|
8a44aa48814b916da76c481a82a9246cf0c428f1
|
examples/cpp/jobshop_earlytardy.cc
|
examples/cpp/jobshop_earlytardy.cc
|
// Copyright 2010-2012 Google
// 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.
//
// This model implements a simple jobshop problem with
// earlyness-tardiness costs.
//
// A earlyness-tardinessjobshop is a standard scheduling problem where
// you must schedule a set of jobs on a set of machines. Each job is
// a sequence of tasks (a task can only start when the preceding task
// finished), each of which occupies a single specific machine during
// a specific duration. Therefore, a job is a sequence of pairs
// (machine id, duration), along with a release data (minimum start
// date of the first task of the job, and due data (end time of the
// last job) with a tardiness linear penalty.
// The objective is to minimize the sum of early-tardy penalties for each job.
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "linear_solver/linear_solver.h"
#include "util/string_array.h"
#include "cpp/jobshop_earlytardy.h"
DEFINE_string(
jet_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jet format:\n"
" - the first line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\", ended by due_date, early_cost,"
"late_cost\n"
"note: jobs with one task are not supported");
DEFINE_int32(machine_count, 10, "Machine count");
DEFINE_int32(job_count, 10, "Job count");
DEFINE_int32(max_release_date, 0, "Max release date");
DEFINE_int32(max_early_cost, 0, "Max earlyness weight");
DEFINE_int32(max_tardy_cost, 3, "Max tardiness weight");
DEFINE_int32(max_duration, 10, "Max duration of a task");
DEFINE_int32(scale_factor, 130, "Scale factor (in percent)");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
DEFINE_bool(time_placement, false, "Use MIP based time placement");
DECLARE_bool(log_prefix);
namespace operations_research {
class TimePlacement : public DecisionBuilder {
public:
TimePlacement(const EtJobShopData& data,
const std::vector<SequenceVar*>& all_sequences,
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks)
: data_(data),
all_sequences_(all_sequences),
jobs_to_tasks_(jobs_to_tasks),
horizon_(data_.horizon()),
mp_solver_("TimePlacement", MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING),
num_tasks_(0) {
for (int i = 0; i < jobs_to_tasks_.size(); ++i) {
num_tasks_ += jobs_to_tasks_[i].size();
}
}
virtual ~TimePlacement() {}
virtual Decision* Next(Solver* const solver) {
mp_solver_.Clear();
std::vector<std::vector<MPVariable*> > all_vars;
hash_map<IntervalVar*, MPVariable*> mapping;
const double infinity = mp_solver_.infinity();
all_vars.resize(all_sequences_.size());
// Creates the MP Variables.
for (int s = 0; s < jobs_to_tasks_.size(); ++s) {
for (int t = 0; t < jobs_to_tasks_[s].size(); ++t) {
IntervalVar* const task = jobs_to_tasks_[s][t];
const string name = StringPrintf("J%dT%d", s, t);
MPVariable* const var =
mp_solver_.MakeIntVar(task->StartMin(), task->StartMax(), name);
mapping[task] = var;
}
}
// Adds the jobs precedence constraints.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size() - 1; ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
const int duration = first_task->DurationMax();
IntervalVar* const second_task = jobs_to_tasks_[j][t + 1];
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Adds the ranked machines constraints.
for (int s = 0; s < all_sequences_.size(); ++s) {
SequenceVar* const sequence = all_sequences_[s];
std::vector<int> rank_firsts;
std::vector<int> rank_lasts;
std::vector<int> unperformed;
sequence->FillSequence(&rank_firsts, &rank_lasts, &unperformed);
CHECK_EQ(0, rank_lasts.size());
CHECK_EQ(0, unperformed.size());
for (int i = 0; i < rank_firsts.size() - 1; ++i) {
IntervalVar* const first_task = sequence->Interval(rank_firsts[i]);
const int duration = first_task->DurationMax();
IntervalVar* const second_task = sequence->Interval(rank_firsts[i + 1]);
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Creates penalty terms and objective.
std::vector<MPVariable*> terms;
mp_solver_.MakeIntVarArray(jobs_to_tasks_.size(),
0,
infinity,
"terms",
&terms);
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
mp_solver_.MutableObjective()->SetCoefficient(terms[j], 1.0);
}
mp_solver_.MutableObjective()->SetMinimization();
// Forces penalty terms to be above late and early costs.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
IntervalVar* const last_task = jobs_to_tasks_[j].back();
const int duration = last_task->DurationMin();
MPVariable* const mp_start = mapping[last_task];
const Job& job = data_.GetJob(j);
const int ideal_start = job.due_date - duration;
const int early_offset = job.early_cost * ideal_start;
MPConstraint* const early_ct =
mp_solver_.MakeRowConstraint(early_offset, infinity);
early_ct->SetCoefficient(terms[j], 1);
early_ct->SetCoefficient(mp_start, job.early_cost);
const int tardy_offset = job.tardy_cost * ideal_start;
MPConstraint* const tardy_ct =
mp_solver_.MakeRowConstraint(-tardy_offset, infinity);
tardy_ct->SetCoefficient(terms[j], 1);
tardy_ct->SetCoefficient(mp_start, -job.tardy_cost);
}
// Solve.
CHECK_EQ(MPSolver::OPTIMAL, mp_solver_.Solve());
// Inject MIP solution into the CP part.
LOG(INFO) << "MP cost = " << mp_solver_.objective_value();
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size(); ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
MPVariable* const first_var = mapping[first_task];
const int date = first_var->solution_value();
first_task->SetStartRange(date, date);
}
}
return NULL;
}
virtual string DebugString() const {
return "TimePlacement";
}
private:
const EtJobShopData& data_;
const std::vector<SequenceVar*>& all_sequences_;
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks_;
const int horizon_;
MPSolver mp_solver_;
int num_tasks_;
};
void EtJobShop(const EtJobShopData& data) {
Solver solver("et_jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
const std::vector<Task>& tasks = job.all_tasks;
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Add release date.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][0];
Constraint* const prec =
solver.MakeIntervalVarRelation(t,
Solver::STARTS_AFTER,
job.release_date);
solver.AddConstraint(prec);
}
std::vector<IntVar*> penalties;
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][machine_count - 1];
IntVar* const penalty =
solver.MakeConvexPiecewiseExpr(t->EndExpr(),
job.early_cost,
job.due_date,
job.due_date,
job.tardy_cost)->Var();
penalties.push_back(penalty);
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Objective: minimize the weighted penalties.
IntVar* const objective_var = solver.MakeSum(penalties)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
FLAGS_time_placement ?
solver.RevAlloc(new TimePlacement(data, all_sequences, jobs_to_tasks)) :
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
FLAGS_log_prefix = false;
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
operations_research::EtJobShopData data;
if (!FLAGS_jet_file.empty()) {
data.LoadJetFile(FLAGS_jet_file);
} else {
data.GenerateRandomData(FLAGS_machine_count,
FLAGS_job_count,
FLAGS_max_release_date,
FLAGS_max_early_cost,
FLAGS_max_tardy_cost,
FLAGS_max_duration,
FLAGS_scale_factor,
FLAGS_seed);
}
operations_research::EtJobShop(data);
return 0;
}
|
// Copyright 2010-2012 Google
// 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.
//
// This model implements a simple jobshop problem with
// earlyness-tardiness costs.
//
// A earlyness-tardinessjobshop is a standard scheduling problem where
// you must schedule a set of jobs on a set of machines. Each job is
// a sequence of tasks (a task can only start when the preceding task
// finished), each of which occupies a single specific machine during
// a specific duration. Therefore, a job is a sequence of pairs
// (machine id, duration), along with a release data (minimum start
// date of the first task of the job, and due data (end time of the
// last job) with a tardiness linear penalty.
// The objective is to minimize the sum of early-tardy penalties for each job.
//
// This will be modelled by sets of intervals variables (see class
// IntervalVar in constraint_solver/constraint_solver.h), one per
// task, representing the [start_time, end_time] of the task. Tasks
// in the same job will be linked by precedence constraints. Tasks on
// the same machine will be covered by Sequence constraints.
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "base/commandlineflags.h"
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "constraint_solver/constraint_solver.h"
#include "linear_solver/linear_solver.h"
#include "util/string_array.h"
#include "cpp/jobshop_earlytardy.h"
DEFINE_string(
jet_file,
"",
"Required: input file description the scheduling problem to solve, "
"in our jet format:\n"
" - the first line is \"<number of jobs> <number of machines>\"\n"
" - then one line per job, with a single space-separated "
"list of \"<machine index> <duration>\", ended by due_date, early_cost,"
"late_cost\n"
"note: jobs with one task are not supported");
DEFINE_int32(machine_count, 10, "Machine count");
DEFINE_int32(job_count, 10, "Job count");
DEFINE_int32(max_release_date, 0, "Max release date");
DEFINE_int32(max_early_cost, 0, "Max earlyness weight");
DEFINE_int32(max_tardy_cost, 3, "Max tardiness weight");
DEFINE_int32(max_duration, 10, "Max duration of a task");
DEFINE_int32(scale_factor, 130, "Scale factor (in percent)");
DEFINE_int32(seed, 1, "Random seed");
DEFINE_int32(time_limit_in_ms, 0, "Time limit in ms, 0 means no limit.");
DEFINE_bool(time_placement, false, "Use MIP based time placement");
DECLARE_bool(log_prefix);
namespace operations_research {
class TimePlacement : public DecisionBuilder {
public:
TimePlacement(const EtJobShopData& data,
const std::vector<SequenceVar*>& all_sequences,
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks)
: data_(data),
all_sequences_(all_sequences),
jobs_to_tasks_(jobs_to_tasks),
mp_solver_("TimePlacement", MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING),
num_tasks_(0) {
for (int i = 0; i < jobs_to_tasks_.size(); ++i) {
num_tasks_ += jobs_to_tasks_[i].size();
}
}
virtual ~TimePlacement() {}
virtual Decision* Next(Solver* const solver) {
mp_solver_.Clear();
std::vector<std::vector<MPVariable*> > all_vars;
hash_map<IntervalVar*, MPVariable*> mapping;
const double infinity = mp_solver_.infinity();
all_vars.resize(all_sequences_.size());
// Creates the MP Variables.
for (int s = 0; s < jobs_to_tasks_.size(); ++s) {
for (int t = 0; t < jobs_to_tasks_[s].size(); ++t) {
IntervalVar* const task = jobs_to_tasks_[s][t];
const string name = StringPrintf("J%dT%d", s, t);
MPVariable* const var =
mp_solver_.MakeIntVar(task->StartMin(), task->StartMax(), name);
mapping[task] = var;
}
}
// Adds the jobs precedence constraints.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size() - 1; ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
const int duration = first_task->DurationMax();
IntervalVar* const second_task = jobs_to_tasks_[j][t + 1];
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Adds the ranked machines constraints.
for (int s = 0; s < all_sequences_.size(); ++s) {
SequenceVar* const sequence = all_sequences_[s];
std::vector<int> rank_firsts;
std::vector<int> rank_lasts;
std::vector<int> unperformed;
sequence->FillSequence(&rank_firsts, &rank_lasts, &unperformed);
CHECK_EQ(0, rank_lasts.size());
CHECK_EQ(0, unperformed.size());
for (int i = 0; i < rank_firsts.size() - 1; ++i) {
IntervalVar* const first_task = sequence->Interval(rank_firsts[i]);
const int duration = first_task->DurationMax();
IntervalVar* const second_task = sequence->Interval(rank_firsts[i + 1]);
MPVariable* const first_var = mapping[first_task];
MPVariable* const second_var = mapping[second_task];
MPConstraint* const ct =
mp_solver_.MakeRowConstraint(duration, infinity);
ct->SetCoefficient(second_var, 1.0);
ct->SetCoefficient(first_var, -1.0);
}
}
// Creates penalty terms and objective.
std::vector<MPVariable*> terms;
mp_solver_.MakeIntVarArray(jobs_to_tasks_.size(),
0,
infinity,
"terms",
&terms);
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
mp_solver_.MutableObjective()->SetCoefficient(terms[j], 1.0);
}
mp_solver_.MutableObjective()->SetMinimization();
// Forces penalty terms to be above late and early costs.
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
IntervalVar* const last_task = jobs_to_tasks_[j].back();
const int duration = last_task->DurationMin();
MPVariable* const mp_start = mapping[last_task];
const Job& job = data_.GetJob(j);
const int ideal_start = job.due_date - duration;
const int early_offset = job.early_cost * ideal_start;
MPConstraint* const early_ct =
mp_solver_.MakeRowConstraint(early_offset, infinity);
early_ct->SetCoefficient(terms[j], 1);
early_ct->SetCoefficient(mp_start, job.early_cost);
const int tardy_offset = job.tardy_cost * ideal_start;
MPConstraint* const tardy_ct =
mp_solver_.MakeRowConstraint(-tardy_offset, infinity);
tardy_ct->SetCoefficient(terms[j], 1);
tardy_ct->SetCoefficient(mp_start, -job.tardy_cost);
}
// Solve.
CHECK_EQ(MPSolver::OPTIMAL, mp_solver_.Solve());
// Inject MIP solution into the CP part.
LOG(INFO) << "MP cost = " << mp_solver_.objective_value();
for (int j = 0; j < jobs_to_tasks_.size(); ++j) {
for (int t = 0; t < jobs_to_tasks_[j].size(); ++t) {
IntervalVar* const first_task = jobs_to_tasks_[j][t];
MPVariable* const first_var = mapping[first_task];
const int date = first_var->solution_value();
first_task->SetStartRange(date, date);
}
}
return NULL;
}
virtual string DebugString() const {
return "TimePlacement";
}
private:
const EtJobShopData& data_;
const std::vector<SequenceVar*>& all_sequences_;
const std::vector<std::vector<IntervalVar*> >& jobs_to_tasks_;
MPSolver mp_solver_;
int num_tasks_;
};
void EtJobShop(const EtJobShopData& data) {
Solver solver("et_jobshop");
const int machine_count = data.machine_count();
const int job_count = data.job_count();
const int horizon = data.horizon();
// ----- Creates all Intervals and vars -----
// Stores all tasks attached interval variables per job.
std::vector<std::vector<IntervalVar*> > jobs_to_tasks(job_count);
// machines_to_tasks stores the same interval variables as above, but
// grouped my machines instead of grouped by jobs.
std::vector<std::vector<IntervalVar*> > machines_to_tasks(machine_count);
// Creates all individual interval variables.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
const std::vector<Task>& tasks = job.all_tasks;
for (int task_index = 0; task_index < tasks.size(); ++task_index) {
const Task& task = tasks[task_index];
CHECK_EQ(job_id, task.job_id);
const string name = StringPrintf("J%dM%dI%dD%d",
task.job_id,
task.machine_id,
task_index,
task.duration);
IntervalVar* const one_task =
solver.MakeFixedDurationIntervalVar(0,
horizon,
task.duration,
false,
name);
jobs_to_tasks[task.job_id].push_back(one_task);
machines_to_tasks[task.machine_id].push_back(one_task);
}
}
// ----- Creates model -----
// Creates precedences inside jobs.
for (int job_id = 0; job_id < job_count; ++job_id) {
const int task_count = jobs_to_tasks[job_id].size();
for (int task_index = 0; task_index < task_count - 1; ++task_index) {
IntervalVar* const t1 = jobs_to_tasks[job_id][task_index];
IntervalVar* const t2 = jobs_to_tasks[job_id][task_index + 1];
Constraint* const prec =
solver.MakeIntervalVarRelation(t2, Solver::STARTS_AFTER_END, t1);
solver.AddConstraint(prec);
}
}
// Add release date.
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][0];
Constraint* const prec =
solver.MakeIntervalVarRelation(t,
Solver::STARTS_AFTER,
job.release_date);
solver.AddConstraint(prec);
}
std::vector<IntVar*> penalties;
for (int job_id = 0; job_id < job_count; ++job_id) {
const Job& job = data.GetJob(job_id);
IntervalVar* const t = jobs_to_tasks[job_id][machine_count - 1];
IntVar* const penalty =
solver.MakeConvexPiecewiseExpr(t->EndExpr(),
job.early_cost,
job.due_date,
job.due_date,
job.tardy_cost)->Var();
penalties.push_back(penalty);
}
// Adds disjunctive constraints on unary resources.
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
solver.AddConstraint(
solver.MakeDisjunctiveConstraint(machines_to_tasks[machine_id]));
}
// Creates sequences variables on machines. A sequence variable is a
// dedicated variable whose job is to sequence interval variables.
std::vector<SequenceVar*> all_sequences;
for (int machine_id = 0; machine_id < machine_count; ++machine_id) {
const string name = StringPrintf("Machine_%d", machine_id);
SequenceVar* const sequence =
solver.MakeSequenceVar(machines_to_tasks[machine_id], name);
all_sequences.push_back(sequence);
}
// Objective: minimize the weighted penalties.
IntVar* const objective_var = solver.MakeSum(penalties)->Var();
OptimizeVar* const objective_monitor = solver.MakeMinimize(objective_var, 1);
// ----- Search monitors and decision builder -----
// This decision builder will rank all tasks on all machines.
DecisionBuilder* const sequence_phase =
solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT);
// After the ranking of tasks, the schedule is still loose and any
// task can be postponed at will. But, because the problem is now a PERT
// (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique),
// we can schedule each task at its earliest start time. This is
// conveniently done by fixing the objective variable to its
// minimum value.
DecisionBuilder* const obj_phase =
FLAGS_time_placement ?
solver.RevAlloc(new TimePlacement(data, all_sequences, jobs_to_tasks)) :
solver.MakePhase(objective_var,
Solver::CHOOSE_FIRST_UNBOUND,
Solver::ASSIGN_MIN_VALUE);
// The main decision builder (ranks all tasks, then fixes the
// objective_variable).
DecisionBuilder* const main_phase =
solver.Compose(sequence_phase, obj_phase);
// Search log.
const int kLogFrequency = 1000000;
SearchMonitor* const search_log =
solver.MakeSearchLog(kLogFrequency, objective_monitor);
SearchLimit* limit = NULL;
if (FLAGS_time_limit_in_ms > 0) {
limit = solver.MakeTimeLimit(FLAGS_time_limit_in_ms);
}
// Search.
solver.Solve(main_phase, search_log, objective_monitor, limit);
}
} // namespace operations_research
static const char kUsage[] =
"Usage: see flags.\nThis program runs a simple job shop optimization "
"output besides the debug LOGs of the solver.";
int main(int argc, char **argv) {
FLAGS_log_prefix = false;
google::SetUsageMessage(kUsage);
google::ParseCommandLineFlags(&argc, &argv, true);
operations_research::EtJobShopData data;
if (!FLAGS_jet_file.empty()) {
data.LoadJetFile(FLAGS_jet_file);
} else {
data.GenerateRandomData(FLAGS_machine_count,
FLAGS_job_count,
FLAGS_max_release_date,
FLAGS_max_early_cost,
FLAGS_max_tardy_cost,
FLAGS_max_duration,
FLAGS_scale_factor,
FLAGS_seed);
}
operations_research::EtJobShop(data);
return 0;
}
|
implement time placement code for early tardy
|
implement time placement code for early tardy
|
C++
|
apache-2.0
|
LeslieW/or-tools2,bulentsoykan/or-tools,omerucn/or-tools,jggtrujillo/or-tools,petesburgh/or-tools,zafar-hussain/or-tools,LeslieW/or-tools,LeslieW/or-tools2,zafar-hussain/or-tools,gtara/or-tools,gtara/or-tools,yoghadj/or-tools,LeslieW/or-tools,petesburgh/or-tools,petesburgh/or-tools,omerucn/or-tools,omerucn/or-tools,jggtrujillo/or-tools,zafar-hussain/or-tools,yoghadj/or-tools,zafar-hussain/or-tools,yoghadj/or-tools,gtara/or-tools,gtara/or-tools,omerucn/or-tools,yoghadj/or-tools,bulentsoykan/or-tools,zafar-hussain/or-tools,gtara/or-tools,LeslieW/or-tools,bulentsoykan/or-tools,jggtrujillo/or-tools,bulentsoykan/or-tools,LeslieW/or-tools2,LeslieW/or-tools,LeslieW/or-tools2,LeslieW/or-tools,LeslieW/or-tools2,omerucn/or-tools,gtara/or-tools,jggtrujillo/or-tools,omerucn/or-tools,bulentsoykan/or-tools,petesburgh/or-tools,zafar-hussain/or-tools,LeslieW/or-tools2,petesburgh/or-tools,petesburgh/or-tools,LeslieW/or-tools,yoghadj/or-tools,yoghadj/or-tools,jggtrujillo/or-tools,jggtrujillo/or-tools,bulentsoykan/or-tools
|
62381d0762ad978d808fb1b8119415a07e028e28
|
cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp
|
cpp/ql/test/experimental/query-tests/Security/CWE/CWE-377/semmle/tests/test.cpp
|
typedef int FILE;
#define NULL (0)
FILE *fopen(char *filename, const char *mode);
FILE *fdopen(int handle, char *mode);
char * tmpnam(char * name);
int mkstemp(char * name);
char * strcat(char *str1, const char *str2);
int umask(int pmode);
int chmod(char * filename,int pmode);
int fprintf(FILE *fp,const char *fmt, ...);
int fclose(FILE *stream);
int funcTest1()
{
FILE *fp;
char *filename = tmpnam(NULL); // BAD
fp = fopen(filename,"w");
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int funcTest2()
{
FILE *fp;
int fd;
char filename[80];
strcat (filename, "/tmp/name.XXXXXX");
fd = mkstemp(filename);
if ( fd < 0 ) {
return 1;
}
fp = fdopen(fd,"w"); // GOOD
return 0;
}
int funcTest3()
{
FILE *fp;
char filename[80];
strcat(filename, "/tmp/tmp.name");
fp = fopen(filename,"w"); // BAD
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int funcTest4()
{
FILE *fp;
char filename[80];
umask(0022);
strcat(filename, "/tmp/tmp.name");
fp = fopen(filename,"w"); // GOOD
chmod(filename,0666);
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int main(int argc, char *argv[])
{
funcTest1();
funcTest2();
funcTest3();
funcTest4();
return 0;
}
|
typedef int FILE;
#define NULL (0)
FILE *fopen(char *filename, const char *mode);
FILE *fdopen(int handle, char *mode);
char * tmpnam(char * name);
int mkstemp(char * name);
char * strcat(char *str1, const char *str2);
int umask(int pmode);
int chmod(char * filename,int pmode);
int fprintf(FILE *fp,const char *fmt, ...);
int fclose(FILE *stream);
int funcTest1()
{
FILE *fp;
char *filename = tmpnam(NULL); // BAD
fp = fopen(filename,"w");
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int funcTest2()
{
FILE *fp;
int fd;
char filename[80];
strcat (filename, "/tmp/name.XXXXXX");
fd = mkstemp(filename);
if ( fd < 0 ) {
return 1;
}
fp = fdopen(fd,"w"); // GOOD
return 0;
}
int funcTest3()
{
FILE *fp;
char filename[80];
strcat(filename, "/tmp/tmp.name");
fp = fopen(filename,"w"); // BAD [NOT DETECTED]
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int funcTest4()
{
FILE *fp;
char filename[80];
umask(0022);
strcat(filename, "/tmp/tmp.name");
fp = fopen(filename,"w"); // GOOD
chmod(filename,0666);
fprintf(fp,"%s\n","data to file");
fclose(fp);
return 0;
}
int main(int argc, char *argv[])
{
funcTest1();
funcTest2();
funcTest3();
funcTest4();
return 0;
}
|
Update test.cpp
|
Update test.cpp
|
C++
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
895de14be1ed2560fe98ab0d7fce8b5ced86fe48
|
C++/pku_cplusplus/oop/rectangle.cc
|
C++/pku_cplusplus/oop/rectangle.cc
|
/*
* Author: Haibo Hao
* Email : [email protected]
* Copyright (C) 2017 NCIC
**/
#include <iostream>
class CRectangle{
public:
int width, hight;
void Init(int width_, int hight_){
width = width_;
hight = hight_;
}
int Area(){
return width*hight;
}
int Perimeter(){
return 2*(width + hight);
}
};
int main(int argc, char* argv[]){
int width, hight;
std::cin >> width >> hight;
CRectangle r;
r.Init(width, hight);
std::cout << "The sizeof CRectangle: ";
std::cout << sizeof(CRectangle) << std::endl;
std::cout << r.Area() << std::endl;
std::cout << r.Perimeter() << std::endl;
return 0;
}
|
/*
* Author: Haibo Hao
* Email : [email protected]
* Copyright (C) 2017 NCIC
**/
#include <iostream>
class CRectangle{
public:
int width, hight;
void Init(int width_, int hight_){
width = width_;
hight = hight_;
}
int Area(){
return width*hight;
}
int Perimeter(){
return 2*(width + hight);
}
};
int main(int argc, char* argv[]){
int width, hight;
std::cin >> width >> hight;
CRectangle r;
r.Init(width, hight);
std::cout << "The sizeof CRectangle: ";
std::cout << sizeof(CRectangle) << std::endl;
std::cout << r.Area() << std::endl;
std::cout << r.Perimeter() << std::endl;
return 0;
}
|
test emoji
|
:lollipop: test emoji
|
C++
|
mit
|
haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial,haohaibo/tutorial
|
db30b6bbb4cbf946036bdcb6685379b7345c1450
|
storage/src/vespa/storage/storageserver/rpc/cluster_controller_api_rpc_service.cpp
|
storage/src/vespa/storage/storageserver/rpc/cluster_controller_api_rpc_service.cpp
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "cluster_controller_api_rpc_service.h"
#include "shared_rpc_resources.h"
#include "slime_cluster_state_bundle_codec.h"
#include <vespa/storage/storageserver/communicationmanager.h>
#include <vespa/storage/storageserver/message_dispatcher.h>
#include <vespa/storage/storageserver/rpcrequestwrapper.h>
#include <vespa/vdslib/state/clusterstate.h>
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/rpcrequest.h>
#include <vespa/storageapi/message/state.h>
#include <vespa/vespalib/util/host_name.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".storage.cluster_controller_api_rpc_service");
namespace storage::rpc {
ClusterControllerApiRpcService::ClusterControllerApiRpcService(
MessageDispatcher& message_dispatcher,
SharedRpcResources& rpc_resources)
: _message_dispatcher(message_dispatcher),
_closed(false)
{
register_server_methods(rpc_resources);
}
ClusterControllerApiRpcService::~ClusterControllerApiRpcService() = default;
void ClusterControllerApiRpcService::close() {
_closed.store(true);
}
void ClusterControllerApiRpcService::register_server_methods(SharedRpcResources& rpc_resources) {
FRT_ReflectionBuilder rb(&rpc_resources.supervisor());
rb.DefineMethod("getnodestate3", "sii", "ss", FRT_METHOD(ClusterControllerApiRpcService::RPC_getNodeState2), this);
rb.MethodDesc("Get state of this node");
rb.ParamDesc("nodestate", "Expected state of given node. If correct, the "
"request will be queued on target until it changes. To not give "
"any state use the string 'unknown', enforcing a direct reply.");
rb.ParamDesc("timeout", "Timeout of message in milliseconds, set by the state requester");
rb.ReturnDesc("nodestate", "State string for this node");
rb.ReturnDesc("hostinfo", "Information about host this node is running on");
//-------------------------------------------------------------------------
rb.DefineMethod("getnodestate2", "si", "s", FRT_METHOD(ClusterControllerApiRpcService::RPC_getNodeState2), this);
rb.MethodDesc("Get state of this node");
rb.ParamDesc("nodestate", "Expected state of given node. If correct, the "
"request will be queued on target until it changes. To not give "
"any state use the string 'unknown', enforcing a direct reply.");
rb.ParamDesc("timeout", "Timeout of message in milliseconds, set by the state requester");
rb.ReturnDesc("nodestate", "State string for this node");
//-------------------------------------------------------------------------
rb.DefineMethod("setsystemstate2", "s", "", FRT_METHOD(ClusterControllerApiRpcService::RPC_setSystemState2), this);
rb.MethodDesc("Set systemstate on this node");
rb.ParamDesc("systemstate", "New systemstate to set");
//-------------------------------------------------------------------------
rb.DefineMethod("setdistributionstates", "bix", "", FRT_METHOD(ClusterControllerApiRpcService::RPC_setDistributionStates), this);
rb.MethodDesc("Set distribution states for cluster and bucket spaces");
rb.ParamDesc("compressionType", "Compression type for payload");
rb.ParamDesc("uncompressedSize", "Uncompressed size for payload");
rb.ParamDesc("payload", "Binary Slime format payload");
//-------------------------------------------------------------------------
rb.DefineMethod("activate_cluster_state_version", "i", "i", FRT_METHOD(ClusterControllerApiRpcService::RPC_activateClusterStateVersion), this);
rb.MethodDesc("Explicitly activates an already prepared cluster state version");
rb.ParamDesc("activate_version", "Expected cluster state version to activate");
rb.ReturnDesc("actual_version", "Cluster state version that was prepared on the node prior to receiving RPC");
//-------------------------------------------------------------------------
rb.DefineMethod("getcurrenttime", "", "lis", FRT_METHOD(ClusterControllerApiRpcService::RPC_getCurrentTime), this);
rb.MethodDesc("Get current time on this node");
rb.ReturnDesc("seconds", "Current time in seconds since epoch");
rb.ReturnDesc("nanoseconds", "additional nanoseconds since epoch");
rb.ReturnDesc("hostname", "Host name");
}
// TODO remove? is this used by anyone?
void ClusterControllerApiRpcService::RPC_getCurrentTime(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call getCurrentTime() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
//TODO Should we unify on std::chrono here too ?
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
req->GetReturn()->AddInt64(t.tv_sec);
req->GetReturn()->AddInt32(t.tv_nsec);
vespalib::string hostname = vespalib::HostName::get();
req->GetReturn()->AddString(hostname.c_str());
// all handled, will return immediately
}
void ClusterControllerApiRpcService::detach_and_forward_to_enqueuer(
std::shared_ptr<api::StorageMessage> cmd,
FRT_RPCRequest* req)
{
// Create a request object to avoid needing a separate transport type
cmd->setTransportContext(std::make_unique<StorageTransportContext>(std::make_unique<RPCRequestWrapper>(req)));
req->Detach();
_message_dispatcher.dispatch_async(std::move(cmd));
}
void ClusterControllerApiRpcService::RPC_getNodeState2(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call getNodeState2() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
vespalib::string expected(req->GetParams()->GetValue(0)._string._str,
req->GetParams()->GetValue(0)._string._len);
auto cmd = std::make_shared<api::GetNodeStateCommand>(expected != "unknown"
? std::make_unique<lib::NodeState>(expected)
: std::unique_ptr<lib::NodeState>());
cmd->setPriority(api::StorageMessage::VERYHIGH);
cmd->setTimeout(std::chrono::milliseconds(req->GetParams()->GetValue(1)._intval32));
if (req->GetParams()->GetNumValues() > 2) {
cmd->setSourceIndex(req->GetParams()->GetValue(2)._intval32);
}
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
void ClusterControllerApiRpcService::RPC_setSystemState2(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call setSystemState2() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
vespalib::string systemStateStr(req->GetParams()->GetValue(0)._string._str,
req->GetParams()->GetValue(0)._string._len);
lib::ClusterState systemState(systemStateStr);
auto cmd = std::make_shared<api::SetSystemStateCommand>(lib::ClusterStateBundle(systemState));
cmd->setPriority(api::StorageMessage::VERYHIGH);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
namespace {
std::shared_ptr<const lib::ClusterStateBundle> decode_bundle_from_params(const FRT_Values& params) {
const uint32_t uncompressed_length = params[1]._intval32;
if (uncompressed_length > ClusterControllerApiRpcService::StateBundleMaxUncompressedSize) {
throw std::range_error(vespalib::make_string("RPC ClusterStateBundle uncompressed size (%u) is "
"greater than max size (%u)", uncompressed_length,
ClusterControllerApiRpcService::StateBundleMaxUncompressedSize));
}
SlimeClusterStateBundleCodec codec;
EncodedClusterStateBundle encoded_bundle;
encoded_bundle._compression_type = vespalib::compression::CompressionConfig::toType(params[0]._intval8);
encoded_bundle._uncompressed_length = uncompressed_length;
// Caution: type cast to const ptr is essential or DataBuffer behavior changes!
encoded_bundle._buffer = std::make_unique<vespalib::DataBuffer>(
static_cast<const char*>(params[2]._data._buf), params[2]._data._len);
return codec.decode(encoded_bundle);
}
}
void ClusterControllerApiRpcService::RPC_setDistributionStates(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call setDistributionStates() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
std::shared_ptr<const lib::ClusterStateBundle> state_bundle;
try {
state_bundle = decode_bundle_from_params(*req->GetParams());
} catch (std::exception& e) {
LOG(error, "setDistributionStates RPC failed decoding: %s", e.what());
req->SetError(RPCRequestWrapper::ERR_BAD_REQUEST, e.what());
return;
}
LOG(debug, "Got state bundle %s", state_bundle->toString().c_str());
// TODO add constructor taking in shared_ptr directly instead?
auto cmd = std::make_shared<api::SetSystemStateCommand>(*state_bundle);
cmd->setPriority(api::StorageMessage::VERYHIGH);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
void ClusterControllerApiRpcService::RPC_activateClusterStateVersion(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call activate_cluster_state_version() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
const uint32_t activate_version = req->GetParams()->GetValue(0)._intval32;
auto cmd = std::make_shared<api::ActivateClusterStateVersionCommand>(activate_version);
cmd->setPriority(api::StorageMessage::VERYHIGH);
LOG(debug, "Got state activation request for version %u", activate_version);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "cluster_controller_api_rpc_service.h"
#include "shared_rpc_resources.h"
#include "slime_cluster_state_bundle_codec.h"
#include <vespa/storage/storageserver/communicationmanager.h>
#include <vespa/storage/storageserver/message_dispatcher.h>
#include <vespa/storage/storageserver/rpcrequestwrapper.h>
#include <vespa/vdslib/state/clusterstate.h>
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/require_capabilities.h>
#include <vespa/fnet/frt/rpcrequest.h>
#include <vespa/storageapi/message/state.h>
#include <vespa/vespalib/util/host_name.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".storage.cluster_controller_api_rpc_service");
namespace storage::rpc {
ClusterControllerApiRpcService::ClusterControllerApiRpcService(
MessageDispatcher& message_dispatcher,
SharedRpcResources& rpc_resources)
: _message_dispatcher(message_dispatcher),
_closed(false)
{
register_server_methods(rpc_resources);
}
ClusterControllerApiRpcService::~ClusterControllerApiRpcService() = default;
void ClusterControllerApiRpcService::close() {
_closed.store(true);
}
namespace {
std::unique_ptr<FRT_RequireCapabilities> make_cc_api_capability_filter() {
return std::make_unique<FRT_RequireCapabilities>(vespalib::net::tls::CapabilitySet::of({
vespalib::net::tls::Capability::content_cluster_controller_internal_state_api()
}));
}
}
void ClusterControllerApiRpcService::register_server_methods(SharedRpcResources& rpc_resources) {
FRT_ReflectionBuilder rb(&rpc_resources.supervisor());
rb.DefineMethod("getnodestate3", "sii", "ss", FRT_METHOD(ClusterControllerApiRpcService::RPC_getNodeState2), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Get state of this node");
rb.ParamDesc("nodestate", "Expected state of given node. If correct, the "
"request will be queued on target until it changes. To not give "
"any state use the string 'unknown', enforcing a direct reply.");
rb.ParamDesc("timeout", "Timeout of message in milliseconds, set by the state requester");
rb.ReturnDesc("nodestate", "State string for this node");
rb.ReturnDesc("hostinfo", "Information about host this node is running on");
//-------------------------------------------------------------------------
rb.DefineMethod("getnodestate2", "si", "s", FRT_METHOD(ClusterControllerApiRpcService::RPC_getNodeState2), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Get state of this node");
rb.ParamDesc("nodestate", "Expected state of given node. If correct, the "
"request will be queued on target until it changes. To not give "
"any state use the string 'unknown', enforcing a direct reply.");
rb.ParamDesc("timeout", "Timeout of message in milliseconds, set by the state requester");
rb.ReturnDesc("nodestate", "State string for this node");
//-------------------------------------------------------------------------
rb.DefineMethod("setsystemstate2", "s", "", FRT_METHOD(ClusterControllerApiRpcService::RPC_setSystemState2), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Set systemstate on this node");
rb.ParamDesc("systemstate", "New systemstate to set");
//-------------------------------------------------------------------------
rb.DefineMethod("setdistributionstates", "bix", "", FRT_METHOD(ClusterControllerApiRpcService::RPC_setDistributionStates), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Set distribution states for cluster and bucket spaces");
rb.ParamDesc("compressionType", "Compression type for payload");
rb.ParamDesc("uncompressedSize", "Uncompressed size for payload");
rb.ParamDesc("payload", "Binary Slime format payload");
//-------------------------------------------------------------------------
rb.DefineMethod("activate_cluster_state_version", "i", "i", FRT_METHOD(ClusterControllerApiRpcService::RPC_activateClusterStateVersion), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Explicitly activates an already prepared cluster state version");
rb.ParamDesc("activate_version", "Expected cluster state version to activate");
rb.ReturnDesc("actual_version", "Cluster state version that was prepared on the node prior to receiving RPC");
//-------------------------------------------------------------------------
rb.DefineMethod("getcurrenttime", "", "lis", FRT_METHOD(ClusterControllerApiRpcService::RPC_getCurrentTime), this);
rb.RequestAccessFilter(make_cc_api_capability_filter());
rb.MethodDesc("Get current time on this node");
rb.ReturnDesc("seconds", "Current time in seconds since epoch");
rb.ReturnDesc("nanoseconds", "additional nanoseconds since epoch");
rb.ReturnDesc("hostname", "Host name");
}
// TODO remove? is this used by anyone?
void ClusterControllerApiRpcService::RPC_getCurrentTime(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call getCurrentTime() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
//TODO Should we unify on std::chrono here too ?
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
req->GetReturn()->AddInt64(t.tv_sec);
req->GetReturn()->AddInt32(t.tv_nsec);
vespalib::string hostname = vespalib::HostName::get();
req->GetReturn()->AddString(hostname.c_str());
// all handled, will return immediately
}
void ClusterControllerApiRpcService::detach_and_forward_to_enqueuer(
std::shared_ptr<api::StorageMessage> cmd,
FRT_RPCRequest* req)
{
// Create a request object to avoid needing a separate transport type
cmd->setTransportContext(std::make_unique<StorageTransportContext>(std::make_unique<RPCRequestWrapper>(req)));
req->Detach();
_message_dispatcher.dispatch_async(std::move(cmd));
}
void ClusterControllerApiRpcService::RPC_getNodeState2(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call getNodeState2() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
vespalib::string expected(req->GetParams()->GetValue(0)._string._str,
req->GetParams()->GetValue(0)._string._len);
auto cmd = std::make_shared<api::GetNodeStateCommand>(expected != "unknown"
? std::make_unique<lib::NodeState>(expected)
: std::unique_ptr<lib::NodeState>());
cmd->setPriority(api::StorageMessage::VERYHIGH);
cmd->setTimeout(std::chrono::milliseconds(req->GetParams()->GetValue(1)._intval32));
if (req->GetParams()->GetNumValues() > 2) {
cmd->setSourceIndex(req->GetParams()->GetValue(2)._intval32);
}
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
void ClusterControllerApiRpcService::RPC_setSystemState2(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call setSystemState2() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
vespalib::string systemStateStr(req->GetParams()->GetValue(0)._string._str,
req->GetParams()->GetValue(0)._string._len);
lib::ClusterState systemState(systemStateStr);
auto cmd = std::make_shared<api::SetSystemStateCommand>(lib::ClusterStateBundle(systemState));
cmd->setPriority(api::StorageMessage::VERYHIGH);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
namespace {
std::shared_ptr<const lib::ClusterStateBundle> decode_bundle_from_params(const FRT_Values& params) {
const uint32_t uncompressed_length = params[1]._intval32;
if (uncompressed_length > ClusterControllerApiRpcService::StateBundleMaxUncompressedSize) {
throw std::range_error(vespalib::make_string("RPC ClusterStateBundle uncompressed size (%u) is "
"greater than max size (%u)", uncompressed_length,
ClusterControllerApiRpcService::StateBundleMaxUncompressedSize));
}
SlimeClusterStateBundleCodec codec;
EncodedClusterStateBundle encoded_bundle;
encoded_bundle._compression_type = vespalib::compression::CompressionConfig::toType(params[0]._intval8);
encoded_bundle._uncompressed_length = uncompressed_length;
// Caution: type cast to const ptr is essential or DataBuffer behavior changes!
encoded_bundle._buffer = std::make_unique<vespalib::DataBuffer>(
static_cast<const char*>(params[2]._data._buf), params[2]._data._len);
return codec.decode(encoded_bundle);
}
}
void ClusterControllerApiRpcService::RPC_setDistributionStates(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call setDistributionStates() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
std::shared_ptr<const lib::ClusterStateBundle> state_bundle;
try {
state_bundle = decode_bundle_from_params(*req->GetParams());
} catch (std::exception& e) {
LOG(error, "setDistributionStates RPC failed decoding: %s", e.what());
req->SetError(RPCRequestWrapper::ERR_BAD_REQUEST, e.what());
return;
}
LOG(debug, "Got state bundle %s", state_bundle->toString().c_str());
// TODO add constructor taking in shared_ptr directly instead?
auto cmd = std::make_shared<api::SetSystemStateCommand>(*state_bundle);
cmd->setPriority(api::StorageMessage::VERYHIGH);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
void ClusterControllerApiRpcService::RPC_activateClusterStateVersion(FRT_RPCRequest* req) {
if (_closed) {
LOG(debug, "Not handling RPC call activate_cluster_state_version() as we have closed");
req->SetError(RPCRequestWrapper::ERR_NODE_SHUTTING_DOWN, "Node shutting down");
return;
}
const uint32_t activate_version = req->GetParams()->GetValue(0)._intval32;
auto cmd = std::make_shared<api::ActivateClusterStateVersionCommand>(activate_version);
cmd->setPriority(api::StorageMessage::VERYHIGH);
LOG(debug, "Got state activation request for version %u", activate_version);
detach_and_forward_to_enqueuer(std::move(cmd), req);
}
}
|
Add capability filter to cluster controller API RPCs on content nodes
|
Add capability filter to cluster controller API RPCs on content nodes
|
C++
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
962a4c2cc63c106d0f6da143530aa199dd020773
|
stan/math/opencl/prim/beta_lpdf.hpp
|
stan/math/opencl/prim/beta_lpdf.hpp
|
#ifndef STAN_MATH_OPENCL_PRIM_BETA_LPDF_HPP
#define STAN_MATH_OPENCL_PRIM_BETA_LPDF_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/prim/size.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
namespace stan {
namespace math {
/** \ingroup opencl
* The log of the beta density for the specified scalar(s) given the specified
* sample stan::math::size(s). y, alpha, or beta can each either be scalar or a
* vector on OpenCL device. Any vector inputs must be the same length.
*
* <p> The result log probability is defined to be the sum of
* the log probabilities for each observation/alpha/beta triple.
*
* Prior sample sizes, alpha and beta, must be greater than 0.
*
* @tparam T_y_cl type of scalar outcome
* @tparam T_scale_succ_cl type of prior scale for successes
* @tparam T_scale_fail_cl type of prior scale for failures
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) prior sample stan::math::size(s).
* @param beta (Sequence of) prior sample stan::math::size(s).
* @return The log of the product of densities.
*/
template <bool propto, typename T_y_cl, typename T_scale_succ_cl,
typename T_scale_fail_cl,
require_all_prim_or_rev_kernel_expression_t<
T_y_cl, T_scale_succ_cl, T_scale_fail_cl>* = nullptr,
require_any_not_stan_scalar_t<T_y_cl, T_scale_succ_cl,
T_scale_fail_cl>* = nullptr>
return_type_t<T_y_cl, T_scale_succ_cl, T_scale_fail_cl> beta_lpdf(
const T_y_cl& y, const T_scale_succ_cl& alpha,
const T_scale_fail_cl& beta) {
using std::isfinite;
static const char* function = "beta_lpdf(OpenCL)";
using T_partials_return
= partials_return_t<T_y_cl, T_scale_succ_cl, T_scale_fail_cl>;
check_consistent_sizes(function, "Random variable", y,
"First shape parameter", alpha,
"Second shape parameter", beta);
const size_t N = max_size(y, alpha, beta);
if (N == 0) {
return 0.0;
}
if (!include_summand<propto, T_y_cl, T_scale_succ_cl,
T_scale_fail_cl>::value) {
return 0.0;
}
const auto& y_val = value_of(y);
const auto& alpha_val = value_of(alpha);
const auto& beta_val = value_of(beta);
operands_and_partials<T_y_cl, T_scale_succ_cl, T_scale_fail_cl> ops_partials(
y, alpha, beta);
auto check_alpha_pos_finite = check_cl(function, "First shape parameter",
alpha_val, "positive finite");
auto alpha_pos_finite = alpha_val > 0 && isfinite(alpha_val);
auto check_beta_pos_finite = check_cl(function, "Second shape parameter",
beta_val, "positive finite");
auto beta_pos_finite = beta_val > 0 && isfinite(beta_val);
auto check_y_bounded
= check_cl(function, "Random variable", y_val, "in the interval [0, 1]");
auto y_bounded = 0 <= y_val && y_val <= 1;
auto log_y_expr = log(y_val);
auto log1m_y_expr = log1p(-y_val);
auto alpha_beta_expr = alpha_val + beta_val;
auto zero_expr
= as_operation_cl(0); // simplifiy the kernel by only using one zero
auto logp_expr = colwise_sum(
static_select<include_summand<propto, T_scale_succ_cl>::value>(
-lgamma(alpha_val), zero_expr)
+ static_select<include_summand<propto, T_scale_fail_cl>::value>(
-lgamma(beta_val), zero_expr)
+ static_select<include_summand<propto, T_y_cl, T_scale_succ_cl>::value>(
elt_multiply((alpha_val - 1.0), log_y_expr), zero_expr)
+ static_select<include_summand<propto, T_y_cl, T_scale_fail_cl>::value>(
elt_multiply((beta_val - 1.0), log1m_y_expr), zero_expr)
+ static_select<
include_summand<propto, T_scale_succ_cl, T_scale_fail_cl>::value>(
lgamma(alpha_beta_expr), zero_expr));
auto y_deriv_expr = calc_if<!is_constant<T_y_cl>::value>(
elt_divide((alpha_val - 1), y_val)
+ elt_divide((beta_val - 1), (y_val - 1)));
auto digamma_alpha_beta_expr = digamma(alpha_beta_expr);
auto alpha_deriv_expr = calc_if<!is_constant<T_scale_succ_cl>::value>(
log_y_expr + digamma_alpha_beta_expr - digamma(alpha_val));
auto beta_deriv_expr = calc_if<!is_constant<T_scale_fail_cl>::value>(
log1m_y_expr + digamma_alpha_beta_expr - digamma(beta_val));
matrix_cl<double> logp_cl;
matrix_cl<double> y_deriv_cl;
matrix_cl<double> alpha_deriv_cl;
matrix_cl<double> beta_deriv_cl;
results(check_alpha_pos_finite, check_beta_pos_finite, check_y_bounded,
logp_cl, y_deriv_cl, alpha_deriv_cl, beta_deriv_cl)
= expressions(alpha_pos_finite, beta_pos_finite, y_bounded, logp_expr,
y_deriv_expr, alpha_deriv_expr, beta_deriv_expr);
T_partials_return logp = sum(from_matrix_cl(logp_cl));
if (!is_constant<T_y_cl>::value) {
ops_partials.edge1_.partials_ = std::move(y_deriv_cl);
}
if (!is_constant<T_scale_succ_cl>::value) {
ops_partials.edge2_.partials_ = std::move(alpha_deriv_cl);
}
if (!is_constant<T_scale_fail_cl>::value) {
ops_partials.edge3_.partials_ = std::move(beta_deriv_cl);
}
return ops_partials.build(logp);
}
} // namespace math
} // namespace stan
#endif
#endif
|
#ifndef STAN_MATH_OPENCL_PRIM_BETA_LPDF_HPP
#define STAN_MATH_OPENCL_PRIM_BETA_LPDF_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/prim/size.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <stan/math/prim/fun/elt_multiply.hpp>
#include <stan/math/prim/fun/elt_divide.hpp>
namespace stan {
namespace math {
/** \ingroup opencl
* The log of the beta density for the specified scalar(s) given the specified
* sample stan::math::size(s). y, alpha, or beta can each either be scalar or a
* vector on OpenCL device. Any vector inputs must be the same length.
*
* <p> The result log probability is defined to be the sum of
* the log probabilities for each observation/alpha/beta triple.
*
* Prior sample sizes, alpha and beta, must be greater than 0.
*
* @tparam T_y_cl type of scalar outcome
* @tparam T_scale_succ_cl type of prior scale for successes
* @tparam T_scale_fail_cl type of prior scale for failures
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) prior sample stan::math::size(s).
* @param beta (Sequence of) prior sample stan::math::size(s).
* @return The log of the product of densities.
*/
template <bool propto, typename T_y_cl, typename T_scale_succ_cl,
typename T_scale_fail_cl,
require_all_prim_or_rev_kernel_expression_t<
T_y_cl, T_scale_succ_cl, T_scale_fail_cl>* = nullptr,
require_any_not_stan_scalar_t<T_y_cl, T_scale_succ_cl,
T_scale_fail_cl>* = nullptr>
return_type_t<T_y_cl, T_scale_succ_cl, T_scale_fail_cl> beta_lpdf(
const T_y_cl& y, const T_scale_succ_cl& alpha,
const T_scale_fail_cl& beta) {
using std::isfinite;
static const char* function = "beta_lpdf(OpenCL)";
using T_partials_return
= partials_return_t<T_y_cl, T_scale_succ_cl, T_scale_fail_cl>;
check_consistent_sizes(function, "Random variable", y,
"First shape parameter", alpha,
"Second shape parameter", beta);
const size_t N = max_size(y, alpha, beta);
if (N == 0) {
return 0.0;
}
if (!include_summand<propto, T_y_cl, T_scale_succ_cl,
T_scale_fail_cl>::value) {
return 0.0;
}
const auto& y_val = value_of(y);
const auto& alpha_val = value_of(alpha);
const auto& beta_val = value_of(beta);
operands_and_partials<T_y_cl, T_scale_succ_cl, T_scale_fail_cl> ops_partials(
y, alpha, beta);
auto check_alpha_pos_finite = check_cl(function, "First shape parameter",
alpha_val, "positive finite");
auto alpha_pos_finite = alpha_val > 0 && isfinite(alpha_val);
auto check_beta_pos_finite = check_cl(function, "Second shape parameter",
beta_val, "positive finite");
auto beta_pos_finite = beta_val > 0 && isfinite(beta_val);
auto check_y_bounded
= check_cl(function, "Random variable", y_val, "in the interval [0, 1]");
auto y_bounded = 0 <= y_val && y_val <= 1;
auto log_y_expr = log(y_val);
auto log1m_y_expr = log1p(-y_val);
auto alpha_beta_expr = alpha_val + beta_val;
auto zero_expr
= as_operation_cl(0); // simplifiy the kernel by only using one zero
auto logp_expr = colwise_sum(
static_select<include_summand<propto, T_scale_succ_cl>::value>(
-lgamma(alpha_val), zero_expr)
+ static_select<include_summand<propto, T_scale_fail_cl>::value>(
-lgamma(beta_val), zero_expr)
+ static_select<include_summand<propto, T_y_cl, T_scale_succ_cl>::value>(
elt_multiply((alpha_val - 1.0), log_y_expr), zero_expr)
+ static_select<include_summand<propto, T_y_cl, T_scale_fail_cl>::value>(
elt_multiply((beta_val - 1.0), log1m_y_expr), zero_expr)
+ static_select<
include_summand<propto, T_scale_succ_cl, T_scale_fail_cl>::value>(
lgamma(alpha_beta_expr), zero_expr));
auto y_deriv_expr = calc_if<!is_constant<T_y_cl>::value>(
elt_divide((alpha_val - 1), y_val)
+ elt_divide((beta_val - 1), (y_val - 1)));
auto digamma_alpha_beta_expr = digamma(alpha_beta_expr);
auto alpha_deriv_expr = calc_if<!is_constant<T_scale_succ_cl>::value>(
log_y_expr + digamma_alpha_beta_expr - digamma(alpha_val));
auto beta_deriv_expr = calc_if<!is_constant<T_scale_fail_cl>::value>(
log1m_y_expr + digamma_alpha_beta_expr - digamma(beta_val));
matrix_cl<double> logp_cl;
matrix_cl<double> y_deriv_cl;
matrix_cl<double> alpha_deriv_cl;
matrix_cl<double> beta_deriv_cl;
results(check_alpha_pos_finite, check_beta_pos_finite, check_y_bounded,
logp_cl, y_deriv_cl, alpha_deriv_cl, beta_deriv_cl)
= expressions(alpha_pos_finite, beta_pos_finite, y_bounded, logp_expr,
y_deriv_expr, alpha_deriv_expr, beta_deriv_expr);
T_partials_return logp = sum(from_matrix_cl(logp_cl));
if (!is_constant<T_y_cl>::value) {
ops_partials.edge1_.partials_ = std::move(y_deriv_cl);
}
if (!is_constant<T_scale_succ_cl>::value) {
ops_partials.edge2_.partials_ = std::move(alpha_deriv_cl);
}
if (!is_constant<T_scale_fail_cl>::value) {
ops_partials.edge3_.partials_ = std::move(beta_deriv_cl);
}
return ops_partials.build(logp);
}
} // namespace math
} // namespace stan
#endif
#endif
|
add elt_multiply/elt_divide includes
|
add elt_multiply/elt_divide includes
|
C++
|
bsd-3-clause
|
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
|
63ba3108b3821e94858171929227a19f1f16537f
|
ArticyImporter/Source/ArticyImporter/Private/CodeGeneration/InterfacesGenerator.cpp
|
ArticyImporter/Source/ArticyImporter/Private/CodeGeneration/InterfacesGenerator.cpp
|
//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "InterfacesGenerator.h"
#include "CodeFileGenerator.h"
#include "ObjectDefinitionsImport.h"
#include "ArticyImportData.h"
void InterfacesGenerator::GenerateCode(const UArticyImportData* Data)
{
CodeFileGenerator(CodeGenerator::GetGeneratedInterfacesFilename(Data)+".h", true, [&](CodeFileGenerator* header)
{
header->Line("#include \"CoreUObject.h\"");
header->Line("#include \"" + CodeGenerator::GetGeneratedInterfacesFilename(Data) + ".generated.h\"");
header->Line();
for (auto pair : Data->GetObjectDefs().GetFeatures())
{
FArticyTemplateFeatureDef feature = pair.Value;
header->Line();
header->UInterface(CodeGenerator::GetFeatureInterfaceClassName(Data, feature, true),
"MinimalAPI, BlueprintType, Category=\"" + Data->GetProject().TechnicalName + " Feature Interfaces\", meta=(CannotImplementInterfaceInBlueprint)",
"UNINTERFACE generated from Articy " + feature.GetDisplayName() + " Feature", [&]
{
header->Line("public:", false, true, -1);
header->Line();
header->Method("virtual class " + feature.GetCppType(Data, true), "GetFeature" + feature.GetTechnicalName(), "", [&]
{
header->Line("return nullptr", true);
}, "", true, "BlueprintCallable", "const");
});
}
});
}
|
//
// Copyright (c) articy Software GmbH & Co. KG. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
#include "InterfacesGenerator.h"
#include "CodeFileGenerator.h"
#include "ObjectDefinitionsImport.h"
#include "ArticyImportData.h"
void InterfacesGenerator::GenerateCode(const UArticyImportData* Data)
{
CodeFileGenerator(CodeGenerator::GetGeneratedInterfacesFilename(Data)+".h", true, [&](CodeFileGenerator* header)
{
header->Line("#include \"CoreUObject.h\"");
if(Data->GetObjectDefs().GetFeatures().Num() > 0)
header->Line("#include \"" + CodeGenerator::GetGeneratedInterfacesFilename(Data) + ".generated.h\"");
header->Line();
for (auto pair : Data->GetObjectDefs().GetFeatures())
{
FArticyTemplateFeatureDef feature = pair.Value;
header->Line();
header->UInterface(CodeGenerator::GetFeatureInterfaceClassName(Data, feature, true),
"MinimalAPI, BlueprintType, Category=\"" + Data->GetProject().TechnicalName + " Feature Interfaces\", meta=(CannotImplementInterfaceInBlueprint)",
"UNINTERFACE generated from Articy " + feature.GetDisplayName() + " Feature", [&]
{
header->Line("public:", false, true, -1);
header->Line();
header->Method("virtual class " + feature.GetCppType(Data, true), "GetFeature" + feature.GetTechnicalName(), "", [&]
{
header->Line("return nullptr", true);
}, "", true, "BlueprintCallable", "const");
});
}
});
}
|
Fix invalid code generation for interfaces when no interfaces are in the project.
|
Fix invalid code generation for interfaces when no interfaces are in the project.
|
C++
|
mit
|
ArticySoftware/ArticyImporterForUnreal,ArticySoftware/ArticyImporterForUnreal,ArticySoftware/ArticyImporterForUnreal
|
e397e5d32567a12bffc9de865202a23a3e0ed96e
|
cpp/ql/test/experimental/library-tests/rangeanalysis/arraylengthanalysis/test.cpp
|
cpp/ql/test/experimental/library-tests/rangeanalysis/arraylengthanalysis/test.cpp
|
void *malloc(unsigned long);
void sink(...);
typedef struct A {
int a;
int b;
char * c;
} A;
void test1(unsigned int count) {
if (count < 1) {
return;
}
A* aptr = (A *) malloc(sizeof(A) * count);
sink(aptr); // (count, 0, Zero, 0)
unsigned int* ptr = &count;
sink(ptr); // (Zero, 1, Zero, 0) TODO none, as the feature is not implemented
int* a = (int *) malloc(sizeof(int) * count);
sink(a); // (count, 0, Zero, 0)
a = (int *) malloc(sizeof(int) * (count - 1));
sink(a); // (count, -1, Zero, 0)
a = (int *) malloc(sizeof(int) * (count + 1));
sink(a); // (count, 1, Zero, 0)
a = (int *) malloc(sizeof(int) * (2 * count));
sink(a); // none, as the size expression is too complicated
char* c = (char *)malloc(count);
sink(c); // /count, 0, Zero, 0)
sink((unsigned char*)c); // (count, 0, Zero, 0)
void* v = c;
sink(v); // (count, 0, Zero, 0)
v = malloc(count);
sink((char *)v); // none, as we don't track void* allocations
int stack[100];
sink(stack); // (Zero, 100, Zero, 0)
for(unsigned int i = 0; i < count; ++i) {
int* b = (int*) malloc(sizeof(int) * count);
sink(b); // (count, 0, Zero, 0)
}
}
void test2(unsigned int count, bool b) {
int* a = (int *) malloc(sizeof(int) * count);
a = a + 2;
sink(a); // (count, 0, Zero, 2)
for(unsigned int i = 2; i < count; ++i) {
sink(a); // none
a++;
sink(a); // none
}
a = (int*) malloc(sizeof(int) * count);
if (b) {
a += 2;
sink(a); // (count, 0, Zero, 2)
} else {
a += 3;
sink(a); // (count, 0, Zero, 2)
}
sink(a); // none
a -= 2;
sink(a); // none
a = (int*) malloc(sizeof(int) * count);
for(unsigned int i = 0; i < count; i++) {
sink(&a[i]); // (count, 0, i, 0)
}
a = (int*) malloc(sizeof(int) * count);
sink(a); // (count, 0, Zero, 0)
a += 3;
sink(a); // (count, 0, Zero, 3)
a -= 1;
sink(a); // (count, 0, Zero, 2)
a -= 2;
sink(a); // (count, 0, Zero, 0)
a -= 10;
sink(a); // (count, 0, Zero, -10)
a = (int*) malloc(sizeof(int) * (count + 1));
sink(a); // (count, 1, Zero, 0)
a += count;
sink(a); // (count, 1, count, 0);
a += 1;
sink(a); // (count, 1, count, 1);
a -= count;
sink(a); // none
a = (int*) malloc(sizeof(int) * (count + 1));
a += count + 1;
sink(a); // TODO, should be (count, 1, count, 1), but is (count, 1, count + 1, 0)
a += 1;
sink(a); // TODO, should be (count, 1, count, 2), but is (count, 1, count + 1, 1)
a = (int*) malloc(sizeof(int) * (1024 - count));
sink(a); // none, as the size expression is too complicated
}
|
void *malloc(unsigned long);
void sink(...);
typedef struct A {
int a;
int b;
char * c;
} A;
void test1(unsigned int count) {
if (count < 1) {
return;
}
A* aptr = (A *) malloc(sizeof(A) * count);
sink(aptr); // (count, 0, Zero, 0)
unsigned int* ptr = &count;
sink(ptr); // (Zero, 1, Zero, 0) TODO none, as the feature is not implemented
int* a = (int *) malloc(sizeof(int) * count);
sink(a); // (count, 0, Zero, 0)
a = (int *) malloc(sizeof(int) * (count - 1));
sink(a); // (count, -1, Zero, 0)
a = (int *) malloc(sizeof(int) * (count + 1));
sink(a); // (count, 1, Zero, 0)
a = (int *) malloc(sizeof(int) * (2 * count));
sink(a); // none, as the size expression is too complicated
char* c = (char *)malloc(count);
sink(c); // /count, 0, Zero, 0)
sink((unsigned char*)c); // (count, 0, Zero, 0)
void* v = c;
sink(v); // (count, 0, Zero, 0)
v = malloc(count);
sink((char *)v); // none, as we don't track void* allocations
int stack[100];
sink(stack); // (Zero, 100, Zero, 0)
for(unsigned int i = 0; i < count; ++i) {
int* b = (int*) malloc(sizeof(int) * count);
sink(b); // (count, 0, Zero, 0)
}
}
void test2(unsigned int count, bool b) {
int* a = (int *) malloc(sizeof(int) * count);
a = a + 2;
sink(a); // (count, 0, Zero, 2)
for(unsigned int i = 2; i < count; ++i) {
sink(a); // none
a++;
sink(a); // none
}
a = (int*) malloc(sizeof(int) * count);
if (b) {
a += 2;
sink(a); // (count, 0, Zero, 2)
} else {
a += 3;
sink(a); // (count, 0, Zero, 2)
}
sink(a); // none
a -= 2;
sink(a); // none
a = (int*) malloc(sizeof(int) * count);
for(unsigned int i = 0; i < count; i++) {
sink(&a[i]); // (count, 0, i, 0)
}
a = (int*) malloc(sizeof(int) * count);
sink(a); // (count, 0, Zero, 0)
a += 3;
sink(a); // (count, 0, Zero, 3)
a -= 1;
sink(a); // (count, 0, Zero, 2)
a -= 2;
sink(a); // (count, 0, Zero, 0)
a -= 10;
sink(a); // (count, 0, Zero, -10)
a = (int*) malloc(sizeof(int) * (count + 1));
sink(a); // (count, 1, Zero, 0)
a += count;
sink(a); // (count, 1, count, 0);
a += 1;
sink(a); // (count, 1, count, 1);
a -= count;
sink(a); // none
a = (int*) malloc(sizeof(int) * (count + 1));
a += count + 1;
sink(a); // TODO, should be (count, 1, count, 1), but is (count, 1, count + 1, 0)
a += 1;
sink(a); // TODO, should be (count, 1, count, 2), but is (count, 1, count + 1, 1)
a = (int*) malloc(sizeof(int) * (1024 - count));
sink(a); // none, as the size expression is too complicated
}
void test3(unsigned int object) {
unsigned int* ptr = &object;
sink(ptr); // TODO, none, but should be (Zero, 1, Zero, 0)
}
|
Add new testcase to arraylengthanalysis library.
|
Add new testcase to arraylengthanalysis library.
|
C++
|
mit
|
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
|
f844f8f0afc1cb721d809e8ebe368020481d49b9
|
AI/aialphabeta.cpp
|
AI/aialphabeta.cpp
|
#include "aialphabeta.h"
#include <QVector>
#include <QPoint>
#include <QDebug>
#include "constants.h"
#define n BOARD_SIZE
#define INF 1000000
#define timelimit 1000
#define check(x, y) ((x) >= 0 && (x) < n && (y) >= 0 && (y) < n)
struct Choice
{
Choice (int _score = 0, int _x = 0, int _y = 0)
: score(_score), x(_x), y(_y)
{
}
int score;
int x, y;
bool operator < (const Choice &o) const
{
return score > o.score;
}
};
AIAlphaBeta::AIAlphaBeta(QObject *parent) : AIThread(parent)
{
}
void AIAlphaBeta::run()
{
timer = 0;
rx = n / 2, ry = n / 2;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (chessboard[i][j] == BLACK) board[i][j] = 0;
else if (chessboard[i][j] == WHITE) board[i][j] = 1;
else board[i][j] = -1;
}
for (max_deep = 0; timer < timelimit; max_deep++)
{
int tmp = dfs(0, -INF - 233, INF + 233, max_deep);
qDebug() << "depth:" << max_deep << "expectance:" << tmp;
if (tmp <= -INF || tmp >= INF) break;
}
qDebug() << timer << "phases have been visited.";
response(rx, ry);
}
bool AIAlphaBeta::exist(const int &x, const int &y)
{
for (int dx = -2; dx <= 2; dx++)
for (int dy = -2; dy <= 2; dy++)
{
int p = x + dx, q = y + dy;
if (check(p, q) && chessboard[p][q] != -1) return true;
}
return false;
}
int AIAlphaBeta::dfs(int p, int alpha, int beta, int depth)
{
if (gameOver()) return -INF;
if (depth < 0) return evaluate() * (p ? -1 : 1);
timer++;
bool firstLayer = depth == max_deep;
QPoint tmpPoint;
tmpPoint = fourAlive(p);
if (tmpPoint.rx() != -1)
{
if (firstLayer)
{
rx = tmpPoint.rx();
ry = tmpPoint.ry();
}
return INF;
}
tmpPoint = fourAlive(p ^ 1);
if (tmpPoint.rx() != -1)
{
if (firstLayer)
{
rx = tmpPoint.rx();
ry = tmpPoint.ry();
return -INF;
}
board[tmpPoint.rx()][tmpPoint.ry()] = p;
int ret = - dfs(p ^ 1, -beta, -alpha, depth);
board[tmpPoint.rx()][tmpPoint.ry()] = -1;
return ret;
}
QVector<Choice> que;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (board[i][j] != -1) continue;
if (! exist(i, j)) continue;
que.push_back(Choice(
//potential(i, j, p) + potential(i, j, p ^ 1),
//qMax(potential(i, j, p), potential(i, j, p ^ 1)),
qMax(potential(i, j, p), potential(i, j, p ^ 1)) * 2 +
qMax(potential2(i, j, p), potential2(i, j, p ^ 1)),
i, j));
}
qSort(que);
while (que.size() > 10)
que.pop_back();
Choice c;
/*foreach (c, que) {
qDebug() << c.x << ' ' << c.y << ' ' << c.score;
}*/
foreach (c, que) {
board[c.x][c.y] = p;
int tmp = -dfs(p ^ 1, -beta, -alpha, depth - 1);
board[c.x][c.y] = -1;
if (tmp >= beta)
return beta;
if (tmp > alpha)
{
alpha = tmp;
if (firstLayer) rx = c.x, ry = c.y;
}
}
return alpha;
}
int AIAlphaBeta::potential(const int &x, const int &y, const int &p)
{
int ret = 0;
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
if (! dx && ! dy) continue;
int tmp = 0;
int c = 0;
for (int s = 1, px = x, py = y; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1))
{
tmp = 0;
break;
}
if (board[px][py] == -1) tmp += 1;
else // board[px][py] == p
{
c++;
tmp += (6 - s) * (6 - s);
}
}
ret += tmp;
}
return ret;
}
const int d4[][2] = {
{1, -1},
{1, 0},
{1, 1},
{0, 1},
};
int AIAlphaBeta::potential2(const int &x, const int &y, const int &p)
{
int ret = 0;
int dx, dy;
for (int d = 0; d < 4; d++)
{
int c = 0, cs = 1;
dx = d4[d][0], dy = d4[d][1];
for (int s = 1, px = x + dx, py = y + dy; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1)) break;
cs++;
if (board[px][py] == p) c++;
}
dx = -dx, dy = -dy;
for (int s = 1, px = x + dx, py = y + dy; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1)) break;
cs++;
if (board[px][py] == p) c++;
}
if (cs >= 5) ret += c * c * c;
}
return ret;
}
QPoint AIAlphaBeta::fourAlive(const int &p)
{
for (int d = 0; d < 4; d++)
{
int dx = d4[d][0];
int dy = d4[d][1];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (board[i][j] != -1) continue;
int c = 0;
for (int x = i + dx, y = j + dy; check(x, y) && board[x][y] == p; x += dx, y += dy) c++;
for (int x = i - dx, y = j - dy; check(x, y) && board[x][y] == p; x -= dx, y -= dy) c++;
if (c >= 4) return QPoint(i, j);
}
}
return QPoint(-1, -1);
}
int AIAlphaBeta::evaluate()
{
int ret = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
int t = board[i][j];
if (t == -1) continue;
ret += potential(i, j, t) * (board[i][j] == 0 ? 1 : -1);
}
return ret;
}
bool AIAlphaBeta::gameOver()
{
for (int i = 0; i < n; i++)
{
if (linkCheck(i, 0, 0, 1)) return true;
if (linkCheck(0, i, 1, 0)) return true;
if (linkCheck(i, 0, 1, 1)) return true;
if (linkCheck(i, 0, -1, 1)) return true;
if (linkCheck(0, i, 1, 1)) return true;
if (linkCheck(n - 1, i, -1, 1)) return true;
}
return false;
}
bool AIAlphaBeta::linkCheck(int x, int y, int dx, int dy)
{
int c = -1, s = 0;
for (; check(x, y); x += dx, y += dy)
{
int t = board[x][y];
if (t == c)
{
s++;
if (s >= 5 && t != -1)
{
return true;
}
}
else
{
c = t;
s = 1;
}
}
return false;
}
#undef n
#undef INF
#undef timelimit
#undef check
|
#include "aialphabeta.h"
#include <QVector>
#include <QPoint>
#include <QDebug>
#include "constants.h"
#define n BOARD_SIZE
#define INF 1000000
#define timelimit 12345
#define check(x, y) ((x) >= 0 && (x) < n && (y) >= 0 && (y) < n)
struct Choice
{
Choice (int _score = 0, int _x = 0, int _y = 0)
: score(_score), x(_x), y(_y)
{
}
int score;
int x, y;
bool operator < (const Choice &o) const
{
return score > o.score;
}
};
AIAlphaBeta::AIAlphaBeta(QObject *parent) : AIThread(parent)
{
}
void AIAlphaBeta::run()
{
timer = 0;
rx = n / 2, ry = n / 2;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (chessboard[i][j] == BLACK) board[i][j] = 0;
else if (chessboard[i][j] == WHITE) board[i][j] = 1;
else board[i][j] = -1;
}
for (max_deep = 0; timer < timelimit; max_deep++)
{
int tmp = dfs(0, -INF - 233, INF + 233, max_deep);
qDebug() << "depth:" << max_deep << "expectance:" << tmp;
if (tmp <= -INF || tmp >= INF) break;
}
qDebug() << timer << "phases have been visited.";
response(rx, ry);
}
bool AIAlphaBeta::exist(const int &x, const int &y)
{
for (int dx = -2; dx <= 2; dx++)
for (int dy = -2; dy <= 2; dy++)
{
int p = x + dx, q = y + dy;
if (check(p, q) && chessboard[p][q] != -1) return true;
}
return false;
}
int AIAlphaBeta::dfs(int p, int alpha, int beta, int depth)
{
if (gameOver()) return -INF;
if (depth < 0) return evaluate() * (p ? -1 : 1);
timer++;
bool firstLayer = depth == max_deep;
QPoint tmpPoint;
tmpPoint = fourAlive(p);
if (tmpPoint.rx() != -1)
{
if (firstLayer)
{
rx = tmpPoint.rx();
ry = tmpPoint.ry();
}
return INF;
}
tmpPoint = fourAlive(p ^ 1);
if (tmpPoint.rx() != -1)
{
if (firstLayer)
{
rx = tmpPoint.rx();
ry = tmpPoint.ry();
return -INF;
}
board[tmpPoint.rx()][tmpPoint.ry()] = p;
int ret = - dfs(p ^ 1, -beta, -alpha, depth);
board[tmpPoint.rx()][tmpPoint.ry()] = -1;
return ret;
}
QVector<Choice> que;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (board[i][j] != -1) continue;
if (! exist(i, j)) continue;
que.push_back(Choice(
//potential(i, j, p) + potential(i, j, p ^ 1),
//qMax(potential(i, j, p), potential(i, j, p ^ 1)),
qMax(potential(i, j, p), potential(i, j, p ^ 1)) +
qMax(potential2(i, j, p), potential2(i, j, p ^ 1)) * 2,
i, j));
}
qSort(que);
while (que.size() > 10)
que.pop_back();
Choice c;
/*foreach (c, que) {
qDebug() << c.x << ' ' << c.y << ' ' << c.score;
}*/
foreach (c, que) {
board[c.x][c.y] = p;
int tmp = -dfs(p ^ 1, -beta, -alpha, depth - 1);
board[c.x][c.y] = -1;
if (tmp >= beta)
return beta;
if (tmp > alpha)
{
alpha = tmp;
if (firstLayer) rx = c.x, ry = c.y;
}
}
return alpha;
}
int AIAlphaBeta::potential(const int &x, const int &y, const int &p)
{
int ret = 0;
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
if (! dx && ! dy) continue;
int tmp = 0;
for (int s = 1, px = x, py = y; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1))
{
tmp = 0;
break;
}
if (board[px][py] == -1) tmp += 1;
else // board[px][py] == p
{
tmp += (6 - s) * (6 - s);
}
}
ret += tmp;
}
return ret;
}
const int d4[][2] = {
{1, -1},
{1, 0},
{1, 1},
{0, 1},
};
int AIAlphaBeta::potential2(const int &x, const int &y, const int &p)
{
int ret = 0;
int dx, dy;
for (int d = 0; d < 4; d++)
{
int c = 0, cs = 1;
dx = d4[d][0], dy = d4[d][1];
for (int s = 1, px = x + dx, py = y + dy; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1)) break;
cs++;
if (board[px][py] == p) c++;
}
dx = -dx, dy = -dy;
for (int s = 1, px = x + dx, py = y + dy; s < 5; s++, px += dx, py += dy)
{
if (! check(px, py)) break;
if (board[px][py] == (p ^ 1)) break;
cs++;
if (board[px][py] == p) c++;
}
if (cs >= 5) ret += c * c * c;
}
return ret;
}
QPoint AIAlphaBeta::fourAlive(const int &p)
{
for (int d = 0; d < 4; d++)
{
int dx = d4[d][0];
int dy = d4[d][1];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
if (board[i][j] != -1) continue;
int c = 0;
for (int x = i + dx, y = j + dy; check(x, y) && board[x][y] == p; x += dx, y += dy) c++;
for (int x = i - dx, y = j - dy; check(x, y) && board[x][y] == p; x -= dx, y -= dy) c++;
if (c >= 4) return QPoint(i, j);
}
}
return QPoint(-1, -1);
}
int AIAlphaBeta::evaluate()
{
int ret = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
int t = board[i][j];
if (t == -1) continue;
ret += potential(i, j, t) * (board[i][j] == 0 ? 1 : -1);
}
return ret;
}
bool AIAlphaBeta::gameOver()
{
for (int i = 0; i < n; i++)
{
if (linkCheck(i, 0, 0, 1)) return true;
if (linkCheck(0, i, 1, 0)) return true;
if (linkCheck(i, 0, 1, 1)) return true;
if (linkCheck(i, 0, -1, 1)) return true;
if (linkCheck(0, i, 1, 1)) return true;
if (linkCheck(n - 1, i, -1, 1)) return true;
}
return false;
}
bool AIAlphaBeta::linkCheck(int x, int y, int dx, int dy)
{
int c = -1, s = 0;
for (; check(x, y); x += dx, y += dy)
{
int t = board[x][y];
if (t == c)
{
s++;
if (s >= 5 && t != -1)
{
return true;
}
}
else
{
c = t;
s = 1;
}
}
return false;
}
#undef n
#undef INF
#undef timelimit
#undef check
|
fix bug
|
fix bug
|
C++
|
mit
|
wangck1998/Gomoku-AI,wangck1998/Gomoku-AI
|
97b272657434f9fb2194ec4316f9100518477fc7
|
naturalneighbor/naturalneighbor.cpp
|
naturalneighbor/naturalneighbor.cpp
|
#include <cmath>
#include <vector>
#include "kdtree.h"
#include "geometry.h"
#include "naturalneighbor.h"
namespace naturalneighbor {
typedef geometry::Point <double, 3> Point;
std::vector<double> *natural_neighbor(std::vector<Point>& known_coordinates,
std::vector<double>& known_values,
std::vector<Point>& interpolation_points,
int coord_max) {
/*
* Assumptions:
* - known_coordinates and known_values are in parallel
* - interpolation_points are regularly spaced and ordered
* such that X is the outermost loop, then Y, then Z.
*/
kdtree::kdtree<double> *tree = new kdtree::kdtree<double>();
for (std::size_t i = 0; i < known_coordinates.size(); i++) {
tree->add(&known_coordinates[i], &known_values[i]);
}
tree->build();
auto interpolation_values = new std::vector<double>(interpolation_points.size(), 0);
auto contribution_counter = new std::vector<double>(interpolation_points.size(), 0);
int xscale = coord_max*coord_max;
int yscale = coord_max;
// Scatter method discrete Sibson
// For each interpolation point p, search neighboring interpolation points
// within a sphere of radius r, where r = distance to nearest known point.
for (std::size_t i = 0; i < interpolation_points.size(); i++) {
const kdtree::QueryResult *q = tree->nearest_iterative(interpolation_points[i]);
double comparison_distance = q->distance; // Actually distance squared
int r = floor(sqrt(comparison_distance));
int px = interpolation_points[i][0];
int py = interpolation_points[i][1];
int pz = interpolation_points[i][2];
// Search neighboring interpolation points within a bounding box
// of r indices. From this subset of points, calculate their distance
// and tally the ones that fall within the sphere of radius r surrounding
// interpolation_points[i].
for (auto x = px - r; x < px + r; x++) {
if (x < 0 || x >= coord_max) { continue; }
for (auto y = py - r; y < py + r; y++) {
if (y < 0 || y >= coord_max) { continue; }
for (auto z = pz - r; z < pz + r; z++) {
if (z < 0 || z >= coord_max) { continue; }
int idx = x*xscale + y*yscale + z;
double distance_x = interpolation_points[idx][0] - px;
double distance_y = interpolation_points[idx][1] - py;
double distance_z = interpolation_points[idx][2] - pz;
if (distance_x*distance_x + distance_y*distance_y
+ distance_z*distance_z > comparison_distance){
continue;
}
(*interpolation_values)[idx] += q->value;
(*contribution_counter)[idx] += 1;
}
}
}
}
for (std::size_t i = 0; i < interpolation_values->size(); i++) {
if ((*contribution_counter)[i] != 0) {
(*interpolation_values)[i] /= (*contribution_counter)[i];
} else {
(*interpolation_values)[i] = 0; //TODO: this is just 0, better way to mark NAN?
}
}
delete tree;
delete contribution_counter;
return interpolation_values;
}
} // namespace naturalneighbor
|
#include <cmath>
#include <vector>
#include "kdtree.h"
#include "geometry.h"
#include "naturalneighbor.h"
namespace naturalneighbor {
typedef geometry::Point <double, 3> Point;
std::vector<double> *natural_neighbor(std::vector<Point>& known_coordinates,
std::vector<double>& known_values,
std::vector<Point>& interpolation_points,
int coord_max) {
/*
* Assumptions:
* - known_coordinates and known_values are in parallel
* - interpolation_points are regularly spaced and ordered
* such that X is the outermost loop, then Y, then Z.
*/
kdtree::kdtree<double> *tree = new kdtree::kdtree<double>();
for (std::size_t i = 0; i < known_coordinates.size(); i++) {
tree->add(&known_coordinates[i], &known_values[i]);
}
tree->build();
auto interpolation_values = new std::vector<double>(interpolation_points.size(), 0.0);
auto contribution_counter = new std::vector<int>(interpolation_points.size(), 0);
int xscale = coord_max*coord_max;
int yscale = coord_max;
// Scatter method discrete Sibson
// For each interpolation point p, search neighboring interpolation points
// within a sphere of radius r, where r = distance to nearest known point.
for (std::size_t i = 0; i < interpolation_points.size(); i++) {
const kdtree::QueryResult *q = tree->nearest_iterative(interpolation_points[i]);
double comparison_distance = q->distance; // Actually distance squared
int r = floor(sqrt(comparison_distance));
int px = interpolation_points[i][0];
int py = interpolation_points[i][1];
int pz = interpolation_points[i][2];
// Search neighboring interpolation points within a bounding box
// of r indices. From this subset of points, calculate their distance
// and tally the ones that fall within the sphere of radius r surrounding
// interpolation_points[i].
for (auto x = px - r; x < px + r; x++) {
if (x < 0 || x >= coord_max) { continue; }
for (auto y = py - r; y < py + r; y++) {
if (y < 0 || y >= coord_max) { continue; }
for (auto z = pz - r; z < pz + r; z++) {
if (z < 0 || z >= coord_max) { continue; }
int idx = x*xscale + y*yscale + z;
double distance_x = interpolation_points[idx][0] - px;
double distance_y = interpolation_points[idx][1] - py;
double distance_z = interpolation_points[idx][2] - pz;
if (distance_x*distance_x + distance_y*distance_y
+ distance_z*distance_z > comparison_distance){
continue;
}
(*interpolation_values)[idx] += q->value;
(*contribution_counter)[idx] += 1;
}
}
}
}
for (std::size_t i = 0; i < interpolation_values->size(); i++) {
if ((*contribution_counter)[i] != 0) {
(*interpolation_values)[i] /= (*contribution_counter)[i];
} else {
(*interpolation_values)[i] = 0; //TODO: this is just 0, better way to mark NAN?
}
}
delete tree;
delete contribution_counter;
return interpolation_values;
}
} // namespace naturalneighbor
|
Make contribution counter use integers
|
Make contribution counter use integers
|
C++
|
mit
|
innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation
|
71baed437d9b50c303f46ffe79ca118ad14e1735
|
rcl/test/rcl/test_subscription_content_filter_options.cpp
|
rcl/test/rcl/test_subscription_content_filter_options.cpp
|
// Copyright 2022 Open Source Robotics Foundation, 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 <gtest/gtest.h>
#include "rcl/error_handling.h"
#include "rcl/node.h"
#include "rcl/rcl.h"
#include "rcl/subscription.h"
#include "osrf_testing_tools_cpp/scope_exit.hpp"
#include "test_msgs/msg/basic_types.h"
TEST(TestSubscriptionOptionsContentFilter, subscription_options_failure) {
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
const char * filter_expression1 = "filter=1";
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 1, nullptr, &subscription_options)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_fini(
nullptr)
);
rcl_reset_error();
}
TEST(TestSubscriptionOptionsContentFilter, subscription_options_success)
{
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
const char * filter_expression1 = "filter=1";
{
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 0, nullptr, &subscription_options)
);
rmw_subscription_content_filter_options_t * content_filter_options =
subscription_options.rmw_subscription_options.content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression1, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
}
const char * filter_expression2 = "(filter1=%0 OR filter1=%1) AND filter2=%2";
const char * expression_parameters2[] = {
"1", "2", "3",
};
size_t expression_parameters_count2 = sizeof(expression_parameters2) / sizeof(char *);
{
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_set_content_filter_options(
filter_expression2, expression_parameters_count2,
expression_parameters2, &subscription_options)
);
rmw_subscription_content_filter_options_t * content_filter_options =
subscription_options.rmw_subscription_options.content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2[i]);
}
}
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_fini(&subscription_options)
);
}
class TestSubscriptionContentFilterOptions : public ::testing::Test
{
public:
rcl_context_t * context_ptr;
rcl_node_t * node_ptr;
rcl_subscription_t * subscription_ptr;
void SetUp()
{
rcl_ret_t ret;
{
rcl_init_options_t init_options = rcl_get_zero_initialized_init_options();
ret = rcl_init_options_init(&init_options, rcl_get_default_allocator());
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT(
{
EXPECT_EQ(RCL_RET_OK, rcl_init_options_fini(&init_options)) << rcl_get_error_string().str;
});
this->context_ptr = new rcl_context_t;
*this->context_ptr = rcl_get_zero_initialized_context();
ret = rcl_init(0, nullptr, &init_options, this->context_ptr);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
this->node_ptr = new rcl_node_t;
*this->node_ptr = rcl_get_zero_initialized_node();
constexpr char name[] = "test_subscription_content_filter_options_node";
rcl_node_options_t node_options = rcl_node_get_default_options();
ret = rcl_node_init(this->node_ptr, name, "", this->context_ptr, &node_options);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
const rosidl_message_type_support_t * ts =
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes);
constexpr char topic[] = "chatter";
this->subscription_ptr = new rcl_subscription_t;
*this->subscription_ptr = rcl_get_zero_initialized_subscription();
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
ret = rcl_subscription_init(
this->subscription_ptr, this->node_ptr, ts, topic, &subscription_options);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
void TearDown()
{
rcl_ret_t ret = rcl_subscription_fini(this->subscription_ptr, this->node_ptr);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_node_fini(this->node_ptr);
delete this->node_ptr;
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_shutdown(this->context_ptr);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_context_fini(this->context_ptr);
delete this->context_ptr;
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
};
TEST_F(TestSubscriptionContentFilterOptions, content_filter_options_failure) {
rcl_subscription_content_filter_options_t content_filter_options =
rcl_get_zero_initialized_subscription_content_filter_options();
const char * filter_expression1 = "filter=1";
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_init(
nullptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
this->subscription_ptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
this->subscription_ptr, filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
this->subscription_ptr, filter_expression1, 1, nullptr, &content_filter_options)
);
rcl_reset_error();
// set
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_set(
nullptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
this->subscription_ptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
this->subscription_ptr, filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
this->subscription_ptr, filter_expression1, 1, nullptr, &content_filter_options)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_fini(
nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_fini(
this->subscription_ptr, nullptr)
);
rcl_reset_error();
}
TEST_F(TestSubscriptionContentFilterOptions, content_filter_options_success)
{
rmw_subscription_content_filter_options_t * content_filter_options;
const char * filter_expression1 = "filter=1";
const char * filter_expression1_update = "filter=2";
rcl_subscription_content_filter_options_t subscription_content_filter_options =
rcl_get_zero_initialized_subscription_content_filter_options();
{
// init with filter_expression1
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_init(
this->subscription_ptr, filter_expression1, 0, nullptr,
&subscription_content_filter_options)
);
content_filter_options =
&subscription_content_filter_options.rmw_subscription_content_filter_options;
EXPECT_STREQ(filter_expression1, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
// set with filter_expression1_update
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_set(
this->subscription_ptr, filter_expression1_update, 0, nullptr,
&subscription_content_filter_options)
);
content_filter_options =
&subscription_content_filter_options.rmw_subscription_content_filter_options;
EXPECT_STREQ(filter_expression1_update, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
}
const char * filter_expression2 = "(filter1=%0 OR filter1=%1) AND filter2=%2";
const char * expression_parameters2[] = {
"1", "2", "3",
};
size_t expression_parameters_count2 = sizeof(expression_parameters2) / sizeof(char *);
const char * filter_expression2_update = "(filter1=%0 AND filter1=%1) OR filter2=%2";
const char * expression_parameters2_update[] = {
"11", "22", "33",
};
size_t expression_parameters_count2_update = sizeof(expression_parameters2) / sizeof(char *);
rcl_subscription_content_filter_options_t subscription_content_filter_options2 =
rcl_get_zero_initialized_subscription_content_filter_options();
{
// init with filter_expression2 and expression_parameters2
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_init(
this->subscription_ptr, filter_expression2, expression_parameters_count2,
expression_parameters2, &subscription_content_filter_options2)
);
content_filter_options =
&subscription_content_filter_options2.rmw_subscription_content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2[i]);
}
// set with filter_expression2_update and expression_parameters2_update
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_set(
this->subscription_ptr, filter_expression2_update, expression_parameters_count2_update,
expression_parameters2_update, &subscription_content_filter_options2)
);
content_filter_options =
&subscription_content_filter_options2.rmw_subscription_content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2_update, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2_update,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2_update; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2_update[i]);
}
}
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_fini(
this->subscription_ptr, &subscription_content_filter_options)
);
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_fini(
this->subscription_ptr, &subscription_content_filter_options2)
);
}
|
// Copyright 2022 Open Source Robotics Foundation, 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 <gtest/gtest.h>
#include "rcl/error_handling.h"
#include "rcl/node.h"
#include "rcl/rcl.h"
#include "rcl/subscription.h"
#include "osrf_testing_tools_cpp/scope_exit.hpp"
#include "test_msgs/msg/basic_types.h"
TEST(TestSubscriptionOptionsContentFilter, subscription_options_failure) {
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
const char * filter_expression1 = "filter=1";
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 1, nullptr, &subscription_options)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_options_fini(
nullptr)
);
rcl_reset_error();
}
TEST(TestSubscriptionOptionsContentFilter, subscription_options_success)
{
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
const char * filter_expression1 = "filter=1";
{
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_set_content_filter_options(
filter_expression1, 0, nullptr, &subscription_options)
);
rmw_subscription_content_filter_options_t * content_filter_options =
subscription_options.rmw_subscription_options.content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression1, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
}
const char * filter_expression2 = "(filter1=%0 OR filter1=%1) AND filter2=%2";
const char * expression_parameters2[] = {
"1", "2", "3",
};
size_t expression_parameters_count2 = sizeof(expression_parameters2) / sizeof(char *);
{
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_set_content_filter_options(
filter_expression2, expression_parameters_count2,
expression_parameters2, &subscription_options)
);
rmw_subscription_content_filter_options_t * content_filter_options =
subscription_options.rmw_subscription_options.content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2[i]);
}
}
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_options_fini(&subscription_options)
);
}
class TestSubscriptionContentFilterOptions : public ::testing::Test
{
public:
std::unique_ptr<rcl_context_t> context_;
std::unique_ptr<rcl_node_t> node_;
std::unique_ptr<rcl_subscription_t> subscription_;
void SetUp()
{
rcl_ret_t ret;
{
rcl_init_options_t init_options = rcl_get_zero_initialized_init_options();
ret = rcl_init_options_init(&init_options, rcl_get_default_allocator());
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT(
{
EXPECT_EQ(RCL_RET_OK, rcl_init_options_fini(&init_options)) << rcl_get_error_string().str;
});
context_ = std::make_unique<rcl_context_t>();
*context_ = rcl_get_zero_initialized_context();
ret = rcl_init(0, nullptr, &init_options, &*context_);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
node_ = std::make_unique<rcl_node_t>();
*node_ = rcl_get_zero_initialized_node();
constexpr char name[] = "test_subscription_content_filter_options_node";
rcl_node_options_t node_options = rcl_node_get_default_options();
ret = rcl_node_init(&*node_, name, "", &*context_, &node_options);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
const rosidl_message_type_support_t * ts =
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes);
constexpr char topic[] = "chatter";
subscription_ = std::make_unique<rcl_subscription_t>();
*subscription_ = rcl_get_zero_initialized_subscription();
rcl_subscription_options_t subscription_options = rcl_subscription_get_default_options();
ret = rcl_subscription_init(
&*subscription_, &*node_, ts, topic, &subscription_options);
ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
void TearDown()
{
rcl_ret_t ret = rcl_subscription_fini(&*subscription_, &*node_);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_node_fini(&*node_);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_shutdown(&*context_);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
ret = rcl_context_fini(&*context_);
EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string().str;
}
};
TEST_F(TestSubscriptionContentFilterOptions, content_filter_options_failure) {
rcl_subscription_content_filter_options_t content_filter_options =
rcl_get_zero_initialized_subscription_content_filter_options();
const char * filter_expression1 = "filter=1";
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_init(
nullptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
&*subscription_, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
&*subscription_, filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_init(
&*subscription_, filter_expression1, 1, nullptr, &content_filter_options)
);
rcl_reset_error();
// set
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_set(
nullptr, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
&*subscription_, nullptr, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
&*subscription_, filter_expression1, 0, nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_set(
&*subscription_, filter_expression1, 1, nullptr, &content_filter_options)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_SUBSCRIPTION_INVALID,
rcl_subscription_content_filter_options_fini(
nullptr, nullptr)
);
rcl_reset_error();
EXPECT_EQ(
RCL_RET_INVALID_ARGUMENT,
rcl_subscription_content_filter_options_fini(
&*subscription_, nullptr)
);
rcl_reset_error();
}
TEST_F(TestSubscriptionContentFilterOptions, content_filter_options_success)
{
rmw_subscription_content_filter_options_t * content_filter_options;
const char * filter_expression1 = "filter=1";
const char * filter_expression1_update = "filter=2";
rcl_subscription_content_filter_options_t subscription_content_filter_options =
rcl_get_zero_initialized_subscription_content_filter_options();
{
// init with filter_expression1
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_init(
&*subscription_, filter_expression1, 0, nullptr,
&subscription_content_filter_options)
);
content_filter_options =
&subscription_content_filter_options.rmw_subscription_content_filter_options;
EXPECT_STREQ(filter_expression1, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
// set with filter_expression1_update
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_set(
&*subscription_, filter_expression1_update, 0, nullptr,
&subscription_content_filter_options)
);
content_filter_options =
&subscription_content_filter_options.rmw_subscription_content_filter_options;
EXPECT_STREQ(filter_expression1_update, content_filter_options->filter_expression);
EXPECT_EQ(0u, content_filter_options->expression_parameters.size);
EXPECT_EQ(nullptr, content_filter_options->expression_parameters.data);
}
const char * filter_expression2 = "(filter1=%0 OR filter1=%1) AND filter2=%2";
const char * expression_parameters2[] = {
"1", "2", "3",
};
size_t expression_parameters_count2 = sizeof(expression_parameters2) / sizeof(char *);
const char * filter_expression2_update = "(filter1=%0 AND filter1=%1) OR filter2=%2";
const char * expression_parameters2_update[] = {
"11", "22", "33",
};
size_t expression_parameters_count2_update = sizeof(expression_parameters2) / sizeof(char *);
rcl_subscription_content_filter_options_t subscription_content_filter_options2 =
rcl_get_zero_initialized_subscription_content_filter_options();
{
// init with filter_expression2 and expression_parameters2
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_init(
&*subscription_, filter_expression2, expression_parameters_count2,
expression_parameters2, &subscription_content_filter_options2)
);
content_filter_options =
&subscription_content_filter_options2.rmw_subscription_content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2[i]);
}
// set with filter_expression2_update and expression_parameters2_update
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_set(
&*subscription_, filter_expression2_update, expression_parameters_count2_update,
expression_parameters2_update, &subscription_content_filter_options2)
);
content_filter_options =
&subscription_content_filter_options2.rmw_subscription_content_filter_options;
ASSERT_NE(nullptr, content_filter_options);
EXPECT_STREQ(filter_expression2_update, content_filter_options->filter_expression);
ASSERT_EQ(
expression_parameters_count2_update,
content_filter_options->expression_parameters.size);
for (size_t i = 0; i < expression_parameters_count2_update; ++i) {
EXPECT_STREQ(
content_filter_options->expression_parameters.data[i],
expression_parameters2_update[i]);
}
}
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_fini(
&*subscription_, &subscription_content_filter_options)
);
EXPECT_EQ(
RCL_RET_OK,
rcl_subscription_content_filter_options_fini(
&*subscription_, &subscription_content_filter_options2)
);
}
|
Fix leak in test_subscription_content_filter_options.cpp (#978)
|
Fix leak in test_subscription_content_filter_options.cpp (#978)
Signed-off-by: Shane Loretz <[email protected]>
|
C++
|
apache-2.0
|
ros2/rcl,ros2/rcl
|
ea5babf48da3682d9bc8e47722a2b46e90b666bb
|
Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx
|
Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkReflectiveImageRegionConstIterator_hxx
#define __itkReflectiveImageRegionConstIterator_hxx
#include "itkReflectiveImageRegionConstIterator.h"
namespace itk
{
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator():ImageConstIteratorWithIndex< TImage >()
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(TImage *ptr, const RegionType & region):
ImageConstIteratorWithIndex< TImage >(ptr, region)
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(const Self & it)
{
this->Operator = ( it );
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(
const ImageConstIteratorWithIndex< TImage > & it)
{
this->ImageConstIteratorWithIndex< TImage >::operator=(it);
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage > &
ReflectiveImageRegionConstIterator< TImage >
::operator=(const Self & it)
{
if(this != &it)
{
this->ImageConstIteratorWithIndex< TImage >::operator=(it);
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = it.m_BeginOffset[dim];
m_EndOffset[dim] = it.m_EndOffset[dim];
}
}
return *this;
}
template< typename TImage >
void
ReflectiveImageRegionConstIterator< TImage >
::GoToBegin(void)
{
this->m_PositionIndex = this->m_BeginIndex + this->m_BeginOffset;
this->m_Position = this->m_Image->GetBufferPointer()
+ this->m_Image->ComputeOffset(this->m_PositionIndex);
this->m_Remaining = false;
SizeType size = this->m_Region.GetSize();
for ( unsigned int i = 0; i < TImage::ImageDimension; ++i )
{
m_IsFirstPass[i] = true;
SizeValueType tempSize = size[i];
if ( tempSize > 0 )
{
this->m_Remaining = true;
}
}
}
template< typename TImage >
bool
ReflectiveImageRegionConstIterator< TImage >
::IsReflected(unsigned int dim) const
{
return !m_IsFirstPass[dim];
}
template< typename TImage >
void
ReflectiveImageRegionConstIterator< TImage >
::FillOffsets(const OffsetValueType & value)
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = value;
m_EndOffset[dim] = value;
}
}
//----------------------------------------------------------------------
// Advance along the line
//----------------------------------------------------------------------
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage > &
ReflectiveImageRegionConstIterator< TImage >
::operator++()
{
this->m_Remaining = false;
for ( unsigned int in = 0; in < TImage::ImageDimension; in++ )
{
if ( m_IsFirstPass[in] )
{
if ( this->m_PositionIndex[in]+1 < this->m_EndIndex[in] )
{
this->m_PositionIndex[in]++;
this->m_Position += this->m_OffsetTable[in];
this->m_Remaining = true;
break;
}
else
{
this->m_PositionIndex[in] = this->m_EndIndex[in] - m_EndOffset[in] - 1;
this->m_Position -= (this->m_EndOffset[in]) * (this->m_OffsetTable[in]);
m_IsFirstPass[in] = false;
this->m_Remaining = true;
break;
}
}
else
{
if ( this->m_PositionIndex[in]-1 >= this->m_BeginIndex[in] )
{
this->m_PositionIndex[in]--;
this->m_Position -= this->m_OffsetTable[in];
this->m_Remaining = true;
break;
}
else
{
this->m_PositionIndex[in] = this->m_BeginIndex[in] + m_BeginOffset[in];
this->m_Position += (this->m_BeginOffset[in]) * (this->m_OffsetTable[in]);
m_IsFirstPass[in] = true;
}
}
}
if ( !this->m_Remaining ) // It will not advance here otherwise
{
this->m_Position = this->m_End;
}
return *this;
}
} // end namespace itk
#endif
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkReflectiveImageRegionConstIterator_hxx
#define __itkReflectiveImageRegionConstIterator_hxx
#include "itkReflectiveImageRegionConstIterator.h"
namespace itk
{
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator():ImageConstIteratorWithIndex< TImage >()
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(TImage *ptr, const RegionType & region):
ImageConstIteratorWithIndex< TImage >(ptr, region)
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(const Self & it)
{
this->operator= ( it );
this->GoToBegin();
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage >
::ReflectiveImageRegionConstIterator(
const ImageConstIteratorWithIndex< TImage > & it)
{
this->ImageConstIteratorWithIndex< TImage >::operator=(it);
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = 0;
m_EndOffset[dim] = 0;
}
}
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage > &
ReflectiveImageRegionConstIterator< TImage >
::operator=(const Self & it)
{
if(this != &it)
{
this->ImageConstIteratorWithIndex< TImage >::operator=(it);
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = it.m_BeginOffset[dim];
m_EndOffset[dim] = it.m_EndOffset[dim];
}
}
return *this;
}
template< typename TImage >
void
ReflectiveImageRegionConstIterator< TImage >
::GoToBegin(void)
{
this->m_PositionIndex = this->m_BeginIndex + this->m_BeginOffset;
this->m_Position = this->m_Image->GetBufferPointer()
+ this->m_Image->ComputeOffset(this->m_PositionIndex);
this->m_Remaining = false;
SizeType size = this->m_Region.GetSize();
for ( unsigned int i = 0; i < TImage::ImageDimension; ++i )
{
m_IsFirstPass[i] = true;
SizeValueType tempSize = size[i];
if ( tempSize > 0 )
{
this->m_Remaining = true;
}
}
}
template< typename TImage >
bool
ReflectiveImageRegionConstIterator< TImage >
::IsReflected(unsigned int dim) const
{
return !m_IsFirstPass[dim];
}
template< typename TImage >
void
ReflectiveImageRegionConstIterator< TImage >
::FillOffsets(const OffsetValueType & value)
{
for( unsigned int dim = 0; dim < TImage::ImageDimension; dim++ )
{
m_BeginOffset[dim] = value;
m_EndOffset[dim] = value;
}
}
//----------------------------------------------------------------------
// Advance along the line
//----------------------------------------------------------------------
template< typename TImage >
ReflectiveImageRegionConstIterator< TImage > &
ReflectiveImageRegionConstIterator< TImage >
::operator++()
{
this->m_Remaining = false;
for ( unsigned int in = 0; in < TImage::ImageDimension; in++ )
{
if ( m_IsFirstPass[in] )
{
if ( this->m_PositionIndex[in]+1 < this->m_EndIndex[in] )
{
this->m_PositionIndex[in]++;
this->m_Position += this->m_OffsetTable[in];
this->m_Remaining = true;
break;
}
else
{
this->m_PositionIndex[in] = this->m_EndIndex[in] - m_EndOffset[in] - 1;
this->m_Position -= (this->m_EndOffset[in]) * (this->m_OffsetTable[in]);
m_IsFirstPass[in] = false;
this->m_Remaining = true;
break;
}
}
else
{
if ( this->m_PositionIndex[in]-1 >= this->m_BeginIndex[in] )
{
this->m_PositionIndex[in]--;
this->m_Position -= this->m_OffsetTable[in];
this->m_Remaining = true;
break;
}
else
{
this->m_PositionIndex[in] = this->m_BeginIndex[in] + m_BeginOffset[in];
this->m_Position += (this->m_BeginOffset[in]) * (this->m_OffsetTable[in]);
m_IsFirstPass[in] = true;
}
}
}
if ( !this->m_Remaining ) // It will not advance here otherwise
{
this->m_Position = this->m_End;
}
return *this;
}
} // end namespace itk
#endif
|
Fix typo in ReflectiveImageRegionConstIterator.
|
COMP: Fix typo in ReflectiveImageRegionConstIterator.
Operate = needed to be operator=
Change-Id: I9c274438b369959c77551181e31a03e708e5f466
|
C++
|
apache-2.0
|
BRAINSia/ITK,fedral/ITK,zachary-williamson/ITK,heimdali/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,LucHermitte/ITK,vfonov/ITK,BRAINSia/ITK,heimdali/ITK,Kitware/ITK,jcfr/ITK,BlueBrain/ITK,jcfr/ITK,jcfr/ITK,Kitware/ITK,fedral/ITK,atsnyder/ITK,biotrump/ITK,PlutoniumHeart/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,msmolens/ITK,eile/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,blowekamp/ITK,richardbeare/ITK,jmerkow/ITK,spinicist/ITK,LucHermitte/ITK,biotrump/ITK,hendradarwin/ITK,malaterre/ITK,biotrump/ITK,hendradarwin/ITK,eile/ITK,richardbeare/ITK,jcfr/ITK,hjmjohnson/ITK,fedral/ITK,BRAINSia/ITK,eile/ITK,fedral/ITK,atsnyder/ITK,heimdali/ITK,msmolens/ITK,jmerkow/ITK,stnava/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,ajjl/ITK,stnava/ITK,BRAINSia/ITK,biotrump/ITK,hendradarwin/ITK,spinicist/ITK,thewtex/ITK,hjmjohnson/ITK,malaterre/ITK,LucHermitte/ITK,fbudin69500/ITK,atsnyder/ITK,ajjl/ITK,LucHermitte/ITK,fbudin69500/ITK,vfonov/ITK,PlutoniumHeart/ITK,malaterre/ITK,Kitware/ITK,jmerkow/ITK,eile/ITK,msmolens/ITK,richardbeare/ITK,stnava/ITK,LucHermitte/ITK,spinicist/ITK,zachary-williamson/ITK,malaterre/ITK,vfonov/ITK,spinicist/ITK,malaterre/ITK,atsnyder/ITK,Kitware/ITK,BRAINSia/ITK,jmerkow/ITK,zachary-williamson/ITK,LucasGandel/ITK,msmolens/ITK,atsnyder/ITK,InsightSoftwareConsortium/ITK,biotrump/ITK,thewtex/ITK,LucHermitte/ITK,blowekamp/ITK,ajjl/ITK,eile/ITK,zachary-williamson/ITK,msmolens/ITK,fbudin69500/ITK,malaterre/ITK,zachary-williamson/ITK,malaterre/ITK,Kitware/ITK,malaterre/ITK,eile/ITK,hendradarwin/ITK,LucasGandel/ITK,BRAINSia/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,spinicist/ITK,jcfr/ITK,blowekamp/ITK,msmolens/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,ajjl/ITK,msmolens/ITK,blowekamp/ITK,jmerkow/ITK,atsnyder/ITK,BRAINSia/ITK,hendradarwin/ITK,jmerkow/ITK,blowekamp/ITK,hjmjohnson/ITK,blowekamp/ITK,stnava/ITK,heimdali/ITK,vfonov/ITK,hjmjohnson/ITK,spinicist/ITK,stnava/ITK,InsightSoftwareConsortium/ITK,Kitware/ITK,jmerkow/ITK,jmerkow/ITK,heimdali/ITK,msmolens/ITK,Kitware/ITK,hendradarwin/ITK,stnava/ITK,jcfr/ITK,eile/ITK,fbudin69500/ITK,LucHermitte/ITK,BlueBrain/ITK,atsnyder/ITK,atsnyder/ITK,vfonov/ITK,thewtex/ITK,ajjl/ITK,biotrump/ITK,richardbeare/ITK,jcfr/ITK,thewtex/ITK,BlueBrain/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,heimdali/ITK,eile/ITK,biotrump/ITK,LucasGandel/ITK,LucasGandel/ITK,fbudin69500/ITK,LucasGandel/ITK,vfonov/ITK,PlutoniumHeart/ITK,hjmjohnson/ITK,zachary-williamson/ITK,zachary-williamson/ITK,heimdali/ITK,LucasGandel/ITK,fedral/ITK,fedral/ITK,BlueBrain/ITK,ajjl/ITK,ajjl/ITK,eile/ITK,hjmjohnson/ITK,thewtex/ITK,atsnyder/ITK,spinicist/ITK,fbudin69500/ITK,richardbeare/ITK,LucasGandel/ITK,PlutoniumHeart/ITK,LucasGandel/ITK,vfonov/ITK,spinicist/ITK,blowekamp/ITK,jcfr/ITK,fedral/ITK,spinicist/ITK,fbudin69500/ITK,hendradarwin/ITK,hendradarwin/ITK,malaterre/ITK,stnava/ITK,blowekamp/ITK,zachary-williamson/ITK,PlutoniumHeart/ITK,stnava/ITK,vfonov/ITK,thewtex/ITK,fedral/ITK,biotrump/ITK,heimdali/ITK,BlueBrain/ITK,ajjl/ITK,fbudin69500/ITK,LucHermitte/ITK,thewtex/ITK,zachary-williamson/ITK
|
3855cb56ad457a92cb6cacf0326b032328fa7afa
|
NaoTHSoccer/Source/Cognition/Modules/VisualCortex/ScanGrid/ScanGridProvider.cpp
|
NaoTHSoccer/Source/Cognition/Modules/VisualCortex/ScanGrid/ScanGridProvider.cpp
|
#include "ScanGridProvider.h"
ScanGridProvider::ScanGridProvider()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_verticals", "draw vertical scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_horizontals", "draw horizontal scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_vertical_min_y", "", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_v_scan_pattern", "", false);
getDebugParameterList().add(¶meters);
}
ScanGridProvider::~ScanGridProvider()
{
getDebugParameterList().remove(¶meters);
}
void ScanGridProvider::execute(CameraInfo::CameraID id)
{
this->cameraID = id;
if(!getCameraMatrix().valid) {
return;
}
getScanGrid().reset();
const int width = getImage().width();
const int height = getImage().height();
// calculate horizon
int horizon_offset = 2;
int max_horizon =
std::max((int) (getArtificialHorizon().begin().y + horizon_offset), 0);
int min_horizon =
std::max((int) (getArtificialHorizon().end().y + horizon_offset), 0);
if (min_horizon > max_horizon) {
std::swap(min_horizon, max_horizon);
}
if (max_horizon >= height) {
// camera doesn't point to the ground
return;
}
Vector2i pointInImage;
// project max_scan_distance_mm on the image plain
// to obtain the upper limit of vertical scanlines
Vector3d cameraMatrixOffset = Vector3d(getCameraMatrix().translation.x,
getCameraMatrix().translation.y,
0);
Vector3d farthestPoint = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) *
Vector3d(parameters.max_scan_distance_mm, 0, 0));
if(!CameraGeometry::relativePointToImage(getCameraMatrix(), getCameraInfo(),
farthestPoint, pointInImage))
{
// projection failed
return;
}
// should be under the horizon and not higher than top of the image
int min_scan_y = std::max(pointInImage.y, max_horizon);
// should not be lower than the bottom of the image
if(min_scan_y >= height) {
return;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_vertical_min_y",
LINE_PX(ColorClasses::black, 0, min_scan_y, width-1, min_scan_y);
);
double fieldWidthCovered = calculateMaxFieldWidth(min_scan_y);
if (fieldWidthCovered <= 0) {
return;
}
// calculate the number of vertical scanlines at min_scan_y,
// so the gap at min_scan_y is horizontal_gap_mm
int numberOfVerticals = std::min(
(int) (fieldWidthCovered / parameters.horizontal_gap_mm),
parameters.max_vertical_scanlines);
// calculate vertical scan pattern by creating points
// on the field and projecting them back onto the image
calculate_vertical_scan_pattern(min_scan_y);
if(getScanGrid().vScanPattern.empty()) {
return;
}
double minGap = width / (double) numberOfVerticals;
double focalLength = getCameraInfo().getFocalLength();
double cameraHeight = getCameraMatrix().translation.z;
int max_scan_y;
double distance;
std::vector<size_t> line_start_increasing_length;
std::vector<double> v_gaps;
double gap_modifier = parameters.vertical_gap_mm / parameters.horizontal_gap_mm;
int vScan_idx = static_cast<int>(getScanGrid().vScanPattern.size()) - 1;
for(double gap = minGap; gap < width; gap *= 2)
{
// distance to an object with a size of "gap" in the image,
// if it would have a size of "horizontal_gap_mm" on the field
distance = parameters.horizontal_gap_mm * focalLength / gap;
// determine the start of the vertical scanline
if(distance < cameraHeight) {
max_scan_y = height-1;
} else {
// project distance onto the ground plane
distance = std::sqrt(distance * distance - cameraHeight * cameraHeight);
// project point in the distance onto the image,
// to obtain the start of the scanline
Vector3d pointOnField = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle())
* Vector3d(distance, 0, 0));
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
pointOnField,
pointInImage);
if(!projectionSucces) {
break;
}
max_scan_y = std::min(pointInImage.y, height-1);
if (max_scan_y <= min_scan_y) {
continue;
}
}
// determine start in vertical scan pattern,
// iterate backwards because most scanlines are short
size_t bottom_idx = 0;
for(; vScan_idx >= 0; vScan_idx--)
{
int y = getScanGrid().vScanPattern[static_cast<size_t>(vScan_idx)];
if(y > max_scan_y) {
bottom_idx = std::min(getScanGrid().vScanPattern.size()-1, static_cast<size_t>(vScan_idx)+1);
break;
}
}
line_start_increasing_length.push_back(bottom_idx);
// vertical gap sizes
v_gaps.push_back(gap_modifier * gap);
if(max_scan_y >= height-1) {
// bottom of the image reached
break;
}
}
if(line_start_increasing_length.empty()) {
return;
}
if(parameters.uniform_vertical_lengths) {
line_start_increasing_length = {line_start_increasing_length.back()};
}
// fill the image with vertical scanlines
getScanGrid().vertical.resize(numberOfVerticals);
std::vector<size_t>::iterator line_start_itr =
line_start_increasing_length.begin();
int frequency;
for(int i=1; i<=numberOfVerticals; i*=2) {
frequency = i*2;
for(int j=i-1; j<numberOfVerticals; j+=frequency) {
int x = (int) (j*minGap);
ScanGrid::VScanLine scanline;
scanline.x = x;
scanline.bottom = *line_start_itr;
scanline.top = getScanGrid().vScanPattern.size()-1;
getScanGrid().vertical[j] = scanline;
//if(next(line) == linesIncreasingLength.end()) {
// getScanGrid().longverticals.push_back(j);
//}
}
if(next(line_start_itr) != line_start_increasing_length.end()){
++line_start_itr;
}
}
// calculate approximate number of horizontals with the current v_gaps
line_start_itr = line_start_increasing_length.begin();
double last_y = min_scan_y;
double n_horizontals = 0;
for(double v_gap : v_gaps) {
double y = getScanGrid().vScanPattern[*line_start_itr];
n_horizontals += (y - last_y) / v_gap;
last_y = y;
++line_start_itr;
}
// adjust v_gaps if too many horizontals
if (n_horizontals > parameters.max_horizontal_scanlines) {
gap_modifier = n_horizontals / parameters.max_horizontal_scanlines;
for(double& v_gap : v_gaps) {
v_gap *= gap_modifier;
}
}
getScanGrid().horizontal.reserve(parameters.max_horizontal_scanlines);
gap_modifier = parameters.h_field_scan_rate_mm / parameters.horizontal_gap_mm;
// fill the image with horizontal scanlines
size_t i = 0;
double y = min_scan_y;
double h_skip = gap_modifier * minGap;
while(y < height) {
ScanGrid::HScanLine horizontal;
horizontal.left_x = 0;
horizontal.right_x = width-1;
horizontal.y = (int) y;
horizontal.skip = std::max((int) h_skip, parameters.min_horizontal_gap_px);
getScanGrid().horizontal.push_back(horizontal);
double v_gap = v_gaps[i];
size_t h_line_start = line_start_increasing_length[i];
if(y + v_gap > getScanGrid().vScanPattern[h_line_start]) {
if(++i >= v_gaps.size()) {
break;
}
// adjust gaps
v_gap = v_gaps[i];
h_line_start = line_start_increasing_length[i];
h_skip = gap_modifier * v_gap;
}
y += v_gap;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_verticals",
for(const ScanGrid::VScanLine& scanline: getScanGrid().vertical)
{
LINE_PX(ColorClasses::blue,
scanline.x, getScanGrid().vScanPattern.at(scanline.bottom),
scanline.x, getScanGrid().vScanPattern.at(scanline.top));
for(size_t ii=scanline.bottom; ii<=scanline.top; ++ii)
{
POINT_PX(ColorClasses::red, scanline.x, getScanGrid().vScanPattern.at(ii));
//Test
const int xx = scanline.x;
const int yy = getScanGrid().vScanPattern.at(ii);
getImage().getY(xx, yy);
}
}
);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_horizontals",
for(const ScanGrid::HScanLine& scanline: getScanGrid().horizontal)
{
LINE_PX(ColorClasses::blue, scanline.left_x, scanline.y, scanline.right_x, scanline.y);
for(int x=scanline.left_x; x<=scanline.right_x; x+=scanline.skip)
{
POINT_PX(ColorClasses::red, x, scanline.y);
//Test
getImage().getY(x, scanline.y);
}
}
);
}//end execute
double ScanGridProvider::calculateMaxFieldWidth(int y)
{
// project the left and right image corner onto the field
// and caluclate the distance between thems
Vector2d projectedLeftCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
0,
y,
0.0,
projectedLeftCorner))
{
return -1.;
}
Vector2d projectedRightCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
getImage().width()-1,
y,
0.0,
projectedRightCorner))
{
return -1.;
}
return (projectedLeftCorner - projectedRightCorner).abs();
}
bool ScanGridProvider::calculate_vertical_scan_pattern(int min_scan_y)
{
std::vector<int>& scan_pattern = getScanGrid().vScanPattern;
//std::vector<int> scan_pattern;
const double width = getImage().width();
const double height = getImage().height();
// get depicted field point at the bottom of the image
Vector2d field_point;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
width/2,
height,
0.0,
field_point))
{
return false;
}
Vector3d field_point_3d(field_point.x, field_point.y, 0);
// camera direction
Vector3d direction_3d = RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) *
Vector3d(parameters.v_field_scan_rate_mm, 0, 0);
// create scan points starting from the bottom of the image
int y = getImage().height()-1;
Vector2i image_point;
bool skip_to_small = false;
while(y > min_scan_y)
{
DEBUG_REQUEST("Vision:ScanGridProvider:draw_v_scan_pattern",
POINT_PX(ColorClasses::red, getImage().width()/2, y);
);
scan_pattern.push_back(y);
if(!skip_to_small) {
field_point_3d += direction_3d;
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
field_point_3d,
image_point);
if(!projectionSucces) {
return false;
}
if(y - image_point.y < parameters.min_vertical_gap_px) {
y -= parameters.min_vertical_gap_px;
skip_to_small = true;
} else {
y = image_point.y;
}
} else {
y -= parameters.min_vertical_gap_px;
}
}
return true;
}
|
#include "ScanGridProvider.h"
ScanGridProvider::ScanGridProvider()
:
cameraID(CameraInfo::Top)
{
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_verticals", "draw vertical scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_horizontals", "draw horizontal scanlines", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_vertical_min_y", "", false);
DEBUG_REQUEST_REGISTER("Vision:ScanGridProvider:draw_v_scan_pattern", "", false);
getDebugParameterList().add(¶meters);
}
ScanGridProvider::~ScanGridProvider()
{
getDebugParameterList().remove(¶meters);
}
void ScanGridProvider::execute(CameraInfo::CameraID id)
{
this->cameraID = id;
if(!getCameraMatrix().valid) {
return;
}
getScanGrid().reset();
const int width = getImage().width();
const int height = getImage().height();
// calculate horizon
int horizon_offset = 2;
int max_horizon =
std::max((int) (getArtificialHorizon().begin().y + horizon_offset), 0);
int min_horizon =
std::max((int) (getArtificialHorizon().end().y + horizon_offset), 0);
if (min_horizon > max_horizon) {
std::swap(min_horizon, max_horizon);
}
if (max_horizon >= height) {
// camera doesn't point to the ground
return;
}
Vector2i pointInImage;
// project max_scan_distance_mm on the image plain
// to obtain the upper limit of vertical scanlines
Vector3d cameraMatrixOffset = Vector3d(getCameraMatrix().translation.x,
getCameraMatrix().translation.y,
0);
Vector3d farthestPoint = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) *
Vector3d(parameters.max_scan_distance_mm, 0, 0));
if(!CameraGeometry::relativePointToImage(getCameraMatrix(), getCameraInfo(),
farthestPoint, pointInImage))
{
// projection failed
return;
}
// should be under the horizon and not higher than top of the image
int min_scan_y = std::max(pointInImage.y, max_horizon);
// should not be lower than the bottom of the image
if(min_scan_y >= height) {
return;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_vertical_min_y",
LINE_PX(ColorClasses::black, 0, min_scan_y, width-1, min_scan_y);
);
double fieldWidthCovered = calculateMaxFieldWidth(min_scan_y);
if (fieldWidthCovered <= 0) {
return;
}
// calculate the number of vertical scanlines at min_scan_y,
// so the gap at min_scan_y is horizontal_gap_mm
int numberOfVerticals = std::min(
(int) (fieldWidthCovered / parameters.horizontal_gap_mm),
parameters.max_vertical_scanlines);
// calculate vertical scan pattern by creating points
// on the field and projecting them back onto the image
calculate_vertical_scan_pattern(min_scan_y);
if(getScanGrid().vScanPattern.empty()) {
return;
}
double minGap = width / (double) numberOfVerticals;
double focalLength = getCameraInfo().getFocalLength();
double cameraHeight = getCameraMatrix().translation.z;
int max_scan_y;
double distance;
std::vector<size_t> line_start_increasing_length;
std::vector<double> v_gaps;
double gap_modifier = parameters.vertical_gap_mm / parameters.horizontal_gap_mm;
int vScan_idx = static_cast<int>(getScanGrid().vScanPattern.size()) - 1;
for(double gap = minGap; gap < width; gap *= 2)
{
// distance to an object with a size of "gap" in the image,
// if it would have a size of "horizontal_gap_mm" on the field
distance = parameters.horizontal_gap_mm * focalLength / gap;
// determine the start of the vertical scanline
if(distance < cameraHeight) {
max_scan_y = height-1;
} else {
// project distance onto the ground plane
distance = std::sqrt(distance * distance - cameraHeight * cameraHeight);
// project point in the distance onto the image,
// to obtain the start of the scanline
Vector3d pointOnField = cameraMatrixOffset +
(RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle())
* Vector3d(distance, 0, 0));
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
pointOnField,
pointInImage);
if(!projectionSucces) {
break;
}
max_scan_y = std::min(pointInImage.y, height-1);
if (max_scan_y <= min_scan_y) {
continue;
}
}
// determine start in vertical scan pattern,
// iterate backwards because most scanlines are short
size_t bottom_idx = 0;
for(; vScan_idx >= 0; vScan_idx--)
{
int y = getScanGrid().vScanPattern[static_cast<size_t>(vScan_idx)];
if(y > max_scan_y) {
bottom_idx = std::min(getScanGrid().vScanPattern.size()-1, static_cast<size_t>(vScan_idx)+1);
break;
}
}
line_start_increasing_length.push_back(bottom_idx);
// vertical gap sizes
v_gaps.push_back(gap_modifier * gap);
if(max_scan_y >= height-1) {
// bottom of the image reached
break;
}
}
if(line_start_increasing_length.empty()) {
return;
}
// set all lines to the same lenghts
if(parameters.uniform_vertical_lengths) {
std::fill(line_start_increasing_length.begin(), line_start_increasing_length.end(), line_start_increasing_length.back());
}
// fill the image with vertical scanlines
getScanGrid().vertical.resize(numberOfVerticals);
std::vector<size_t>::iterator line_start_itr =
line_start_increasing_length.begin();
int frequency;
for(int i=1; i<=numberOfVerticals; i*=2) {
frequency = i*2;
for(int j=i-1; j<numberOfVerticals; j+=frequency) {
int x = (int) (j*minGap);
ScanGrid::VScanLine scanline;
scanline.x = x;
scanline.bottom = *line_start_itr;
scanline.top = getScanGrid().vScanPattern.size()-1;
getScanGrid().vertical[j] = scanline;
//if(next(line) == linesIncreasingLength.end()) {
// getScanGrid().longverticals.push_back(j);
//}
}
if(next(line_start_itr) != line_start_increasing_length.end()){
++line_start_itr;
}
}
// calculate approximate number of horizontals with the current v_gaps
line_start_itr = line_start_increasing_length.begin();
double last_y = min_scan_y;
double n_horizontals = 0;
for(double v_gap : v_gaps) {
double y = getScanGrid().vScanPattern[*line_start_itr];
n_horizontals += (y - last_y) / v_gap;
last_y = y;
++line_start_itr;
}
// adjust v_gaps if too many horizontals
if (n_horizontals > parameters.max_horizontal_scanlines) {
gap_modifier = n_horizontals / parameters.max_horizontal_scanlines;
for(double& v_gap : v_gaps) {
v_gap *= gap_modifier;
}
}
getScanGrid().horizontal.reserve(parameters.max_horizontal_scanlines);
gap_modifier = parameters.h_field_scan_rate_mm / parameters.horizontal_gap_mm;
// fill the image with horizontal scanlines
size_t i = 0;
double y = min_scan_y;
double h_skip = gap_modifier * minGap;
while(y < height) {
ScanGrid::HScanLine horizontal;
horizontal.left_x = 0;
horizontal.right_x = width-1;
horizontal.y = (int) y;
horizontal.skip = std::max((int) h_skip, parameters.min_horizontal_gap_px);
getScanGrid().horizontal.push_back(horizontal);
double v_gap = v_gaps[i];
size_t h_line_start = line_start_increasing_length[i];
if(y + v_gap > getScanGrid().vScanPattern[h_line_start]) {
if(++i >= v_gaps.size()) {
break;
}
// adjust gaps
v_gap = v_gaps[i];
h_line_start = line_start_increasing_length[i];
h_skip = gap_modifier * v_gap;
}
y += v_gap;
}
DEBUG_REQUEST("Vision:ScanGridProvider:draw_verticals",
for(const ScanGrid::VScanLine& scanline: getScanGrid().vertical)
{
LINE_PX(ColorClasses::blue,
scanline.x, getScanGrid().vScanPattern.at(scanline.bottom),
scanline.x, getScanGrid().vScanPattern.at(scanline.top));
for(size_t ii=scanline.bottom; ii<=scanline.top; ++ii)
{
POINT_PX(ColorClasses::red, scanline.x, getScanGrid().vScanPattern.at(ii));
//Test
const int xx = scanline.x;
const int yy = getScanGrid().vScanPattern.at(ii);
getImage().getY(xx, yy);
}
}
);
DEBUG_REQUEST("Vision:ScanGridProvider:draw_horizontals",
for(const ScanGrid::HScanLine& scanline: getScanGrid().horizontal)
{
LINE_PX(ColorClasses::blue, scanline.left_x, scanline.y, scanline.right_x, scanline.y);
for(int x=scanline.left_x; x<=scanline.right_x; x+=scanline.skip)
{
POINT_PX(ColorClasses::red, x, scanline.y);
//Test
getImage().getY(x, scanline.y);
}
}
);
}//end execute
double ScanGridProvider::calculateMaxFieldWidth(int y)
{
// project the left and right image corner onto the field
// and caluclate the distance between thems
Vector2d projectedLeftCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
0,
y,
0.0,
projectedLeftCorner))
{
return -1.;
}
Vector2d projectedRightCorner;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
getImage().width()-1,
y,
0.0,
projectedRightCorner))
{
return -1.;
}
return (projectedLeftCorner - projectedRightCorner).abs();
}
bool ScanGridProvider::calculate_vertical_scan_pattern(int min_scan_y)
{
std::vector<int>& scan_pattern = getScanGrid().vScanPattern;
//std::vector<int> scan_pattern;
const double width = getImage().width();
const double height = getImage().height();
// get depicted field point at the bottom of the image
Vector2d field_point;
if(!CameraGeometry::imagePixelToFieldCoord(
getCameraMatrix(), getCameraInfo(),
width/2,
height,
0.0,
field_point))
{
return false;
}
Vector3d field_point_3d(field_point.x, field_point.y, 0);
// camera direction
Vector3d direction_3d = RotationMatrix::getRotationZ(getCameraMatrix().rotation.getZAngle()) *
Vector3d(parameters.v_field_scan_rate_mm, 0, 0);
// create scan points starting from the bottom of the image
int y = getImage().height()-1;
Vector2i image_point;
bool skip_to_small = false;
while(y > min_scan_y)
{
DEBUG_REQUEST("Vision:ScanGridProvider:draw_v_scan_pattern",
POINT_PX(ColorClasses::red, getImage().width()/2, y);
);
scan_pattern.push_back(y);
if(!skip_to_small) {
field_point_3d += direction_3d;
bool projectionSucces = CameraGeometry::relativePointToImage(
getCameraMatrix(), getCameraInfo(),
field_point_3d,
image_point);
if(!projectionSucces) {
return false;
}
if(y - image_point.y < parameters.min_vertical_gap_px) {
y -= parameters.min_vertical_gap_px;
skip_to_small = true;
} else {
y = image_point.y;
}
} else {
y -= parameters.min_vertical_gap_px;
}
}
return true;
}
|
use std::fill to set all values in a vector
|
bugfix: use std::fill to set all values in a vector
|
C++
|
apache-2.0
|
BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH
|
6b42d0db0b0dfad4fd131740847aebe0f8a19010
|
elang/optimizer/node_factory.cc
|
elang/optimizer/node_factory.cc
|
// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <unordered_map>
#include "elang/optimizer/node_factory.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "elang/base/zone.h"
#include "elang/base/zone_user.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/sequence_id_source.h"
#include "elang/optimizer/types.h"
#include "elang/optimizer/type_factory.h"
#include "elang/optimizer/type_visitor.h"
namespace elang {
namespace optimizer {
//////////////////////////////////////////////////////////////////////
//
// NodeFactory::LiteralNodeCache
//
class NodeFactory::LiteralNodeCache final : public ZoneUser {
public:
class DefaultValueFactory;
LiteralNodeCache(Zone* zone, TypeFactory* type_factory);
~LiteralNodeCache();
#define V(Name, mnemonic, data_type, ...) \
Node* New##Name(Type* type, data_type data);
FOR_EACH_OPTIMIZER_CONCRETE_LITERAL_NODE(V)
#undef V
Node* NewFunctionReference(Type* output_type, Function* function);
Node* NewNull(Type* type);
private:
#define V(Name, name, data_type, ...) \
std::unordered_map<data_type, Node*> name##_cache_;
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
std::unordered_map<Function*, Node*> function_literal_cache_;
std::unordered_map<Type*, Node*> null_literal_cache_;
std::unordered_map<base::StringPiece16, Node*> string_cache_;
TypeFactory* const type_factory_;
DISALLOW_COPY_AND_ASSIGN(LiteralNodeCache);
};
NodeFactory::LiteralNodeCache::LiteralNodeCache(Zone* zone,
TypeFactory* type_factory)
: ZoneUser(zone), type_factory_(type_factory) {
}
NodeFactory::LiteralNodeCache::~LiteralNodeCache() {
}
#define V(Name, name, data_type, ...) \
Node* NodeFactory::LiteralNodeCache::New##Name(Type* type, data_type data) { \
auto const it = name##_cache_.find(data); \
if (it != name##_cache_.end()) \
return it->second; \
auto const literal = new (zone()) Name##Node(type, data); \
name##_cache_[data] = literal; \
return literal; \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
Node* NodeFactory::LiteralNodeCache::NewFunctionReference(Type* output_type,
Function* function) {
DCHECK_EQ(output_type->as<PointerType>()->pointee(),
function->function_type());
auto const it = function_literal_cache_.find(function);
if (it != function_literal_cache_.end())
return it->second;
auto const literal =
new (zone()) FunctionReferenceNode(output_type, function);
function_literal_cache_[function] = literal;
return literal;
}
Node* NodeFactory::LiteralNodeCache::NewNull(Type* type) {
auto const it = null_literal_cache_.find(type);
if (it != null_literal_cache_.end())
return it->second;
auto const literal = new (zone()) NullNode(type);
null_literal_cache_[type] = literal;
return literal;
}
Node* NodeFactory::LiteralNodeCache::NewString(Type* type,
base::StringPiece16 data) {
auto const it = string_cache_.find(data);
if (it != string_cache_.end())
return it->second;
auto const size = data.size() * sizeof(base::char16);
auto const chars = static_cast<base::char16*>(zone()->Allocate(size));
::memcpy(chars, data.data(), size);
base::StringPiece16 saved_data(chars, data.size());
auto const literal = new (zone()) StringNode(type, saved_data);
string_cache_[saved_data] = literal;
return literal;
}
//////////////////////////////////////////////////////////////////////
//
// NodeFactory::LiteralNodeCache::DefaultValueFactory
//
class NodeFactory::LiteralNodeCache::DefaultValueFactory : public TypeVisitor {
public:
explicit DefaultValueFactory(LiteralNodeCache* cache);
~DefaultValueFactory() = default;
Node* value() const {
DCHECK(value_);
return value_;
}
private:
Node* value_;
// TypeVisitor
void DoDefaultVisit(Type* type) final;
#define V(Name, ...) void Visit##Name##Type(Name##Type* type) final;
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
LiteralNodeCache* const cache_;
DISALLOW_COPY_AND_ASSIGN(DefaultValueFactory);
};
NodeFactory::LiteralNodeCache::DefaultValueFactory::DefaultValueFactory(
LiteralNodeCache* cache)
: cache_(cache), value_(nullptr) {
}
void NodeFactory::LiteralNodeCache::DefaultValueFactory::DoDefaultVisit(
Type* type) {
DCHECK(!type->is<PrimitiveValueType>());
value_ = cache_->NewNull(type);
}
#define V(Name, name, data_type, ...) \
void NodeFactory::LiteralNodeCache::DefaultValueFactory::Visit##Name##Type( \
Name##Type* type) { \
value_ = cache_->New##Name(type, static_cast<data_type>(0)); \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
//////////////////////////////////////////////////////////////////////
//
// NodeFactory
//
NodeFactory::NodeFactory(TypeFactory* type_factory)
: TypeFactoryUser(type_factory),
literal_node_cache_(new LiteralNodeCache(zone(), type_factory)),
node_id_source_(new SequenceIdSource()),
false_value_(NewBool(false)),
true_value_(NewBool(true)),
void_value_(new (zone()) VoidNode(void_type())) {
}
NodeFactory::~NodeFactory() {
}
Node* NodeFactory::DefaultValueOf(Type* type) {
if (type == void_type())
return void_value_;
LiteralNodeCache::DefaultValueFactory factory(literal_node_cache_.get());
type->Accept(&factory);
return factory.value();
}
Node* NodeFactory::NewFunctionReference(Function* function) {
auto const output_type = NewPointerType(function->function_type());
return literal_node_cache_->NewFunctionReference(output_type, function);
}
size_t NodeFactory::NewNodeId() {
return node_id_source_->NextId();
}
Node* NodeFactory::NewNull(Type* type) {
return literal_node_cache_->NewNull(type);
}
// Arithmetic nodes
#define V(Name, ...) \
Node* NodeFactory::New##Name(Node* input0, Node* input1) { \
auto const output_type = input0->output_type(); \
DCHECK_EQ(output_type, input1->output_type()); \
auto const node = new (zone()) Name##Node(output_type, input0, input1); \
node->set_id(NewNodeId()); \
return node; \
}
FOR_EACH_OPTIMIZER_CONCRETE_ARITHMETIC_NODE(V)
#undef V
// Literal nodes
#define V(Name, name, data_type, ...) \
Node* NodeFactory::New##Name(data_type data) { \
return literal_node_cache_->New##Name(name##_type(), data); \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
Node* NodeFactory::NewEntry(Type* parameters_type) {
auto const output_type =
NewTupleType({control_type(), effect_type(), parameters_type});
auto const node = new (zone()) EntryNode(output_type);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewExit(Node* control, Node* effect) {
DCHECK(control->IsValidControl()) << *control;
DCHECK(effect->IsValidEffect()) << *effect;
auto const node = new (zone()) ExitNode(void_type(), zone());
node->AppendInput(control);
node->AppendInput(effect);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewGet(Node* input, size_t field) {
DCHECK(input->IsValidData()) << *input;
auto const output_type = input->output_type()->as<TupleType>()->get(field);
auto const node = new (zone()) GetNode(output_type, input, field);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewParameter(Node* input, size_t field) {
auto const entry_node = input->as<EntryNode>();
DCHECK(entry_node) << *input;
auto const output_type = entry_node->parameter_type(field);
auto const node = new (zone()) ParameterNode(output_type, input, field);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewRet(Node* control, Node* value) {
DCHECK(control->IsValidControl()) << *control;
DCHECK(value->IsValidData()) << *value;
auto const node = new (zone()) RetNode(control_type(), control, value);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewString(base::StringPiece16 data) {
return literal_node_cache_->NewString(string_type(), data);
}
} // namespace optimizer
} // namespace elang
|
// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <unordered_map>
#include "elang/optimizer/node_factory.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "elang/base/zone.h"
#include "elang/base/zone_user.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/sequence_id_source.h"
#include "elang/optimizer/types.h"
#include "elang/optimizer/type_factory.h"
#include "elang/optimizer/type_visitor.h"
namespace elang {
namespace optimizer {
//////////////////////////////////////////////////////////////////////
//
// NodeFactory::LiteralNodeCache
//
class NodeFactory::LiteralNodeCache final : public ZoneUser {
public:
class DefaultValueFactory;
LiteralNodeCache(Zone* zone, TypeFactory* type_factory);
~LiteralNodeCache();
#define V(Name, mnemonic, data_type, ...) \
Node* New##Name(Type* type, data_type data);
FOR_EACH_OPTIMIZER_CONCRETE_LITERAL_NODE(V)
#undef V
Node* NewFunctionReference(Type* output_type, Function* function);
Node* NewNull(Type* type);
private:
#define V(Name, name, data_type, ...) \
std::unordered_map<data_type, Node*> name##_cache_;
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
std::unordered_map<Function*, Node*> function_literal_cache_;
std::unordered_map<Type*, Node*> null_literal_cache_;
std::unordered_map<base::StringPiece16, Node*> string_cache_;
TypeFactory* const type_factory_;
DISALLOW_COPY_AND_ASSIGN(LiteralNodeCache);
};
NodeFactory::LiteralNodeCache::LiteralNodeCache(Zone* zone,
TypeFactory* type_factory)
: ZoneUser(zone), type_factory_(type_factory) {
}
NodeFactory::LiteralNodeCache::~LiteralNodeCache() {
}
#define V(Name, name, data_type, ...) \
Node* NodeFactory::LiteralNodeCache::New##Name(Type* type, data_type data) { \
auto const it = name##_cache_.find(data); \
if (it != name##_cache_.end()) \
return it->second; \
auto const literal = new (zone()) Name##Node(type, data); \
name##_cache_[data] = literal; \
return literal; \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
Node* NodeFactory::LiteralNodeCache::NewFunctionReference(Type* output_type,
Function* function) {
DCHECK_EQ(output_type->as<PointerType>()->pointee(),
function->function_type());
auto const it = function_literal_cache_.find(function);
if (it != function_literal_cache_.end())
return it->second;
auto const literal =
new (zone()) FunctionReferenceNode(output_type, function);
function_literal_cache_[function] = literal;
return literal;
}
Node* NodeFactory::LiteralNodeCache::NewNull(Type* type) {
auto const it = null_literal_cache_.find(type);
if (it != null_literal_cache_.end())
return it->second;
auto const literal = new (zone()) NullNode(type);
null_literal_cache_[type] = literal;
return literal;
}
Node* NodeFactory::LiteralNodeCache::NewString(Type* type,
base::StringPiece16 data) {
auto const it = string_cache_.find(data);
if (it != string_cache_.end())
return it->second;
auto const size = data.size() * sizeof(base::char16);
auto const chars = static_cast<base::char16*>(zone()->Allocate(size));
::memcpy(chars, data.data(), size);
base::StringPiece16 saved_data(chars, data.size());
auto const literal = new (zone()) StringNode(type, saved_data);
string_cache_[saved_data] = literal;
return literal;
}
//////////////////////////////////////////////////////////////////////
//
// NodeFactory::LiteralNodeCache::DefaultValueFactory
//
class NodeFactory::LiteralNodeCache::DefaultValueFactory : public TypeVisitor {
public:
explicit DefaultValueFactory(LiteralNodeCache* cache);
~DefaultValueFactory() = default;
Node* value() const {
DCHECK(value_);
return value_;
}
private:
Node* value_;
// TypeVisitor
void DoDefaultVisit(Type* type) final;
#define V(Name, ...) void Visit##Name##Type(Name##Type* type) final;
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
LiteralNodeCache* const cache_;
DISALLOW_COPY_AND_ASSIGN(DefaultValueFactory);
};
NodeFactory::LiteralNodeCache::DefaultValueFactory::DefaultValueFactory(
LiteralNodeCache* cache)
: cache_(cache), value_(nullptr) {
}
void NodeFactory::LiteralNodeCache::DefaultValueFactory::DoDefaultVisit(
Type* type) {
DCHECK(!type->is<PrimitiveValueType>());
value_ = cache_->NewNull(type);
}
#define V(Name, name, data_type, ...) \
void NodeFactory::LiteralNodeCache::DefaultValueFactory::Visit##Name##Type( \
Name##Type* type) { \
value_ = cache_->New##Name(type, static_cast<data_type>(0)); \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
//////////////////////////////////////////////////////////////////////
//
// NodeFactory
//
NodeFactory::NodeFactory(TypeFactory* type_factory)
: TypeFactoryUser(type_factory),
literal_node_cache_(new LiteralNodeCache(zone(), type_factory)),
node_id_source_(new SequenceIdSource()),
false_value_(NewBool(false)),
true_value_(NewBool(true)),
void_value_(new (zone()) VoidNode(void_type())) {
}
NodeFactory::~NodeFactory() {
}
Node* NodeFactory::DefaultValueOf(Type* type) {
if (type == void_type())
return void_value_;
LiteralNodeCache::DefaultValueFactory factory(literal_node_cache_.get());
type->Accept(&factory);
return factory.value();
}
Node* NodeFactory::NewFunctionReference(Function* function) {
auto const output_type = NewPointerType(function->function_type());
return literal_node_cache_->NewFunctionReference(output_type, function);
}
size_t NodeFactory::NewNodeId() {
return node_id_source_->NextId();
}
Node* NodeFactory::NewNull(Type* type) {
return literal_node_cache_->NewNull(type);
}
// Arithmetic nodes
#define V(Name, ...) \
Node* NodeFactory::New##Name(Node* input0, Node* input1) { \
auto const output_type = input0->output_type(); \
DCHECK_EQ(output_type, input1->output_type()); \
auto const node = new (zone()) Name##Node(output_type, input0, input1); \
node->set_id(NewNodeId()); \
return node; \
}
FOR_EACH_OPTIMIZER_CONCRETE_ARITHMETIC_NODE(V)
#undef V
// Literal nodes
#define V(Name, name, data_type, ...) \
Node* NodeFactory::New##Name(data_type data) { \
return literal_node_cache_->New##Name(name##_type(), data); \
}
FOR_EACH_OPTIMIZER_PRIMITIVE_VALUE_TYPE(V)
#undef V
Node* NodeFactory::NewEntry(Type* parameters_type) {
auto const output_type =
NewTupleType({control_type(), effect_type(), parameters_type});
auto const node = new (zone()) EntryNode(output_type);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewExit(Node* control, Node* effect) {
DCHECK(control->IsValidControl()) << *control;
DCHECK(effect->IsValidEffect()) << *effect;
auto const node = new (zone()) ExitNode(void_type(), zone());
node->AppendInput(control);
node->AppendInput(effect);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewGet(Node* input, size_t field) {
DCHECK(input->IsValidData()) << *input;
auto const output_type = input->output_type()->as<TupleType>()->get(field);
auto const node = new (zone()) GetNode(output_type, input, field);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewIf(Node* control, Node* data) {
DCHECK(control->IsValidControl()) << *control;
DCHECK(data->IsValidData()) << *data;
auto const node = new (zone()) IfNode(control_type(), control, data);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewIfFalse(Node* control) {
DCHECK(control->IsValidControl()) << *control;
auto const node = new (zone()) IfFalseNode(control_type(), control);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewIfTrue(Node* control) {
DCHECK(control->IsValidControl()) << *control;
auto const node = new (zone()) IfTrueNode(control_type(), control);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewParameter(Node* input, size_t field) {
auto const entry_node = input->as<EntryNode>();
DCHECK(entry_node) << *input;
auto const output_type = entry_node->parameter_type(field);
auto const node = new (zone()) ParameterNode(output_type, input, field);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewRet(Node* control, Node* value) {
DCHECK(control->IsValidControl()) << *control;
DCHECK(value->IsValidData()) << *value;
auto const node = new (zone()) RetNode(control_type(), control, value);
node->set_id(NewNodeId());
return node;
}
Node* NodeFactory::NewString(base::StringPiece16 data) {
return literal_node_cache_->NewString(string_type(), data);
}
} // namespace optimizer
} // namespace elang
|
Introduce |NodeFactory::NewIf()|, |NodeFactory::NewIfFalse()| and |NodeFactory::NewTrue()|.
|
elang/optimizer: Introduce |NodeFactory::NewIf()|, |NodeFactory::NewIfFalse()| and |NodeFactory::NewTrue()|.
|
C++
|
apache-2.0
|
eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang,eval1749/elang
|
0aa63bbaa41b03f8a0f02d703cd141feefb73542
|
OpenSim/Common/AbstractProperty.cpp
|
OpenSim/Common/AbstractProperty.cpp
|
/* -------------------------------------------------------------------------- *
* OpenSim: AbstractProperty.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the 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. *
* -------------------------------------------------------------------------- */
//============================================================================
// INCLUDES
//============================================================================
#include "AbstractProperty.h"
#include "Object.h"
#include <limits>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
AbstractProperty::AbstractProperty()
{
setNull();
}
//_____________________________________________________________________________
/**
* Constructor.
*/
AbstractProperty::AbstractProperty(const std::string& name,
const std::string& comment)
{
setNull();
_name = name;
_comment = comment;
}
//_____________________________________________________________________________
/**
* Set member variables to their null values.
*/
void AbstractProperty::setNull()
{
_name = "";
_comment = "";
_valueIsDefault = false;
_minListSize = 0;
_maxListSize = std::numeric_limits<int>::max();
}
void AbstractProperty::clear() {
clearValues();
}
// Set the use default flag for this property, and propagate that through
// any contained Objects.
void AbstractProperty::setAllPropertiesUseDefault(bool shouldUseDefault) {
setValueIsDefault(shouldUseDefault);
if (!isObjectProperty())
return;
for (int i=0; i < size(); ++i)
updValueAsObject(i).setAllPropertiesUseDefault(shouldUseDefault);
}
// Implement the policy that locates a property value's element within its
// parent element and then ask the concrete property to deserialize itself from
// that element.
void AbstractProperty::readFromXMLParentElement(Xml::Element& parent,
int versionNumber)
{
// If this property has a real name (that is, doesn't use the object type
// tag as a name), look for the first element whose tag is
// that name and read it if found. That is, we're looking for
// <propName> ... </propName>
if (!isUnnamedProperty()) {
Xml::element_iterator propElt = parent.element_begin(getName());
if (propElt != parent.element_end()) {
readFromXMLElement(*propElt, versionNumber);
setValueIsDefault(false);
return;
}
}
// Didn't find a property element by its name (or it didn't have one).
// There is still hope: If this is an object property, restricted to
// contain exactly one Object, then it is allowed to have an alternate
// form.
if (!isOneObjectProperty()) {
setValueIsDefault(true); // no special format allowed
return;
}
// The property contains just a single object so we can look for the
// abbreviated form:
// <ObjectTypeTag name=propName> contents </ObjectTypeTag>
// In case this is an unnamed property, only the type has to be right in
// the source XML file, and any name (or no name attribute) is acceptable.
// If the current property does have a property name, we select the first
// element that has that as the value of its name attribute; then it is
// an error if the type tag is not acceptable. On the other hand, if there
// is no property name, we select the first element that has an acceptable
// type; we don't care about its name attribute in that case.
// As a final loophole, if we fail to find a matching name, but there is
// an unnamed object in the file whose type is acceptable, we'll use that
// rather than report an error. That allows us to add a name to a
// formerly unnamed one-object property in the code yet still read old
// files that contain unnamed objects.
// If we find a promising element, we'll canonicalize by adding a parent
// property element temporarily to produce:
// <propName>
// <ObjectTypeTag name=propName> contents </ObjectTypeTag>
// </propName>
// or
// <Unnamed>
// <ObjectTypeTag> contents </ObjectTypeTag>
// </Unnamed>
// and then delegate to the concrete property the job of reading in the
// property value.
Xml::element_iterator prev = parent.element_end();
Xml::element_iterator iter = parent.element_begin();
if (isUnnamedProperty()) {
for (; iter != parent.element_end(); prev=iter++)
if (isAcceptableObjectTag(iter->getElementTag()))
break; // Found a good tag; name doesn't matter.
} else { // this property has a name
// First pass: look for an object with that name attribute
for (; iter != parent.element_end(); prev=iter++)
if (iter->getOptionalAttributeValue("name") == getName()) {
// Found the right name; tag must be acceptable.
if (!isAcceptableObjectTag(iter->getElementTag())) {
throw OpenSim::Exception
("Found XML element with expected property name=" + getName()
+ " in parent element " + parent.getElementTag()
+ " but its tag " + iter->getElementTag()
+ " was not an acceptable type for this property.");
return;
}
break;
}
if (iter == parent.element_end()) {
// Second pass: look for an unnamed object with the right type
prev = parent.element_end();
iter = parent.element_begin();
for (; iter != parent.element_end(); prev=iter++) {
if ( iter->getOptionalAttributeValue("name").empty()
&& isAcceptableObjectTag(iter->getElementTag()))
break; // Found a good tag; we'll ignore the name
}
}
}
if (iter == parent.element_end()) {
// Couldn't find an acceptable element for this one-object property.
setValueIsDefault(true);
return;
}
// Found a match. Borrow the object node briefly and canonicalize it
// into a conventional <propName> object </propName> structure.
std::string propName = isUnnamedProperty() ? "Unnamed" : getName();
Xml::Element dummy(propName);
dummy.insertNodeAfter(dummy.node_end(), parent.removeNode(iter));
parent.insertNodeAfter(parent.node_end(), dummy);
readFromXMLElement(dummy, versionNumber);
// Now put the node back where we found it.
parent.insertNodeBefore(prev,
dummy.removeNode(dummy.element_begin()));
setValueIsDefault(false);
parent.removeNode(parent.element_begin(dummy.getElementTag()));
dummy.clearOrphan();
}
void AbstractProperty::writeToXMLParentElement(Xml::Element& parent) const {
// Add comment if any.
if (!getComment().empty())
parent.insertNodeAfter(parent.node_end(), Xml::Comment(getComment()));
if (!isOneObjectProperty()) {
// Concrete property will be represented by an Xml element of
// the form <propName> value(s) </propName>.
assert(!getName().empty());
Xml::Element propElement(getName());
writeToXMLElement(propElement);
parent.insertNodeAfter(parent.node_end(), propElement);
return;
}
// This is a one-object property. It will be represented by an Xml
// element
// <ObjectTypeTag name=propName ...> value </ObjectTypeTag>
// (if the property has a name), or
// <ObjectTypeTag ...> value </ObjectTypeTag>
// otherwise.
const Object& obj = getValueAsObject();
// If this is a named property then the lone object must have its
// name attribute set to the property name.
obj.updateXMLNode(parent, isUnnamedProperty() ? "" : getName());
}
|
/* -------------------------------------------------------------------------- *
* OpenSim: AbstractProperty.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the 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. *
* -------------------------------------------------------------------------- */
//============================================================================
// INCLUDES
//============================================================================
#include "AbstractProperty.h"
#include "Object.h"
#include <limits>
using namespace OpenSim;
using namespace SimTK;
using namespace std;
//=============================================================================
// CONSTRUCTION
//=============================================================================
//_____________________________________________________________________________
/**
* Default constructor.
*/
AbstractProperty::AbstractProperty()
{
setNull();
}
//_____________________________________________________________________________
/**
* Constructor.
*/
AbstractProperty::AbstractProperty(const std::string& name,
const std::string& comment)
{
setNull();
_name = name;
_comment = comment;
}
//_____________________________________________________________________________
/**
* Set member variables to their null values.
*/
void AbstractProperty::setNull()
{
_name = "";
_comment = "";
_valueIsDefault = false;
_minListSize = 0;
_maxListSize = std::numeric_limits<int>::max();
}
void AbstractProperty::clear() {
clearValues();
}
// Set the use default flag for this property, and propagate that through
// any contained Objects.
void AbstractProperty::setAllPropertiesUseDefault(bool shouldUseDefault) {
setValueIsDefault(shouldUseDefault);
if (!isObjectProperty())
return;
for (int i=0; i < size(); ++i)
updValueAsObject(i).setAllPropertiesUseDefault(shouldUseDefault);
}
// Implement the policy that locates a property value's element within its
// parent element and then ask the concrete property to deserialize itself from
// that element.
void AbstractProperty::readFromXMLParentElement(Xml::Element& parent,
int versionNumber)
{
// If this property has a real name (that is, doesn't use the object type
// tag as a name), look for the first element whose tag is
// that name and read it if found. That is, we're looking for
// <propName> ... </propName>
if (!isUnnamedProperty()) {
Xml::element_iterator propElt = parent.element_begin(getName());
if (propElt != parent.element_end()) {
readFromXMLElement(*propElt, versionNumber);
setValueIsDefault(false);
return;
}
}
// Didn't find a property element by its name (or it didn't have one).
// There is still hope: If this is an object property, restricted to
// contain exactly one Object, then it is allowed to have an alternate
// form.
if (!isOneObjectProperty()) {
setValueIsDefault(true); // no special format allowed
return;
}
// The property contains just a single object so we can look for the
// abbreviated form:
// <ObjectTypeTag name=propName> contents </ObjectTypeTag>
// In case this is an unnamed property, only the type has to be right in
// the source XML file, and any name (or no name attribute) is acceptable.
// If the current property does have a property name, we select the first
// element that has that as the value of its name attribute; then it is
// an error if the type tag is not acceptable. On the other hand, if there
// is no property name, we select the first element that has an acceptable
// type; we don't care about its name attribute in that case.
// As a final loophole, if we fail to find a matching name, but there is
// an unnamed object in the file whose type is acceptable, we'll use that
// rather than report an error. That allows us to add a name to a
// formerly unnamed one-object property in the code yet still read old
// files that contain unnamed objects.
// If we find a promising element, we'll canonicalize by adding a parent
// property element temporarily to produce:
// <propName>
// <ObjectTypeTag name=propName> contents </ObjectTypeTag>
// </propName>
// or
// <Unnamed>
// <ObjectTypeTag> contents </ObjectTypeTag>
// </Unnamed>
// and then delegate to the concrete property the job of reading in the
// property value.
Xml::element_iterator prev = parent.element_end();
Xml::element_iterator iter = parent.element_begin();
if (isUnnamedProperty()) {
for (; iter != parent.element_end(); prev=iter++)
if (isAcceptableObjectTag(iter->getElementTag()))
break; // Found a good tag; name doesn't matter.
} else { // this property has a name
// First pass: look for an object with that name attribute
for (; iter != parent.element_end(); prev=iter++)
if (iter->getOptionalAttributeValue("name") == getName()) {
// Found the right name; tag must be acceptable.
if (!isAcceptableObjectTag(iter->getElementTag())) {
throw OpenSim::Exception
("Found XML element with expected property name=" + getName()
+ " in parent element " + parent.getElementTag()
+ " but its tag " + iter->getElementTag()
+ " was not an acceptable type for this property.");
return;
}
break;
}
if (iter == parent.element_end()) {
// Second pass: look for an unnamed object with the right type
prev = parent.element_end();
iter = parent.element_begin();
for (; iter != parent.element_end(); prev=iter++) {
if ( iter->getOptionalAttributeValue("name").empty()
&& isAcceptableObjectTag(iter->getElementTag()))
break; // Found a good tag; we'll ignore the name
}
}
}
if (iter == parent.element_end()) {
// Couldn't find an acceptable element for this one-object property.
setValueIsDefault(true);
return;
}
// Found a match. Borrow the object node briefly and canonicalize it
// into a conventional <propName> object </propName> structure.
std::string propName = isUnnamedProperty() ? "Unnamed" : getName();
Xml::Element dummy(propName);
dummy.insertNodeAfter(dummy.node_end(), parent.removeNode(iter));
parent.insertNodeAfter(parent.node_end(), dummy);
readFromXMLElement(dummy, versionNumber);
// Now put the node back where we found it.
parent.insertNodeBefore(prev,
dummy.removeNode(dummy.element_begin()));
setValueIsDefault(false);
parent.removeNode(parent.element_begin(dummy.getElementTag()));
dummy.clearOrphan();
}
void AbstractProperty::writeToXMLParentElement(Xml::Element& parent) const {
// Add comment if any.
if (!getComment().empty())
parent.insertNodeAfter(parent.node_end(), Xml::Comment(getComment()));
if (!isOneObjectProperty()) {
// Concrete property will be represented by an Xml element of
// the form <propName> value(s) </propName>.
assert(!getName().empty());
Xml::Element propElement(getName());
writeToXMLElement(propElement);
parent.insertNodeAfter(parent.node_end(), propElement);
return;
}
// This is a one-object property. It will be represented by an Xml
// element
// <ObjectTypeTag name=propName ...> value </ObjectTypeTag>
// (if the property has a name), or
// <ObjectTypeTag ...> value </ObjectTypeTag>
// otherwise.
const Object& obj = getValueAsObject();
// If this is a named property then the lone object must have its
// name attribute set to the property name.
obj.updateXMLNode(parent, this);
}
|
Use the updated Object::updateXMLNode method to determine how to set the name attribute of the node given the property as an argument as to respect its settings (e.g. isUnnamedProperty()) without editing the object.
|
Use the updated Object::updateXMLNode method to determine how to set the name attribute of the node given the property as an argument as to respect its settings (e.g. isUnnamedProperty()) without editing the object.
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
e86c23b26a6eecfbe8a82d0395c3bcbd5e749150
|
OpenSim/Simulation/Model/Marker.cpp
|
OpenSim/Simulation/Model/Marker.cpp
|
/* -------------------------------------------------------------------------- *
* OpenSim: Marker.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Peter Loan *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Marker.h"
#include "Model.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/*
* Default constructor.
*/
Marker::Marker() :
Station()
{
constructProperties();
}
//_____________________________________________________________________________
/*
* Convenience constructor.
*/
Marker::Marker(const std::string& name, const PhysicalFrame& frame,
const SimTK::Vec3& location) :
Station(frame, location)
{
constructProperties();
setName(name);
}
//_____________________________________________________________________________
/*
* Destructor.
*/
Marker::~Marker()
{
}
//_____________________________________________________________________________
/*
* Set the data members of this Marker to their null values.
*/
void Marker::setNull()
{
}
//_____________________________________________________________________________
/*
* Construct properties and initialize their default values.
*/
void Marker::constructProperties()
{
// Indicate whether the Marker is fixed or not (for MarkerPlacement)
constructProperty_fixed(false);
}
void Marker::setParentFrameName(const string& name)
{
updSocket<PhysicalFrame>("parent_frame").setConnecteePath(name);
}
//_____________________________________________________________________________
/*
* Get the 'frame name' field, which is used when the marker is added to
* an existing model.
*/
const string& Marker::getParentFrameName() const
{
return getSocket<PhysicalFrame>("parent_frame").getConnecteePath();
}
void Marker::changeFrame(const PhysicalFrame& parentFrame)
{
if (&parentFrame == &getParentFrame())
return;
setParentFrame(parentFrame);
}
void Marker::changeFramePreserveLocation(const SimTK::State& s,
const PhysicalFrame& parentFrame)
{
if (&parentFrame == &getParentFrame())
return;
// Preserve location means to switch bodies without changing
// the location of the marker in the inertial reference frame.
Vec3 newLocation;
newLocation = findLocationInFrame(s, parentFrame);
set_location(newLocation);
setParentFrame(parentFrame);
}
//_____________________________________________________________________________
/*
* Override default implementation by object to intercept and fix the XML node
* underneath the Marker to match current version
*/
/*virtual*/
void Marker::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
if (versionNumber < XMLDocument::getLatestVersion()){
if (versionNumber < 30501) {
// Parse name of Body under <body>node
SimTK::Xml::element_iterator bIter = aNode.element_begin("body");
SimTK::String bName = bIter->getValue();
// Create nodes for new layout
SimTK::Xml::Element connectorsElement("connectors");
SimTK::Xml::Element frameElement("Connector_PhysicalFrame_");
connectorsElement.insertNodeAfter(connectorsElement.node_end(), frameElement);
frameElement.setAttributeValue("name", "parent_frame");
SimTK::Xml::Element connecteeElement("connectee_name");
// Markers in pre-4.0 models are necessarily 1 level deep
// (model, markers), and Bodies were necessarily 1 level deep;
// here we create the correct relative path (accounting for sets
// being components).
bName = XMLDocument::updateConnecteePath30517("bodyset", bName);
connecteeElement.setValue(bName);
frameElement.insertNodeAfter(frameElement.node_end(), connecteeElement);
aNode.insertNodeAfter(bIter, connectorsElement);
aNode.eraseNode(bIter);
}
}
// Call base class now assuming _node has been corrected for current version
Super::updateFromXMLNode(aNode, versionNumber);
}
void Marker::generateDecorations(bool fixed, const ModelDisplayHints& hints, const SimTK::State& state,
SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const
{
Super::generateDecorations(fixed, hints, state, appendToThis);
if (!fixed) return;
if (!hints.get_show_markers()) return;
// @TODO default color, size, shape should be obtained from hints
const Vec3 color = hints.get_marker_color();
const OpenSim::PhysicalFrame& frame = getParentFrame();
//const Frame& bf = frame.findBaseFrame();
//SimTK::Transform bTrans = frame.findTransformInBaseFrame();
//const Vec3& p_BM = bTrans*get_location();
appendToThis.push_back(
SimTK::DecorativeSphere(.01).setBodyId(frame.getMobilizedBodyIndex())
.setColor(color).setOpacity(1.0)
.setTransform(get_location()));
}
|
/* -------------------------------------------------------------------------- *
* OpenSim: Marker.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Peter Loan *
* *
* 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. *
* -------------------------------------------------------------------------- */
//=============================================================================
// INCLUDES
//=============================================================================
#include "Marker.h"
#include "Model.h"
//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/*
* Default constructor.
*/
Marker::Marker() :
Station()
{
constructProperties();
}
//_____________________________________________________________________________
/*
* Convenience constructor.
*/
Marker::Marker(const std::string& name, const PhysicalFrame& frame,
const SimTK::Vec3& location) :
Station(frame, location)
{
constructProperties();
setName(name);
}
//_____________________________________________________________________________
/*
* Destructor.
*/
Marker::~Marker()
{
}
//_____________________________________________________________________________
/*
* Set the data members of this Marker to their null values.
*/
void Marker::setNull()
{
}
//_____________________________________________________________________________
/*
* Construct properties and initialize their default values.
*/
void Marker::constructProperties()
{
// Indicate whether the Marker is fixed or not (for MarkerPlacement)
constructProperty_fixed(false);
}
void Marker::setParentFrameName(const string& name)
{
updSocket<PhysicalFrame>("parent_frame").setConnecteePath(name);
}
//_____________________________________________________________________________
/*
* Get the 'frame name' field, which is used when the marker is added to
* an existing model.
*/
const string& Marker::getParentFrameName() const
{
return getSocket<PhysicalFrame>("parent_frame").getConnecteePath();
}
void Marker::changeFrame(const PhysicalFrame& parentFrame)
{
if (&parentFrame == &getParentFrame())
return;
setParentFrame(parentFrame);
}
void Marker::changeFramePreserveLocation(const SimTK::State& s,
const PhysicalFrame& parentFrame)
{
if (&parentFrame == &getParentFrame())
return;
// Preserve location means to switch bodies without changing
// the location of the marker in the inertial reference frame.
Vec3 newLocation;
newLocation = findLocationInFrame(s, parentFrame);
set_location(newLocation);
setParentFrame(parentFrame);
}
//_____________________________________________________________________________
/*
* Override default implementation by object to intercept and fix the XML node
* underneath the Marker to match current version
*/
/*virtual*/
void Marker::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
if (versionNumber < XMLDocument::getLatestVersion()){
if (versionNumber < 30501) {
// Parse name of Body under <body>node
SimTK::Xml::element_iterator bIter = aNode.element_begin("body");
SimTK::String bName = bIter->getValue();
// Create nodes for new layout
SimTK::Xml::Element connectorsElement("connectors");
SimTK::Xml::Element frameElement("Connector_PhysicalFrame_");
connectorsElement.insertNodeAfter(connectorsElement.node_end(), frameElement);
frameElement.setAttributeValue("name", "parent_frame");
SimTK::Xml::Element connecteeElement("connectee_name");
// Markers in pre-4.0 models are necessarily 1 level deep
// (model, markers), and Bodies were necessarily 1 level deep;
// here we create the correct relative path (accounting for sets
// being components).
bName = XMLDocument::updateConnecteePath30517("bodyset", bName);
connecteeElement.setValue(bName);
frameElement.insertNodeAfter(frameElement.node_end(), connecteeElement);
aNode.insertNodeAfter(bIter, connectorsElement);
aNode.eraseNode(bIter);
}
}
// Call base class now assuming _node has been corrected for current version
Super::updateFromXMLNode(aNode, versionNumber);
}
void Marker::generateDecorations(bool fixed, const ModelDisplayHints& hints, const SimTK::State& state,
SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const
{
Super::generateDecorations(fixed, hints, state, appendToThis);
if (!fixed) return;
if (!hints.get_show_markers()) return;
// @TODO default color, size, shape should be obtained from hints
const Vec3 color = hints.get_marker_color();
const OpenSim::PhysicalFrame& frame = getParentFrame();
//const Frame& bf = frame.findBaseFrame();
//SimTK::Transform bTrans = frame.findTransformInBaseFrame();
//const Vec3& p_BM = bTrans*get_location();
appendToThis.push_back(
SimTK::DecorativeSphere(.01).setBodyId(frame.getMobilizedBodyIndex())
.setColor(color).setOpacity(1.0)
.setTransform(get_location())
.setScaleFactors(Vec3(1)));
}
|
Fix scale factors for Marker geometry so it doesn't show inside-out in GUI
|
Fix scale factors for Marker geometry so it doesn't show inside-out in GUI
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
73b92c0b05dcac768dd604fe85598a9a5ea6e230
|
CollisionsAdvanced/src/Bitmask.cpp
|
CollisionsAdvanced/src/Bitmask.cpp
|
#include "Bitmask.h"
#include <of3dGraphics.h>
using namespace math;
function<bool(ofVec4f)> Bitmask::defaultColorKey()
{
return [](ofVec4f colorKey) -> bool {
return colorKey.w == 0;
};
}
ofVec4f Bitmask::pixelColor(int x, int y) const
{
auto& pixels = image->getPixels();
auto color = pixels.getColor(x, y);
return ofVec4f(color.r, color.g, color.b, color.a);
}
Bitmask::Bitmask(): image(nullptr), broadPhaseBox(nullptr), dimensions(nullptr), frames(nullptr), frame(nullptr)
{
isColorKey = defaultColorKey();
}
Bitmask::Bitmask(
ofImage& _image, math::AABB& _broadPhaseBox,
Vector2D* _dimensions, vector<unsigned int>* _frames, unsigned int* _frame, function<bool(ofVec4f)> _isColorKey)
: image(&_image), broadPhaseBox(&_broadPhaseBox), frames(_frames), frame(_frame)
{
auto zeroVec = Vector2D();
dimensions = _dimensions == nullptr ? &zeroVec : _dimensions;
if(dimensions->sizeSqr() == 0 || dimensions->sizeSqr() > math::Vector2D(image->getWidth(), image->getHeight()).sizeSqr()) {
dimensions->x = image->getWidth();
dimensions->y = image->getHeight();
}
isColorKey = _isColorKey ? _isColorKey : defaultColorKey();
}
bool Bitmask::testCollision(const Bitmask& other) const
{
//AABB intersection region to apply the bitmask check
auto region = broadPhaseBox->intersection(*other.broadPhaseBox);
/*
Calculates which is the current row and column of the frame of the animation being played.
With this coordinate, we will be able to know exactly which
is the sprite region of the image in which we will need to calculate bitmask
*/
//int rowFrame1 = (*frames)[*frame] / (image->getHeight() / dimensions->y);
//int colFrame1 = (*frames)[*frame] % int((image->getWidth() / dimensions->x));
//int rowFrame2 = (*other.frames)[*other.frame] / (other.image->getHeight() / other.dimensions->y);
//int colFrame2 = (*other.frames)[*other.frame] % int((other.image->getWidth() / other.dimensions->x));
int rowFrame1, rowFrame2, colFrame1, colFrame2;
rowFrame1 = rowFrame2 = colFrame1 = colFrame2 = 0;
/*
We now need to iterate over each pixel of the two images in the exact area of the intersection.
If there are two colors other than Color Key, this means that there was a collision.
We begin the for at the beginning of the intersection rectangle.
*/
for (auto i = int(region.bottom()); i <= int(region.top()); i++) {
/*
Calculates for the sprite 1 and 2 the coordinate of the pixel in the y-image.
This coordinate is based on the current animation frame plus the offset.
We need to calculate the subtraction to push the image to the corner (0,0) of the screen.
The same logic will be applied to x in the internal for.
Image pixels are read with y inverted, so we need to get a coordinate from top to bottom
*/
int y1 = image->getHeight() - (dimensions->y * rowFrame1 + i - int(broadPhaseBox->bottom()));
padValue(y1, 0, int(image->getHeight()) - 1);
int y2 = other.image->getHeight() - (other.dimensions->y * rowFrame2 + i - int(other.broadPhaseBox->bottom()));
padValue(y2, 0, int(other.image->getHeight()) - 1);
for (auto j = int(region.left()); j <= int(region.right()); j++) {
int x1 = dimensions->x * colFrame1 + j - int(broadPhaseBox->left());
padValue(x1, 0, int(image->getWidth()) - 1);
int x2 = other.dimensions->x * colFrame2 + j - int(other.broadPhaseBox->left());
padValue(x2, 0, int(other.image->getWidth()) - 1);
//If this pixel is the color key in any of the images, it's not a collision. Else, pixel collision detected
if (isColorKey(pixelColor(x1, y1)) || other.isColorKey(other.pixelColor(x2, y2)))
continue;
// if (!isColorKey(pixelColor(x1, y1)))
// cout << "Cor da amarela no passou. Essa cor TEM QUE SER 255 242 0 255, seno bug: " << pixelColor(x1, y1) << endl;
// if (!other.isColorKey(other.pixelColor(x2, y2)))
// cout << "Cor da branca no passou. Essa cor NO PODE ter g > 120, seno bug: " << other.pixelColor(x2, y2) << endl;
//
// auto& pixels = image->getPixels();
// auto color = pixels.getColor(x1, y1);
// color.r = color.g = color.b = 0;
// pixels.setColor(x1, y1, color);
//TODO: Collision detected, but just with one pixel isn't too perfect?
return true;
}
}
// image->update();
return false;
}
void Bitmask::transform(math::Vector2D _position, float angle, math::Vector2D _size, bool centered)
{
//TODO: Possibilidade de aplicar coliso de bitmask com sprites redimensionados (escala varivel)
//TODO: Considerar o clculo de rotao para o Bitmask
}
void Bitmask::removeArea(math::AABB& region)
{
//TODO: utilizar canal alpha para esconder informaes
}
void Bitmask::removeArea(math::BoundingCircle& region)
{
//TODO: utilizar canal alpha para esconder informaes
}
Bitmask::~Bitmask()
{
}
|
#include "Bitmask.h"
#include <of3dGraphics.h>
using namespace math;
function<bool(ofVec4f)> Bitmask::defaultColorKey()
{
return [](ofVec4f colorKey) -> bool {
return colorKey.w == 0;
};
}
ofVec4f Bitmask::pixelColor(int x, int y) const
{
auto& pixels = image->getPixels();
auto color = pixels.getColor(x, y);
return ofVec4f(color.r, color.g, color.b, color.a);
}
Bitmask::Bitmask(): image(nullptr), broadPhaseBox(nullptr), dimensions(nullptr), frames(nullptr), frame(nullptr)
{
isColorKey = defaultColorKey();
}
Bitmask::Bitmask(
ofImage& _image, math::AABB& _broadPhaseBox,
Vector2D* _dimensions, vector<unsigned int>* _frames, unsigned int* _frame, function<bool(ofVec4f)> _isColorKey)
: image(&_image), broadPhaseBox(&_broadPhaseBox), frames(_frames), frame(_frame)
{
auto zeroVec = Vector2D();
dimensions = _dimensions == nullptr ? &zeroVec : _dimensions;
if(dimensions->sizeSqr() == 0 || dimensions->sizeSqr() > math::Vector2D(image->getWidth(), image->getHeight()).sizeSqr()) {
dimensions->x = image->getWidth();
dimensions->y = image->getHeight();
}
isColorKey = _isColorKey ? _isColorKey : defaultColorKey();
}
bool Bitmask::testCollision(const Bitmask& other) const
{
//AABB intersection region to apply the bitmask check
auto region = broadPhaseBox->intersection(*other.broadPhaseBox);
/*
Calculates which is the current row and column of the frame of the animation being played.
With this coordinate, we will be able to know exactly which
is the sprite region of the image in which we will need to calculate bitmask
*/
//int rowFrame1 = (*frames)[*frame] / (image->getHeight() / dimensions->y);
int colFrame1 = (*frames)[*frame] % int((image->getWidth() / dimensions->x));
//int rowFrame2 = (*other.frames)[*other.frame] / (other.image->getHeight() / other.dimensions->y);
int colFrame2 = (*other.frames)[*other.frame] % int((other.image->getWidth() / other.dimensions->x));
int rowFrame1, rowFrame2;
rowFrame1 = rowFrame2 = 0;
cout << "Frame em x do cavalo: " << colFrame1 << ", Frame em x da nave: " << colFrame2 << endl;
/*
We now need to iterate over each pixel of the two images in the exact area of the intersection.
If there are two colors other than Color Key, this means that there was a collision.
We begin the for at the beginning of the intersection rectangle.
*/
for (auto i = int(region.bottom()); i <= int(region.top()); i++) {
/*
Calculates for the sprite 1 and 2 the coordinate of the pixel in the y-image.
This coordinate is based on the current animation frame plus the offset.
We need to calculate the subtraction to push the image to the corner (0,0) of the screen.
The same logic will be applied to x in the internal for.
Image pixels are read with y inverted, so we need to get a coordinate from top to bottom
*/
int y1 = image->getHeight() - (dimensions->y * rowFrame1 + i - int(broadPhaseBox->bottom()));
padValue(y1, 0, int(image->getHeight()) - 1);
int y2 = other.image->getHeight() - (other.dimensions->y * rowFrame2 + i - int(other.broadPhaseBox->bottom()));
padValue(y2, 0, int(other.image->getHeight()) - 1);
for (auto j = int(region.left()); j <= int(region.right()); j++) {
int x1 = dimensions->x * colFrame1 + j - int(broadPhaseBox->left());
padValue(x1, 0, int(image->getWidth()) - 1);
int x2 = other.dimensions->x * colFrame2 + j - int(other.broadPhaseBox->left());
padValue(x2, 0, int(other.image->getWidth()) - 1);
//If this pixel is the color key in any of the images, it's not a collision. Else, pixel collision detected
if (isColorKey(pixelColor(x1, y1)) || other.isColorKey(other.pixelColor(x2, y2)))
continue;
// if (!isColorKey(pixelColor(x1, y1)))
// cout << "Cor da amarela no passou. Essa cor TEM QUE SER 255 242 0 255, seno bug: " << pixelColor(x1, y1) << endl;
// if (!other.isColorKey(other.pixelColor(x2, y2)))
// cout << "Cor da branca no passou. Essa cor NO PODE ter g > 120, seno bug: " << other.pixelColor(x2, y2) << endl;
//
// auto& pixels = image->getPixels();
// auto color = pixels.getColor(x1, y1);
// color.r = color.g = color.b = 0;
// pixels.setColor(x1, y1, color);
//TODO: Collision detected, but just with one pixel isn't too perfect?
return true;
}
}
// image->update();
return false;
}
void Bitmask::transform(math::Vector2D _position, float angle, math::Vector2D _size, bool centered)
{
//TODO: Possibilidade de aplicar coliso de bitmask com sprites redimensionados (escala varivel)
//TODO: Considerar o clculo de rotao para o Bitmask
}
void Bitmask::removeArea(math::AABB& region)
{
//TODO: utilizar canal alpha para esconder informaes
}
void Bitmask::removeArea(math::BoundingCircle& region)
{
//TODO: utilizar canal alpha para esconder informaes
}
Bitmask::~Bitmask()
{
}
|
Adjust bitmask algorithm to sprites considering animation frame in width
|
Adjust bitmask algorithm to sprites considering animation frame in width
|
C++
|
apache-2.0
|
rafagan/advanced-collision-demos,rafagan/advanced-collision-demos
|
a6947c3f53d6d97798bea590895eb299edaa8ab1
|
Core/IO/mitkItkImageFileReader.cpp
|
Core/IO/mitkItkImageFileReader.cpp
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkItkImageFileReader.h"
#include "mitkConfig.h"
#include <itkImageFileReader.h>
#include <itksys/SystemTools.hxx>
#include <itksys/Directory.hxx>
#include <itkImage.h>
//#include <itkImageSeriesReader.h>
#include <itkImageFileReader.h>
#include <itkImageIOFactory.h>
#include <itkImageIORegion.h>
//#include <itkImageSeriesReader.h>
//#include <itkDICOMImageIO2.h>
//#include <itkDICOMSeriesFileNames.h>
//#include <itkGDCMImageIO.h>
//#include <itkGDCMSeriesFileNames.h>
//#include <itkNumericSeriesFileNames.h>
void mitk::ItkImageFileReader::GenerateData()
{
mitk::Image::Pointer image = this->GetOutput();
const unsigned int MINDIM = 2;
const unsigned int MAXDIM = 4;
std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;
// Check to see if we can read the file given the name or prefix
if ( m_FileName == "" )
{
itkWarningMacro( << "File Type not supported!" );
return ;
}
if ( m_FileName == "--no-server" )
{
return ;
}
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode );
if ( imageIO.IsNull() )
{
itkWarningMacro( << "File Type not supported!" );
return ;
}
// Got to allocate space for the image. Determine the characteristics of
// the image.
imageIO->SetFileName( m_FileName.c_str() );
imageIO->ReadImageInformation();
unsigned int ndim = imageIO->GetNumberOfDimensions();
if ( ndim < MINDIM || ndim > MAXDIM )
{
itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." );
ndim = MAXDIM;
}
itk::ImageIORegion ioRegion( ndim );
itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();
unsigned int dimensions[ MAXDIM ];
dimensions[ 0 ] = 0;
dimensions[ 1 ] = 0;
dimensions[ 2 ] = 0;
dimensions[ 3 ] = 0;
float spacing[ MAXDIM ];
spacing[ 0 ] = 1.0f;
spacing[ 1 ] = 1.0f;
spacing[ 2 ] = 1.0f;
spacing[ 3 ] = 1.0f;
Point3D origin;
origin.Fill(0);
for ( unsigned int i = 0; i < ndim ; ++i )
{
ioStart[ i ] = 0;
ioSize[ i ] = imageIO->GetDimensions( i );
if(i<MAXDIM)
{
dimensions[ i ] = imageIO->GetDimensions( i );
spacing[ i ] = imageIO->GetSpacing( i );
if(spacing[ i ] <= 0)
spacing[ i ] = 1.0f;
}
if(i<3)
{
origin[ i ] = imageIO->GetOrigin( i );
}
}
ioRegion.SetSize( ioSize );
ioRegion.SetIndex( ioStart );
std::cout << "ioRegion: " << ioRegion << std::endl;
imageIO->SetIORegion( ioRegion );
void* buffer = malloc( imageIO->GetImageSizeInBytes() );
imageIO->Read( buffer );
//mitk::Image::Pointer image = mitk::Image::New();
if((ndim==4) && (dimensions[3]<=1))
ndim = 3;
if((ndim==3) && (dimensions[2]<=1))
ndim = 2;
#if ITK_VERSION_MAJOR == 2 || ( ITK_VERSION_MAJOR == 1 && ITK_VERSION_MINOR > 6 )
mitk::PixelType pixelType( imageIO->GetComponentTypeInfo(), imageIO->GetNumberOfComponents() );
image->Initialize( pixelType, ndim, dimensions );
#else
if ( imageIO->GetNumberOfComponents() > 1)
itkWarningMacro(<<"For older itk versions, only scalar images are supported!");
mitk::PixelType pixelType( imageIO->GetPixelType() );
image->Initialize( pixelType, ndim, dimensions );
#endif
image->SetVolume( buffer );
image->GetSlicedGeometry()->SetOrigin( origin );
image->GetSlicedGeometry()->SetSpacing( spacing );
image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(image->GetSlicedGeometry(), image->GetDimension(3));
free( buffer );
buffer = NULL;
std::cout << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;
// mitk::DataTreeNode::Pointer node = this->GetOutput();
// node->SetData( image );
// add level-window property
//if ( image->GetPixelType().GetNumberOfComponents() == 1 )
//{
// SetDefaultImageProperties( node );
//}
std::cout << "...finished!" << std::endl;
}
bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
// First check the extension
if( filename == "" )
return false;
// check if image is serie
if( filePattern != "" && filePrefix != "" )
return false;
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode );
if ( imageIO.IsNull() )
return false;
return true;
}
mitk::ItkImageFileReader::ItkImageFileReader()
: m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}
mitk::ItkImageFileReader::~ItkImageFileReader()
{
}
|
/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkItkImageFileReader.h"
#include "mitkConfig.h"
#include <itkImageFileReader.h>
#include <itksys/SystemTools.hxx>
#include <itksys/Directory.hxx>
#include <itkImage.h>
//#include <itkImageSeriesReader.h>
#include <itkImageFileReader.h>
#include <itkImageIOFactory.h>
#include <itkImageIORegion.h>
//#include <itkImageSeriesReader.h>
//#include <itkDICOMImageIO2.h>
//#include <itkDICOMSeriesFileNames.h>
//#include <itkGDCMImageIO.h>
//#include <itkGDCMSeriesFileNames.h>
//#include <itkNumericSeriesFileNames.h>
void mitk::ItkImageFileReader::GenerateData()
{
mitk::Image::Pointer image = this->GetOutput();
const unsigned int MINDIM = 2;
const unsigned int MAXDIM = 4;
std::cout << "loading " << m_FileName << " via itk::ImageIOFactory... " << std::endl;
// Check to see if we can read the file given the name or prefix
if ( m_FileName == "" )
{
itkWarningMacro( << "File Type not supported!" );
return ;
}
if ( m_FileName == "--no-server" )
{
return ;
}
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( m_FileName.c_str(), itk::ImageIOFactory::ReadMode );
if ( imageIO.IsNull() )
{
itkWarningMacro( << "File Type not supported!" );
return ;
}
// Got to allocate space for the image. Determine the characteristics of
// the image.
imageIO->SetFileName( m_FileName.c_str() );
imageIO->ReadImageInformation();
unsigned int ndim = imageIO->GetNumberOfDimensions();
if ( ndim < MINDIM || ndim > MAXDIM )
{
itkWarningMacro( << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D." );
ndim = MAXDIM;
}
itk::ImageIORegion ioRegion( ndim );
itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize();
itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex();
unsigned int dimensions[ MAXDIM ];
dimensions[ 0 ] = 0;
dimensions[ 1 ] = 0;
dimensions[ 2 ] = 0;
dimensions[ 3 ] = 0;
float spacing[ MAXDIM ];
spacing[ 0 ] = 1.0f;
spacing[ 1 ] = 1.0f;
spacing[ 2 ] = 1.0f;
spacing[ 3 ] = 1.0f;
Point3D origin;
origin.Fill(0);
for ( unsigned int i = 0; i < ndim ; ++i )
{
ioStart[ i ] = 0;
ioSize[ i ] = imageIO->GetDimensions( i );
if(i<MAXDIM)
{
dimensions[ i ] = imageIO->GetDimensions( i );
spacing[ i ] = imageIO->GetSpacing( i );
if(spacing[ i ] <= 0)
spacing[ i ] = 1.0f;
}
if(i<3)
{
origin[ i ] = imageIO->GetOrigin( i );
}
}
ioRegion.SetSize( ioSize );
ioRegion.SetIndex( ioStart );
std::cout << "ioRegion: " << ioRegion << std::endl;
imageIO->SetIORegion( ioRegion );
void* buffer = malloc( imageIO->GetImageSizeInBytes() );
imageIO->Read( buffer );
//mitk::Image::Pointer image = mitk::Image::New();
if((ndim==4) && (dimensions[3]<=1))
ndim = 3;
if((ndim==3) && (dimensions[2]<=1))
ndim = 2;
#if ITK_VERSION_MAJOR == 2 || ( ITK_VERSION_MAJOR == 1 && ITK_VERSION_MINOR > 6 )
mitk::PixelType pixelType( imageIO->GetComponentTypeInfo(), imageIO->GetNumberOfComponents() );
image->Initialize( pixelType, ndim, dimensions );
#else
if ( imageIO->GetNumberOfComponents() > 1)
itkWarningMacro(<<"For older itk versions, only scalar images are supported!");
mitk::PixelType pixelType( imageIO->GetPixelType() );
image->Initialize( pixelType, ndim, dimensions );
#endif
image->SetVolume( buffer );
#if ITK_VERSION_MAJOR == 2 && ITK_VERSION_MINOR < 4
image->GetSlicedGeometry()->SetOrigin( origin );
image->GetSlicedGeometry()->SetSpacing( spacing );
image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(image->GetSlicedGeometry(), image->GetDimension(3));
#else
// access direction of itk::Image and include spacing
mitk::Matrix3D matrix;
matrix.SetIdentity();
unsigned int i, j, itkDimMax3 = (ndim >= 3? 3 : ndim);
for ( i=0; i < itkDimMax3; ++i)
for( j=0; j < itkDimMax3; ++j )
matrix[i][j] = imageIO->GetDirection(j)[i];
// re-initialize PlaneGeometry with origin and direction
PlaneGeometry* planeGeometry = static_cast<PlaneGeometry*>(image->GetSlicedGeometry(0)->GetGeometry2D(0));
planeGeometry->SetOrigin(origin);
planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix);
// re-initialize SlicedGeometry3D
SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0);
slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2));
slicedGeometry->SetSpacing(spacing);
// re-initialize TimeSlicedGeometry
image->GetTimeSlicedGeometry()->InitializeEvenlyTimed(slicedGeometry, image->GetDimension(3));
#endif
free( buffer );
buffer = NULL;
std::cout << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl;
// mitk::DataTreeNode::Pointer node = this->GetOutput();
// node->SetData( image );
// add level-window property
//if ( image->GetPixelType().GetNumberOfComponents() == 1 )
//{
// SetDefaultImageProperties( node );
//}
std::cout << "...finished!" << std::endl;
}
bool mitk::ItkImageFileReader::CanReadFile(const std::string filename, const std::string filePrefix, const std::string filePattern)
{
// First check the extension
if( filename == "" )
return false;
// check if image is serie
if( filePattern != "" && filePrefix != "" )
return false;
itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( filename.c_str(), itk::ImageIOFactory::ReadMode );
if ( imageIO.IsNull() )
return false;
return true;
}
mitk::ItkImageFileReader::ItkImageFileReader()
: m_FileName(""), m_FilePrefix(""), m_FilePattern("")
{
}
mitk::ItkImageFileReader::~ItkImageFileReader()
{
}
|
read direction matrix from itkImageIO
|
ENH: read direction matrix from itkImageIO
|
C++
|
bsd-3-clause
|
NifTK/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,lsanzdiaz/MITK-BiiG,rfloca/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,NifTK/MITK,danielknorr/MITK,rfloca/MITK,RabadanLab/MITKats,MITK/MITK,iwegner/MITK,fmilano/mitk,iwegner/MITK,rfloca/MITK,nocnokneo/MITK,MITK/MITK,danielknorr/MITK,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,nocnokneo/MITK,NifTK/MITK,iwegner/MITK,nocnokneo/MITK,fmilano/mitk,nocnokneo/MITK,fmilano/mitk,rfloca/MITK,NifTK/MITK,rfloca/MITK,fmilano/mitk,iwegner/MITK,RabadanLab/MITKats,nocnokneo/MITK,fmilano/mitk,MITK/MITK,danielknorr/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,iwegner/MITK,MITK/MITK,rfloca/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,danielknorr/MITK,RabadanLab/MITKats,MITK/MITK,nocnokneo/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,rfloca/MITK,iwegner/MITK,MITK/MITK,danielknorr/MITK
|
f7603fb3522ffcdbcc416e684a218709532bbe26
|
Decoders/LoopableRegionDecoder.cpp
|
Decoders/LoopableRegionDecoder.cpp
|
/*
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Stephen F. Booth <[email protected]>
* 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 Stephen F. Booth 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 <algorithm>
#include <log4cxx/logger.h>
#include "LoopableRegionDecoder.h"
#include "AudioDecoder.h"
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(0), mRepeatCount(0), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
mFrameCount = static_cast<UInt32>(mDecoder->GetTotalFrames() - mStartingFrame);
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame, UInt32 frameCount)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(frameCount), mRepeatCount(0), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame, UInt32 frameCount, UInt32 repeatCount)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(frameCount), mRepeatCount(repeatCount), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::~LoopableRegionDecoder()
{
// Just set our references to NULL, as mDecoder actually owns the objects and will delete them
mInputSource = NULL;
mChannelLayout = NULL;
if(mDecoder)
delete mDecoder, mDecoder = NULL;
}
void LoopableRegionDecoder::Reset()
{
mDecoder->SeekToFrame(mStartingFrame);
mFramesReadInCurrentPass = 0;
mTotalFramesRead = 0;
mCompletedPasses = 0;
}
#pragma mark Functionality
bool LoopableRegionDecoder::OpenFile(CFErrorRef *error)
{
if(!mDecoder->FileIsOpen())
return mDecoder->OpenFile(error);
return true;
}
bool LoopableRegionDecoder::CloseFile(CFErrorRef *error)
{
if(mDecoder->FileIsOpen())
return mDecoder->CloseFile(error);
return true;
}
SInt64 LoopableRegionDecoder::SeekToFrame(SInt64 frame)
{
assert(0 <= frame);
assert(frame < GetTotalFrames());
mCompletedPasses = static_cast<UInt32>(frame / mFrameCount);
mFramesReadInCurrentPass = static_cast<UInt32>(frame % mFrameCount);
mTotalFramesRead = frame;
mDecoder->SeekToFrame(mStartingFrame + mFramesReadInCurrentPass);
return GetCurrentFrame();
}
UInt32 LoopableRegionDecoder::ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
assert(NULL != bufferList);
assert(bufferList->mNumberBuffers == mFormat.mChannelsPerFrame);
assert(0 < frameCount);
// If the repeat count is N then (N + 1) passes must be completed to read all the frames
if((1 + mRepeatCount) == mCompletedPasses)
return 0;
// Allocate an alias to the buffer list, which will contain pointers to the current write position in the output buffer
AudioBufferList *bufferListAlias = static_cast<AudioBufferList *>(calloc(1, offsetof(AudioBufferList, mBuffers) + (sizeof(AudioBuffer) * mFormat.mChannelsPerFrame)));
if(NULL == bufferListAlias) {
log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.AudioDecoder.LoopableRegion");
LOG4CXX_ERROR(logger, "Unable to allocate memory")
return 0;
}
UInt32 initialBufferCapacityBytes = bufferList->mBuffers[0].mDataByteSize;
bufferListAlias->mNumberBuffers = mFormat.mChannelsPerFrame;
// Initially the buffer list alias points to the beginning and contains no data
for(UInt32 i = 0; i < bufferListAlias->mNumberBuffers; ++i) {
bufferListAlias->mBuffers[i].mData = bufferList->mBuffers[i].mData;
bufferListAlias->mBuffers[i].mDataByteSize = bufferList->mBuffers[i].mDataByteSize;
bufferListAlias->mBuffers[i].mNumberChannels = bufferList->mBuffers[i].mNumberChannels;
bufferList->mBuffers[i].mDataByteSize = 0;
}
UInt32 framesRemaining = frameCount;
UInt32 totalFramesRead = 0;
while(0 < framesRemaining) {
UInt32 framesRemainingInCurrentPass = static_cast<UInt32>(mStartingFrame + mFrameCount - mDecoder->GetCurrentFrame());
UInt32 framesToRead = std::min(framesRemaining, framesRemainingInCurrentPass);
// Nothing left to read
if(0 == framesToRead)
break;
UInt32 framesRead = mDecoder->ReadAudio(bufferListAlias, framesToRead);
// A read error occurred
if(0 == framesRead)
break;
// Advance the write pointers and update the capacity
for(UInt32 i = 0; i < bufferListAlias->mNumberBuffers; ++i) {
int8_t *buf = static_cast<int8_t *>(bufferListAlias->mBuffers[i].mData);
bufferListAlias->mBuffers[i].mData = static_cast<void *>(buf + (framesRead * mFormat.mBytesPerFrame));
bufferList->mBuffers[i].mDataByteSize += bufferListAlias->mBuffers[i].mDataByteSize;
bufferListAlias->mBuffers[i].mDataByteSize = initialBufferCapacityBytes - bufferList->mBuffers[i].mDataByteSize;
}
// Housekeeping
mFramesReadInCurrentPass += framesRead;
mTotalFramesRead += framesRead;
totalFramesRead += framesRead;
framesRemaining -= framesRead;
// If this pass is finished, seek to the beginning of the region in preparation for the next read
if(mFrameCount == mFramesReadInCurrentPass) {
++mCompletedPasses;
mFramesReadInCurrentPass = 0;
// Only seek to the beginning of the region if more passes remain
if(mRepeatCount >= mCompletedPasses)
mDecoder->SeekToFrame(mStartingFrame);
}
}
free(bufferListAlias), bufferListAlias = NULL;
return totalFramesRead;
}
|
/*
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Stephen F. Booth <[email protected]>
* 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 Stephen F. Booth 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 <algorithm>
#include <log4cxx/logger.h>
#include "LoopableRegionDecoder.h"
#include "AudioDecoder.h"
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(0), mRepeatCount(0), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
mFrameCount = static_cast<UInt32>(mDecoder->GetTotalFrames() - mStartingFrame);
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame, UInt32 frameCount)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(frameCount), mRepeatCount(0), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::LoopableRegionDecoder(AudioDecoder *decoder, SInt64 startingFrame, UInt32 frameCount, UInt32 repeatCount)
: mDecoder(decoder), mStartingFrame(startingFrame), mFrameCount(frameCount), mRepeatCount(repeatCount), mFramesReadInCurrentPass(0), mTotalFramesRead(0), mCompletedPasses(0)
{
assert(NULL != decoder);
assert(decoder->SupportsSeeking());
mInputSource = mDecoder->GetInputSource();
mFormat = mDecoder->GetFormat();
mChannelLayout = mDecoder->GetChannelLayout();
mSourceFormat = mDecoder->GetSourceFormat();
if(0 != mStartingFrame)
Reset();
}
LoopableRegionDecoder::~LoopableRegionDecoder()
{
// Just set our references to NULL, as mDecoder actually owns the objects and will delete them
mInputSource = NULL;
mChannelLayout = NULL;
if(mDecoder)
delete mDecoder, mDecoder = NULL;
}
void LoopableRegionDecoder::Reset()
{
mDecoder->SeekToFrame(mStartingFrame);
mFramesReadInCurrentPass = 0;
mTotalFramesRead = 0;
mCompletedPasses = 0;
}
#pragma mark Functionality
bool LoopableRegionDecoder::OpenFile(CFErrorRef *error)
{
if(!mDecoder->FileIsOpen())
return mDecoder->OpenFile(error);
return true;
}
bool LoopableRegionDecoder::CloseFile(CFErrorRef *error)
{
if(mDecoder->FileIsOpen())
return mDecoder->CloseFile(error);
return true;
}
SInt64 LoopableRegionDecoder::SeekToFrame(SInt64 frame)
{
assert(0 <= frame);
assert(frame < GetTotalFrames());
mCompletedPasses = static_cast<UInt32>(frame / mFrameCount);
mFramesReadInCurrentPass = static_cast<UInt32>(frame % mFrameCount);
mTotalFramesRead = frame;
mDecoder->SeekToFrame(mStartingFrame + mFramesReadInCurrentPass);
return GetCurrentFrame();
}
UInt32 LoopableRegionDecoder::ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
assert(NULL != bufferList);
assert(0 < frameCount);
// If the repeat count is N then (N + 1) passes must be completed to read all the frames
if((1 + mRepeatCount) == mCompletedPasses)
return 0;
// Allocate an alias to the buffer list, which will contain pointers to the current write position in the output buffer
AudioBufferList *bufferListAlias = static_cast<AudioBufferList *>(calloc(1, offsetof(AudioBufferList, mBuffers) + (sizeof(AudioBuffer) * bufferList->mNumberBuffers)));
if(NULL == bufferListAlias) {
log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger("org.sbooth.AudioEngine.AudioDecoder.LoopableRegion");
LOG4CXX_ERROR(logger, "Unable to allocate memory")
return 0;
}
UInt32 initialBufferCapacityBytes = bufferList->mBuffers[0].mDataByteSize;
bufferListAlias->mNumberBuffers = bufferList->mNumberBuffers;
// Initially the buffer list alias points to the beginning and contains no data
for(UInt32 i = 0; i < bufferListAlias->mNumberBuffers; ++i) {
bufferListAlias->mBuffers[i].mData = bufferList->mBuffers[i].mData;
bufferListAlias->mBuffers[i].mDataByteSize = bufferList->mBuffers[i].mDataByteSize;
bufferListAlias->mBuffers[i].mNumberChannels = bufferList->mBuffers[i].mNumberChannels;
bufferList->mBuffers[i].mDataByteSize = 0;
}
UInt32 framesRemaining = frameCount;
UInt32 totalFramesRead = 0;
while(0 < framesRemaining) {
UInt32 framesRemainingInCurrentPass = static_cast<UInt32>(mStartingFrame + mFrameCount - mDecoder->GetCurrentFrame());
UInt32 framesToRead = std::min(framesRemaining, framesRemainingInCurrentPass);
// Nothing left to read
if(0 == framesToRead)
break;
UInt32 framesRead = mDecoder->ReadAudio(bufferListAlias, framesToRead);
// A read error occurred
if(0 == framesRead)
break;
// Advance the write pointers and update the capacity
for(UInt32 i = 0; i < bufferListAlias->mNumberBuffers; ++i) {
int8_t *buf = static_cast<int8_t *>(bufferListAlias->mBuffers[i].mData);
bufferListAlias->mBuffers[i].mData = static_cast<void *>(buf + (framesRead * mFormat.mBytesPerFrame));
bufferList->mBuffers[i].mDataByteSize += bufferListAlias->mBuffers[i].mDataByteSize;
bufferListAlias->mBuffers[i].mDataByteSize = initialBufferCapacityBytes - bufferList->mBuffers[i].mDataByteSize;
}
// Housekeeping
mFramesReadInCurrentPass += framesRead;
mTotalFramesRead += framesRead;
totalFramesRead += framesRead;
framesRemaining -= framesRead;
// If this pass is finished, seek to the beginning of the region in preparation for the next read
if(mFrameCount == mFramesReadInCurrentPass) {
++mCompletedPasses;
mFramesReadInCurrentPass = 0;
// Only seek to the beginning of the region if more passes remain
if(mRepeatCount >= mCompletedPasses)
mDecoder->SeekToFrame(mStartingFrame);
}
}
free(bufferListAlias), bufferListAlias = NULL;
return totalFramesRead;
}
|
Handle decoders with interleaved data formats
|
Handle decoders with interleaved data formats
|
C++
|
mit
|
sbooth/SFBAudioEngine,sonoramac/SFBAudioEngine,eriser/SFBAudioEngine,sonoramac/SFBAudioEngine,sbooth/SFBAudioEngine,sbooth/SFBAudioEngine
|
ea510fb8e596e287116200553d058e41ce72c2ab
|
Firmware/MotorControl/trapTraj.cpp
|
Firmware/MotorControl/trapTraj.cpp
|
#include <math.h>
#include "odrive_main.h"
// Standard sign function, implemented to match the Python impelmentation
template <typename T>
int sign(T val) {
if (val == T(0))
return T(0);
else
return (std::signbit(val)) ? -1 : 1;
}
TrapezoidalTrajectory::TrapezoidalTrajectory(TrapTrajConfig_t &config) : config_(config) {}
float TrapezoidalTrajectory::planTrapezoidal(float Xf, float Xi,
float Vi, float Vmax,
float Amax, float Dmax) {
float dx_stop = (Vi * Vi) / (Dmax * 2.0f);
float dX = Xf - Xi;
int s = sign(dX);
float Ar = s * Amax; // Maximum Acceleration (signed)
float Dr = -1.0f * s * Dmax; // Maximum Deceleration (signed)
float Vr = s * Vmax; // Maximum Velocity (signed)
float Ta;
float Tv;
float Td;
// Checking for overshoot on "minimum stop"
if (fabs(dX) <= dx_stop) {
Ta = 0;
Tv = 0;
Vr = Vi;
Dr = -1.0f * sign(Vi) * Dmax;
Td = fabs(Vi) / Dmax;
} else {
// Handle the case where initial velocity > Max velocity
if ((s * Vi) > (s * Vr)) {
Ar = -1.0f * s * Amax;
}
Ta = (Vr - Vi) / Ar; // Acceleration time
Td = (-Vr) / Dr; // Deceleration time
// Peak Velocity handling
float dXmin = Ta * (Vr + Vi) / 2.0f + Td * Vr / 2.0f;
// Short move handling
if (fabs(dX) < fabs(dXmin)) {
Vr = s * sqrt((-((Vi * Vi) / Ar) - 2.0f * dX) / (1.0f / Dr - 1.0f / Ar));
Ta = std::max(0.0f, (Vr - Vi) / Ar);
Tv = 0;
Td = std::max(0.0f, -Vr / Dr);
} else {
Tv = (dX - dXmin) / Vr;
}
}
// Populate object's values
Xf_ = Xf;
Xi_ = Xi;
Vi_ = Vi;
Ar_ = Ar;
Dr_ = Dr;
Vr_ = Vr;
Ta_ = Ta;
Tv_ = Tv;
Td_ = Td;
yAccel_ = (Ar * Ta * Ta) / 2.0f + (Vi * Ta) + Xi;
Tav_ = Ta + Tv;
// If it's an overshoot trajectory, we need to re-do our process
// to generate the second-half of the trajectory
if (fabs(dX) <= dx_stop) {
TrapTrajStep_t traj;
traj = evalTrapTraj(Td_);
planTrapezoidal(Xf, traj.Y, traj.Yd, Vmax, Amax, Dmax);
// Fix initial points
Xi_ = Xi;
Vi_ = Vi;
// Fix time points
Ta_ += Td;
yAccel_ = (Ar_ * Ta_ * Ta_) / 2.0f + (Vi_ * Ta_) + Xi_;
Tav_ = Ta_ + Tv_;
}
return Ta_ + Tv_ + Td_;
}
TrapTrajStep_t TrapezoidalTrajectory::evalTrapTraj(float t) {
TrapTrajStep_t trajStep;
if (t < 0.0f) { // Initial Conditions
trajStep.Y = Xi_;
trajStep.Yd = Vi_;
trajStep.Ydd = Ar_;
} else if (t < Ta_) { // Accelerating
trajStep.Y = (Ar_ * (t * t) / 2.0f) + (Vi_ * t) + Xi_;
trajStep.Yd = (Ar_ * t) + Vi_;
trajStep.Ydd = Ar_;
} else if (t < Ta_ + Tv_) { // Coasting
trajStep.Y = yAccel_ + (Vr_ * (t - Ta_));
trajStep.Yd = Vr_;
trajStep.Ydd = 0;
} else if (t < Ta_ + Tv_ + Td_) { // Deceleration
float Tdc = t - Tav_;
trajStep.Y = yAccel_ + (Vr_ * (t - Ta_)) + Dr_ * (Tdc * Tdc) / 2.0f;
trajStep.Yd = Vr_ + Dr_ * Tdc;
trajStep.Ydd = Dr_;
}
return trajStep;
}
|
#include <math.h>
#include "odrive_main.h"
// Standard sign function, implemented to match the Python impelmentation
template <typename T>
int sign(T val) {
if (val == T(0))
return T(0);
else
return (std::signbit(val)) ? -1 : 1;
}
TrapezoidalTrajectory::TrapezoidalTrajectory(TrapTrajConfig_t &config) : config_(config) {}
float TrapezoidalTrajectory::planTrapezoidal(float Xf, float Xi,
float Vi, float Vmax,
float Amax, float Dmax) {
float dx_stop = (Vi * Vi) / (Dmax * 2.0f);
float dX = Xf - Xi;
int s = sign(dX);
float Ar = s * Amax; // Maximum Acceleration (signed)
float Dr = -1.0f * s * Dmax; // Maximum Deceleration (signed)
float Vr = s * Vmax; // Maximum Velocity (signed)
float Ta;
float Tv;
float Td;
// Checking for overshoot on "minimum stop"
if (fabs(dX) <= dx_stop) {
Ta = 0;
Tv = 0;
Vr = Vi;
Dr = -1.0f * sign(Vi) * Dmax;
Td = fabs(Vi) / Dmax;
} else {
// Handle the case where initial velocity > Max velocity
if ((s * Vi) > (s * Vr)) {
Ar = -1.0f * s * Amax;
}
Ta = (Vr - Vi) / Ar; // Acceleration time
Td = (-Vr) / Dr; // Deceleration time
// Peak Velocity handling
float dXmin = Ta * (Vr + Vi) / 2.0f + Td * Vr / 2.0f;
// Short move handling
if (fabs(dX) < fabs(dXmin)) {
Vr = s * sqrt((-((Vi * Vi) / Ar) - 2.0f * dX) / (1.0f / Dr - 1.0f / Ar));
Ta = std::max(0.0f, (Vr - Vi) / Ar);
Tv = 0;
Td = std::max(0.0f, -Vr / Dr);
} else {
Tv = (dX - dXmin) / Vr;
}
}
// Populate object's values
Xf_ = Xf;
Xi_ = Xi;
Vi_ = Vi;
Ar_ = Ar;
Dr_ = Dr;
Vr_ = Vr;
Ta_ = Ta;
Tv_ = Tv;
Td_ = Td;
yAccel_ = (Ar * Ta * Ta) / 2.0f + (Vi * Ta) + Xi;
Tav_ = Ta + Tv;
return Ta + Tv + Td;
}
TrapTrajStep_t TrapezoidalTrajectory::evalTrapTraj(float t) {
TrapTrajStep_t trajStep;
if (t < 0.0f) { // Initial Conditions
trajStep.Y = Xi_;
trajStep.Yd = Vi_;
trajStep.Ydd = Ar_;
} else if (t < Ta_) { // Accelerating
trajStep.Y = (Ar_ * (t * t) / 2.0f) + (Vi_ * t) + Xi_;
trajStep.Yd = (Ar_ * t) + Vi_;
trajStep.Ydd = Ar_;
} else if (t < Ta_ + Tv_) { // Coasting
trajStep.Y = yAccel_ + (Vr_ * (t - Ta_));
trajStep.Yd = Vr_;
trajStep.Ydd = 0;
} else if (t < Ta_ + Tv_ + Td_) { // Deceleration
float Tdc = t - Tav_;
trajStep.Y = yAccel_ + (Vr_ * (t - Ta_)) + Dr_ * (Tdc * Tdc) / 2.0f;
trajStep.Yd = Vr_ + Dr_ * Tdc;
trajStep.Ydd = Dr_;
}
return trajStep;
}
|
Revert "Support overshoot moves"
|
Revert "Support overshoot moves"
This reverts commit 0ea6a5a37bea707ef8e954b80f35176b5add3e4d.
|
C++
|
mit
|
madcowswe/ODriveFirmware,madcowswe/ODriveFirmware,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODriveFirmware,madcowswe/ODrive,madcowswe/ODrive,madcowswe/ODriveFirmware
|
55a9d0360e1730d756af997b74f7ede4c1c21c0e
|
core/src/wallet/ripple/explorers/api/RippleLikeTransactionParser.cpp
|
core/src/wallet/ripple/explorers/api/RippleLikeTransactionParser.cpp
|
/*
*
* RippleLikeTransactionParser
*
* Created by El Khalil Bellakrid on 07/01/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* 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 <wallet/currencies.hpp>
#include "RippleLikeTransactionParser.h"
#define PROXY_PARSE(method, ...) \
auto& currentObject = _hierarchy.top(); \
if (currentObject == "block") { \
return _blockParser.method(__VA_ARGS__); \
} else \
namespace ledger {
namespace core {
bool RippleLikeTransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(Key, str, length, copy) {
return true;
}
}
bool RippleLikeTransactionParser::StartObject() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
if (_lastKey == "Memo") {
// add a new empty RippleLikeMemo to the transaction (it’ll be filled in later by
// the parser)
_transaction->memos.push_back(api::RippleLikeMemo());
}
return true;
}
bool RippleLikeTransactionParser::EndObject(rapidjson::SizeType memberCount) {
auto ¤tObject = _hierarchy.top();
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool RippleLikeTransactionParser::StartArray() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
_arrayDepth += 1;
return true;
}
bool RippleLikeTransactionParser::EndArray(rapidjson::SizeType elementCount) {
_arrayDepth -= 1;
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool RippleLikeTransactionParser::Null() {
PROXY_PARSE(Null) {
return true;
}
}
bool RippleLikeTransactionParser::Bool(bool b) {
PROXY_PARSE(Bool, b) {
return true;
}
}
bool RippleLikeTransactionParser::Int(int i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Uint(unsigned i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Int64(int64_t i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Uint64(uint64_t i) {
PROXY_PARSE(Uint64, i) {
return true;
}
}
bool RippleLikeTransactionParser::Double(double d) {
PROXY_PARSE(Double, d) {
return true;
}
}
bool RippleLikeTransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length,
bool copy) {
PROXY_PARSE(RawNumber, str, length, copy) {
std::string number(str, length);
BigInt value = BigInt::fromString(number);
if (_lastKey == "confirmations") {
_transaction->confirmations = value.toUint64();
} else if (_lastKey == "ledger_index") {
RippleLikeBlockchainExplorer::Block block;
block.height = value.toUint64();
block.currencyName = currencies::RIPPLE.name;
_transaction->block = block;
} else if (_lastKey == "DestinationTag") {
_transaction->destinationTag = Option<uint64_t>(value.toUint64());
} else if (_lastKey == "date" && currentObject != "transaction") {
// we have to adapt the value of date because XRP is using their own epoch,
// which is 2000/01/01, which is 946684800 after the Unix epoch
std::chrono::system_clock::time_point date(std::chrono::seconds(value.toUint64() - 946684800));
_transaction->receivedAt = date;
if (_transaction->block.hasValue()) {
_transaction->block.getValue().time = date;
}
}
return true;
}
}
bool
RippleLikeTransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(String, str, length, copy) {
std::string value(str, length);
if (_lastKey == "hash") {
_transaction->hash = value;
} else if (_lastKey == "Account" && (currentObject == "tx" || currentObject == "transaction")){
_transaction->sender = value;
} else if (_lastKey == "Destination") {
_transaction->receiver = value;
} else if (_lastKey == "Amount") {
BigInt valueBigInt = BigInt::fromString(value);
_transaction->value = valueBigInt;
} else if (_lastKey == "Fee") {
BigInt valueBigInt = BigInt::fromString(value);
_transaction->fees = value;
} else if (_lastKey == "Sequence") {
_transaction->sequence = BigInt::fromString(value);
} else if (_lastKey == "MemoData" && !_transaction->memos.empty()) {
_transaction->memos.back().data = value;
} else if (_lastKey == "MemoFormat" && !_transaction->memos.empty()) {
_transaction->memos.back().fmt = value;
} else if (_lastKey == "MemoType" && !_transaction->memos.empty()) {
_transaction->memos.back().ty = value;
}
return true;
}
}
RippleLikeTransactionParser::RippleLikeTransactionParser(std::string &lastKey) :
_lastKey(lastKey), _blockParser(lastKey) {
_arrayDepth = 0;
}
void RippleLikeTransactionParser::init(RippleLikeBlockchainExplorerTransaction *transaction) {
_transaction = transaction;
}
}
}
|
/*
*
* RippleLikeTransactionParser
*
* Created by El Khalil Bellakrid on 07/01/2019.
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ledger
*
* 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 <wallet/currencies.hpp>
#include "RippleLikeTransactionParser.h"
#define PROXY_PARSE(method, ...) \
auto& currentObject = _hierarchy.top(); \
if (currentObject == "block") { \
return _blockParser.method(__VA_ARGS__); \
} else \
namespace ledger {
namespace core {
const uint64_t XRP_EPOCH_SECONDS_FROM_UNIX_EPOCH = 946684800;
bool RippleLikeTransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(Key, str, length, copy) {
return true;
}
}
bool RippleLikeTransactionParser::StartObject() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
if (_lastKey == "Memo") {
// add a new empty RippleLikeMemo to the transaction (it’ll be filled in later by
// the parser)
_transaction->memos.push_back(api::RippleLikeMemo());
}
return true;
}
bool RippleLikeTransactionParser::EndObject(rapidjson::SizeType memberCount) {
auto ¤tObject = _hierarchy.top();
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool RippleLikeTransactionParser::StartArray() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
_arrayDepth += 1;
return true;
}
bool RippleLikeTransactionParser::EndArray(rapidjson::SizeType elementCount) {
_arrayDepth -= 1;
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool RippleLikeTransactionParser::Null() {
PROXY_PARSE(Null) {
return true;
}
}
bool RippleLikeTransactionParser::Bool(bool b) {
PROXY_PARSE(Bool, b) {
return true;
}
}
bool RippleLikeTransactionParser::Int(int i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Uint(unsigned i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Int64(int64_t i) {
return Uint64(i);
}
bool RippleLikeTransactionParser::Uint64(uint64_t i) {
PROXY_PARSE(Uint64, i) {
return true;
}
}
bool RippleLikeTransactionParser::Double(double d) {
PROXY_PARSE(Double, d) {
return true;
}
}
bool RippleLikeTransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length,
bool copy) {
PROXY_PARSE(RawNumber, str, length, copy) {
std::string number(str, length);
BigInt value = BigInt::fromString(number);
if (_lastKey == "confirmations") {
_transaction->confirmations = value.toUint64();
} else if (_lastKey == "ledger_index") {
RippleLikeBlockchainExplorer::Block block;
block.height = value.toUint64();
block.currencyName = currencies::RIPPLE.name;
_transaction->block = block;
} else if (_lastKey == "DestinationTag") {
_transaction->destinationTag = Option<uint64_t>(value.toUint64());
} else if (_lastKey == "date" && currentObject != "transaction") {
// we have to adapt the value of date because XRP is using their own epoch,
// which is 2000/01/01, which is 946684800 after the Unix epoch
//
// <https://xrpl.org/basic-data-types.html#specifying-time>
std::chrono::system_clock::time_point date(std::chrono::seconds(value.toUint64() - XRP_EPOCH_SECONDS_FROM_UNIX_EPOCH));
_transaction->receivedAt = date;
if (_transaction->block.hasValue()) {
_transaction->block.getValue().time = date;
}
}
return true;
}
}
bool
RippleLikeTransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(String, str, length, copy) {
std::string value(str, length);
if (_lastKey == "hash") {
_transaction->hash = value;
} else if (_lastKey == "Account" && (currentObject == "tx" || currentObject == "transaction")){
_transaction->sender = value;
} else if (_lastKey == "Destination") {
_transaction->receiver = value;
} else if (_lastKey == "Amount") {
BigInt valueBigInt = BigInt::fromString(value);
_transaction->value = valueBigInt;
} else if (_lastKey == "Fee") {
BigInt valueBigInt = BigInt::fromString(value);
_transaction->fees = value;
} else if (_lastKey == "Sequence") {
_transaction->sequence = BigInt::fromString(value);
} else if (_lastKey == "MemoData" && !_transaction->memos.empty()) {
_transaction->memos.back().data = value;
} else if (_lastKey == "MemoFormat" && !_transaction->memos.empty()) {
_transaction->memos.back().fmt = value;
} else if (_lastKey == "MemoType" && !_transaction->memos.empty()) {
_transaction->memos.back().ty = value;
}
return true;
}
}
RippleLikeTransactionParser::RippleLikeTransactionParser(std::string &lastKey) :
_lastKey(lastKey), _blockParser(lastKey) {
_arrayDepth = 0;
}
void RippleLikeTransactionParser::init(RippleLikeBlockchainExplorerTransaction *transaction) {
_transaction = transaction;
}
}
}
|
Add documentation about XRP epoch and make it a constant.
|
Add documentation about XRP epoch and make it a constant.
|
C++
|
mit
|
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
|
80200ee1435b0ad69c041f7f43feb82a1fce98cd
|
service/resource-manipulation/modules/serverBuilder/unittests/RequestHandlerTest.cpp
|
service/resource-manipulation/modules/serverBuilder/unittests/RequestHandlerTest.cpp
|
//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <gtest/gtest.h>
#include <HippoMocks/hippomocks.h>
#include <internal/RequestHandler.h>
#include <OCPlatform.h>
using namespace std;
using namespace testing;
using namespace OIC::Service;
constexpr char EXISTING[]{ "ext" };
constexpr int ORIGIN_VALUE{ 100 };
constexpr int NEW_VALUE{ 1 };
using RegisterResource = OCStackResult (*)(OCResourceHandle&, std::string&,
const std::string&, const std::string&, OC::EntityHandler, uint8_t);
class RequestHandlerTest: public Test
{
public:
ResourceObject::Ptr server;
MockRepository mocks;
protected:
void SetUp() override
{
mocks.OnCallFuncOverload(static_cast<RegisterResource>(OC::OCPlatform::registerResource))
.Return(OC_STACK_OK);
mocks.OnCallFunc(OC::OCPlatform::unregisterResource).Return(OC_STACK_OK);
server = ResourceObject::Builder("a/test", "resourceType", "").build();
server->setAttribute(EXISTING, ORIGIN_VALUE);
}
};
TEST_F(RequestHandlerTest, ResponseHasSameValuesPassedToHandlerConstructor)
{
RequestHandler handler{ OC_EH_ERROR, -1000 };
auto response = handler.buildResponse(*server);
ASSERT_EQ(OC_EH_ERROR, response->getResponseResult());
ASSERT_EQ(-1000, response->getErrorCode());
}
TEST_F(RequestHandlerTest, ResponseHasSameAttrsWithServerAttrs)
{
RequestHandler handler{};
auto response = handler.buildResponse(*server);
ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[EXISTING].getValue<int>());
}
TEST_F(RequestHandlerTest, ResponseHasAttrsSetByCustomAttrRequestHandler)
{
constexpr char key[] { "key" };
constexpr int newValue{ 100 };
ResourceAttributes attrs;
attrs[key] = newValue;
RequestHandler handler{ attrs };
auto response = handler.buildResponse(*server);
ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[key].getValue<int>());
}
class SetRequestHandlerAcceptanceTest: public RequestHandlerTest
{
public:
SetRequestHandler::Ptr setRequestHandler;
ResourceAttributes requestAttrs;
protected:
void SetUp() override
{
RequestHandlerTest::SetUp();
setRequestHandler = make_shared< SetRequestHandler >();
requestAttrs[EXISTING] = NEW_VALUE;
}
};
TEST_F(SetRequestHandlerAcceptanceTest, NothingReplacedWithIgnoreMethod)
{
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::IGNORE, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
TEST_F(SetRequestHandlerAcceptanceTest, NewValueApplyedWithAcceptMethod)
{
setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_EQ(NEW_VALUE, server->getAttribute<int>(EXISTING));
}
TEST_F(SetRequestHandlerAcceptanceTest, ReturnedAttrPairsHaveOldValue)
{
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_EQ(ORIGIN_VALUE, replaced[0].second);
}
TEST_F(SetRequestHandlerAcceptanceTest, NothingHappenedWithEmptyAttrs)
{
setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, ResourceAttributes{ });
ASSERT_EQ(ORIGIN_VALUE, server->getAttribute<int>(EXISTING));
}
TEST_F(SetRequestHandlerAcceptanceTest, NothingReplacedIfTypeMismatch)
{
requestAttrs[EXISTING] = "";
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
TEST_F(SetRequestHandlerAcceptanceTest, NothingReplacedIfRequestAttrsHasUnknownKey)
{
constexpr char unknownKey[]{ "???" };
requestAttrs[EXISTING] = ORIGIN_VALUE;
requestAttrs[unknownKey] = ORIGIN_VALUE;
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
|
//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <gtest/gtest.h>
#include <HippoMocks/hippomocks.h>
#include <internal/RequestHandler.h>
#include <OCPlatform.h>
using namespace std;
using namespace testing;
using namespace OIC::Service;
constexpr char EXISTING[]{ "ext" };
constexpr int ORIGIN_VALUE{ 100 };
constexpr int NEW_VALUE{ 1 };
using RegisterResource = OCStackResult (*)(OCResourceHandle&, std::string&,
const std::string&, const std::string&, OC::EntityHandler, uint8_t);
class RequestHandlerTest: public Test
{
public:
ResourceObject::Ptr server;
MockRepository mocks;
protected:
void SetUp() override
{
mocks.OnCallFuncOverload(static_cast<RegisterResource>(OC::OCPlatform::registerResource))
.Return(OC_STACK_OK);
mocks.OnCallFunc(OC::OCPlatform::unregisterResource).Return(OC_STACK_OK);
server = ResourceObject::Builder("a/test", "resourceType", "").build();
server->setAttribute(EXISTING, ORIGIN_VALUE);
}
};
TEST_F(RequestHandlerTest, ResponseHasSameValuesPassedToHandlerConstructor)
{
RequestHandler handler{ OC_EH_ERROR, -1000 };
auto response = handler.buildResponse(*server);
ASSERT_EQ(OC_EH_ERROR, response->getResponseResult());
ASSERT_EQ(-1000, response->getErrorCode());
}
TEST_F(RequestHandlerTest, ResponseHasSameAttrsWithServerAttrs)
{
RequestHandler handler{};
auto response = handler.buildResponse(*server);
ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[EXISTING].getValue<int>());
}
TEST_F(RequestHandlerTest, ResponseHasAttrsSetByCustomAttrRequestHandler)
{
constexpr char key[] { "key" };
constexpr int newValue{ 100 };
ResourceAttributes attrs;
attrs[key] = newValue;
RequestHandler handler{ attrs };
auto response = handler.buildResponse(*server);
ASSERT_EQ(ORIGIN_VALUE, response->getResourceRepresentation()[key].getValue<int>());
}
class SetRequestHandlerAcceptanceTest: public RequestHandlerTest
{
public:
SetRequestHandler::Ptr setRequestHandler;
ResourceAttributes requestAttrs;
protected:
void SetUp() override
{
RequestHandlerTest::SetUp();
setRequestHandler = make_shared< SetRequestHandler >();
requestAttrs[EXISTING] = NEW_VALUE;
}
};
TEST_F(SetRequestHandlerAcceptanceTest, NothingReplacedWithIgnoreMethod)
{
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::IGNORE, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
TEST_F(SetRequestHandlerAcceptanceTest, NewValueApplyedWithAcceptMethod)
{
setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_EQ(NEW_VALUE, server->getAttribute<int>(EXISTING));
}
TEST_F(SetRequestHandlerAcceptanceTest, ReturnedAttrPairsHaveOldValue)
{
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_EQ(ORIGIN_VALUE, replaced[0].second);
}
TEST_F(SetRequestHandlerAcceptanceTest, NothingHappenedWithEmptyAttrs)
{
setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, ResourceAttributes{ });
ASSERT_EQ(ORIGIN_VALUE, server->getAttribute<int>(EXISTING));
}
TEST_F(SetRequestHandlerAcceptanceTest, EverythingAppliedIfMethodIsAccept)
{
requestAttrs[EXISTING] = "";
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::ACCEPT, *server, requestAttrs);
ASSERT_EQ(ORIGIN_VALUE, replaced[0].second);
}
TEST_F(SetRequestHandlerAcceptanceTest, NoReplaceIfMethodIsDefaultAndTypeMismatch)
{
requestAttrs[EXISTING] = "";
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::DEFAULT, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
TEST_F(SetRequestHandlerAcceptanceTest, NoReplacefMethodIsDefaultAndRequestAttrsHasUnknownKey)
{
constexpr char unknownKey[]{ "???" };
requestAttrs[EXISTING] = ORIGIN_VALUE;
requestAttrs[unknownKey] = ORIGIN_VALUE;
auto replaced = setRequestHandler->applyAcceptanceMethod(
PrimitiveSetResponse::AcceptanceMethod::DEFAULT, *server, requestAttrs);
ASSERT_TRUE(replaced.empty());
}
|
Fix wrong unittests in RequestHandlerTest
|
Fix wrong unittests in RequestHandlerTest
The tests regarding AcceptanceMethod
Change-Id: Iaa18464b9059887c4ab229e8a5f2ca44bdad221f
Signed-off-by: coderhyme <[email protected]>
Reviewed-on: https://gerrit.iotivity.org/gerrit/1549
Tested-by: jenkins-iotivity <[email protected]>
Reviewed-by: Uze Choi <[email protected]>
|
C++
|
apache-2.0
|
rzr/iotivity,WojciechLuczkow/iotivity,rzr/iotivity,santais/iotivity,iotivity/iotivity,santais/iotivity_1.1,rzr/iotivity,WojciechLuczkow/iotivity,WojciechLuczkow/iotivity,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,tienfuc/iotivity-democlient-snap,iotivity/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity,santais/iotivity,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1.0,rzr/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity,iotivity/iotivity,santais/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1,tienfuc/iotivity-democlient-snap,WojciechLuczkow/iotivity,iotivity/iotivity,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1.0,santais/iotivity_1.1,santais/iotivity,tienfuc/iotivity-democlient-snap,iotivity/iotivity,iotivity/iotivity,rzr/iotivity,santais/iotivity_1.1.0,santais/iotivity_1.1,WojciechLuczkow/iotivity,santais/iotivity_1.1.0,tienfuc/iotivity-democlient-snap,santais/iotivity_1.1,WojciechLuczkow/iotivity,WojciechLuczkow/iotivity,santais/iotivity_1.1.0,santais/iotivity_1.1,WojciechLuczkow/iotivity,rzr/iotivity,santais/iotivity_1.1.0,rzr/iotivity,santais/iotivity_1.1.0,iotivity/iotivity,iotivity/iotivity,santais/iotivity
|
134e3e14330597513294e99bbb33f5b4f6362cdf
|
notification/src/objects/command.cc
|
notification/src/objects/command.cc
|
/*
** Copyright 2011-2013 Centreon
**
** 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.
**
** For more information : [email protected]
*/
#include "com/centreon/broker/notification/utilities/qhash_func.hh"
#include <QRegExp>
#include <QStringList>
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/misc/string.hh"
#include "com/centreon/broker/notification/objects/command.hh"
#include "com/centreon/broker/notification/state.hh"
#include "com/centreon/broker/notification/macro_generator.hh"
using namespace com::centreon::broker::notification;
using namespace com::centreon::broker::notification::objects;
const QRegExp command::_macro_regex("\\$(\\w+)\\$");
// Forward declaration.
static void single_pass_replace(
std::string &str,
macro_generator::macro_container const& macros);
/**
* Constructor from a base command string.
*
* @param[in] base_command The command from which to construct this object.
*/
command::command(std::string const& base_command) :
_enable_shell(true), _base_command(base_command) {}
/**
* Copy constructor.
*
* @param[in] obj The object to copy.
*/
command::command(command const& obj) {
command::operator=(obj);
}
/**
* Assignment operator.
*
* @param[in] obj The object to copy.
*
* @return A reference to this object.
*/
command& command::operator=(command const& obj) {
if (this != &obj) {
_enable_shell = obj._enable_shell;
_name = obj._name;
_base_command = obj._base_command;
}
return (*this);
}
/**
* Get the enable shell flag.
*
* @return True if we enable
*/
bool command::get_enable_shell() const throw() {
return (_enable_shell);
}
/**
* Set the enable shell flag.
*
* @param[in] val The new value of the enable shell flag.
*/
void command::set_enable_shell(bool val) {
_enable_shell = val;
}
/**
* Get the name of this command.
*
* @return The name of this command.
*/
std::string const& command::get_name() const throw() {
return (_name);
}
/**
* Set the name of this command.
*
* @param[in] name The new name of this command.
*/
void command::set_name(std::string const& name) {
_name = name;
}
/**
* Resolve this command.
*
* @return A string containing the resolved command.
*/
std::string command::resolve(
contact::ptr const& cnt,
node::ptr const& n,
node_cache const& cache,
state const& st,
action const& act) {
// Match all the macros with the wonderful magic of RegExp.
QString base_command = QString::fromStdString(_base_command);
macro_generator::macro_container macros;
int index = 0;
while ((index = _macro_regex.indexIn(base_command, index)) != -1) {
macros.insert(_macro_regex.cap(1).toStdString(), "");
index += _macro_regex.matchedLength();
}
if (macros.empty())
return (_base_command);
logging::debug(logging::medium)
<< "notification: found " << macros.size() << " macros";
// Generate each macro.
try {
macro_generator generator;
generator.generate(macros, n->get_node_id(), *cnt, st, cache, act);
}
catch (std::exception const& e) {
logging::error(logging::medium)
<< "notification: could not resolve some macro in command '"
<< _name << "': " << e.what();
}
// Replace the macros by their values.
std::string resolved_command = _base_command;
single_pass_replace(resolved_command, macros);
// If it needs to be launched into a shell, wrap it into a shell command.
// The command is correctly escaped in single quotes
// (no secure function doing that in our libraries, unfortunately).
// XXX: do the same for windows.
if (_enable_shell) {
misc::string::replace(resolved_command, "'", "'\\''");
resolved_command.insert(0, "sh -c '");
resolved_command.append("'");
}
return (resolved_command);
}
/**
* @brief Replace all the macros of the string in a single pass.
*
* Marginally faster, and don't mangle contents and values.
*
* @param[in] str The string.
* @param[in] macros The macros to replace.
*/
static void single_pass_replace(
std::string& str,
macro_generator::macro_container const& macros) {
std::vector<std::pair<std::string, std::string> > macro_list;
for (macro_generator::macro_container::iterator it(macros.begin()),
end(macros.end());
it != end;
++it) {
std::string key("$");
key.append(it.key());
key.append("$");
macro_list.push_back(std::make_pair(key, *it));
}
for (std::vector<std::pair<std::string, std::string> >::const_iterator
it(macro_list.begin()),
end(macro_list.end());
it != end;
++it) {
size_t tmp(0);
while ((tmp = str.find(it->first, tmp)) != std::string::npos) {
str.replace(tmp, it->first.size(), it->second);
tmp += it->second.size();
}
}
}
|
/*
** Copyright 2011-2013 Centreon
**
** 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.
**
** For more information : [email protected]
*/
#include "com/centreon/broker/notification/utilities/qhash_func.hh"
#include <QRegExp>
#include <QStringList>
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/misc/string.hh"
#include "com/centreon/broker/notification/objects/command.hh"
#include "com/centreon/broker/notification/state.hh"
#include "com/centreon/broker/notification/macro_generator.hh"
using namespace com::centreon::broker::notification;
using namespace com::centreon::broker::notification::objects;
const QRegExp command::_macro_regex("\\$(\\w+)\\$");
// Forward declaration.
static void single_pass_replace(
std::string &str,
macro_generator::macro_container const& macros);
/**
* Constructor from a base command string.
*
* @param[in] base_command The command from which to construct this object.
*/
command::command(std::string const& base_command) :
_enable_shell(true), _base_command(base_command) {}
/**
* Copy constructor.
*
* @param[in] obj The object to copy.
*/
command::command(command const& obj) {
command::operator=(obj);
}
/**
* Assignment operator.
*
* @param[in] obj The object to copy.
*
* @return A reference to this object.
*/
command& command::operator=(command const& obj) {
if (this != &obj) {
_enable_shell = obj._enable_shell;
_name = obj._name;
_base_command = obj._base_command;
}
return (*this);
}
/**
* Get the enable shell flag.
*
* @return True if we enable
*/
bool command::get_enable_shell() const throw() {
return (_enable_shell);
}
/**
* Set the enable shell flag.
*
* @param[in] val The new value of the enable shell flag.
*/
void command::set_enable_shell(bool val) {
_enable_shell = val;
}
/**
* Get the name of this command.
*
* @return The name of this command.
*/
std::string const& command::get_name() const throw() {
return (_name);
}
/**
* Set the name of this command.
*
* @param[in] name The new name of this command.
*/
void command::set_name(std::string const& name) {
_name = name;
}
/**
* Resolve this command.
*
* @return A string containing the resolved command.
*/
std::string command::resolve(
contact::ptr const& cnt,
node::ptr const& n,
node_cache const& cache,
state const& st,
action const& act) {
// Match all the macros with the wonderful magic of RegExp.
QString base_command = QString::fromStdString(_base_command);
macro_generator::macro_container macros;
int index = 0;
while ((index = _macro_regex.indexIn(base_command, index)) != -1) {
macros.insert(_macro_regex.cap(1).toStdString(), "");
index += _macro_regex.matchedLength();
}
if (macros.empty())
return (_base_command);
logging::debug(logging::medium)
<< "notification: found " << macros.size() << " macros";
// Generate each macro.
try {
macro_generator generator;
generator.generate(macros, n->get_node_id(), *cnt, st, cache, act);
}
catch (std::exception const& e) {
logging::error(logging::medium)
<< "notification: could not resolve some macro in command '"
<< _name << "': " << e.what();
}
// Replace the macros by their values.
std::string resolved_command = _base_command;
single_pass_replace(resolved_command, macros);
// If it needs to be launched into a shell, wrap it into a shell command.
// The command is correctly escaped in single quotes
// (no secure function doing that in our libraries, unfortunately).
// XXX: do the same for windows.
if (_enable_shell) {
misc::string::replace(resolved_command, "'", "'\''");
resolved_command.insert(0, "sh -c '");
resolved_command.append("'");
}
return (resolved_command);
}
/**
* @brief Replace all the macros of the string in a single pass.
*
* Marginally faster, and don't mangle contents and values.
*
* @param[in] str The string.
* @param[in] macros The macros to replace.
*/
static void single_pass_replace(
std::string& str,
macro_generator::macro_container const& macros) {
std::vector<std::pair<std::string, std::string> > macro_list;
for (macro_generator::macro_container::iterator it(macros.begin()),
end(macros.end());
it != end;
++it) {
std::string key("$");
key.append(it.key());
key.append("$");
macro_list.push_back(std::make_pair(key, *it));
}
for (std::vector<std::pair<std::string, std::string> >::const_iterator
it(macro_list.begin()),
end(macro_list.end());
it != end;
++it) {
size_t tmp(0);
while ((tmp = str.find(it->first, tmp)) != std::string::npos) {
str.replace(tmp, it->first.size(), it->second);
tmp += it->second.size();
}
}
}
|
fix the shell escaping (will need to be careful for this, it can be a security break).
|
Notification: fix the shell escaping (will need to be careful for this, it can be a security break).
|
C++
|
apache-2.0
|
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker
|
dab5892dbdb5e6a44fef38b05628c7f5cae1f7b0
|
b.cpp
|
b.cpp
|
#include <maint>
|
#include <maint>
using namespace
|
test push conflict
|
test push conflict
|
C++
|
apache-2.0
|
Da-Huang/Git-Test,Da-Huang/Git-Test
|
aaf33cc39c5d721873097e43142b0650ca3ce1d5
|
example/server/chat/src/main.cc
|
example/server/chat/src/main.cc
|
// belle chat example
#include "belle.hh"
namespace Belle = OB::Belle;
#include <ctime>
#include <string>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <optional>
#include <deque>
using namespace std::string_literals;
// basic ring buffer
template<class T>
class Ringbuf
{
public:
Ringbuf(size_t size = 64):
_size {size}
{
}
~Ringbuf()
{
}
Ringbuf& push(T const& t)
{
_que.emplace_back(t);
if (_que.size() > _size)
{
_que.pop_front();
}
return *this;
}
Ringbuf& shrink_to_fit()
{
while (_que.size() > _size)
{
_que.pop_front();
}
return *this;
}
std::deque<T> const& get() const
{
return _que;
}
size_t max_size() const
{
return _size;
}
Ringbuf max_size(size_t size)
{
_size = size;
if (_que.size() > _size)
{
shrink_to_fit();
}
return *this;
}
Ringbuf& clear()
{
_que.clear();
return *this;
}
size_t size() const
{
return _que.size();
}
bool empty() const
{
return _que.empty();
}
T& operator[](size_t n)
{
return _que.at(n);
}
T const& operator[](size_t n) const
{
return _que.at(n);
}
T& at(size_t n)
{
return _que.at(n);
}
T const& at(size_t n) const
{
return _que.at(n);
}
private:
size_t _size;
std::deque<T> _que;
}; // class Ringbuf
// convert object into a string
template<class T>
std::string to_string(T t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
// read a file into a string
std::optional<std::string> file(std::string const& str);
std::optional<std::string> file(std::string const& str)
{
std::ifstream file {str};
if (! file.is_open())
{
return {};
}
file.seekg(0, std::ios::end);
size_t size (static_cast<size_t>(file.tellg()));
std::string content (size, ' ');
file.seekg(0);
file.read(&content[0], static_cast<std::streamsize>(size));
return content;
}
int main(int argc, char *argv[])
{
// init the server
Belle::Server app;
// set the listening address
std::string address {"127.0.0.1"};
app.address(address);
// set the listening port
int port {8080};
app.port(port);
// enable serving static files from a public directory
// if the path is relative, make sure to run the program
// in the right working directory
app.public_dir("../public");
// serve static content from public dir
// default value is true
app.http_static(true);
// serve dynamic content
// default value is true
app.http_dynamic(true);
// accept websocket upgrade requests
// default value is true
app.websocket(true);
// set default http headers
Belle::Headers headers;
headers.set(Belle::Header::server, "Belle");
headers.set(Belle::Header::cache_control, "private; max-age=0");
app.http_headers(headers);
// handle the following signals
app.signals({SIGINT, SIGTERM});
// set the on signal callback
app.on_signal([&](auto ec, auto sig)
{
// print out the signal received
std::cerr << "\nSignal " << sig << "\n";
// get the io_context and safely stop the server
app.io().stop();
});
// store received messages
std::unordered_map<std::string, Ringbuf<std::string>> chat;
// total number of connected users
int user_count {0};
// add default chat room channels
app.channels()["/"] = Belle::Server::Channel();
app.channels()["/new"] = Belle::Server::Channel();
// add default messages to the '/new' chat room
chat["/new"].push("'/' shows an overview of the rooms");
chat["/new"].push("'/<room_name>' go to an existing room or create a new one");
chat["/new"].push("Try creating a new room called '/dev'");
chat["/new"].push("The index page, '/', will now show 3 rooms");
chat["/new"].push("The most popular room gets moved to the top of the index, try playing around with several tabs open");
chat["/new"].push("The newest comments appear at the top of the page");
// handle ws connections to index room '/'
app.on_websocket("/",
// on data: called after every websocket read
[](Belle::Server::Websocket_Ctx& ctx)
{
// register the route
// data will be broadcasted in the websocket connect and disconnect handlers
});
// handle ws connections to chat rooms '/<chat_room>'
app.on_websocket("^(/[a-z]+)$",
// on begin: called once after connected
[&](Belle::Server::Websocket_Ctx& ctx)
{
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// broadcast the total number of connected users to the channel
ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));
// check if there is any messages stored
if (chat.find(channel) != chat.end())
{
// send out all previous messages to new user
for (auto const& e : chat[channel].get())
{
ctx.send("0" + e);
}
}
// send welcome message
ctx.send("0"s + "> welcome to "s + channel);
},
// on data: called after every websocket read
[&](Belle::Server::Websocket_Ctx& ctx)
{
// a simple protocol:
// in the received message,
// the first character holds an int from 0-9,
// the remaining characters are the message
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// get the message type
int type {std::stoi(to_string(ctx.msg.at(0)))};
// determine action
switch (type)
{
case 0:
chat[channel].push(ctx.msg.substr(1));
ctx.channels.at(channel).broadcast("0" + ctx.msg.substr(1));
break;
default:
break;
}
},
// on end: called once after disconnected
[](Belle::Server::Websocket_Ctx& ctx)
{
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// a user has disconnected
// broadcast the total number of connected users to the channel
ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));
}
);
// set websocket connect callback
// called once at the very beginning after connected
app.on_websocket_connect([&](Belle::Server::Websocket_Ctx& ctx)
{
// increase total user count
++user_count;
// send room count
ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
// send user count
ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
for (auto const& e : ctx.channels)
{
// send count and room info
ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
}
});
// set websocket disconnect callback
// called once at the very end after disconnected
app.on_websocket_disconnect([&](Belle::Server::Websocket_Ctx& ctx)
{
// decrease total user count
--user_count;
// send room count
ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
// send user count
ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
for (auto const& e : ctx.channels)
{
// send count and room info
ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
}
});
// handle route GET '/'
// with no set dynamic route for a route ending in a '/' character,
// the default action is to look for a static file named 'index.html'
// in the corresponding public directory
// handle route GET '/<chat_room>'
app.on_http("^(/[a-z]+)$", Belle::Method::get, [&](Belle::Server::Http_Ctx& ctx)
{
// set http response headers
ctx.res.set("content-type", "text/html");
// send the file contents
if (auto res = file(app.public_dir() + "/chat.html"))
{
ctx.res.body() = std::move(res.value());
}
else
{
throw 404;
}
});
// set custom error callback
app.on_http_error([](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
std::stringstream res; res
<< "Status: " << ctx.res.result_int() << "\n"
<< "Reason: " << ctx.res.result() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// echo the http status code
ctx.res.body() = res.str();
});
// print out the address and port
std::cout
<< "Server: " << address << ":" << port << "\n\n"
<< "Navigate to the following url:\n"
<< " http://" << address << ":" << port << "/new\n\n";
// start the server
app.listen();
// the server blocks until a signal is received
return 0;
}
|
// belle chat example
#include "belle.hh"
namespace Belle = OB::Belle;
#include <ctime>
#include <string>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <optional>
#include <deque>
using namespace std::string_literals;
// basic ring buffer
template<class T>
class Ringbuf
{
public:
Ringbuf(size_t size = 64):
_size {size}
{
}
~Ringbuf()
{
}
Ringbuf& push(T const& t)
{
_que.emplace_back(t);
if (_que.size() > _size)
{
_que.pop_front();
}
return *this;
}
Ringbuf& shrink_to_fit()
{
while (_que.size() > _size)
{
_que.pop_front();
}
return *this;
}
std::deque<T> const& get() const
{
return _que;
}
size_t max_size() const
{
return _size;
}
Ringbuf max_size(size_t size)
{
_size = size;
if (_que.size() > _size)
{
shrink_to_fit();
}
return *this;
}
Ringbuf& clear()
{
_que.clear();
return *this;
}
size_t size() const
{
return _que.size();
}
bool empty() const
{
return _que.empty();
}
T& operator[](size_t n)
{
return _que.at(n);
}
T const& operator[](size_t n) const
{
return _que.at(n);
}
T& at(size_t n)
{
return _que.at(n);
}
T const& at(size_t n) const
{
return _que.at(n);
}
private:
size_t _size;
std::deque<T> _que;
}; // class Ringbuf
// convert object into a string
template<class T>
std::string to_string(T t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
// read a file into a string
std::optional<std::string> file(std::string const& str);
std::optional<std::string> file(std::string const& str)
{
std::ifstream file {str};
if (! file.is_open())
{
return {};
}
file.seekg(0, std::ios::end);
size_t size (static_cast<size_t>(file.tellg()));
std::string content (size, ' ');
file.seekg(0);
file.read(&content[0], static_cast<std::streamsize>(size));
return content;
}
int main(int argc, char *argv[])
{
// init the server
Belle::Server app;
// set the listening address
std::string address {"127.0.0.1"};
app.address(address);
// set the listening port
int port {8080};
app.port(port);
// warn if address:port is already in use
if (! app.available())
{
std::cerr << "Warning: '" << address << ":" << port << "' is in use\n";
}
// enable serving static files from a public directory
// if the path is relative, make sure to run the program
// in the right working directory
app.public_dir("../public");
// serve static content from public dir
// default value is true
app.http_static(true);
// serve dynamic content
// default value is true
app.http_dynamic(true);
// accept websocket upgrade requests
// default value is true
app.websocket(true);
// set default http headers
Belle::Headers headers;
headers.set(Belle::Header::server, "Belle");
headers.set(Belle::Header::cache_control, "private; max-age=0");
app.http_headers(headers);
// handle the following signals
app.signals({SIGINT, SIGTERM});
// set the on signal callback
app.on_signal([&](auto ec, auto sig)
{
// print out the signal received
std::cerr << "\nSignal " << sig << "\n";
// get the io_context and safely stop the server
app.io().stop();
});
// store received messages
std::unordered_map<std::string, Ringbuf<std::string>> chat;
// total number of connected users
int user_count {0};
// add default chat room channels
app.channels()["/"] = Belle::Server::Channel();
app.channels()["/new"] = Belle::Server::Channel();
// add default messages to the '/new' chat room
chat["/new"].push("'/' shows an overview of the rooms");
chat["/new"].push("'/<room_name>' go to an existing room or create a new one");
chat["/new"].push("Try creating a new room called '/dev'");
chat["/new"].push("The index page, '/', will now show 3 rooms");
chat["/new"].push("The most popular room gets moved to the top of the index, try playing around with several tabs open");
chat["/new"].push("The newest comments appear at the top of the page");
// handle ws connections to index room '/'
app.on_websocket("/",
// on data: called after every websocket read
[](Belle::Server::Websocket_Ctx& ctx)
{
// register the route
// data will be broadcasted in the websocket connect and disconnect handlers
});
// handle ws connections to chat rooms '/<chat_room>'
app.on_websocket("^(/[a-z]+)$",
// on begin: called once after connected
[&](Belle::Server::Websocket_Ctx& ctx)
{
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// broadcast the total number of connected users to the channel
ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));
// check if there is any messages stored
if (chat.find(channel) != chat.end())
{
// send out all previous messages to new user
for (auto const& e : chat[channel].get())
{
ctx.send("0" + e);
}
}
// send welcome message
ctx.send("0"s + "> welcome to "s + channel);
},
// on data: called after every websocket read
[&](Belle::Server::Websocket_Ctx& ctx)
{
// a simple protocol:
// in the received message,
// the first character holds an int from 0-9,
// the remaining characters are the message
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// get the message type
int type {std::stoi(to_string(ctx.msg.at(0)))};
// determine action
switch (type)
{
case 0:
chat[channel].push(ctx.msg.substr(1));
ctx.channels.at(channel).broadcast("0" + ctx.msg.substr(1));
break;
default:
break;
}
},
// on end: called once after disconnected
[](Belle::Server::Websocket_Ctx& ctx)
{
// the Websocket automatically joins the channel named after the path on connect
// retrieve and store the path/channel name
std::string channel {ctx.req.path().at(0)};
// a user has disconnected
// broadcast the total number of connected users to the channel
ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));
}
);
// set websocket connect callback
// called once at the very beginning after connected
app.on_websocket_connect([&](Belle::Server::Websocket_Ctx& ctx)
{
// increase total user count
++user_count;
// send room count
ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
// send user count
ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
for (auto const& e : ctx.channels)
{
// send count and room info
ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
}
});
// set websocket disconnect callback
// called once at the very end after disconnected
app.on_websocket_disconnect([&](Belle::Server::Websocket_Ctx& ctx)
{
// decrease total user count
--user_count;
// send room count
ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
// send user count
ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
for (auto const& e : ctx.channels)
{
// send count and room info
ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
}
});
// handle route GET '/'
// with no set dynamic route for a route ending in a '/' character,
// the default action is to look for a static file named 'index.html'
// in the corresponding public directory
// handle route GET '/<chat_room>'
app.on_http("^(/[a-z]+)$", Belle::Method::get, [&](Belle::Server::Http_Ctx& ctx)
{
// set http response headers
ctx.res.set("content-type", "text/html");
// send the file contents
if (auto res = file(app.public_dir() + "/chat.html"))
{
ctx.res.body() = std::move(res.value());
}
else
{
throw 404;
}
});
// set custom error callback
app.on_http_error([](Belle::Server::Http_Ctx& ctx)
{
// stringstream to hold the response
std::stringstream res; res
<< "Status: " << ctx.res.result_int() << "\n"
<< "Reason: " << ctx.res.result() << "\n";
// set http response headers
ctx.res.set("content-type", "text/plain");
// echo the http status code
ctx.res.body() = res.str();
});
// print out the address and port
std::cout
<< "Server: " << address << ":" << port << "\n\n"
<< "Navigate to the following url:\n"
<< " http://" << address << ":" << port << "/new\n\n";
// start the server
app.listen();
// the server blocks until a signal is received
return 0;
}
|
update chat example
|
update chat example
|
C++
|
mit
|
octobanana/belle,octobanana/belle,octobanana/belle,octobanana/belle
|
67ddbbe4948ef56335bb9884a05e3f022d7698cf
|
examples/Particles/LogoDemo.cpp
|
examples/Particles/LogoDemo.cpp
|
#include "LogoDemo.hpp"
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Components.hpp>
#include <NDK/Systems.hpp>
#include <iostream>
namespace
{
const float duration = 10.f;
const float maxSpeed = 100.f;
const float maxMouseForce = 1000.f;
const float mouseForce = 500.f;
const float pauseTime = 3.f;
const float startTime = 2.f;
const float speed = 3.f;
}
struct ParticleData
{
Nz::Color color;
Nz::Vector2f destination;
Nz::Vector2f position;
Nz::Vector2f velocity;
};
struct SpriteController : public Nz::ParticleController
{
void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override
{
if (!enabled)
return;
auto destPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Userdata0);
auto posPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Position);
auto velPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Velocity);
std::uniform_real_distribution<float> dis(-1.f, 1.f);
for (unsigned int i = startId; i <= endId; ++i)
{
Nz::Vector2f newVel = destPtr[i] - posPtr[i];
float length;
newVel.Normalize(&length);
float distance = SquaredDistancePointSegment(oldMousePos, actualMousePos, posPtr[i]);
if (distance < 250.f)
{
Nz::Vector2f mouseLine = actualMousePos - oldMousePos;
float mouseLength;
mouseLine.Normalize(&mouseLength);
if (mouseLength > 5.f)
{
velPtr[i] += mouseLine * std::min(mouseLength * mouseForce, maxMouseForce) * elapsedTime;
velPtr[i] += Nz::Vector2f(dis(randomGen), dis(randomGen)) * std::min(mouseLength, maxMouseForce * 0.1f);
}
}
if (length > 1.f || velPtr[i].GetSquaredLength() > Nz::IntegralPow(30.f, 2))
{
newVel *= maxSpeed;
velPtr[i] = Nz::Lerp(velPtr[i], newVel, 0.4f * elapsedTime);
posPtr[i] += velPtr[i] * elapsedTime;
}
else
{
velPtr[i] = Nz::Vector2f::Zero();
posPtr[i] = destPtr[i];
}
}
}
static float SquaredDistancePointSegment(const Nz::Vector2f& s0, const Nz::Vector2f& s1, const Nz::Vector2f& point)
{
// http://geomalgorithms.com/a02-_lines.html
Nz::Vector2f v = s1 - s0;
Nz::Vector2f w = point - s0;
float c1 = Nz::Vector2f::DotProduct(w, v);
if (c1 <= 0.f)
return point.SquaredDistance(s0);
float c2 = Nz::Vector2f::DotProduct(v, v);
if (c2 <= c1)
return point.SquaredDistance(s1);
float b = c1 / c2;
Nz::Vector2f projPoint = s0 + b * v;
return projPoint.SquaredDistance(point);
}
std::mt19937 randomGen;
bool enabled = false;
float factor = 1000.f;
Nz::Vector2f actualMousePos;
Nz::Vector2f oldMousePos;
};
class SpriteRenderer : public Nz::ParticleRenderer
{
public:
SpriteRenderer(Nz::MaterialRef mat) :
m_material(mat)
{
}
void Render(const Nz::ParticleGroup& system, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
Nz::Vector2f size(1.f, 1.f);
Nz::SparsePtr<const Nz::Vector2f> sizePtr(&size, 0);
Nz::SparsePtr<const Nz::Vector2f> sinCosPtr(nullptr, 0);
renderQueue->AddBillboards(0, m_material, endId - startId + 1, mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position), sizePtr, sinCosPtr, mapper.GetComponentPtr<const Nz::Color>(Nz::ParticleComponent_Color));
}
private:
Nz::MaterialRef m_material;
};
LogoExample::LogoExample(ExampleShared& sharedData) :
ParticleDemo("Logo", sharedData)
{
Nz::ImageParams params;
params.loadFormat = Nz::PixelFormatType_RGBA8;
if (!m_logo.LoadFromFile("resources/Logo.png", params))
NazaraError("Failed to load logo!");
unsigned int width = m_logo.GetWidth();
unsigned int height = m_logo.GetHeight();
m_pixels.reserve(width * height);
for (unsigned int x = 0; x < width; ++x)
{
for (unsigned int y = 0; y < height; ++y)
{
Nz::Color color = m_logo.GetPixelColor(x, y);
if (color.a == 0)
continue;
PixelData data;
data.pos.Set(x, y);
data.color = color;
m_pixels.push_back(data);
}
}
Nz::MaterialRef material = Nz::Material::New();
material->EnableBlending(true);
material->EnableDepthWrite(false);
material->EnableFaceCulling(false);
material->SetDstBlend(Nz::BlendFunc_InvSrcAlpha);
material->SetSrcBlend(Nz::BlendFunc_SrcAlpha);
m_controller = new SpriteController;
m_renderer = new SpriteRenderer(std::move(material));
m_declaration = Nz::ParticleDeclaration::New();
m_declaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(ParticleData, color));
m_declaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, position));
m_declaration->EnableComponent(Nz::ParticleComponent_Userdata0, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, destination));
m_declaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, velocity));
}
void LogoExample::Enter(Ndk::StateMachine& fsm)
{
ParticleDemo::Enter(fsm);
m_shared.world3D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(nullptr);
Nz::TextureRef backgroundTexture = Nz::Texture::New();
if (backgroundTexture->LoadFromFile("resources/stars-background.jpg"))
m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture)));
Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity();
Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(m_pixels.size(), m_declaration);
RegisterParticleGroup(particleGroupEntity);
particleGroup.AddController(m_controller);
particleGroup.SetRenderer(m_renderer);
m_particles = particleGroup.CreateParticles(m_pixels.size());
ResetParticles(-duration * (speed / 2.f));
m_accumulator = pauseTime + duration;
m_totalAccumulator = 0.f;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
controller->actualMousePos = controller->oldMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
}
void LogoExample::Leave(Ndk::StateMachine & fsm)
{
ParticleDemo::Leave(fsm);
}
bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
if (!ParticleDemo::Update(fsm, elapsedTime))
return false;
m_totalAccumulator += elapsedTime;
if (m_totalAccumulator <= startTime)
return true;
m_accumulator += elapsedTime;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
controller->enabled = (m_accumulator > pauseTime);
if (m_mouseClock.GetMilliseconds() > 1000/30)
{
m_mouseClock.Restart();
controller->oldMousePos = controller->actualMousePos;
controller->actualMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
}
if (Nz::Mouse::IsButtonPressed(Nz::Mouse::Left))
{
if (!m_hasClicked)
{
m_hasClicked = true;
std::uniform_real_distribution<float> dis(50.f, 60.f);
ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (std::size_t i = 0; i < m_pixels.size(); ++i)
{
Nz::Vector2f particleToMouse = sprite[i].position - controller->actualMousePos;
float sqDist = particleToMouse.GetSquaredLength();
if (sqDist < 10000.f)
{
float dist = std::sqrt(sqDist);
particleToMouse /= std::max(dist, 1.f);
sprite[i].velocity += particleToMouse * dis(m_shared.randomGen);
}
}
}
}
else
m_hasClicked = false;
return true;
}
void LogoExample::ResetParticles(float elapsed)
{
unsigned int width = m_shared.target->GetWidth();
unsigned int height = m_shared.target->GetHeight();
Nz::Vector2f center = {width / 2.f, height / 2.f};
Nz::Vector2f offset = center - Nz::Vector2f(Nz::Vector2ui(m_logo.GetSize()) / 2);
std::uniform_real_distribution<float> disX(0.f, float(width));
std::uniform_real_distribution<float> disY(-float(height) * 0.5f, float(height) * 1.5f);
ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (PixelData& data : m_pixels)
{
sprite->color = data.color;
sprite->destination = offset + Nz::Vector2f(data.pos);
sprite->position.Set(disX(m_shared.randomGen) - float(width), disY(m_shared.randomGen));
sprite->velocity = Nz::Vector2f::Zero();
sprite++;
}
}
|
#include "LogoDemo.hpp"
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics.hpp>
#include <Nazara/Utility.hpp>
#include <NDK/Components.hpp>
#include <NDK/Systems.hpp>
#include <iostream>
namespace
{
const float duration = 10.f;
const float maxSpeed = 100.f;
const float maxMouseForce = 1000.f;
const float mouseForce = 500.f;
const float pauseTime = 3.f;
const float startTime = 2.f;
const float speed = 3.f;
}
struct ParticleData
{
Nz::Color color;
Nz::Vector2f destination;
Nz::Vector3f position;
Nz::Vector2f velocity;
};
struct SpriteController : public Nz::ParticleController
{
void Apply(Nz::ParticleGroup& system, Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, float elapsedTime) override
{
if (!enabled)
return;
auto destPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Userdata0);
auto posPtr = mapper.GetComponentPtr<Nz::Vector3f>(Nz::ParticleComponent_Position);
auto velPtr = mapper.GetComponentPtr<Nz::Vector2f>(Nz::ParticleComponent_Velocity);
std::uniform_real_distribution<float> dis(-1.f, 1.f);
for (unsigned int i = startId; i <= endId; ++i)
{
Nz::Vector2f newVel = destPtr[i] - Nz::Vector2f(posPtr[i]);
float length;
newVel.Normalize(&length);
float distance = SquaredDistancePointSegment(oldMousePos, actualMousePos, Nz::Vector2f(posPtr[i]));
if (distance < 250.f)
{
Nz::Vector2f mouseLine = actualMousePos - oldMousePos;
float mouseLength;
mouseLine.Normalize(&mouseLength);
if (mouseLength > 5.f)
{
velPtr[i] += mouseLine * std::min(mouseLength * mouseForce, maxMouseForce) * elapsedTime;
velPtr[i] += Nz::Vector2f(dis(randomGen), dis(randomGen)) * std::min(mouseLength, maxMouseForce * 0.1f);
}
}
if (length > 1.f || velPtr[i].GetSquaredLength() > Nz::IntegralPow(30.f, 2))
{
newVel *= maxSpeed;
velPtr[i] = Nz::Lerp(velPtr[i], newVel, 0.4f * elapsedTime);
posPtr[i] += velPtr[i] * elapsedTime;
}
else
{
velPtr[i] = Nz::Vector2f::Zero();
posPtr[i] = destPtr[i];
}
}
}
static float SquaredDistancePointSegment(const Nz::Vector2f& s0, const Nz::Vector2f& s1, const Nz::Vector2f& point)
{
// http://geomalgorithms.com/a02-_lines.html
Nz::Vector2f v = s1 - s0;
Nz::Vector2f w = point - s0;
float c1 = Nz::Vector2f::DotProduct(w, v);
if (c1 <= 0.f)
return point.SquaredDistance(s0);
float c2 = Nz::Vector2f::DotProduct(v, v);
if (c2 <= c1)
return point.SquaredDistance(s1);
float b = c1 / c2;
Nz::Vector2f projPoint = s0 + b * v;
return projPoint.SquaredDistance(point);
}
std::mt19937 randomGen;
bool enabled = false;
float factor = 1000.f;
Nz::Vector2f actualMousePos;
Nz::Vector2f oldMousePos;
};
class SpriteRenderer : public Nz::ParticleRenderer
{
public:
SpriteRenderer(Nz::MaterialRef mat) :
m_material(mat)
{
}
void Render(const Nz::ParticleGroup& system, const Nz::ParticleMapper& mapper, unsigned int startId, unsigned int endId, Nz::AbstractRenderQueue* renderQueue)
{
Nz::Vector2f size(1.f, 1.f);
Nz::SparsePtr<const Nz::Vector2f> sizePtr(&size, 0);
Nz::SparsePtr<const Nz::Vector2f> sinCosPtr(nullptr, 0);
renderQueue->AddBillboards(0, m_material, endId - startId + 1, mapper.GetComponentPtr<const Nz::Vector3f>(Nz::ParticleComponent_Position), sizePtr, sinCosPtr, mapper.GetComponentPtr<const Nz::Color>(Nz::ParticleComponent_Color));
}
private:
Nz::MaterialRef m_material;
};
LogoExample::LogoExample(ExampleShared& sharedData) :
ParticleDemo("Logo", sharedData)
{
Nz::ImageParams params;
params.loadFormat = Nz::PixelFormatType_RGBA8;
if (!m_logo.LoadFromFile("resources/Logo.png", params))
NazaraError("Failed to load logo!");
unsigned int width = m_logo.GetWidth();
unsigned int height = m_logo.GetHeight();
m_pixels.reserve(width * height);
for (unsigned int x = 0; x < width; ++x)
{
for (unsigned int y = 0; y < height; ++y)
{
Nz::Color color = m_logo.GetPixelColor(x, y);
if (color.a == 0)
continue;
PixelData data;
data.pos.Set(x, y);
data.color = color;
m_pixels.push_back(data);
}
}
Nz::MaterialRef material = Nz::Material::New();
material->EnableBlending(true);
material->EnableDepthWrite(false);
material->EnableFaceCulling(false);
material->SetDstBlend(Nz::BlendFunc_InvSrcAlpha);
material->SetSrcBlend(Nz::BlendFunc_SrcAlpha);
m_controller = new SpriteController;
m_renderer = new SpriteRenderer(std::move(material));
m_declaration = Nz::ParticleDeclaration::New();
m_declaration->EnableComponent(Nz::ParticleComponent_Color, Nz::ComponentType_Color, NazaraOffsetOf(ParticleData, color));
m_declaration->EnableComponent(Nz::ParticleComponent_Position, Nz::ComponentType_Float3, NazaraOffsetOf(ParticleData, position));
m_declaration->EnableComponent(Nz::ParticleComponent_Userdata0, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, destination));
m_declaration->EnableComponent(Nz::ParticleComponent_Velocity, Nz::ComponentType_Float2, NazaraOffsetOf(ParticleData, velocity));
}
void LogoExample::Enter(Ndk::StateMachine& fsm)
{
ParticleDemo::Enter(fsm);
m_shared.world3D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(nullptr);
Nz::TextureRef backgroundTexture = Nz::Texture::New();
if (backgroundTexture->LoadFromFile("resources/stars-background.jpg"))
m_shared.world2D->GetSystem<Ndk::RenderSystem>().SetDefaultBackground(Nz::TextureBackground::New(std::move(backgroundTexture)));
Ndk::EntityHandle particleGroupEntity = m_shared.world2D->CreateEntity();
Ndk::ParticleGroupComponent& particleGroup = particleGroupEntity->AddComponent<Ndk::ParticleGroupComponent>(m_pixels.size(), m_declaration);
RegisterParticleGroup(particleGroupEntity);
particleGroup.AddController(m_controller);
particleGroup.SetRenderer(m_renderer);
m_particles = particleGroup.CreateParticles(m_pixels.size());
ResetParticles(-duration * (speed / 2.f));
m_accumulator = pauseTime + duration;
m_totalAccumulator = 0.f;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
controller->actualMousePos = controller->oldMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
}
void LogoExample::Leave(Ndk::StateMachine & fsm)
{
ParticleDemo::Leave(fsm);
}
bool LogoExample::Update(Ndk::StateMachine& fsm, float elapsedTime)
{
if (!ParticleDemo::Update(fsm, elapsedTime))
return false;
m_totalAccumulator += elapsedTime;
if (m_totalAccumulator <= startTime)
return true;
m_accumulator += elapsedTime;
SpriteController* controller = static_cast<SpriteController*>(m_controller.Get());
controller->enabled = (m_accumulator > pauseTime);
if (m_mouseClock.GetMilliseconds() > 1000/30)
{
m_mouseClock.Restart();
controller->oldMousePos = controller->actualMousePos;
controller->actualMousePos = Nz::Vector2f(Nz::Mouse::GetPosition(*m_shared.target));
}
if (Nz::Mouse::IsButtonPressed(Nz::Mouse::Left))
{
if (!m_hasClicked)
{
m_hasClicked = true;
std::uniform_real_distribution<float> dis(50.f, 60.f);
ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (std::size_t i = 0; i < m_pixels.size(); ++i)
{
Nz::Vector2f particleToMouse = sprite[i].position - controller->actualMousePos;
float sqDist = particleToMouse.GetSquaredLength();
if (sqDist < 10000.f)
{
float dist = std::sqrt(sqDist);
particleToMouse /= std::max(dist, 1.f);
sprite[i].velocity += particleToMouse * dis(m_shared.randomGen);
}
}
}
}
else
m_hasClicked = false;
return true;
}
void LogoExample::ResetParticles(float elapsed)
{
unsigned int width = m_shared.target->GetWidth();
unsigned int height = m_shared.target->GetHeight();
Nz::Vector2f center = {width / 2.f, height / 2.f};
Nz::Vector2f offset = center - Nz::Vector2f(Nz::Vector2ui(m_logo.GetSize()) / 2);
std::uniform_real_distribution<float> disX(0.f, float(width));
std::uniform_real_distribution<float> disY(-float(height) * 0.5f, float(height) * 1.5f);
ParticleData* sprite = static_cast<ParticleData*>(m_particles);
for (PixelData& data : m_pixels)
{
sprite->color = data.color;
sprite->destination = offset + Nz::Vector2f(data.pos);
sprite->position.Set(disX(m_shared.randomGen) - float(width), disY(m_shared.randomGen), 0.f);
sprite->velocity = Nz::Vector2f::Zero();
sprite++;
}
}
|
Fix LogoDemo after mapper change
|
Fix LogoDemo after mapper change
|
C++
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
9431ebce5110bbaa686ede04c6141bac34699862
|
ode/ode/src/stack.cpp
|
ode/ode/src/stack.cpp
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith. *
* *
* 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 (see the file LICENSE.TXT); if not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA. *
* *
*************************************************************************/
#include <string.h>
#include <errno.h>
#include "stack.h"
#include "ode/error.h"
//****************************************************************************
#ifndef WIN32
#include <unistd.h>
#include <sys/mman.h>
void dStack::init (int max_size)
{
if (sizeof(long int) != sizeof(char*)) dDebug (0,"internal");
if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON,0,0);
if (int(base) == -1) dError (0,"Stack::init(), mmap() failed, "
"max_size=%d (%s)",max_size,strerror(errno));
size = max_size;
pointer = base;
frame = 0;
}
void dStack::destroy()
{
munmap (base,size);
base = 0;
size = 0;
pointer = 0;
frame = 0;
}
#endif
//****************************************************************************
#ifdef WIN32
#include "windows.h"
void dStack::init (int max_size)
{
if (sizeof(LPVOID) != sizeof(char*)) dDebug (0,"internal");
if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
base = (char*) VirtualAlloc (NULL,max_size,MEM_RESERVE,PAGE_READWRITE);
if (base == 0) dError (0,"Stack::init(), VirtualAlloc() failed, "
"max_size=%d",max_size);
size = max_size;
pointer = base;
frame = 0;
committed = 0;
// get page size
SYSTEM_INFO info;
GetSystemInfo (&info);
pagesize = info.dwPageSize;
}
void dStack::destroy()
{
VirtualFree (base,0,MEM_RELEASE);
base = 0;
size = 0;
pointer = 0;
frame = 0;
}
#endif
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001 Russell L. Smith. *
* *
* 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 (see the file LICENSE.TXT); if not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA. *
* *
*************************************************************************/
#include <string.h>
#include <errno.h>
#include "stack.h"
#include "ode/error.h"
#include "ode/config.h"
//****************************************************************************
// unix version that uses mmap(). some systems have anonymous mmaps and some
// need to mmap /dev/zero.
#ifndef WIN32
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void dStack::init (int max_size)
{
if (sizeof(long int) != sizeof(char*)) dDebug (0,"internal");
if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
#ifndef MMAP_ANONYMOUS
static int dev_zero_fd = -1; // cached file descriptor for /dev/zero
if (dev_zero_fd < 0) dev_zero_fd = open ("/dev/zero", O_RDWR);
if (dev_zero_fd < 0) dError (0,"can't open /dev/zero (%s)",strerror(errno));
base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE, MAP_PRIVATE,
dev_zero_fd,0);
#else
base = (char*) mmap (0,max_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON,0,0);
#endif
if (int(base) == -1) dError (0,"Stack::init(), mmap() failed, "
"max_size=%d (%s)",max_size,strerror(errno));
size = max_size;
pointer = base;
frame = 0;
}
void dStack::destroy()
{
munmap (base,size);
base = 0;
size = 0;
pointer = 0;
frame = 0;
}
#endif
//****************************************************************************
#ifdef WIN32
#include "windows.h"
void dStack::init (int max_size)
{
if (sizeof(LPVOID) != sizeof(char*)) dDebug (0,"internal");
if (max_size <= 0) dDebug (0,"Stack::init() given size <= 0");
base = (char*) VirtualAlloc (NULL,max_size,MEM_RESERVE,PAGE_READWRITE);
if (base == 0) dError (0,"Stack::init(), VirtualAlloc() failed, "
"max_size=%d",max_size);
size = max_size;
pointer = base;
frame = 0;
committed = 0;
// get page size
SYSTEM_INFO info;
GetSystemInfo (&info);
pagesize = info.dwPageSize;
}
void dStack::destroy()
{
VirtualFree (base,0,MEM_RELEASE);
base = 0;
size = 0;
pointer = 0;
frame = 0;
}
#endif
|
support systems like solaris (?) that dont have anonymous mmaps
|
support systems like solaris (?) that dont have anonymous mmaps
|
C++
|
lgpl-2.1
|
forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende,forrestv/opende
|
9d35724651c84efeb03214d79aac6e59d797c379
|
ospray/fb/LocalFB.cpp
|
ospray/fb/LocalFB.cpp
|
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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. //
// ======================================================================== //
//ospray
#include "LocalFB.h"
#include "LocalFB_ispc.h"
namespace ospray {
LocalFrameBuffer::LocalFrameBuffer(const vec2i &size,
ColorBufferFormat colorBufferFormat,
bool hasDepthBuffer,
bool hasAccumBuffer,
bool hasVarianceBuffer,
void *colorBufferToUse)
: FrameBuffer(size, colorBufferFormat, hasDepthBuffer, hasAccumBuffer, hasVarianceBuffer)
{
Assert(size.x > 0);
Assert(size.y > 0);
if (colorBufferToUse)
colorBuffer = colorBufferToUse;
else {
switch (colorBufferFormat) {
case OSP_FB_NONE:
colorBuffer = NULL;
break;
case OSP_FB_RGBA8:
case OSP_FB_SRGBA:
colorBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
break;
case OSP_FB_RGBA32F:
colorBuffer = (uint32*)alignedMalloc(sizeof(uint32)*size.x*size.y);
break;
default:
throw std::runtime_error("color buffer format not supported");
}
}
if (hasDepthBuffer)
depthBuffer = (float*)alignedMalloc(sizeof(float)*size.x*size.y);
else
depthBuffer = NULL;
if (hasAccumBuffer)
accumBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
else
accumBuffer = NULL;
tilesx = divRoundUp(size.x, TILE_SIZE);
tiles = tilesx * divRoundUp(size.y, TILE_SIZE);
tileAccumID = new int32[tiles];
memset(tileAccumID, 0, tiles*sizeof(int32));
if (hasVarianceBuffer) {
varianceBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
tileErrorBuffer = new float[tiles];
// maximum number of regions: all regions are of size 3 are split in half
errorRegion.reserve(divRoundUp(tiles*2, 3));
} else {
varianceBuffer = NULL;
tileErrorBuffer = NULL;
}
ispcEquivalent = ispc::LocalFrameBuffer_create(this,size.x,size.y,
colorBufferFormat,
colorBuffer,
depthBuffer,
accumBuffer,
varianceBuffer,
tileAccumID,
tileErrorBuffer);
}
LocalFrameBuffer::~LocalFrameBuffer()
{
alignedFree(depthBuffer);
alignedFree(colorBuffer);
alignedFree(accumBuffer);
alignedFree(varianceBuffer);
delete[] tileAccumID;
delete[] tileErrorBuffer;
}
std::string LocalFrameBuffer::toString() const
{
return "ospray::LocalFrameBuffer";
}
void LocalFrameBuffer::clear(const uint32 fbChannelFlags)
{
if (fbChannelFlags & OSP_FB_ACCUM) {
// it is only necessary to reset the accumID,
// LocalFrameBuffer_accumulateTile takes care of clearing the
// accumulation buffers
memset(tileAccumID, 0, tiles*sizeof(int32));
// always also clear error buffer (if present)
if (hasVarianceBuffer) {
for (int i = 0; i < tiles; i++)
tileErrorBuffer[i] = inf;
errorRegion.clear();
// initially create one region covering the complete image
errorRegion.push_back(box2i(vec2i(0), vec2i(tilesx, divRoundUp(size.y, TILE_SIZE))));
}
}
}
void LocalFrameBuffer::setTile(Tile &tile)
{
if (pixelOp)
pixelOp->preAccum(tile);
if (accumBuffer)
ispc::LocalFrameBuffer_accumulateTile(getIE(),(ispc::Tile&)tile);
if (pixelOp)
pixelOp->postAccum(tile);
if (colorBuffer) {
switch (colorBufferFormat) {
case OSP_FB_RGBA8:
ispc::LocalFrameBuffer_writeTile_RGBA8(getIE(),(ispc::Tile&)tile);
break;
case OSP_FB_SRGBA:
ispc::LocalFrameBuffer_writeTile_SRGBA(getIE(),(ispc::Tile&)tile);
break;
case OSP_FB_RGBA32F:
ispc::LocalFrameBuffer_writeTile_RGBA32F(getIE(),(ispc::Tile&)tile);
break;
default:
NOTIMPLEMENTED;
}
}
}
int32 LocalFrameBuffer::accumID(const vec2i &tile)
{
return tileAccumID[tile.y * tilesx + tile.x];
}
float LocalFrameBuffer::tileError(const vec2i &tile)
{
const int idx = tile.y * tilesx + tile.x;
return hasVarianceBuffer ? tileErrorBuffer[idx] : inf;
}
float LocalFrameBuffer::endFrame(const float errorThreshold)
{
if (hasVarianceBuffer) {
// process regions first, but don't process newly split regions again
int regions = errorThreshold > 0.f ? errorRegion.size() : 0;
for (int i = 0; i < regions; i++) {
box2i& region = errorRegion[i];
float err = 0.f;
float maxErr = 0.0f;
for (int y = region.lower.y; y < region.upper.y; y++)
for (int x = region.lower.x; x < region.upper.x; x++) {
int idx = y * tilesx + x;
err += tileErrorBuffer[idx];
maxErr = std::max(maxErr, tileErrorBuffer[idx]);
}
// set all tiles of this region to local max error to enforce their refinement as a group
for (int y = region.lower.y; y < region.upper.y; y++)
for (int x = region.lower.x; x < region.upper.x; x++) {
int idx = y * tilesx + x;
tileErrorBuffer[idx] = maxErr;
}
vec2i size = region.size();
int area = reduce_mul(size);
err /= area; // avg
if (err < 4.f*errorThreshold) { // split region?
if (area <= 2) { // would just contain single tile after split: remove
regions--;
errorRegion[i] = errorRegion[regions];
errorRegion[regions]= errorRegion.back();
errorRegion.pop_back();
i--;
continue;
}
vec2i split = region.lower + size / 2; // TODO: find split with equal variance
errorRegion.push_back(region); // region reference might become invalid
if (size.x > size.y) {
errorRegion[i].upper.x = split.x;
errorRegion.back().lower.x = split.x;
} else {
errorRegion[i].upper.y = split.y;
errorRegion.back().lower.y = split.y;
}
}
}
float maxErr = 0.0f;
for (int i = 0; i < tiles; i++)
maxErr = std::max(maxErr, tileErrorBuffer[i]);
return maxErr;
} else
return inf;
}
const void *LocalFrameBuffer::mapDepthBuffer()
{
this->refInc();
return (const void *)depthBuffer;
}
const void *LocalFrameBuffer::mapColorBuffer()
{
this->refInc();
return (const void *)colorBuffer;
}
void LocalFrameBuffer::unmap(const void *mappedMem)
{
Assert(mappedMem == colorBuffer || mappedMem == depthBuffer );
this->refDec();
}
} // ::ospray
|
// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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. //
// ======================================================================== //
//ospray
#include "LocalFB.h"
#include "LocalFB_ispc.h"
namespace ospray {
LocalFrameBuffer::LocalFrameBuffer(const vec2i &size,
ColorBufferFormat colorBufferFormat,
bool hasDepthBuffer,
bool hasAccumBuffer,
bool hasVarianceBuffer,
void *colorBufferToUse)
: FrameBuffer(size, colorBufferFormat, hasDepthBuffer, hasAccumBuffer, hasVarianceBuffer)
{
Assert(size.x > 0);
Assert(size.y > 0);
if (colorBufferToUse)
colorBuffer = colorBufferToUse;
else {
switch (colorBufferFormat) {
case OSP_FB_NONE:
colorBuffer = NULL;
break;
case OSP_FB_RGBA8:
case OSP_FB_SRGBA:
colorBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
break;
case OSP_FB_RGBA32F:
colorBuffer = (uint32*)alignedMalloc(sizeof(uint32)*size.x*size.y);
break;
default:
throw std::runtime_error("color buffer format not supported");
}
}
if (hasDepthBuffer)
depthBuffer = (float*)alignedMalloc(sizeof(float)*size.x*size.y);
else
depthBuffer = NULL;
if (hasAccumBuffer)
accumBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
else
accumBuffer = NULL;
tilesx = divRoundUp(size.x, TILE_SIZE);
tiles = tilesx * divRoundUp(size.y, TILE_SIZE);
tileAccumID = (int32*)alignedMalloc(sizeof(int32)*tiles);
memset(tileAccumID, 0, tiles*sizeof(int32));
if (hasVarianceBuffer) {
varianceBuffer = (vec4f*)alignedMalloc(sizeof(vec4f)*size.x*size.y);
tileErrorBuffer = (float*)alignedMalloc(sizeof(float)*tiles);
// maximum number of regions: all regions are of size 3 are split in half
errorRegion.reserve(divRoundUp(tiles*2, 3));
} else {
varianceBuffer = NULL;
tileErrorBuffer = NULL;
}
ispcEquivalent = ispc::LocalFrameBuffer_create(this,size.x,size.y,
colorBufferFormat,
colorBuffer,
depthBuffer,
accumBuffer,
varianceBuffer,
tileAccumID,
tileErrorBuffer);
}
LocalFrameBuffer::~LocalFrameBuffer()
{
alignedFree(depthBuffer);
alignedFree(colorBuffer);
alignedFree(accumBuffer);
alignedFree(varianceBuffer);
alignedFree(tileAccumID);
alignedFree(tileErrorBuffer);
}
std::string LocalFrameBuffer::toString() const
{
return "ospray::LocalFrameBuffer";
}
void LocalFrameBuffer::clear(const uint32 fbChannelFlags)
{
if (fbChannelFlags & OSP_FB_ACCUM) {
// it is only necessary to reset the accumID,
// LocalFrameBuffer_accumulateTile takes care of clearing the
// accumulation buffers
memset(tileAccumID, 0, tiles*sizeof(int32));
// always also clear error buffer (if present)
if (hasVarianceBuffer) {
for (int i = 0; i < tiles; i++)
tileErrorBuffer[i] = inf;
errorRegion.clear();
// initially create one region covering the complete image
errorRegion.push_back(box2i(vec2i(0),
vec2i(tilesx,
divRoundUp(size.y, TILE_SIZE))));
}
}
}
void LocalFrameBuffer::setTile(Tile &tile)
{
if (pixelOp)
pixelOp->preAccum(tile);
if (accumBuffer)
ispc::LocalFrameBuffer_accumulateTile(getIE(),(ispc::Tile&)tile);
if (pixelOp)
pixelOp->postAccum(tile);
if (colorBuffer) {
switch (colorBufferFormat) {
case OSP_FB_RGBA8:
ispc::LocalFrameBuffer_writeTile_RGBA8(getIE(),(ispc::Tile&)tile);
break;
case OSP_FB_SRGBA:
ispc::LocalFrameBuffer_writeTile_SRGBA(getIE(),(ispc::Tile&)tile);
break;
case OSP_FB_RGBA32F:
ispc::LocalFrameBuffer_writeTile_RGBA32F(getIE(),(ispc::Tile&)tile);
break;
default:
NOTIMPLEMENTED;
}
}
}
int32 LocalFrameBuffer::accumID(const vec2i &tile)
{
return tileAccumID[tile.y * tilesx + tile.x];
}
float LocalFrameBuffer::tileError(const vec2i &tile)
{
const int idx = tile.y * tilesx + tile.x;
return hasVarianceBuffer ? tileErrorBuffer[idx] : inf;
}
float LocalFrameBuffer::endFrame(const float errorThreshold)
{
if (hasVarianceBuffer) {
// process regions first, but don't process newly split regions again
int regions = errorThreshold > 0.f ? errorRegion.size() : 0;
for (int i = 0; i < regions; i++) {
box2i& region = errorRegion[i];
float err = 0.f;
float maxErr = 0.0f;
for (int y = region.lower.y; y < region.upper.y; y++)
for (int x = region.lower.x; x < region.upper.x; x++) {
int idx = y * tilesx + x;
err += tileErrorBuffer[idx];
maxErr = std::max(maxErr, tileErrorBuffer[idx]);
}
// set all tiles of this region to local max error to enforce their refinement as a group
for (int y = region.lower.y; y < region.upper.y; y++)
for (int x = region.lower.x; x < region.upper.x; x++) {
int idx = y * tilesx + x;
tileErrorBuffer[idx] = maxErr;
}
vec2i size = region.size();
int area = reduce_mul(size);
err /= area; // avg
if (err < 4.f*errorThreshold) { // split region?
if (area <= 2) { // would just contain single tile after split: remove
regions--;
errorRegion[i] = errorRegion[regions];
errorRegion[regions]= errorRegion.back();
errorRegion.pop_back();
i--;
continue;
}
vec2i split = region.lower + size / 2; // TODO: find split with equal variance
errorRegion.push_back(region); // region reference might become invalid
if (size.x > size.y) {
errorRegion[i].upper.x = split.x;
errorRegion.back().lower.x = split.x;
} else {
errorRegion[i].upper.y = split.y;
errorRegion.back().lower.y = split.y;
}
}
}
float maxErr = 0.0f;
for (int i = 0; i < tiles; i++)
maxErr = std::max(maxErr, tileErrorBuffer[i]);
return maxErr;
} else
return inf;
}
const void *LocalFrameBuffer::mapDepthBuffer()
{
this->refInc();
return (const void *)depthBuffer;
}
const void *LocalFrameBuffer::mapColorBuffer()
{
this->refInc();
return (const void *)colorBuffer;
}
void LocalFrameBuffer::unmap(const void *mappedMem)
{
Assert(mappedMem == colorBuffer || mappedMem == depthBuffer );
this->refDec();
}
} // ::ospray
|
make everything in LocalFB aligned...() for memory allocation
|
make everything in LocalFB aligned...() for memory allocation
|
C++
|
apache-2.0
|
wilsonCernWq/ospray,MengjiaoH/ospray,wilsonCernWq/ospray,MengjiaoH/ospray,ospray/OSPRay,Twinklebear/OSPRay,wilsonCernWq/ospray,ospray/OSPRay,MengjiaoH/ospray,ospray/OSPRay,MengjiaoH/ospray,Twinklebear/OSPRay,ospray/OSPRay,Twinklebear/OSPRay,MengjiaoH/ospray,Twinklebear/OSPRay
|
b76e94672251fc50140f5b8d8803b557bcf14bd4
|
Source/core/rendering/InlineBox.cpp
|
Source/core/rendering/InlineBox.cpp
|
/*
* Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/rendering/InlineBox.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RootInlineBox.h"
#include "platform/Partitions.h"
#include "platform/fonts/FontMetrics.h"
#ifndef NDEBUG
#include <stdio.h>
#endif
using namespace std;
namespace WebCore {
struct SameSizeAsInlineBox {
virtual ~SameSizeAsInlineBox() { }
void* a[4];
FloatPoint b;
float c;
uint32_t d : 32;
#ifndef NDEBUG
bool f;
#endif
};
COMPILE_ASSERT(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), InlineBox_size_guard);
#ifndef NDEBUG
InlineBox::~InlineBox()
{
if (!m_hasBadParent && m_parent)
m_parent->setHasBadChildList();
}
#endif
void InlineBox::remove()
{
if (parent())
parent()->removeChild(this);
}
void* InlineBox::operator new(size_t sz)
{
return partitionAlloc(Partitions::getRenderingPartition(), sz);
}
void InlineBox::operator delete(void* ptr)
{
partitionFree(ptr);
}
#ifndef NDEBUG
const char* InlineBox::boxName() const
{
return "InlineBox";
}
void InlineBox::showTreeForThis() const
{
renderer().showTreeForThis();
}
void InlineBox::showLineTreeForThis() const
{
renderer().containingBlock()->showLineTreeAndMark(this, "*");
}
void InlineBox::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj, int depth) const
{
int printedCharacters = 0;
if (this == markedBox1)
printedCharacters += fprintf(stderr, "%s", markedLabel1);
if (this == markedBox2)
printedCharacters += fprintf(stderr, "%s", markedLabel2);
if (&renderer() == obj)
printedCharacters += fprintf(stderr, "*");
for (; printedCharacters < depth * 2; printedCharacters++)
fputc(' ', stderr);
showBox(printedCharacters);
}
void InlineBox::showBox(int printedCharacters) const
{
printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
fputc(' ', stderr);
fprintf(stderr, "\t%s %p\n", renderer().renderName(), &renderer());
}
#endif
float InlineBox::logicalHeight() const
{
if (hasVirtualLogicalHeight())
return virtualLogicalHeight();
if (renderer().isText())
return m_bitfields.isText() ? renderer().style(isFirstLineStyle())->fontMetrics().height() : 0;
if (renderer().isBox() && parent())
return isHorizontal() ? toRenderBox(renderer()).height().toFloat() : toRenderBox(renderer()).width().toFloat();
ASSERT(isInlineFlowBox());
RenderBoxModelObject* flowObject = boxModelObject();
const FontMetrics& fontMetrics = renderer().style(isFirstLineStyle())->fontMetrics();
float result = fontMetrics.height();
if (parent())
result += flowObject->borderAndPaddingLogicalHeight();
return result;
}
int InlineBox::baselinePosition(FontBaseline baselineType) const
{
return boxModelObject()->baselinePosition(baselineType, m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
}
LayoutUnit InlineBox::lineHeight() const
{
return boxModelObject()->lineHeight(m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
}
int InlineBox::caretMinOffset() const
{
return renderer().caretMinOffset();
}
int InlineBox::caretMaxOffset() const
{
return renderer().caretMaxOffset();
}
void InlineBox::dirtyLineBoxes()
{
markDirty();
for (InlineFlowBox* curr = parent(); curr && !curr->isDirty(); curr = curr->parent())
curr->markDirty();
}
void InlineBox::deleteLine()
{
if (!m_bitfields.extracted() && renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(0);
destroy();
}
void InlineBox::extractLine()
{
m_bitfields.setExtracted(true);
if (renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(0);
}
void InlineBox::attachLine()
{
m_bitfields.setExtracted(false);
if (renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(this);
}
void InlineBox::adjustPosition(float dx, float dy)
{
m_topLeft.move(dx, dy);
if (renderer().isReplaced())
toRenderBox(renderer()).move(dx, dy);
}
void InlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
{
if (!paintInfo.shouldPaintWithinRoot(&renderer()) || (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection))
return;
LayoutPoint childPoint = paintOffset;
if (parent()->renderer().style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock().
childPoint = renderer().containingBlock()->flipForWritingModeForChild(&toRenderBox(renderer()), childPoint);
RenderBlock::paintAsInlineBlock(&renderer(), paintInfo, childPoint);
}
bool InlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
{
// Hit test all phases of replaced elements atomically, as though the replaced element established its
// own stacking context. (See Appendix E.2, section 6.4 on inline block/table elements in the CSS2.1
// specification.)
LayoutPoint childPoint = accumulatedOffset;
if (parent()->renderer().style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock().
childPoint = renderer().containingBlock()->flipForWritingModeForChild(&toRenderBox(renderer()), childPoint);
return renderer().hitTest(request, result, locationInContainer, childPoint);
}
const RootInlineBox& InlineBox::root() const
{
if (m_parent)
return m_parent->root();
ASSERT(isRootInlineBox());
return static_cast<const RootInlineBox&>(*this);
}
RootInlineBox& InlineBox::root()
{
if (m_parent)
return m_parent->root();
ASSERT(isRootInlineBox());
return static_cast<RootInlineBox&>(*this);
}
bool InlineBox::nextOnLineExists() const
{
if (!m_bitfields.determinedIfNextOnLineExists()) {
m_bitfields.setDeterminedIfNextOnLineExists(true);
if (!parent())
m_bitfields.setNextOnLineExists(false);
else if (nextOnLine())
m_bitfields.setNextOnLineExists(true);
else
m_bitfields.setNextOnLineExists(parent()->nextOnLineExists());
}
return m_bitfields.nextOnLineExists();
}
InlineBox* InlineBox::nextLeafChild() const
{
InlineBox* leaf = 0;
for (InlineBox* box = nextOnLine(); box && !leaf; box = box->nextOnLine())
leaf = box->isLeaf() ? box : toInlineFlowBox(box)->firstLeafChild();
if (!leaf && parent())
leaf = parent()->nextLeafChild();
return leaf;
}
InlineBox* InlineBox::prevLeafChild() const
{
InlineBox* leaf = 0;
for (InlineBox* box = prevOnLine(); box && !leaf; box = box->prevOnLine())
leaf = box->isLeaf() ? box : toInlineFlowBox(box)->lastLeafChild();
if (!leaf && parent())
leaf = parent()->prevLeafChild();
return leaf;
}
InlineBox* InlineBox::nextLeafChildIgnoringLineBreak() const
{
InlineBox* leaf = nextLeafChild();
if (leaf && leaf->isLineBreak())
return 0;
return leaf;
}
InlineBox* InlineBox::prevLeafChildIgnoringLineBreak() const
{
InlineBox* leaf = prevLeafChild();
if (leaf && leaf->isLineBreak())
return 0;
return leaf;
}
RenderObject::SelectionState InlineBox::selectionState()
{
return renderer().selectionState();
}
bool InlineBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const
{
// Non-replaced elements can always accommodate an ellipsis.
if (!renderer().isReplaced())
return true;
IntRect boxRect(left(), 0, m_logicalWidth, 10);
IntRect ellipsisRect(ltr ? blockEdge - ellipsisWidth : blockEdge, 0, ellipsisWidth, 10);
return !(boxRect.intersects(ellipsisRect));
}
float InlineBox::placeEllipsisBox(bool, float, float, float, float& truncatedWidth, bool&)
{
// Use -1 to mean "we didn't set the position."
truncatedWidth += logicalWidth();
return -1;
}
void InlineBox::clearKnownToHaveNoOverflow()
{
m_bitfields.setKnownToHaveNoOverflow(false);
if (parent() && parent()->knownToHaveNoOverflow())
parent()->clearKnownToHaveNoOverflow();
}
FloatPoint InlineBox::locationIncludingFlipping()
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return FloatPoint(x(), y());
RenderBlockFlow& block = root().block();
if (block.style()->isHorizontalWritingMode())
return FloatPoint(x(), block.height() - height() - y());
return FloatPoint(block.width() - width() - x(), y());
}
void InlineBox::flipForWritingMode(FloatRect& rect)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return;
root().block().flipForWritingMode(rect);
}
FloatPoint InlineBox::flipForWritingMode(const FloatPoint& point)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return point;
return root().block().flipForWritingMode(point);
}
void InlineBox::flipForWritingMode(LayoutRect& rect)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return;
root().block().flipForWritingMode(rect);
}
LayoutPoint InlineBox::flipForWritingMode(const LayoutPoint& point)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return point;
return root().block().flipForWritingMode(point);
}
} // namespace WebCore
#ifndef NDEBUG
void showTree(const WebCore::InlineBox* b)
{
if (b)
b->showTreeForThis();
}
void showLineTree(const WebCore::InlineBox* b)
{
if (b)
b->showLineTreeForThis();
}
#endif
|
/*
* Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/rendering/InlineBox.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RootInlineBox.h"
#include "platform/Partitions.h"
#include "platform/fonts/FontMetrics.h"
#ifndef NDEBUG
#include <stdio.h>
#endif
using namespace std;
namespace WebCore {
struct SameSizeAsInlineBox {
virtual ~SameSizeAsInlineBox() { }
void* a[4];
FloatPoint b;
float c;
uint32_t d : 32;
#ifndef NDEBUG
bool f;
#endif
};
COMPILE_ASSERT(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), InlineBox_size_guard);
#ifndef NDEBUG
InlineBox::~InlineBox()
{
if (!m_hasBadParent && m_parent)
m_parent->setHasBadChildList();
}
#endif
void InlineBox::remove()
{
if (parent())
parent()->removeChild(this);
}
void* InlineBox::operator new(size_t sz)
{
return partitionAlloc(Partitions::getRenderingPartition(), sz);
}
void InlineBox::operator delete(void* ptr)
{
partitionFree(ptr);
}
#ifndef NDEBUG
const char* InlineBox::boxName() const
{
return "InlineBox";
}
void InlineBox::showTreeForThis() const
{
renderer().showTreeForThis();
}
void InlineBox::showLineTreeForThis() const
{
renderer().containingBlock()->showLineTreeAndMark(this, "*");
}
void InlineBox::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj, int depth) const
{
int printedCharacters = 0;
if (this == markedBox1)
printedCharacters += fprintf(stderr, "%s", markedLabel1);
if (this == markedBox2)
printedCharacters += fprintf(stderr, "%s", markedLabel2);
if (&renderer() == obj)
printedCharacters += fprintf(stderr, "*");
for (; printedCharacters < depth * 2; printedCharacters++)
fputc(' ', stderr);
showBox(printedCharacters);
}
void InlineBox::showBox(int printedCharacters) const
{
printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
fputc(' ', stderr);
fprintf(stderr, "\t%s %p {pos=%g,%g size=%g,%g} baseline=%i/%i\n",
renderer().renderName(), &renderer(), x(), y(), width(), height(),
baselinePosition(AlphabeticBaseline),
baselinePosition(IdeographicBaseline));
}
#endif
float InlineBox::logicalHeight() const
{
if (hasVirtualLogicalHeight())
return virtualLogicalHeight();
if (renderer().isText())
return m_bitfields.isText() ? renderer().style(isFirstLineStyle())->fontMetrics().height() : 0;
if (renderer().isBox() && parent())
return isHorizontal() ? toRenderBox(renderer()).height().toFloat() : toRenderBox(renderer()).width().toFloat();
ASSERT(isInlineFlowBox());
RenderBoxModelObject* flowObject = boxModelObject();
const FontMetrics& fontMetrics = renderer().style(isFirstLineStyle())->fontMetrics();
float result = fontMetrics.height();
if (parent())
result += flowObject->borderAndPaddingLogicalHeight();
return result;
}
int InlineBox::baselinePosition(FontBaseline baselineType) const
{
return boxModelObject()->baselinePosition(baselineType, m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
}
LayoutUnit InlineBox::lineHeight() const
{
return boxModelObject()->lineHeight(m_bitfields.firstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
}
int InlineBox::caretMinOffset() const
{
return renderer().caretMinOffset();
}
int InlineBox::caretMaxOffset() const
{
return renderer().caretMaxOffset();
}
void InlineBox::dirtyLineBoxes()
{
markDirty();
for (InlineFlowBox* curr = parent(); curr && !curr->isDirty(); curr = curr->parent())
curr->markDirty();
}
void InlineBox::deleteLine()
{
if (!m_bitfields.extracted() && renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(0);
destroy();
}
void InlineBox::extractLine()
{
m_bitfields.setExtracted(true);
if (renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(0);
}
void InlineBox::attachLine()
{
m_bitfields.setExtracted(false);
if (renderer().isBox())
toRenderBox(renderer()).setInlineBoxWrapper(this);
}
void InlineBox::adjustPosition(float dx, float dy)
{
m_topLeft.move(dx, dy);
if (renderer().isReplaced())
toRenderBox(renderer()).move(dx, dy);
}
void InlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
{
if (!paintInfo.shouldPaintWithinRoot(&renderer()) || (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection))
return;
LayoutPoint childPoint = paintOffset;
if (parent()->renderer().style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock().
childPoint = renderer().containingBlock()->flipForWritingModeForChild(&toRenderBox(renderer()), childPoint);
RenderBlock::paintAsInlineBlock(&renderer(), paintInfo, childPoint);
}
bool InlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
{
// Hit test all phases of replaced elements atomically, as though the replaced element established its
// own stacking context. (See Appendix E.2, section 6.4 on inline block/table elements in the CSS2.1
// specification.)
LayoutPoint childPoint = accumulatedOffset;
if (parent()->renderer().style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock().
childPoint = renderer().containingBlock()->flipForWritingModeForChild(&toRenderBox(renderer()), childPoint);
return renderer().hitTest(request, result, locationInContainer, childPoint);
}
const RootInlineBox& InlineBox::root() const
{
if (m_parent)
return m_parent->root();
ASSERT(isRootInlineBox());
return static_cast<const RootInlineBox&>(*this);
}
RootInlineBox& InlineBox::root()
{
if (m_parent)
return m_parent->root();
ASSERT(isRootInlineBox());
return static_cast<RootInlineBox&>(*this);
}
bool InlineBox::nextOnLineExists() const
{
if (!m_bitfields.determinedIfNextOnLineExists()) {
m_bitfields.setDeterminedIfNextOnLineExists(true);
if (!parent())
m_bitfields.setNextOnLineExists(false);
else if (nextOnLine())
m_bitfields.setNextOnLineExists(true);
else
m_bitfields.setNextOnLineExists(parent()->nextOnLineExists());
}
return m_bitfields.nextOnLineExists();
}
InlineBox* InlineBox::nextLeafChild() const
{
InlineBox* leaf = 0;
for (InlineBox* box = nextOnLine(); box && !leaf; box = box->nextOnLine())
leaf = box->isLeaf() ? box : toInlineFlowBox(box)->firstLeafChild();
if (!leaf && parent())
leaf = parent()->nextLeafChild();
return leaf;
}
InlineBox* InlineBox::prevLeafChild() const
{
InlineBox* leaf = 0;
for (InlineBox* box = prevOnLine(); box && !leaf; box = box->prevOnLine())
leaf = box->isLeaf() ? box : toInlineFlowBox(box)->lastLeafChild();
if (!leaf && parent())
leaf = parent()->prevLeafChild();
return leaf;
}
InlineBox* InlineBox::nextLeafChildIgnoringLineBreak() const
{
InlineBox* leaf = nextLeafChild();
if (leaf && leaf->isLineBreak())
return 0;
return leaf;
}
InlineBox* InlineBox::prevLeafChildIgnoringLineBreak() const
{
InlineBox* leaf = prevLeafChild();
if (leaf && leaf->isLineBreak())
return 0;
return leaf;
}
RenderObject::SelectionState InlineBox::selectionState()
{
return renderer().selectionState();
}
bool InlineBox::canAccommodateEllipsis(bool ltr, int blockEdge, int ellipsisWidth) const
{
// Non-replaced elements can always accommodate an ellipsis.
if (!renderer().isReplaced())
return true;
IntRect boxRect(left(), 0, m_logicalWidth, 10);
IntRect ellipsisRect(ltr ? blockEdge - ellipsisWidth : blockEdge, 0, ellipsisWidth, 10);
return !(boxRect.intersects(ellipsisRect));
}
float InlineBox::placeEllipsisBox(bool, float, float, float, float& truncatedWidth, bool&)
{
// Use -1 to mean "we didn't set the position."
truncatedWidth += logicalWidth();
return -1;
}
void InlineBox::clearKnownToHaveNoOverflow()
{
m_bitfields.setKnownToHaveNoOverflow(false);
if (parent() && parent()->knownToHaveNoOverflow())
parent()->clearKnownToHaveNoOverflow();
}
FloatPoint InlineBox::locationIncludingFlipping()
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return FloatPoint(x(), y());
RenderBlockFlow& block = root().block();
if (block.style()->isHorizontalWritingMode())
return FloatPoint(x(), block.height() - height() - y());
return FloatPoint(block.width() - width() - x(), y());
}
void InlineBox::flipForWritingMode(FloatRect& rect)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return;
root().block().flipForWritingMode(rect);
}
FloatPoint InlineBox::flipForWritingMode(const FloatPoint& point)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return point;
return root().block().flipForWritingMode(point);
}
void InlineBox::flipForWritingMode(LayoutRect& rect)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return;
root().block().flipForWritingMode(rect);
}
LayoutPoint InlineBox::flipForWritingMode(const LayoutPoint& point)
{
if (!renderer().style()->isFlippedBlocksWritingMode())
return point;
return root().block().flipForWritingMode(point);
}
} // namespace WebCore
#ifndef NDEBUG
void showTree(const WebCore::InlineBox* b)
{
if (b)
b->showTreeForThis();
}
void showLineTree(const WebCore::InlineBox* b)
{
if (b)
b->showLineTreeForThis();
}
#endif
|
Add more details to showLineTree() output
|
Add more details to showLineTree() output
Sample of the new output:
InlineFlowBox 0x397ffa898130 RenderInline 0x397ffa840170 {pos=30,13 size=212.271,15} baseline=24/20
[email protected]
BUG=
Review URL: https://codereview.chromium.org/215583003
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@170229 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
|
78e34c601132bf78f218c27ab4329a5ceb6ffea6
|
SurgSim/Devices/DeviceUtilities.cpp
|
SurgSim/Devices/DeviceUtilities.cpp
|
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Devices/DeviceUtilities.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Framework/Log.h"
namespace SurgSim
{
namespace Device
{
std::shared_ptr<Input::DeviceInterface> createDevice(const std::vector<std::string>& classNames,
const std::string& name)
{
std::shared_ptr<Input::DeviceInterface> device;
auto& factory = Input::DeviceInterface::getFactory();
for (const auto& className : classNames)
{
if (factory.isRegistered(className))
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Trying to create a " << className;
device = factory.create(className, name);
if (device->initialize())
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Successfully created a " << className;
break;
}
else
{
device = nullptr;
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Failed to initialize a " << className;
}
}
else
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Cannot create a " << className <<
" because the executable was built without support for that device. To use such a device, enable " <<
"the BUILD_DEVICE_* setting in cmake, and #include either the specific device's header or " <<
"SurgSim/Devices/Devices.h.";
}
}
return device;
}
}; // namespace Device
}; // namespace SurgSim
|
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions 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 "SurgSim/Devices/DeviceUtilities.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Framework/Log.h"
namespace SurgSim
{
namespace Device
{
std::shared_ptr<Input::DeviceInterface> createDevice(const std::vector<std::string>& classNames,
const std::string& name)
{
std::shared_ptr<Input::DeviceInterface> device;
auto& factory = Input::DeviceInterface::getFactory();
for (const auto& className : classNames)
{
if (factory.isRegistered(className))
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Trying to create a " << className;
device = factory.create(className, name);
if (device->initialize())
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Successfully created a " << className;
break;
}
else
{
device = nullptr;
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << "Failed to initialize a " << className;
}
}
else
{
SURGSIM_LOG_INFO(Framework::Logger::getLogger("Devices")) << className <<
" is not registered in the Devices factory.";
}
}
return device;
}
}; // namespace Device
}; // namespace SurgSim
|
Remove ambiguity from DeviceUtilities log message.
|
Remove ambiguity from DeviceUtilities log message.
|
C++
|
apache-2.0
|
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
|
fd2bde02e1cedb4cc3e0b41f6e858ca62a3d0f1b
|
chrome/browser/component_updater/test/component_updater_ping_manager_unittest.cc
|
chrome/browser/component_updater/test/component_updater_ping_manager_unittest.cc
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/version.h"
#include "chrome/browser/component_updater/component_updater_ping_manager.h"
#include "chrome/browser/component_updater/crx_update_item.h"
#include "chrome/browser/component_updater/test/component_updater_service_unittest.h"
#include "chrome/browser/component_updater/test/url_request_post_interceptor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace component_updater {
class ComponentUpdaterPingManagerTest : public testing::Test {
public:
ComponentUpdaterPingManagerTest();
virtual ~ComponentUpdaterPingManagerTest();
void RunThreadsUntilIdle();
// Overrides from testing::Test.
virtual void SetUp() OVERRIDE;
virtual void TearDown() OVERRIDE;
protected:
scoped_ptr<PingManager> ping_manager_;
private:
scoped_refptr<net::TestURLRequestContextGetter> context_;
content::TestBrowserThreadBundle thread_bundle_;
};
ComponentUpdaterPingManagerTest::ComponentUpdaterPingManagerTest()
: context_(new net::TestURLRequestContextGetter(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO))),
thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
}
ComponentUpdaterPingManagerTest::~ComponentUpdaterPingManagerTest() {
context_ = NULL;
}
void ComponentUpdaterPingManagerTest::SetUp() {
ping_manager_.reset(new PingManager(
GURL("http://localhost2/update2"), context_));
}
void ComponentUpdaterPingManagerTest::TearDown() {
ping_manager_.reset();
}
void ComponentUpdaterPingManagerTest::RunThreadsUntilIdle() {
base::RunLoop().RunUntilIdle();
}
TEST_F(ComponentUpdaterPingManagerTest, PingManagerTest) {
scoped_ptr<InterceptorFactory> interceptor_factory(new InterceptorFactory);
URLRequestPostInterceptor* interceptor =
interceptor_factory->CreateInterceptor();
EXPECT_TRUE(interceptor);
// Test eventresult="1" is sent for successful updates.
CrxUpdateItem item;
item.id = "abc";
item.status = CrxUpdateItem::kUpdated;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"1\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test eventresult="0" is sent for failed updates.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kNoUpdate;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"0\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test the error values and the fingerprints.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kNoUpdate;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
item.previous_fp = "prev fp";
item.next_fp = "next fp";
item.error_category = 1;
item.error_code = 2;
item.extra_code1 = -1;
item.diff_error_category = 10;
item.diff_error_code = 20;
item.diff_extra_code1 = -10;
item.diff_update_failed = true;
item.crx_diffurls.push_back(GURL("http://host/path"));
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"0\" errorcat=\"1\" "
"errorcode=\"2\" extracode1=\"-1\" diffresult=\"0\" differrorcat=\"10\" "
"differrorcode=\"20\" diffextracode1=\"-10\" "
"previousfp=\"prev fp\" nextfp=\"next fp\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test the download metrics.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kUpdated;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
CrxDownloader::DownloadMetrics download_metrics;
download_metrics.url = GURL("http://host1/path1");
download_metrics.downloader = CrxDownloader::DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.bytes_downloaded = 123;
download_metrics.bytes_total = 456;
download_metrics.download_time_ms = 987;
item.download_metrics.push_back(download_metrics);
download_metrics = CrxDownloader::DownloadMetrics();
download_metrics.url = GURL("http://host2/path2");
download_metrics.downloader = CrxDownloader::DownloadMetrics::kBits;
download_metrics.error = 0;
download_metrics.bytes_downloaded = 1230;
download_metrics.bytes_total = 4560;
download_metrics.download_time_ms = 9870;
item.download_metrics.push_back(download_metrics);
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"1\"/>"
"<event eventtype=\"14\" eventresult=\"0\" downloader=\"direct\" "
"errorcode=\"-1\" url=\"http://host1/path1\" downloaded=\"123\" "
"total=\"456\" download_time_ms=\"987\"/>"
"<event eventtype=\"14\" eventresult=\"1\" downloader=\"bits\" "
"url=\"http://host2/path2\" downloaded=\"1230\" total=\"4560\" "
"download_time_ms=\"9870\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
}
} // namespace component_updater
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/version.h"
#include "chrome/browser/component_updater/component_updater_ping_manager.h"
#include "chrome/browser/component_updater/crx_update_item.h"
#include "chrome/browser/component_updater/test/component_updater_service_unittest.h"
#include "chrome/browser/component_updater/test/url_request_post_interceptor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace component_updater {
class ComponentUpdaterPingManagerTest : public testing::Test {
public:
ComponentUpdaterPingManagerTest();
virtual ~ComponentUpdaterPingManagerTest();
void RunThreadsUntilIdle();
// Overrides from testing::Test.
virtual void SetUp() OVERRIDE;
virtual void TearDown() OVERRIDE;
protected:
scoped_ptr<PingManager> ping_manager_;
private:
scoped_refptr<net::TestURLRequestContextGetter> context_;
content::TestBrowserThreadBundle thread_bundle_;
};
ComponentUpdaterPingManagerTest::ComponentUpdaterPingManagerTest()
: context_(new net::TestURLRequestContextGetter(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO))),
thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
}
ComponentUpdaterPingManagerTest::~ComponentUpdaterPingManagerTest() {
context_ = NULL;
}
void ComponentUpdaterPingManagerTest::SetUp() {
ping_manager_.reset(new PingManager(
GURL("http://localhost2/update2"), context_));
}
void ComponentUpdaterPingManagerTest::TearDown() {
ping_manager_.reset();
}
void ComponentUpdaterPingManagerTest::RunThreadsUntilIdle() {
base::RunLoop().RunUntilIdle();
}
// Test is flaky: http://crbug.com/349547
TEST_F(ComponentUpdaterPingManagerTest, DISABLED_PingManagerTest) {
scoped_ptr<InterceptorFactory> interceptor_factory(new InterceptorFactory);
URLRequestPostInterceptor* interceptor =
interceptor_factory->CreateInterceptor();
EXPECT_TRUE(interceptor);
// Test eventresult="1" is sent for successful updates.
CrxUpdateItem item;
item.id = "abc";
item.status = CrxUpdateItem::kUpdated;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"1\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test eventresult="0" is sent for failed updates.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kNoUpdate;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"0\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test the error values and the fingerprints.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kNoUpdate;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
item.previous_fp = "prev fp";
item.next_fp = "next fp";
item.error_category = 1;
item.error_code = 2;
item.extra_code1 = -1;
item.diff_error_category = 10;
item.diff_error_code = 20;
item.diff_extra_code1 = -10;
item.diff_update_failed = true;
item.crx_diffurls.push_back(GURL("http://host/path"));
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"0\" errorcat=\"1\" "
"errorcode=\"2\" extracode1=\"-1\" diffresult=\"0\" differrorcat=\"10\" "
"differrorcode=\"20\" diffextracode1=\"-10\" "
"previousfp=\"prev fp\" nextfp=\"next fp\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
// Test the download metrics.
item = CrxUpdateItem();
item.id = "abc";
item.status = CrxUpdateItem::kUpdated;
item.previous_version = base::Version("1.0");
item.next_version = base::Version("2.0");
CrxDownloader::DownloadMetrics download_metrics;
download_metrics.url = GURL("http://host1/path1");
download_metrics.downloader = CrxDownloader::DownloadMetrics::kUrlFetcher;
download_metrics.error = -1;
download_metrics.bytes_downloaded = 123;
download_metrics.bytes_total = 456;
download_metrics.download_time_ms = 987;
item.download_metrics.push_back(download_metrics);
download_metrics = CrxDownloader::DownloadMetrics();
download_metrics.url = GURL("http://host2/path2");
download_metrics.downloader = CrxDownloader::DownloadMetrics::kBits;
download_metrics.error = 0;
download_metrics.bytes_downloaded = 1230;
download_metrics.bytes_total = 4560;
download_metrics.download_time_ms = 9870;
item.download_metrics.push_back(download_metrics);
ping_manager_->OnUpdateComplete(&item);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, interceptor->GetCount()) << interceptor->GetRequestsAsString();
EXPECT_NE(string::npos, interceptor->GetRequests()[0].find(
"<app appid=\"abc\" version=\"1.0\" nextversion=\"2.0\">"
"<event eventtype=\"3\" eventresult=\"1\"/>"
"<event eventtype=\"14\" eventresult=\"0\" downloader=\"direct\" "
"errorcode=\"-1\" url=\"http://host1/path1\" downloaded=\"123\" "
"total=\"456\" download_time_ms=\"987\"/>"
"<event eventtype=\"14\" eventresult=\"1\" downloader=\"bits\" "
"url=\"http://host2/path2\" downloaded=\"1230\" total=\"4560\" "
"download_time_ms=\"9870\"/></app>"))
<< interceptor->GetRequestsAsString();
interceptor->Reset();
}
} // namespace component_updater
|
Disable flaky ComponentUpdaterPingManagerTest.PingManagerTest
|
Disable flaky ComponentUpdaterPingManagerTest.PingManagerTest
[email protected]
BUG=349547
Review URL: https://codereview.chromium.org/177703005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@255115 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
dednal/chromium.src,littlstar/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,ondra-novak/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,ltilve/chromium,Jonekee/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,jaruba/chromium.src,littlstar/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,anirudhSK/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,patrickm/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,anirudhSK/chromium,anirudhSK/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,patrickm/chromium.src,chuan9/chromium-crosswalk,ondra-novak/chromium.src,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,Just-D/chromium-1,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,M4sse/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,dednal/chromium.src,jaruba/chromium.src,patrickm/chromium.src,M4sse/chromium.src,ltilve/chromium,M4sse/chromium.src,markYoungH/chromium.src
|
4c1ae350270d08d8ebdac664ff8210f6d1d1f0a0
|
TASKS/TASK_2/sources/rectMatrix.cpp
|
TASKS/TASK_2/sources/rectMatrix.cpp
|
#include <cstdarg>
#include <iostream>
#include "rectMatrix.h"
#ifdef DEBUG
#define debugMsg(id, msg) std::cout << "Matrix[" << id << "]:" << msg << std::endl;
#else
#define debugMsg(id, msg) ;
#endif
namespace classes {
double& m_proxy::operator [](unsigned int column) {
if (column < colsCount)
return dataRow[column];
else
throw OUT_OF_COLUMNS;
}
unsigned int RectMatrix::idCounter = 0;
RectMatrix::RectMatrix(const RectMatrix& that)
: columns(that.columns), rows(that.rows), id(idCounter++)
{
debugMsg(id, "Copy constructor call.")
unsigned long size = columns*rows;
data = new double[columns*rows];
for(unsigned int i = 0; i < size; i++)
data[i] = that.data[i];
}
RectMatrix::RectMatrix(const m_size& size, ...)
: columns(size.columns), rows(size.rows), id(idCounter++)
{
debugMsg(id, "Custom constructor call.")
if (!columns || !rows)
debugMsg(id, "[WARNING]: null-size matrix!")
va_list args;
va_start(args, size);
unsigned long lenght = columns*rows;
data = new double[lenght];
for (unsigned int i = 0; i < lenght; i++)
data[i] = va_arg(args, double);
va_end(args);
}
RectMatrix::RectMatrix(void)
: columns(0), rows(0), id(idCounter++)
{
debugMsg(id, "Default constructor call.")
debugMsg(id, "[WARNING]: null-size matrix!")
unsigned long lenght = columns*rows;
data = new double[lenght];
data[0] = 0.;
}
RectMatrix::~RectMatrix(void) {
debugMsg(id, "Destructor call.")
delete [] data;
}
m_proxy RectMatrix::operator [](unsigned int row) {
if (row < rows)
return m_proxy(data+(row*columns), columns);
else
throw OUT_OF_ROWS;
}
double& RectMatrix::operator ()(unsigned int row, unsigned int column) {
if (row < rows) {
if (column < columns)
return data[row*columns+column];
else
throw OUT_OF_COLUMNS;
} else
throw OUT_OF_ROWS;
}
void RectMatrix::operator =(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] = that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator +=(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] += that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator -=(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] -= that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator *=(const RectMatrix& that) {
if(isMultiplyValid(that)) {
double* temp = new double[that.columns*rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < that.columns; j++)
for (int r = 0; r < columns; r++)
temp[i*that.columns + j] += data[i*columns + r]*that.data[r*that.columns + j];
delete [] data;
columns = that.columns;
data = temp;
} else
throw NOT_VALID_MUL;
}
void RectMatrix::operator *=(double scalar) {
for (int i = 0; i < columns*rows; i++)
data[i] *= scalar;
}
bool RectMatrix::isAddValid(const RectMatrix& that) const {
return columns == that.columns && rows == that.rows;
}
bool RectMatrix::isMultiplyValid(const RectMatrix& that) const {
return columns == that.rows;
}
}
int main() {
classes::m_size size(2, 3);
classes::RectMatrix m(size,
2., 3., 4.,
9., 8., 5.
);
classes::m_size size1(3, 1);
classes::RectMatrix m1(size1,
1.,
1.,
1.
);
classes::m_size size2(0, 1);
classes::RectMatrix m2(size2);
std::cout << m.isAddValid(m1) << std::endl;
std::cout << m.isMultiplyValid(m1) << std::endl;
for (int i = 0; i < size.rows; i++) {
for (int j = 0; j < size.columns; j++) {
try {
std::cout << (int)(m[i][j]) << " ";
} catch (classes::ERROR_CODE err) {
switch(err) {
case classes::OUT_OF_ROWS:
std::cout << " [OOR] ";
break;
case classes::OUT_OF_COLUMNS:
std::cout << " [OOC] ";
break;
default:
std::cout << " [OOF] ";
}
}
}
std::cout << std::endl;
}
std::cout << std::endl;
m *= m1;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 1; j++) {
std::cout << (int)m(i, j) << " ";
}
std::cout << std::endl;
}
}
|
#include <cstdarg>
#include <iostream>
#include <iomanip>
#include "rectMatrix.h"
#ifdef DEBUG
#define debugMsg(id, msg) std::cout << "Matrix[" << id << "]:" << msg << std::endl;
#else
#define debugMsg(id, msg) ;
#endif
namespace classes {
double& m_proxy::operator [](unsigned int column) {
if (column < colsCount)
return dataRow[column];
else
throw OUT_OF_COLUMNS;
}
unsigned int RectMatrix::idCounter = 0;
RectMatrix::RectMatrix(const RectMatrix& that)
: columns(that.columns), rows(that.rows), id(idCounter++)
{
debugMsg(id, "Copy constructor call.")
unsigned long size = columns*rows;
data = new double[columns*rows];
for(unsigned int i = 0; i < size; i++)
data[i] = that.data[i];
}
RectMatrix::RectMatrix(const m_size& size, ...)
: columns(size.columns), rows(size.rows), id(idCounter++)
{
debugMsg(id, "Custom constructor call.")
if (!columns || !rows)
debugMsg(id, "[WARNING]: null-size matrix!")
va_list args;
va_start(args, size);
unsigned long lenght = columns*rows;
data = new double[lenght];
for (unsigned int i = 0; i < lenght; i++)
data[i] = va_arg(args, double);
va_end(args);
}
RectMatrix::RectMatrix(void)
: columns(0), rows(0), id(idCounter++)
{
debugMsg(id, "Default constructor call.")
debugMsg(id, "[WARNING]: null-size matrix!")
unsigned long lenght = columns*rows;
data = new double[lenght];
data[0] = 0.;
}
RectMatrix::~RectMatrix(void) {
debugMsg(id, "Destructor call.")
delete [] data;
}
m_proxy RectMatrix::operator [](unsigned int row) {
if (row < rows)
return m_proxy(data+(row*columns), columns);
else
throw OUT_OF_ROWS;
}
double& RectMatrix::operator ()(unsigned int row, unsigned int column) {
if (row < rows) {
if (column < columns)
return data[row*columns+column];
else
throw OUT_OF_COLUMNS;
} else
throw OUT_OF_ROWS;
}
void RectMatrix::operator =(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] = that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator +=(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] += that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator -=(const RectMatrix& that) {
if(isAddValid(that))
for (int i = 0; i < columns*rows; i++)
data[i] -= that.data[i];
else
throw NOT_VALID_ADD;
}
void RectMatrix::operator *=(const RectMatrix& that) {
if(isMultiplyValid(that)) {
double* temp = new double[that.columns*rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < that.columns; j++)
for (int r = 0; r < columns; r++)
temp[i*that.columns + j] += data[i*columns + r]*that.data[r*that.columns + j];
delete [] data;
columns = that.columns;
data = temp;
} else
throw NOT_VALID_MUL;
}
void RectMatrix::operator *=(double scalar) {
for (int i = 0; i < columns*rows; i++)
data[i] *= scalar;
}
bool RectMatrix::isAddValid(const RectMatrix& that) const {
return columns == that.columns && rows == that.rows;
}
bool RectMatrix::isMultiplyValid(const RectMatrix& that) const {
return columns == that.rows;
}
double RectMatrix::getMax() const {
double max = data[0];
unsigned int size = columns*rows;
for (int i = 0; i < size; i++)
if (data[i] > max) max = data[i];
return max;
}
double RectMatrix::getMin() const {
double min = data[0];
unsigned int size = columns*rows;
for (int i = 0; i < size; i++)
if (data[i] < min) min = data[i];
return min;
}
void RectMatrix::print() const {
std::cout << "Matrix[" << id << "]:" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
std::cout << std::setw(6) << std::setprecision(3) << std::right << data[i*columns + j] << std::right << ' ';
}
std::cout << std::endl;
}
}
RectMatrix rectMatrixManip::operator +(const RectMatrix& left, const RectMatrix& right) {
RectMatrix result(left);
result += right;
return RectMatrix(result);
}
RectMatrix rectMatrixManip::operator -(const RectMatrix& left, const RectMatrix& right) {
RectMatrix result(left);
result -= right;
return RectMatrix(result);
}
RectMatrix rectMatrixManip::operator *(const RectMatrix& left, const RectMatrix& right) {
RectMatrix result(left);
result *= right;
return RectMatrix(result);
}
RectMatrix rectMatrixManip::operator *(const double scalar, const RectMatrix& origin) {
RectMatrix result(origin);
result *= scalar;
return RectMatrix(result);
}
}
|
Implement non class member operators and print
|
Implement non class member operators and print
|
C++
|
mit
|
reeFridge/learn-oop-through-cpp
|
301cc63204f67ba1f62bf511a5291deda23de8d5
|
tensorflow/compiler/mlir/tensorflow/transforms/tpu_outside_compilation_cluster.cc
|
tensorflow/compiler/mlir/tensorflow/transforms/tpu_outside_compilation_cluster.cc
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/IR/Types.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/analysis/side_effect_analysis.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TFTPU {
namespace {
constexpr char kXlaOutsideCompilationAttr[] = "_xla_outside_compilation";
struct TPUOutsideCompilationCluster
: public TF::PerFunctionAggregateAnalysisConsumerPass<
TPUOutsideCompilationCluster, TF::SideEffectAnalysis> {
void runOnFunction(FuncOp func,
const TF::SideEffectAnalysis::Info& side_effect_analysis);
};
bool IsVariant(Value value) {
return getElementTypeOrSelf(value.getType()).isa<TF::VariantType>();
}
bool HasOutsideCompiledAncestor(Operation* op) {
Operation* parent = op->getParentOp();
while (parent) {
if (parent->getAttrOfType<StringAttr>(kXlaOutsideCompilationAttr))
return true;
parent = parent->getParentOp();
}
return false;
}
// Represents an outside compiled cluster. All ops that are added to the same
// cluster will be extracted together in a later pass.
class OutsideCompiledCluster {
public:
explicit OutsideCompiledCluster(int number)
: cluster_name_(llvm::formatv("cluster{0}", number).str()) {}
// Attempts to add an op to this cluster. Ops can be grouped to the same
// cluster if they have data dependency and are inside the same block.
bool AddOp(Operation* op,
const TF::SideEffectAnalysis::Info& side_effect_analysis) {
// Check if the op is safe to add before adding it.
if (IsSafeToAdd(op, side_effect_analysis)) {
op->setAttr(kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_, op->getContext()));
host_cluster_ops_.insert(op);
return true;
}
return false;
}
// If any tf.variants are inputs/outputs to the cluster, add them to the
// cluster unless they are already marks with outside compilation attribute.
bool AddVariantInputsOutputs() {
bool added_op = false;
llvm::SmallPtrSet<Operation*, 8> expanded_cluster_ops(host_cluster_ops_);
for (Operation* cluster_op : host_cluster_ops_) {
// Walk the clustered operations to handle nested ops.
cluster_op->walk([&](Operation* op) {
// Add any operations that provide variant inputs to the cluster.
for (auto value : op->getOperands()) {
auto input_defining_op = value.getDefiningOp();
if (IsVariant(value) && input_defining_op &&
!HasOutsideCompiledAncestor(input_defining_op) &&
!input_defining_op->getAttrOfType<StringAttr>(
kXlaOutsideCompilationAttr)) {
expanded_cluster_ops.insert(input_defining_op);
input_defining_op->setAttr(
kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_,
input_defining_op->getContext()));
added_op = true;
}
}
// Add any operations that consume variant outputs to the cluster.
for (auto value : op->getResults()) {
if (IsVariant(value)) {
for (auto user : value.getUsers()) {
if (!host_cluster_ops_.contains(user) &&
!HasOutsideCompiledAncestor(user) &&
!user->getAttrOfType<StringAttr>(
kXlaOutsideCompilationAttr)) {
expanded_cluster_ops.insert(user);
user->setAttr(
kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_, user->getContext()));
added_op = true;
}
}
}
}
});
}
host_cluster_ops_.swap(expanded_cluster_ops);
return added_op;
}
private:
// Checks if it is safe for `op` to be merged into this cluster.
bool IsSafeToAdd(Operation* op,
const TF::SideEffectAnalysis::Info& side_effect_analysis) {
if (host_cluster_ops_.empty()) return true;
// If there is an intermediate data or side effect dependency between the op
// and ops in the cluster, it's not safe to add.
llvm::SmallSetVector<Operation*, 4> op_stack;
// Materialize data dependencies as the llvm::concat doesn't support
// non-materialized iteration.
auto data_deps = llvm::to_vector<4>(op->getUsers());
llvm::SmallVector<Operation*, 4> control_deps =
side_effect_analysis.DirectControlSuccessors(op);
for (auto* dep : llvm::concat<Operation*>(data_deps, control_deps)) {
if (!host_cluster_ops_.contains(dep)) op_stack.insert(dep);
}
while (!op_stack.empty()) {
auto* next_op = op_stack.pop_back_val();
auto data_deps = llvm::to_vector<4>(next_op->getUsers());
llvm::SmallVector<Operation*, 4> control_deps =
side_effect_analysis.DirectControlSuccessors(next_op);
for (auto* dep : llvm::concat<Operation*>(data_deps, control_deps)) {
if (host_cluster_ops_.contains(dep)) return false;
op_stack.insert(dep);
}
}
return true;
}
// `host_cluster_op_` stores a set of ops that will be grouped and computed
// on host as single XlaHostCompute op. An outside compiled op can be grouped
// to a single cluster if it has data dependency to another op already in the
// cluster.
llvm::SmallPtrSet<Operation*, 8> host_cluster_ops_;
std::string cluster_name_;
};
void TPUOutsideCompilationCluster::runOnFunction(
FuncOp func, const TF::SideEffectAnalysis::Info& side_effect_analysis) {
llvm::SmallVector<OutsideCompiledCluster, 8> clusters;
int cluster_counter = 0;
func.walk([&](tf_device::ClusterOp tpu_cluster) {
llvm::SmallVector<Operation*, 4> outside_ops;
tpu_cluster.walk([&](Operation* op) {
if (op->getAttrOfType<StringAttr>(kXlaOutsideCompilationAttr))
outside_ops.emplace_back(op);
});
// In order to cluster ops feeding results to the same operation, traverse
// the ops in reverse order.
for (Operation* op : llvm::reverse(outside_ops)) {
// Try to add the op to existing clusters.
bool added = false;
for (auto& cluster : clusters)
if ((added = cluster.AddOp(op, side_effect_analysis))) break;
// If the op cannot be added to existing clusters, create a new cluster.
if (!added) {
OutsideCompiledCluster new_cluster(cluster_counter++);
new_cluster.AddOp(op, side_effect_analysis);
clusters.push_back(new_cluster);
}
}
});
for (auto& cluster : clusters) {
bool variants_to_add = true;
while (variants_to_add) variants_to_add = cluster.AddVariantInputsOutputs();
}
}
} // anonymous namespace
std::unique_ptr<OperationPass<ModuleOp>>
CreateTPUOutsideCompilationClusterPass() {
return std::make_unique<TPUOutsideCompilationCluster>();
}
static PassRegistration<TPUOutsideCompilationCluster> pass(
"tf-tpu-outside-compilation-cluster",
"Identifies clusters of operations assigned to outside compilation");
} // namespace TFTPU
} // namespace mlir
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/IR/Types.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/analysis/side_effect_analysis.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TFTPU {
namespace {
constexpr char kXlaOutsideCompilationAttr[] = "_xla_outside_compilation";
struct TPUOutsideCompilationCluster
: public TF::PerFunctionAggregateAnalysisConsumerPass<
TPUOutsideCompilationCluster, TF::SideEffectAnalysis> {
void runOnFunction(FuncOp func,
const TF::SideEffectAnalysis::Info& side_effect_analysis);
};
bool IsVariant(Value value) {
return getElementTypeOrSelf(value.getType()).isa<TF::VariantType>();
}
bool HasOutsideCompiledAncestor(Operation* op) {
Operation* parent = op->getParentOp();
while (parent) {
if (parent->getAttrOfType<StringAttr>(kXlaOutsideCompilationAttr))
return true;
parent = parent->getParentOp();
}
return false;
}
// Represents an outside compiled cluster. All ops that are added to the same
// cluster will be extracted together in a later pass.
class OutsideCompiledCluster {
public:
explicit OutsideCompiledCluster(int number)
: cluster_name_(llvm::formatv("cluster{0}", number).str()) {}
// Attempts to add an op to this cluster. Ops can be grouped to the same
// cluster if they have data dependency and are inside the same block.
bool AddOp(Operation* op,
const TF::SideEffectAnalysis::Info& side_effect_analysis) {
// Check if the op is safe to add before adding it.
if (IsSafeToAdd(op, side_effect_analysis)) {
op->setAttr(kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_, op->getContext()));
host_cluster_ops_.insert(op);
return true;
}
return false;
}
// If any tf.variants are inputs/outputs to the cluster, add them to the
// cluster unless they are already marks with outside compilation attribute.
bool AddVariantInputsOutputs() {
bool added_op = false;
llvm::SmallPtrSet<Operation*, 8> expanded_cluster_ops(host_cluster_ops_);
for (Operation* cluster_op : host_cluster_ops_) {
// Walk the clustered operations to handle nested ops.
cluster_op->walk([&](Operation* op) {
// Add any operations that provide variant inputs to the cluster.
for (auto value : op->getOperands()) {
auto input_defining_op = value.getDefiningOp();
if (IsVariant(value) && input_defining_op &&
!HasOutsideCompiledAncestor(input_defining_op) &&
!input_defining_op->getAttrOfType<StringAttr>(
kXlaOutsideCompilationAttr)) {
expanded_cluster_ops.insert(input_defining_op);
input_defining_op->setAttr(
kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_,
input_defining_op->getContext()));
added_op = true;
}
}
// Add any operations that consume variant outputs to the cluster.
for (auto value : op->getResults()) {
if (IsVariant(value)) {
for (auto user : value.getUsers()) {
if (!host_cluster_ops_.contains(user) &&
!HasOutsideCompiledAncestor(user) &&
!user->getAttrOfType<StringAttr>(
kXlaOutsideCompilationAttr)) {
expanded_cluster_ops.insert(user);
user->setAttr(
kXlaOutsideCompilationAttr,
StringAttr::get(cluster_name_, user->getContext()));
added_op = true;
}
}
}
}
});
}
host_cluster_ops_.swap(expanded_cluster_ops);
return added_op;
}
private:
// TODO(hinsu): Consider using GraphCycles data structure available in xla
// directory to avoid potentially full traversal for each new op and cluster
// pair.
// Checks if it is safe for `op` to be merged into this cluster.
bool IsSafeToAdd(Operation* op,
const TF::SideEffectAnalysis::Info& side_effect_analysis) {
if (host_cluster_ops_.empty()) return true;
// If there is an intermediate data or side effect dependency between the op
// and ops in the cluster, it's not safe to add.
std::vector<Operation*> dependencies;
// Materialize data dependencies as the llvm::concat doesn't support
// non-materialized iteration.
auto data_deps = llvm::to_vector<4>(op->getUsers());
llvm::SmallVector<Operation*, 4> control_deps =
side_effect_analysis.DirectControlSuccessors(op);
for (auto* dep : llvm::concat<Operation*>(data_deps, control_deps)) {
if (!host_cluster_ops_.contains(dep)) dependencies.push_back(dep);
}
llvm::SmallPtrSet<Operation*, 4> visited;
while (!dependencies.empty()) {
Operation* next_op = dependencies.back();
dependencies.pop_back();
if (visited.count(next_op)) continue;
visited.insert(next_op);
auto data_deps = llvm::to_vector<4>(next_op->getUsers());
llvm::SmallVector<Operation*, 4> control_deps =
side_effect_analysis.DirectControlSuccessors(next_op);
for (auto* dep : llvm::concat<Operation*>(data_deps, control_deps)) {
if (host_cluster_ops_.contains(dep)) return false;
dependencies.push_back(dep);
}
}
return true;
}
// `host_cluster_op_` stores a set of ops that will be grouped and computed
// on host as single XlaHostCompute op. An outside compiled op can be grouped
// to a single cluster if it has data dependency to another op already in the
// cluster.
llvm::SmallPtrSet<Operation*, 8> host_cluster_ops_;
std::string cluster_name_;
};
void TPUOutsideCompilationCluster::runOnFunction(
FuncOp func, const TF::SideEffectAnalysis::Info& side_effect_analysis) {
llvm::SmallVector<OutsideCompiledCluster, 8> clusters;
int cluster_counter = 0;
func.walk([&](tf_device::ClusterOp tpu_cluster) {
llvm::SmallVector<Operation*, 4> outside_ops;
tpu_cluster.walk([&](Operation* op) {
if (op->getAttrOfType<StringAttr>(kXlaOutsideCompilationAttr))
outside_ops.emplace_back(op);
});
// In order to cluster ops feeding results to the same operation, traverse
// the ops in reverse order.
for (Operation* op : llvm::reverse(outside_ops)) {
// Try to add the op to existing clusters.
bool added = false;
for (auto& cluster : clusters)
if ((added = cluster.AddOp(op, side_effect_analysis))) break;
// If the op cannot be added to existing clusters, create a new cluster.
if (!added) {
OutsideCompiledCluster new_cluster(cluster_counter++);
new_cluster.AddOp(op, side_effect_analysis);
clusters.push_back(new_cluster);
}
}
});
for (auto& cluster : clusters) {
bool variants_to_add = true;
while (variants_to_add) variants_to_add = cluster.AddVariantInputsOutputs();
}
}
} // anonymous namespace
std::unique_ptr<OperationPass<ModuleOp>>
CreateTPUOutsideCompilationClusterPass() {
return std::make_unique<TPUOutsideCompilationCluster>();
}
static PassRegistration<TPUOutsideCompilationCluster> pass(
"tf-tpu-outside-compilation-cluster",
"Identifies clusters of operations assigned to outside compilation");
} // namespace TFTPU
} // namespace mlir
|
Speed up tf-tpu-outside-compilation-cluster pass by not processing dependent ops multiple times
|
Speed up tf-tpu-outside-compilation-cluster pass by not processing dependent ops multiple times
Currently, this uses stack to maintain the op worklist using SetVector which will cause some ops to be visited multiple times as the ops are not necessarily popped in the topological order. This will have exponential complexity.
Visited ops are now tracked exclusively to make it linear time. Added a TODO to use GraphCycle data structure that should help further improve the performance.
PiperOrigin-RevId: 347715110
Change-Id: Iba936427f2a7b8e3552dc8ae72e24b947201d496
|
C++
|
apache-2.0
|
cxxgtxy/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,cxxgtxy/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,annarev/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,yongtang/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,annarev/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,petewarden/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,karllessard/tensorflow,annarev/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,gautam1858/tensorflow,annarev/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,annarev/tensorflow,petewarden/tensorflow,sarvex/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,gautam1858/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,yongtang/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,karllessard/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred
|
29e8c3529787c78b24da680744524e2c9f3ae83d
|
examples/undocumented/libshogun/evaluation_cross_validation_mkl_weight_storage.cpp
|
examples/undocumented/libshogun/evaluation_cross_validation_mkl_weight_storage.cpp
|
/*
* 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.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/base/init.h>
#include <shogun/classifier/mkl/MKLClassification.h>
#include <shogun/classifier/svm/LibSVM.h>
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/evaluation/CrossValidation.h>
#include <shogun/evaluation/StratifiedCrossValidationSplitting.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/lib/parameter_observers/ParameterObserverCV.h>
#include <shogun/mathematics/Statistics.h>
using namespace shogun;
void gen_rand_data(SGVector<float64_t> lab, SGMatrix<float64_t> feat,
float64_t dist)
{
index_t dims=feat.num_rows;
index_t num=lab.vlen;
for (int32_t i=0; i<num; i++)
{
if (i<num/2)
{
lab[i]=-1.0;
for (int32_t j=0; j<dims; j++)
feat(j, i)=CMath::random(0.0, 1.0)+dist;
}
else
{
lab[i]=1.0;
for (int32_t j=0; j<dims; j++)
feat(j, i)=CMath::random(0.0, 1.0)-dist;
}
}
lab.display_vector("lab");
feat.display_matrix("feat");
}
SGMatrix<float64_t> calculate_weights(ParameterObserverCV& obs)
{
SGMatrix<float64_t> weights;
for (auto o : obs.get_observations())
{
for (auto fold : o->get_folds_results())
{
CMKLClassification* machine =
(CMKLClassification*)fold->get_trained_machine();
SG_REF(machine)
CCombinedKernel* k = (CCombinedKernel*)machine->get_kernel();
auto w = k->get_subkernel_weights();
/* Allocate memory needed */
if (!weights.matrix)
{
weights = SGMatrix<float64_t>(
w.vlen, o->get_num_folds() * o->get_num_runs());
}
/* Copy the weights inside the matrix */
index_t run_shift =
fold->get_current_run_index() * w.vlen * o->get_num_folds();
index_t fold_shift = fold->get_current_fold_index() * w.vlen;
sg_memcpy(
&weights.matrix[run_shift + fold_shift], w.vector,
w.vlen * sizeof(float64_t));
SG_UNREF(k)
SG_UNREF(machine)
}
}
return weights;
}
void test_mkl_cross_validation()
{
/* generate random data */
index_t num=10;
index_t dims=2;
float64_t dist=0.5;
SGVector<float64_t> lab(num);
SGMatrix<float64_t> feat(dims, num);
gen_rand_data(lab, feat, dist);
/*create train labels */
CLabels* labels=new CBinaryLabels(lab);
/* create train features */
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>();
features->set_feature_matrix(feat);
SG_REF(features);
/* create combined features */
CCombinedFeatures* comb_features=new CCombinedFeatures();
comb_features->append_feature_obj(features);
comb_features->append_feature_obj(features);
comb_features->append_feature_obj(features);
SG_REF(comb_features);
/* create multiple gaussian kernels */
CCombinedKernel* kernel=new CCombinedKernel();
kernel->append_kernel(new CGaussianKernel(10, 0.1));
kernel->append_kernel(new CGaussianKernel(10, 1));
kernel->append_kernel(new CGaussianKernel(10, 2));
kernel->init(comb_features, comb_features);
SG_REF(kernel);
/* create mkl using libsvm, due to a mem-bug, interleaved is not possible */
CMKLClassification* svm=new CMKLClassification(new CLibSVM());
svm->set_interleaved_optimization_enabled(false);
svm->set_kernel(kernel);
SG_REF(svm);
/* create cross-validation instance */
index_t num_folds=3;
CSplittingStrategy* split=new CStratifiedCrossValidationSplitting(labels,
num_folds);
CEvaluation* eval=new CContingencyTableEvaluation(ACCURACY);
CCrossValidation* cross=new CCrossValidation(svm, comb_features, labels, split, eval, false);
/* add print output listener and mkl storage listener */
ParameterObserverCV mkl_obs{true};
cross->subscribe_to_parameters(&mkl_obs);
/* perform cross-validation, this will print loads of information */
CEvaluationResult* result=cross->evaluate();
/* print mkl weights */
auto weights = calculate_weights(mkl_obs);
weights.display_matrix("mkl weights");
/* print mean and variance of each kernel weight. These could for example
* been used to compute confidence intervals */
CStatistics::matrix_mean(weights, false).display_vector("mean per kernel");
CStatistics::matrix_variance(weights, false).display_vector("variance per kernel");
CStatistics::matrix_std_deviation(weights, false).display_vector("std-dev per kernel");
/* Clear */
mkl_obs.clear();
SG_UNREF(result);
/* again for two runs */
cross->set_num_runs(2);
result=cross->evaluate();
/* print mkl weights */
SGMatrix<float64_t> weights_2 = calculate_weights(mkl_obs);
weights_2.display_matrix("mkl weights");
/* print mean and variance of each kernel weight. These could for example
* been used to compute confidence intervals */
CStatistics::matrix_mean(weights_2, false)
.display_vector("mean per kernel");
CStatistics::matrix_variance(weights_2, false)
.display_vector("variance per kernel");
CStatistics::matrix_std_deviation(weights_2, false)
.display_vector("std-dev per kernel");
/* clean up */
SG_UNREF(result);
SG_UNREF(cross);
SG_UNREF(kernel);
SG_UNREF(features);
SG_UNREF(comb_features);
SG_UNREF(svm);
}
int main()
{
init_shogun_with_defaults();
// sg_io->set_loglevel(MSG_DEBUG);
test_mkl_cross_validation();
exit_shogun();
return 0;
}
|
/*
* 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.
*
* Written (W) 2012 Heiko Strathmann
*/
#include <shogun/base/init.h>
#include <shogun/classifier/mkl/MKLClassification.h>
#include <shogun/classifier/svm/LibSVM.h>
#include <shogun/evaluation/ContingencyTableEvaluation.h>
#include <shogun/evaluation/CrossValidation.h>
#include <shogun/evaluation/StratifiedCrossValidationSplitting.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/CombinedKernel.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/labels/BinaryLabels.h>
#include <shogun/lib/parameter_observers/ParameterObserverCV.h>
#include <shogun/mathematics/Statistics.h>
using namespace shogun;
void gen_rand_data(SGVector<float64_t> lab, SGMatrix<float64_t> feat,
float64_t dist)
{
index_t dims=feat.num_rows;
index_t num=lab.vlen;
for (int32_t i=0; i<num; i++)
{
if (i<num/2)
{
lab[i]=-1.0;
for (int32_t j=0; j<dims; j++)
feat(j, i)=CMath::random(0.0, 1.0)+dist;
}
else
{
lab[i]=1.0;
for (int32_t j=0; j<dims; j++)
feat(j, i)=CMath::random(0.0, 1.0)-dist;
}
}
lab.display_vector("lab");
feat.display_matrix("feat");
}
SGMatrix<float64_t> calculate_weights(ParameterObserverCV& obs, int32_t folds, int32_t run, int32_t len)
{
int32_t column = 0;
SGMatrix<float64_t> weights(len, folds*run);
for (auto o : obs.get_observations())
{
for (auto fold : o->get_folds_results())
{
CMKLClassification* machine =
(CMKLClassification*)fold->get_trained_machine();
SG_REF(machine)
CCombinedKernel* k = (CCombinedKernel*)machine->get_kernel();
auto w = k->get_subkernel_weights();
/* Copy the weights inside the matrix */
/* Each of the columns will represent a set of weights */
for (int i=0; i<w.size(); i++)
{
weights.set_element(w[i], i, column);
}
SG_UNREF(k)
SG_UNREF(machine)
column++;
}
}
return weights;
}
void test_mkl_cross_validation()
{
/* generate random data */
index_t num=10;
index_t dims=2;
float64_t dist=0.5;
SGVector<float64_t> lab(num);
SGMatrix<float64_t> feat(dims, num);
gen_rand_data(lab, feat, dist);
/*create train labels */
CLabels* labels=new CBinaryLabels(lab);
/* create train features */
CDenseFeatures<float64_t>* features=new CDenseFeatures<float64_t>();
features->set_feature_matrix(feat);
SG_REF(features);
/* create combined features */
CCombinedFeatures* comb_features=new CCombinedFeatures();
comb_features->append_feature_obj(features);
comb_features->append_feature_obj(features);
comb_features->append_feature_obj(features);
SG_REF(comb_features);
/* create multiple gaussian kernels */
CCombinedKernel* kernel=new CCombinedKernel();
kernel->append_kernel(new CGaussianKernel(10, 0.1));
kernel->append_kernel(new CGaussianKernel(10, 1));
kernel->append_kernel(new CGaussianKernel(10, 2));
kernel->init(comb_features, comb_features);
SG_REF(kernel);
/* create mkl using libsvm, due to a mem-bug, interleaved is not possible */
CMKLClassification* svm=new CMKLClassification(new CLibSVM());
svm->set_interleaved_optimization_enabled(false);
svm->set_kernel(kernel);
SG_REF(svm);
/* create cross-validation instance */
index_t num_folds=3;
CSplittingStrategy* split=new CStratifiedCrossValidationSplitting(labels,
num_folds);
CEvaluation* eval=new CContingencyTableEvaluation(ACCURACY);
CCrossValidation* cross=new CCrossValidation(svm, comb_features, labels, split, eval, false);
/* add print output listener and mkl storage listener */
ParameterObserverCV mkl_obs{true};
cross->subscribe_to_parameters(&mkl_obs);
/* perform cross-validation, this will print loads of information */
CEvaluationResult* result=cross->evaluate();
/* print mkl weights */
auto weights = calculate_weights(mkl_obs, num_folds, 1, 3);
weights.display_matrix("mkl weights");
/* print mean and variance of each kernel weight. These could for example
* been used to compute confidence intervals */
CStatistics::matrix_mean(weights, false).display_vector("mean per kernel");
CStatistics::matrix_variance(weights, false).display_vector("variance per kernel");
CStatistics::matrix_std_deviation(weights, false).display_vector("std-dev per kernel");
/* Clear */
mkl_obs.clear();
SG_UNREF(result);
/* again for two runs */
cross->set_num_runs(2);
result=cross->evaluate();
/* print mkl weights */
SGMatrix<float64_t> weights_2 = calculate_weights(mkl_obs, num_folds, 2, 3);
weights_2.display_matrix("mkl weights");
/* print mean and variance of each kernel weight. These could for example
* been used to compute confidence intervals */
CStatistics::matrix_mean(weights_2, false)
.display_vector("mean per kernel");
CStatistics::matrix_variance(weights_2, false)
.display_vector("variance per kernel");
CStatistics::matrix_std_deviation(weights_2, false)
.display_vector("std-dev per kernel");
/* clean up */
SG_UNREF(result);
SG_UNREF(cross);
SG_UNREF(kernel);
SG_UNREF(features);
SG_UNREF(comb_features);
SG_UNREF(svm);
}
int main()
{
init_shogun_with_defaults();
// sg_io->set_loglevel(MSG_DEBUG);
test_mkl_cross_validation();
exit_shogun();
return 0;
}
|
Update undocumented meta example on cross validation (MKL).
|
[ParameterObservers] Update undocumented meta example on cross validation (MKL).
|
C++
|
bsd-3-clause
|
besser82/shogun,sorig/shogun,geektoni/shogun,besser82/shogun,sorig/shogun,lisitsyn/shogun,shogun-toolbox/shogun,sorig/shogun,karlnapf/shogun,besser82/shogun,karlnapf/shogun,karlnapf/shogun,lambday/shogun,lisitsyn/shogun,lambday/shogun,geektoni/shogun,shogun-toolbox/shogun,lisitsyn/shogun,shogun-toolbox/shogun,shogun-toolbox/shogun,besser82/shogun,geektoni/shogun,karlnapf/shogun,shogun-toolbox/shogun,lambday/shogun,geektoni/shogun,lambday/shogun,lisitsyn/shogun,besser82/shogun,lisitsyn/shogun,sorig/shogun,lisitsyn/shogun,sorig/shogun,lambday/shogun,geektoni/shogun,shogun-toolbox/shogun,geektoni/shogun,lambday/shogun,karlnapf/shogun,karlnapf/shogun,besser82/shogun,sorig/shogun
|
cd3f29c1bb0f3460c06226d4a22d1c94387be95d
|
lib/node_modules/@stdlib/math/base/special/powm1/benchmark/cpp/benchmark.boost.cpp
|
lib/node_modules/@stdlib/math/base/special/powm1/benchmark/cpp/benchmark.boost.cpp
|
/**
* Benchmark Boost `powm1`.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/math/special_functions/powm1.hpp>
using boost::random::uniform_real_distribution;
using boost::random::mt19937;
#define NAME "powm1"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
double elapsed;
double x;
double y;
double z;
double t;
int i;
// Define a new pseudorandom number generator:
mt19937 rng;
// Define a uniform distribution for generating pseudorandom numbers as "doubles" between a minimum value (inclusive) and a maximum value (exclusive):
uniform_real_distribution<> randu1( 0.0, 2.0 );
uniform_real_distribution<> randu2( -50.0, 50.0 );
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
x = randu1( rng );
y = randu2( rng );
z = boost::math::powm1( x, y );
if ( y != y ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( z != z ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# cpp::boost::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
return 0;
}
|
/**
* Benchmark Boost `powm1`.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/math/special_functions/powm1.hpp>
using boost::random::uniform_real_distribution;
using boost::random::mt19937;
#define NAME "powm1"
#define ITERATIONS 1000000
#define REPEATS 3
/**
* Prints the TAP version.
*/
void print_version() {
printf( "TAP version 13\n" );
}
/**
* Prints the TAP summary.
*
* @param total total number of tests
* @param passing total number of passing tests
*/
void print_summary( int total, int passing ) {
printf( "#\n" );
printf( "1..%d\n", total ); // TAP plan
printf( "# total %d\n", total );
printf( "# pass %d\n", passing );
printf( "#\n" );
printf( "# ok\n" );
}
/**
* Prints benchmarks results.
*
* @param elapsed elapsed time in seconds
*/
void print_results( double elapsed ) {
double rate = (double)ITERATIONS / elapsed;
printf( " ---\n" );
printf( " iterations: %d\n", ITERATIONS );
printf( " elapsed: %0.9f\n", elapsed );
printf( " rate: %0.9f\n", rate );
printf( " ...\n" );
}
/**
* Returns a clock time.
*
* @return clock time
*/
double tic() {
struct timeval now;
gettimeofday( &now, NULL );
return (double)now.tv_sec + (double)now.tv_usec/1.0e6;
}
/**
* Runs a benchmark.
*
* @return elapsed time in seconds
*/
double benchmark() {
double elapsed;
double x;
double y;
double z;
double t;
int i;
// Define a new pseudorandom number generator:
mt19937 rng;
// Define a uniform distribution for generating pseudorandom numbers as "doubles" between a minimum value (inclusive) and a maximum value (exclusive):
uniform_real_distribution<> randu1( 0.0, 2.0 );
uniform_real_distribution<> randu2( -50.0, 50.0 );
t = tic();
for ( i = 0; i < ITERATIONS; i++ ) {
x = randu1( rng );
y = randu2( rng );
z = boost::math::powm1( x, y );
if ( z != z ) {
printf( "should not return NaN\n" );
break;
}
}
elapsed = tic() - t;
if ( z != z ) {
printf( "should not return NaN\n" );
}
return elapsed;
}
/**
* Main execution sequence.
*/
int main( void ) {
double elapsed;
int i;
print_version();
for ( i = 0; i < REPEATS; i++ ) {
printf( "# cpp::boost::%s\n", NAME );
elapsed = benchmark();
print_results( elapsed );
printf( "ok %d benchmark finished\n", i+1 );
}
print_summary( REPEATS, REPEATS );
return 0;
}
|
Fix check for return value
|
Fix check for return value
|
C++
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
448d377c589ec2f4231e41daad11a7d5110c61c5
|
source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp
|
source/Plugins/InstrumentationRuntime/MainThreadChecker/MainThreadCheckerRuntime.cpp
|
//===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MainThreadCheckerRuntime.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/RegularExpression.h"
#include "Plugins/Process/Utility/HistoryThread.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/NameLookup.h"
#include "swift/ClangImporter/ClangImporter.h"
#include <memory>
using namespace lldb;
using namespace lldb_private;
MainThreadCheckerRuntime::~MainThreadCheckerRuntime() {
Deactivate();
}
lldb::InstrumentationRuntimeSP
MainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));
}
void MainThreadCheckerRuntime::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), "MainThreadChecker instrumentation runtime plugin.",
CreateInstance, GetTypeStatic);
}
void MainThreadCheckerRuntime::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {
return ConstString("MainThreadChecker");
}
lldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {
return eInstrumentationRuntimeTypeMainThreadChecker;
}
const RegularExpression &
MainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {
static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
return regex;
}
bool MainThreadCheckerRuntime::CheckIfRuntimeIsValid(
const lldb::ModuleSP module_sp) {
static ConstString test_sym("__main_thread_checker_on_report");
const Symbol *symbol =
module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
return symbol != nullptr;
}
static std::string TranslateObjCNameToSwiftName(std::string className,
std::string selector,
StackFrameSP swiftFrame) {
if (className.empty() || selector.empty())
return "";
ModuleSP swiftModule = swiftFrame->GetFrameCodeAddress().GetModule();
if (!swiftModule)
return "";
SwiftASTContext *ctx = llvm::dyn_cast_or_null<SwiftASTContext>(
swiftModule->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));
if (!ctx)
return "";
swift::ClangImporter *imp = ctx->GetClangImporter();
if (!imp)
return "";
size_t numArguments = llvm::StringRef(selector).count(':');
llvm::SmallVector<llvm::StringRef, 4> parts;
llvm::StringRef(selector).split(parts, ":", /*MaxSplit*/ -1,
/*KeepEmpty*/ false);
llvm::SmallVector<swift::Identifier, 2> selectorIdentifiers;
for (size_t i = 0; i < parts.size(); i++) {
selectorIdentifiers.push_back(ctx->GetIdentifier(parts[i]));
}
class MyConsumer : public swift::VisibleDeclConsumer {
public:
swift::ObjCSelector selectorToLookup;
swift::DeclName result;
MyConsumer(swift::ObjCSelector selector) : selectorToLookup(selector) {}
virtual void foundDecl(swift::ValueDecl *VD,
swift::DeclVisibilityKind Reason) {
if (result)
return; // Take the first result.
swift::ClassDecl *cls = llvm::dyn_cast<swift::ClassDecl>(VD);
if (!cls)
return;
auto funcs = cls->lookupDirect(selectorToLookup, true);
if (funcs.size() == 0)
return;
// If the decl is actually an accessor, use the property name instead.
swift::AbstractFunctionDecl *decl = funcs.front();
if (auto accessor = llvm::dyn_cast<swift::AccessorDecl>(decl)) {
result = accessor->getStorage()->getFullName();
return;
}
result = decl->getFullName();
}
};
MyConsumer consumer(swift::ObjCSelector(*ctx->GetASTContext(), numArguments,
selectorIdentifiers));
// FIXME(mracek): Switch to a new API that translates the Clang class name
// to Swift class name, once this API exists. Now we assume they are the same.
imp->lookupValue(ctx->GetIdentifier(className), consumer);
if (!consumer.result)
return "";
llvm::SmallString<32> scratchSpace;
return className + "." + consumer.result.getString(scratchSpace).str();
}
StructuredData::ObjectSP
MainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
ProcessSP process_sp = GetProcessSP();
if (!process_sp)
return StructuredData::ObjectSP();
ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
ModuleSP runtime_module_sp = GetRuntimeModuleSP();
Target &target = process_sp->GetTarget();
if (!frame_sp)
return StructuredData::ObjectSP();
RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
if (!regctx_sp)
return StructuredData::ObjectSP();
const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
if (!reginfo)
return StructuredData::ObjectSP();
uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
if (!apiname_ptr)
return StructuredData::ObjectSP();
std::string apiName = "";
Status read_error;
target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
if (read_error.Fail())
return StructuredData::ObjectSP();
std::string className = "";
std::string selector = "";
if (apiName.substr(0, 2) == "-[") {
size_t spacePos = apiName.find(" ");
if (spacePos != std::string::npos) {
className = apiName.substr(2, spacePos - 2);
selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
}
}
// Gather the PCs of the user frames in the backtrace.
StructuredData::Array *trace = new StructuredData::Array();
auto trace_sp = StructuredData::ObjectSP(trace);
StackFrameSP responsible_frame;
for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
Address addr = frame->GetFrameCodeAddress();
if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
continue;
// The first non-runtime frame is responsible for the bug.
if (!responsible_frame)
responsible_frame = frame;
// First frame in stacktrace should point to a real PC, not return address.
if (I != 0 && trace->GetSize() == 0) {
addr.Slide(-1);
}
lldb::addr_t PC = addr.GetLoadAddress(&target);
trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
}
if (responsible_frame) {
if (responsible_frame->GetLanguage() == eLanguageTypeSwift) {
std::string swiftApiName =
TranslateObjCNameToSwiftName(className, selector, responsible_frame);
if (swiftApiName != "")
apiName = swiftApiName;
}
}
auto *d = new StructuredData::Dictionary();
auto dict_sp = StructuredData::ObjectSP(d);
d->AddStringItem("instrumentation_class", "MainThreadChecker");
d->AddStringItem("api_name", apiName);
d->AddStringItem("class_name", className);
d->AddStringItem("selector", selector);
d->AddStringItem("description",
apiName + " must be used from main thread only");
d->AddIntegerItem("tid", thread_sp->GetIndexID());
d->AddItem("trace", trace_sp);
return dict_sp;
}
bool MainThreadCheckerRuntime::NotifyBreakpointHit(
void *baton, StoppointCallbackContext *context, user_id_t break_id,
user_id_t break_loc_id) {
assert(baton && "null baton");
if (!baton)
return false; //< false => resume execution.
MainThreadCheckerRuntime *const instance =
static_cast<MainThreadCheckerRuntime *>(baton);
ProcessSP process_sp = instance->GetProcessSP();
ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
if (!process_sp || !thread_sp ||
process_sp != context->exe_ctx_ref.GetProcessSP())
return false;
if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
return false;
StructuredData::ObjectSP report =
instance->RetrieveReportData(context->exe_ctx_ref);
if (report) {
std::string description = report->GetAsDictionary()
->GetValueForKey("description")
->GetAsString()
->GetValue();
thread_sp->SetStopInfo(
InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
*thread_sp, description, report));
return true;
}
return false;
}
void MainThreadCheckerRuntime::Activate() {
if (IsActive())
return;
ProcessSP process_sp = GetProcessSP();
if (!process_sp)
return;
ModuleSP runtime_module_sp = GetRuntimeModuleSP();
ConstString symbol_name("__main_thread_checker_on_report");
const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
symbol_name, eSymbolTypeCode);
if (symbol == nullptr)
return;
if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
return;
Target &target = process_sp->GetTarget();
addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
if (symbol_address == LLDB_INVALID_ADDRESS)
return;
Breakpoint *breakpoint =
process_sp->GetTarget()
.CreateBreakpoint(symbol_address, /*internal=*/true,
/*hardware=*/false)
.get();
breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,
true);
breakpoint->SetBreakpointKind("main-thread-checker-report");
SetBreakpointID(breakpoint->GetID());
SetActive(true);
}
void MainThreadCheckerRuntime::Deactivate() {
SetActive(false);
auto BID = GetBreakpointID();
if (BID == LLDB_INVALID_BREAK_ID)
return;
if (ProcessSP process_sp = GetProcessSP()) {
process_sp->GetTarget().RemoveBreakpointByID(BID);
SetBreakpointID(LLDB_INVALID_BREAK_ID);
}
}
lldb::ThreadCollectionSP
MainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(
StructuredData::ObjectSP info) {
ThreadCollectionSP threads;
threads = std::make_shared<ThreadCollection>();
ProcessSP process_sp = GetProcessSP();
if (info->GetObjectForDotSeparatedPath("instrumentation_class")
->GetStringValue() != "MainThreadChecker")
return threads;
std::vector<lldb::addr_t> PCs;
auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
PCs.push_back(PC->GetAsInteger()->GetValue());
return true;
});
if (PCs.empty())
return threads;
StructuredData::ObjectSP thread_id_obj =
info->GetObjectForDotSeparatedPath("tid");
tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
uint32_t stop_id = 0;
bool stop_id_is_valid = false;
HistoryThread *history_thread =
new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid);
ThreadSP new_thread_sp(history_thread);
// Save this in the Process' ExtendedThreadList so a strong pointer retains
// the object
process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
threads->AddThread(new_thread_sp);
return threads;
}
|
//===-- MainThreadCheckerRuntime.cpp ----------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MainThreadCheckerRuntime.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Variable.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/InstrumentationRuntimeStopInfo.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/SectionLoadList.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/RegularExpression.h"
#include "Plugins/Process/Utility/HistoryThread.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/NameLookup.h"
#include "swift/ClangImporter/ClangImporter.h"
#include <memory>
using namespace lldb;
using namespace lldb_private;
MainThreadCheckerRuntime::~MainThreadCheckerRuntime() {
Deactivate();
}
lldb::InstrumentationRuntimeSP
MainThreadCheckerRuntime::CreateInstance(const lldb::ProcessSP &process_sp) {
return InstrumentationRuntimeSP(new MainThreadCheckerRuntime(process_sp));
}
void MainThreadCheckerRuntime::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), "MainThreadChecker instrumentation runtime plugin.",
CreateInstance, GetTypeStatic);
}
void MainThreadCheckerRuntime::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString MainThreadCheckerRuntime::GetPluginNameStatic() {
return ConstString("MainThreadChecker");
}
lldb::InstrumentationRuntimeType MainThreadCheckerRuntime::GetTypeStatic() {
return eInstrumentationRuntimeTypeMainThreadChecker;
}
const RegularExpression &
MainThreadCheckerRuntime::GetPatternForRuntimeLibrary() {
static RegularExpression regex(llvm::StringRef("libMainThreadChecker.dylib"));
return regex;
}
bool MainThreadCheckerRuntime::CheckIfRuntimeIsValid(
const lldb::ModuleSP module_sp) {
static ConstString test_sym("__main_thread_checker_on_report");
const Symbol *symbol =
module_sp->FindFirstSymbolWithNameAndType(test_sym, lldb::eSymbolTypeAny);
return symbol != nullptr;
}
static std::string TranslateObjCNameToSwiftName(std::string className,
std::string selector,
StackFrameSP swiftFrame) {
if (className.empty() || selector.empty())
return "";
ModuleSP swiftModule = swiftFrame->GetFrameCodeAddress().GetModule();
if (!swiftModule)
return "";
SwiftASTContext *ctx = llvm::dyn_cast_or_null<SwiftASTContext>(
swiftModule->GetTypeSystemForLanguage(lldb::eLanguageTypeSwift));
if (!ctx)
return "";
swift::ClangImporter *imp = ctx->GetClangImporter();
if (!imp)
return "";
size_t numArguments = llvm::StringRef(selector).count(':');
llvm::SmallVector<llvm::StringRef, 4> parts;
llvm::StringRef(selector).split(parts, ":", /*MaxSplit*/ -1,
/*KeepEmpty*/ false);
llvm::SmallVector<swift::Identifier, 2> selectorIdentifiers;
for (size_t i = 0; i < parts.size(); i++) {
selectorIdentifiers.push_back(ctx->GetIdentifier(parts[i]));
}
class MyConsumer : public swift::VisibleDeclConsumer {
public:
swift::ObjCSelector selectorToLookup;
swift::DeclName result;
MyConsumer(swift::ObjCSelector selector) : selectorToLookup(selector) {}
virtual void foundDecl(swift::ValueDecl *VD,
swift::DeclVisibilityKind Reason,
swift::DynamicLookupInfo) {
if (result)
return; // Take the first result.
swift::ClassDecl *cls = llvm::dyn_cast<swift::ClassDecl>(VD);
if (!cls)
return;
auto funcs = cls->lookupDirect(selectorToLookup, true);
if (funcs.size() == 0)
return;
// If the decl is actually an accessor, use the property name instead.
swift::AbstractFunctionDecl *decl = funcs.front();
if (auto accessor = llvm::dyn_cast<swift::AccessorDecl>(decl)) {
result = accessor->getStorage()->getFullName();
return;
}
result = decl->getFullName();
}
};
MyConsumer consumer(swift::ObjCSelector(*ctx->GetASTContext(), numArguments,
selectorIdentifiers));
// FIXME(mracek): Switch to a new API that translates the Clang class name
// to Swift class name, once this API exists. Now we assume they are the same.
imp->lookupValue(ctx->GetIdentifier(className), consumer);
if (!consumer.result)
return "";
llvm::SmallString<32> scratchSpace;
return className + "." + consumer.result.getString(scratchSpace).str();
}
StructuredData::ObjectSP
MainThreadCheckerRuntime::RetrieveReportData(ExecutionContextRef exe_ctx_ref) {
ProcessSP process_sp = GetProcessSP();
if (!process_sp)
return StructuredData::ObjectSP();
ThreadSP thread_sp = exe_ctx_ref.GetThreadSP();
StackFrameSP frame_sp = thread_sp->GetSelectedFrame();
ModuleSP runtime_module_sp = GetRuntimeModuleSP();
Target &target = process_sp->GetTarget();
if (!frame_sp)
return StructuredData::ObjectSP();
RegisterContextSP regctx_sp = frame_sp->GetRegisterContext();
if (!regctx_sp)
return StructuredData::ObjectSP();
const RegisterInfo *reginfo = regctx_sp->GetRegisterInfoByName("arg1");
if (!reginfo)
return StructuredData::ObjectSP();
uint64_t apiname_ptr = regctx_sp->ReadRegisterAsUnsigned(reginfo, 0);
if (!apiname_ptr)
return StructuredData::ObjectSP();
std::string apiName = "";
Status read_error;
target.ReadCStringFromMemory(apiname_ptr, apiName, read_error);
if (read_error.Fail())
return StructuredData::ObjectSP();
std::string className = "";
std::string selector = "";
if (apiName.substr(0, 2) == "-[") {
size_t spacePos = apiName.find(" ");
if (spacePos != std::string::npos) {
className = apiName.substr(2, spacePos - 2);
selector = apiName.substr(spacePos + 1, apiName.length() - spacePos - 2);
}
}
// Gather the PCs of the user frames in the backtrace.
StructuredData::Array *trace = new StructuredData::Array();
auto trace_sp = StructuredData::ObjectSP(trace);
StackFrameSP responsible_frame;
for (unsigned I = 0; I < thread_sp->GetStackFrameCount(); ++I) {
StackFrameSP frame = thread_sp->GetStackFrameAtIndex(I);
Address addr = frame->GetFrameCodeAddress();
if (addr.GetModule() == runtime_module_sp) // Skip PCs from the runtime.
continue;
// The first non-runtime frame is responsible for the bug.
if (!responsible_frame)
responsible_frame = frame;
// First frame in stacktrace should point to a real PC, not return address.
if (I != 0 && trace->GetSize() == 0) {
addr.Slide(-1);
}
lldb::addr_t PC = addr.GetLoadAddress(&target);
trace->AddItem(StructuredData::ObjectSP(new StructuredData::Integer(PC)));
}
if (responsible_frame) {
if (responsible_frame->GetLanguage() == eLanguageTypeSwift) {
std::string swiftApiName =
TranslateObjCNameToSwiftName(className, selector, responsible_frame);
if (swiftApiName != "")
apiName = swiftApiName;
}
}
auto *d = new StructuredData::Dictionary();
auto dict_sp = StructuredData::ObjectSP(d);
d->AddStringItem("instrumentation_class", "MainThreadChecker");
d->AddStringItem("api_name", apiName);
d->AddStringItem("class_name", className);
d->AddStringItem("selector", selector);
d->AddStringItem("description",
apiName + " must be used from main thread only");
d->AddIntegerItem("tid", thread_sp->GetIndexID());
d->AddItem("trace", trace_sp);
return dict_sp;
}
bool MainThreadCheckerRuntime::NotifyBreakpointHit(
void *baton, StoppointCallbackContext *context, user_id_t break_id,
user_id_t break_loc_id) {
assert(baton && "null baton");
if (!baton)
return false; //< false => resume execution.
MainThreadCheckerRuntime *const instance =
static_cast<MainThreadCheckerRuntime *>(baton);
ProcessSP process_sp = instance->GetProcessSP();
ThreadSP thread_sp = context->exe_ctx_ref.GetThreadSP();
if (!process_sp || !thread_sp ||
process_sp != context->exe_ctx_ref.GetProcessSP())
return false;
if (process_sp->GetModIDRef().IsLastResumeForUserExpression())
return false;
StructuredData::ObjectSP report =
instance->RetrieveReportData(context->exe_ctx_ref);
if (report) {
std::string description = report->GetAsDictionary()
->GetValueForKey("description")
->GetAsString()
->GetValue();
thread_sp->SetStopInfo(
InstrumentationRuntimeStopInfo::CreateStopReasonWithInstrumentationData(
*thread_sp, description, report));
return true;
}
return false;
}
void MainThreadCheckerRuntime::Activate() {
if (IsActive())
return;
ProcessSP process_sp = GetProcessSP();
if (!process_sp)
return;
ModuleSP runtime_module_sp = GetRuntimeModuleSP();
ConstString symbol_name("__main_thread_checker_on_report");
const Symbol *symbol = runtime_module_sp->FindFirstSymbolWithNameAndType(
symbol_name, eSymbolTypeCode);
if (symbol == nullptr)
return;
if (!symbol->ValueIsAddress() || !symbol->GetAddressRef().IsValid())
return;
Target &target = process_sp->GetTarget();
addr_t symbol_address = symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
if (symbol_address == LLDB_INVALID_ADDRESS)
return;
Breakpoint *breakpoint =
process_sp->GetTarget()
.CreateBreakpoint(symbol_address, /*internal=*/true,
/*hardware=*/false)
.get();
breakpoint->SetCallback(MainThreadCheckerRuntime::NotifyBreakpointHit, this,
true);
breakpoint->SetBreakpointKind("main-thread-checker-report");
SetBreakpointID(breakpoint->GetID());
SetActive(true);
}
void MainThreadCheckerRuntime::Deactivate() {
SetActive(false);
auto BID = GetBreakpointID();
if (BID == LLDB_INVALID_BREAK_ID)
return;
if (ProcessSP process_sp = GetProcessSP()) {
process_sp->GetTarget().RemoveBreakpointByID(BID);
SetBreakpointID(LLDB_INVALID_BREAK_ID);
}
}
lldb::ThreadCollectionSP
MainThreadCheckerRuntime::GetBacktracesFromExtendedStopInfo(
StructuredData::ObjectSP info) {
ThreadCollectionSP threads;
threads = std::make_shared<ThreadCollection>();
ProcessSP process_sp = GetProcessSP();
if (info->GetObjectForDotSeparatedPath("instrumentation_class")
->GetStringValue() != "MainThreadChecker")
return threads;
std::vector<lldb::addr_t> PCs;
auto trace = info->GetObjectForDotSeparatedPath("trace")->GetAsArray();
trace->ForEach([&PCs](StructuredData::Object *PC) -> bool {
PCs.push_back(PC->GetAsInteger()->GetValue());
return true;
});
if (PCs.empty())
return threads;
StructuredData::ObjectSP thread_id_obj =
info->GetObjectForDotSeparatedPath("tid");
tid_t tid = thread_id_obj ? thread_id_obj->GetIntegerValue() : 0;
uint32_t stop_id = 0;
bool stop_id_is_valid = false;
HistoryThread *history_thread =
new HistoryThread(*process_sp, tid, PCs, stop_id, stop_id_is_valid);
ThreadSP new_thread_sp(history_thread);
// Save this in the Process' ExtendedThreadList so a strong pointer retains
// the object
process_sp->GetExtendedThreadList().AddThread(new_thread_sp);
threads->AddThread(new_thread_sp);
return threads;
}
|
Update for change to VisibleDeclConsumer
|
Update for change to VisibleDeclConsumer
|
C++
|
apache-2.0
|
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
|
06110e954667c1c911d9428f430b6b8cb7902b34
|
plugins/ipc/stipc.cpp
|
plugins/ipc/stipc.cpp
|
#include <wayfire/singleton-plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/output-layout.hpp>
#include <getopt.h>
#include "ipc.hpp"
extern "C" {
#include <wlr/backend/wayland.h>
#include <wlr/backend/multi.h>
#include <wlr/backend/headless.h>
#include <wlr/types/wlr_pointer.h>
#include <wlr/types/wlr_keyboard.h>
#include <wlr/interfaces/wlr_keyboard.h>
#include <wlr/types/wlr_output_layout.h>
#include <libevdev/libevdev.h>
}
#include <wayfire/util/log.hpp>
#include <wayfire/core.hpp>
static void locate_wayland_backend(wlr_backend *backend, void *data)
{
if (wlr_backend_is_wl(backend))
{
wlr_backend **result = (wlr_backend**)data;
*result = backend;
}
}
namespace wf
{
static nlohmann::json geometry_to_json(wf::geometry_t g)
{
nlohmann::json j;
j["x"] = g.x;
j["y"] = g.y;
j["width"] = g.width;
j["height"] = g.height;
return j;
}
static std::string layer_to_string(uint32_t layer)
{
switch (layer)
{
case LAYER_BACKGROUND:
return "background";
case LAYER_BOTTOM:
return "bottom";
case LAYER_WORKSPACE:
return "workspace";
case LAYER_TOP:
return "top";
case LAYER_UNMANAGED:
return "unmanaged";
case LAYER_LOCK:
return "lock";
case LAYER_DESKTOP_WIDGET:
return "dew";
case LAYER_MINIMIZED:
return "minimized";
default:
break;
}
return "none";
}
class headless_input_backend_t
{
public:
wlr_backend *backend;
wlr_input_device *pointer;
wlr_input_device *keyboard;
headless_input_backend_t()
{
auto& core = wf::get_core();
backend = wlr_headless_backend_create(core.display);
wlr_multi_backend_add(core.backend, backend);
wlr_backend_start(backend);
pointer = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_POINTER);
keyboard = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_KEYBOARD);
}
~headless_input_backend_t()
{
auto& core = wf::get_core();
wlr_multi_backend_remove(core.backend, backend);
wlr_backend_destroy(backend);
}
void do_key(uint32_t key, wl_keyboard_key_state state)
{
wlr_event_keyboard_key ev;
ev.keycode = key;
ev.state = state;
ev.update_state = true;
ev.time_msec = get_current_time();
wlr_keyboard_notify_key(keyboard->keyboard, &ev);
}
void do_button(uint32_t button, wlr_button_state state)
{
wlr_event_pointer_button ev;
ev.device = pointer;
ev.button = button;
ev.state = state;
ev.time_msec = get_current_time();
wl_signal_emit(&pointer->pointer->events.button, &ev);
}
void do_motion(double x, double y)
{
auto layout = wf::get_core().output_layout->get_handle();
auto box = wlr_output_layout_get_box(layout, NULL);
wlr_event_pointer_motion_absolute ev;
ev.device = pointer;
ev.time_msec = get_current_time();
ev.x = 1.0 * (x - box->x) / box->width;
ev.y = 1.0 * (y - box->y) / box->height;
wl_signal_emit(&pointer->pointer->events.motion_absolute, &ev);
}
headless_input_backend_t(const headless_input_backend_t&) = delete;
headless_input_backend_t(headless_input_backend_t&&) = delete;
headless_input_backend_t& operator =(const headless_input_backend_t&) = delete;
headless_input_backend_t& operator =(headless_input_backend_t&&) = delete;
};
static inline nlohmann::json get_ok()
{
return nlohmann::json{
{"result", "ok"}
};
}
static inline nlohmann::json get_error(std::string msg)
{
return nlohmann::json{
{"error", std::string(msg)}
};
}
class ipc_plugin_t
{
public:
ipc_plugin_t()
{
input = std::make_unique<headless_input_backend_t>();
char *pre_socket = getenv("_WAYFIRE_SOCKET");
const auto& dname = wf::get_core().wayland_display;
std::string socket = pre_socket ?: "/tmp/wayfire-" + dname + ".socket";
setenv("WAYFIRE_SOCKET", socket.c_str(), 1);
server = std::make_unique<ipc::server_t>(socket);
server->register_method("core/list_views", list_views);
server->register_method("core/create_wayland_output", create_wayland_output);
server->register_method("core/feed_key", feed_key);
server->register_method("core/feed_button", feed_button);
server->register_method("core/move_cursor", move_cursor);
server->register_method("core/run", run);
server->register_method("core/ping", ping);
}
using method_t = ipc::server_t::method_cb;
method_t list_views = [] (nlohmann::json)
{
auto response = nlohmann::json::array();
for (auto& view : wf::get_core().get_all_views())
{
nlohmann::json v;
v["title"] = view->get_title();
v["app-id"] = view->get_app_id();
v["geometry"] = geometry_to_json(view->get_wm_geometry());
v["base-geometry"] = geometry_to_json(view->get_output_geometry());
v["state"] = {
{"tiled", view->tiled_edges},
{"fullscreen", view->fullscreen},
{"minimized", view->minimized},
};
uint32_t layer = -1;
if (view->get_output())
{
layer = view->get_output()->workspace->get_view_layer(view);
}
v["layer"] = layer_to_string(layer);
response.push_back(v);
}
return response;
};
method_t create_wayland_output = [] (nlohmann::json)
{
auto backend = wf::get_core().backend;
wlr_backend *wayland_backend = NULL;
wlr_multi_for_each_backend(backend, locate_wayland_backend,
&wayland_backend);
if (!wayland_backend)
{
return get_error("Wayfire is not running in nested wayland mode!");
}
wlr_wl_output_create(wayland_backend);
return get_ok();
};
struct key_t
{
bool modifier;
int code;
};
std::variant<key_t, std::string> parse_key(nlohmann::json data)
{
if (!data.count("combo") || !data["combo"].is_string())
{
return std::string("Missing or wrong json type for `combo`!");
}
std::string combo = data["combo"];
if (combo.size() < 4)
{
return std::string("Missing or wrong json type for `combo`!");
}
// Check super modifier
bool modifier = false;
if (combo.substr(0, 2) == "S-")
{
modifier = true;
combo = combo.substr(2);
}
int key = libevdev_event_code_from_name(EV_KEY, combo.c_str());
if (key == -1)
{
return std::string("Failed to parse combo \"" + combo + "\"");
}
return key_t{modifier, key};
}
method_t feed_key = [=] (nlohmann::json data)
{
auto result = parse_key(data);
auto key = std::get_if<key_t>(&result);
if (!key)
{
return get_error(std::get<std::string>(result));
}
if (key->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED);
}
input->do_key(key->code, WL_KEYBOARD_KEY_STATE_PRESSED);
input->do_key(key->code, WL_KEYBOARD_KEY_STATE_RELEASED);
if (key->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED);
}
return get_ok();
};
method_t feed_button = [=] (nlohmann::json data)
{
auto result = parse_key(data);
auto button = std::get_if<key_t>(&result);
if (!button)
{
return get_error(std::get<std::string>(result));
}
if (!data.count("mode") || !data["mode"].is_string())
{
return get_error("No mode specified");
}
auto mode = data["mode"];
if ((mode == "press") || (mode == "full"))
{
if (button->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED);
}
input->do_button(button->code, WLR_BUTTON_PRESSED);
}
if ((mode == "release") || (mode == "full"))
{
input->do_button(button->code, WLR_BUTTON_RELEASED);
if (button->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED);
}
}
return get_ok();
};
method_t move_cursor = [=] (nlohmann::json data)
{
if (!data.count("x") || !data.count("y") ||
!data["x"].is_number() || !data["y"].is_number())
{
return get_error("Move cursor needs double x/y arguments");
}
double x = data["x"];
double y = data["y"];
input->do_motion(x, y);
return get_ok();
};
method_t run = [=] (nlohmann::json data)
{
if (!data.count("cmd") || !data["cmd"].is_string())
{
return get_error("run command needs a cmd to run");
}
wf::get_core().run(data["cmd"]);
return get_ok();
};
method_t ping = [=] (nlohmann::json data)
{
return get_ok();
};
std::unique_ptr<ipc::server_t> server;
std::unique_ptr<headless_input_backend_t> input;
};
}
DECLARE_WAYFIRE_PLUGIN((wf::singleton_plugin_t<wf::ipc_plugin_t, false>));
|
#include <wayfire/singleton-plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/output.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/output-layout.hpp>
#include <getopt.h>
#include "ipc.hpp"
extern "C" {
#include <wlr/backend/wayland.h>
#include <wlr/backend/multi.h>
#include <wlr/backend/headless.h>
#include <wlr/types/wlr_pointer.h>
#include <wlr/types/wlr_keyboard.h>
#include <wlr/interfaces/wlr_keyboard.h>
#include <wlr/types/wlr_output_layout.h>
#include <libevdev/libevdev.h>
}
#include <wayfire/util/log.hpp>
#include <wayfire/core.hpp>
static void locate_wayland_backend(wlr_backend *backend, void *data)
{
if (wlr_backend_is_wl(backend))
{
wlr_backend **result = (wlr_backend**)data;
*result = backend;
}
}
namespace wf
{
static nlohmann::json geometry_to_json(wf::geometry_t g)
{
nlohmann::json j;
j["x"] = g.x;
j["y"] = g.y;
j["width"] = g.width;
j["height"] = g.height;
return j;
}
static std::string layer_to_string(uint32_t layer)
{
switch (layer)
{
case LAYER_BACKGROUND:
return "background";
case LAYER_BOTTOM:
return "bottom";
case LAYER_WORKSPACE:
return "workspace";
case LAYER_TOP:
return "top";
case LAYER_UNMANAGED:
return "unmanaged";
case LAYER_LOCK:
return "lock";
case LAYER_DESKTOP_WIDGET:
return "dew";
case LAYER_MINIMIZED:
return "minimized";
default:
break;
}
return "none";
}
class headless_input_backend_t
{
public:
wlr_backend *backend;
wlr_input_device *pointer;
wlr_input_device *keyboard;
headless_input_backend_t()
{
auto& core = wf::get_core();
backend = wlr_headless_backend_create(core.display);
wlr_multi_backend_add(core.backend, backend);
wlr_backend_start(backend);
pointer = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_POINTER);
keyboard = wlr_headless_add_input_device(backend, WLR_INPUT_DEVICE_KEYBOARD);
}
~headless_input_backend_t()
{
auto& core = wf::get_core();
wlr_multi_backend_remove(core.backend, backend);
wlr_backend_destroy(backend);
}
void do_key(uint32_t key, wl_keyboard_key_state state)
{
wlr_event_keyboard_key ev;
ev.keycode = key;
ev.state = state;
ev.update_state = true;
ev.time_msec = get_current_time();
wlr_keyboard_notify_key(keyboard->keyboard, &ev);
}
void do_button(uint32_t button, wlr_button_state state)
{
wlr_event_pointer_button ev;
ev.device = pointer;
ev.button = button;
ev.state = state;
ev.time_msec = get_current_time();
wl_signal_emit(&pointer->pointer->events.button, &ev);
}
void do_motion(double x, double y)
{
auto layout = wf::get_core().output_layout->get_handle();
auto box = wlr_output_layout_get_box(layout, NULL);
wlr_event_pointer_motion_absolute ev;
ev.device = pointer;
ev.time_msec = get_current_time();
ev.x = 1.0 * (x - box->x) / box->width;
ev.y = 1.0 * (y - box->y) / box->height;
wl_signal_emit(&pointer->pointer->events.motion_absolute, &ev);
}
headless_input_backend_t(const headless_input_backend_t&) = delete;
headless_input_backend_t(headless_input_backend_t&&) = delete;
headless_input_backend_t& operator =(const headless_input_backend_t&) = delete;
headless_input_backend_t& operator =(headless_input_backend_t&&) = delete;
};
static inline nlohmann::json get_ok()
{
return nlohmann::json{
{"result", "ok"}
};
}
static inline nlohmann::json get_error(std::string msg)
{
return nlohmann::json{
{"error", std::string(msg)}
};
}
class ipc_plugin_t
{
public:
ipc_plugin_t()
{
input = std::make_unique<headless_input_backend_t>();
char *pre_socket = getenv("_WAYFIRE_SOCKET");
const auto& dname = wf::get_core().wayland_display;
std::string socket = pre_socket ?: "/tmp/wayfire-" + dname + ".socket";
setenv("WAYFIRE_SOCKET", socket.c_str(), 1);
server = std::make_unique<ipc::server_t>(socket);
server->register_method("core/list_views", list_views);
server->register_method("core/create_wayland_output", create_wayland_output);
server->register_method("core/feed_key", feed_key);
server->register_method("core/feed_button", feed_button);
server->register_method("core/move_cursor", move_cursor);
server->register_method("core/run", run);
server->register_method("core/ping", ping);
server->register_method("core/get_display", get_display);
}
using method_t = ipc::server_t::method_cb;
method_t list_views = [] (nlohmann::json)
{
auto response = nlohmann::json::array();
for (auto& view : wf::get_core().get_all_views())
{
nlohmann::json v;
v["title"] = view->get_title();
v["app-id"] = view->get_app_id();
v["geometry"] = geometry_to_json(view->get_wm_geometry());
v["base-geometry"] = geometry_to_json(view->get_output_geometry());
v["state"] = {
{"tiled", view->tiled_edges},
{"fullscreen", view->fullscreen},
{"minimized", view->minimized},
};
uint32_t layer = -1;
if (view->get_output())
{
layer = view->get_output()->workspace->get_view_layer(view);
}
v["layer"] = layer_to_string(layer);
response.push_back(v);
}
return response;
};
method_t create_wayland_output = [] (nlohmann::json)
{
auto backend = wf::get_core().backend;
wlr_backend *wayland_backend = NULL;
wlr_multi_for_each_backend(backend, locate_wayland_backend,
&wayland_backend);
if (!wayland_backend)
{
return get_error("Wayfire is not running in nested wayland mode!");
}
wlr_wl_output_create(wayland_backend);
return get_ok();
};
struct key_t
{
bool modifier;
int code;
};
std::variant<key_t, std::string> parse_key(nlohmann::json data)
{
if (!data.count("combo") || !data["combo"].is_string())
{
return std::string("Missing or wrong json type for `combo`!");
}
std::string combo = data["combo"];
if (combo.size() < 4)
{
return std::string("Missing or wrong json type for `combo`!");
}
// Check super modifier
bool modifier = false;
if (combo.substr(0, 2) == "S-")
{
modifier = true;
combo = combo.substr(2);
}
int key = libevdev_event_code_from_name(EV_KEY, combo.c_str());
if (key == -1)
{
return std::string("Failed to parse combo \"" + combo + "\"");
}
return key_t{modifier, key};
}
method_t feed_key = [=] (nlohmann::json data)
{
auto result = parse_key(data);
auto key = std::get_if<key_t>(&result);
if (!key)
{
return get_error(std::get<std::string>(result));
}
if (key->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED);
}
input->do_key(key->code, WL_KEYBOARD_KEY_STATE_PRESSED);
input->do_key(key->code, WL_KEYBOARD_KEY_STATE_RELEASED);
if (key->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED);
}
return get_ok();
};
method_t feed_button = [=] (nlohmann::json data)
{
auto result = parse_key(data);
auto button = std::get_if<key_t>(&result);
if (!button)
{
return get_error(std::get<std::string>(result));
}
if (!data.count("mode") || !data["mode"].is_string())
{
return get_error("No mode specified");
}
auto mode = data["mode"];
if ((mode == "press") || (mode == "full"))
{
if (button->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_PRESSED);
}
input->do_button(button->code, WLR_BUTTON_PRESSED);
}
if ((mode == "release") || (mode == "full"))
{
input->do_button(button->code, WLR_BUTTON_RELEASED);
if (button->modifier)
{
input->do_key(KEY_LEFTMETA, WL_KEYBOARD_KEY_STATE_RELEASED);
}
}
return get_ok();
};
method_t move_cursor = [=] (nlohmann::json data)
{
if (!data.count("x") || !data.count("y") ||
!data["x"].is_number() || !data["y"].is_number())
{
return get_error("Move cursor needs double x/y arguments");
}
double x = data["x"];
double y = data["y"];
input->do_motion(x, y);
return get_ok();
};
method_t run = [=] (nlohmann::json data)
{
if (!data.count("cmd") || !data["cmd"].is_string())
{
return get_error("run command needs a cmd to run");
}
wf::get_core().run(data["cmd"]);
return get_ok();
};
method_t ping = [=] (nlohmann::json data)
{
return get_ok();
};
method_t get_display = [=] (nlohmann::json data)
{
nlohmann::json dpy;
dpy["wayland"] = wf::get_core().wayland_display;
dpy["xwayland"] = wf::get_core().get_xwayland_display();
return dpy;
};
std::unique_ptr<ipc::server_t> server;
std::unique_ptr<headless_input_backend_t> input;
};
}
DECLARE_WAYFIRE_PLUGIN((wf::singleton_plugin_t<wf::ipc_plugin_t, false>));
|
add command to get display numbers
|
add command to get display numbers
|
C++
|
mit
|
ammen99/wayfire,ammen99/wayfire
|
1aafcb90209ebdfdeb974fad8bdc28ebfffaa486
|
oox/source/helper/attributelist.cxx
|
oox/source/helper/attributelist.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "oox/helper/attributelist.hxx"
#include <osl/diagnose.h>
#include <rtl/ustrbuf.hxx>
#include "oox/token/tokenmap.hxx"
namespace oox {
// ============================================================================
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::xml::sax;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
// ============================================================================
namespace {
const sal_Int32 XSTRING_ENCCHAR_LEN = 7;
bool lclAddHexDigit( sal_Unicode& orcChar, sal_Unicode cDigit, int nBitShift )
{
if( ('0' <= cDigit) && (cDigit <= '9') ) { orcChar |= ((cDigit - '0') << nBitShift); return true; }
if( ('a' <= cDigit) && (cDigit <= 'f') ) { orcChar |= ((cDigit - 'a' + 10) << nBitShift); return true; }
if( ('A' <= cDigit) && (cDigit <= 'F') ) { orcChar |= ((cDigit - 'A' + 10) << nBitShift); return true; }
return false;
}
sal_Unicode lclGetXChar( const sal_Unicode*& rpcStr, const sal_Unicode* pcEnd )
{
sal_Unicode cChar = 0;
if( (pcEnd - rpcStr >= XSTRING_ENCCHAR_LEN) &&
(rpcStr[ 0 ] == '_') &&
(rpcStr[ 1 ] == 'x') &&
(rpcStr[ 6 ] == '_') &&
lclAddHexDigit( cChar, rpcStr[ 2 ], 12 ) &&
lclAddHexDigit( cChar, rpcStr[ 3 ], 8 ) &&
lclAddHexDigit( cChar, rpcStr[ 4 ], 4 ) &&
lclAddHexDigit( cChar, rpcStr[ 5 ], 0 ) )
{
rpcStr += XSTRING_ENCCHAR_LEN;
return cChar;
}
return *rpcStr++;
}
} // namespace
// ----------------------------------------------------------------------------
sal_Int32 AttributeConversion::decodeToken( const OUString& rValue )
{
return StaticTokenMap::get().getTokenFromUnicode( rValue );
}
OUString AttributeConversion::decodeXString( const OUString& rValue )
{
// string shorter than one encoded character - no need to decode
if( rValue.getLength() < XSTRING_ENCCHAR_LEN )
return rValue;
OUStringBuffer aBuffer;
const sal_Unicode* pcStr = rValue.getStr();
const sal_Unicode* pcEnd = pcStr + rValue.getLength();
while( pcStr < pcEnd )
aBuffer.append( lclGetXChar( pcStr, pcEnd ) );
return aBuffer.makeStringAndClear();
}
double AttributeConversion::decodeDouble( const OUString& rValue )
{
return rValue.toDouble();
}
sal_Int32 AttributeConversion::decodeInteger( const OUString& rValue )
{
return rValue.toInt32();
}
sal_uInt32 AttributeConversion::decodeUnsigned( const OUString& rValue )
{
return getLimitedValue< sal_uInt32, sal_Int64 >( rValue.toInt64(), 0, SAL_MAX_UINT32 );
}
sal_Int64 AttributeConversion::decodeHyper( const OUString& rValue )
{
return rValue.toInt64();
}
sal_Int32 AttributeConversion::decodeIntegerHex( const OUString& rValue )
{
return rValue.toInt32( 16 );
}
// ============================================================================
AttributeList::AttributeList( const Reference< XFastAttributeList >& rxAttribs ) :
mxAttribs( rxAttribs )
{
OSL_ENSURE( mxAttribs.is(), "AttributeList::AttributeList - missing attribute list interface" );
}
bool AttributeList::hasAttribute( sal_Int32 nAttrToken ) const
{
return mxAttribs->hasAttribute( nAttrToken );
}
// optional return values -----------------------------------------------------
OptValue< sal_Int32 > AttributeList::getToken( sal_Int32 nAttrToken ) const
{
sal_Int32 nToken = mxAttribs->getOptionalValueToken( nAttrToken, XML_TOKEN_INVALID );
return OptValue< sal_Int32 >( nToken != XML_TOKEN_INVALID, nToken );
}
OptValue< OUString > AttributeList::getString( sal_Int32 nAttrToken ) const
{
// check if the attribute exists (empty string may be different to missing attribute)
if( mxAttribs->hasAttribute( nAttrToken ) )
return OptValue< OUString >( mxAttribs->getOptionalValue( nAttrToken ) );
return OptValue< OUString >();
}
OptValue< OUString > AttributeList::getXString( sal_Int32 nAttrToken ) const
{
// check if the attribute exists (empty string may be different to missing attribute)
if( mxAttribs->hasAttribute( nAttrToken ) )
return OptValue< OUString >( AttributeConversion::decodeXString( mxAttribs->getOptionalValue( nAttrToken ) ) );
return OptValue< OUString >();
}
OptValue< double > AttributeList::getDouble( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< double >( bValid, bValid ? AttributeConversion::decodeDouble( aValue ) : 0.0 );
}
OptValue< sal_Int32 > AttributeList::getInteger( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int32 >( bValid, bValid ? AttributeConversion::decodeInteger( aValue ) : 0 );
}
OptValue< sal_uInt32 > AttributeList::getUnsigned( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_uInt32 >( bValid, AttributeConversion::decodeUnsigned( aValue ) );
}
OptValue< sal_Int64 > AttributeList::getHyper( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int64 >( bValid, bValid ? AttributeConversion::decodeHyper( aValue ) : 0 );
}
OptValue< sal_Int32 > AttributeList::getIntegerHex( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int32 >( bValid, bValid ? AttributeConversion::decodeIntegerHex( aValue ) : 0 );
}
OptValue< bool > AttributeList::getBool( sal_Int32 nAttrToken ) const
{
// boolean attributes may be "t", "f", "true", "false", "on", "off", "1", or "0"
switch( getToken( nAttrToken, XML_TOKEN_INVALID ) )
{
case XML_t: return OptValue< bool >( true ); // used in VML
case XML_true: return OptValue< bool >( true );
case XML_on: return OptValue< bool >( true );
case XML_f: return OptValue< bool >( false ); // used in VML
case XML_false: return OptValue< bool >( false );
case XML_off: return OptValue< bool >( false );
}
OptValue< sal_Int32 > onValue = getInteger( nAttrToken );
return OptValue< bool >( onValue.has(), onValue.get() != 0 );
}
OptValue< DateTime > AttributeList::getDateTime( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
DateTime aDateTime;
bool bValid = (aValue.getLength() == 19) && (aValue[ 4 ] == '-') && (aValue[ 7 ] == '-') &&
(aValue[ 10 ] == 'T') && (aValue[ 13 ] == ':') && (aValue[ 16 ] == ':');
if( bValid )
{
aDateTime.Year = static_cast< sal_uInt16 >( aValue.copy( 0, 4 ).toInt32() );
aDateTime.Month = static_cast< sal_uInt16 >( aValue.copy( 5, 2 ).toInt32() );
aDateTime.Day = static_cast< sal_uInt16 >( aValue.copy( 8, 2 ).toInt32() );
aDateTime.Hours = static_cast< sal_uInt16 >( aValue.copy( 11, 2 ).toInt32() );
aDateTime.Minutes = static_cast< sal_uInt16 >( aValue.copy( 14, 2 ).toInt32() );
aDateTime.Seconds = static_cast< sal_uInt16 >( aValue.copy( 17, 2 ).toInt32() );
}
return OptValue< DateTime >( bValid, aDateTime );
}
// defaulted return values ----------------------------------------------------
sal_Int32 AttributeList::getToken( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return mxAttribs->getOptionalValueToken( nAttrToken, nDefault );
}
OUString AttributeList::getString( sal_Int32 nAttrToken, const OUString& rDefault ) const
{
try
{
return mxAttribs->getValue( nAttrToken );
}
catch( Exception& )
{
}
return rDefault;
}
OUString AttributeList::getXString( sal_Int32 nAttrToken, const OUString& rDefault ) const
{
return getXString( nAttrToken ).get( rDefault );
}
double AttributeList::getDouble( sal_Int32 nAttrToken, double fDefault ) const
{
return getDouble( nAttrToken ).get( fDefault );
}
sal_Int32 AttributeList::getInteger( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return getInteger( nAttrToken ).get( nDefault );
}
sal_uInt32 AttributeList::getUnsigned( sal_Int32 nAttrToken, sal_uInt32 nDefault ) const
{
return getUnsigned( nAttrToken ).get( nDefault );
}
sal_Int64 AttributeList::getHyper( sal_Int32 nAttrToken, sal_Int64 nDefault ) const
{
return getHyper( nAttrToken ).get( nDefault );
}
sal_Int32 AttributeList::getIntegerHex( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return getIntegerHex( nAttrToken ).get( nDefault );
}
bool AttributeList::getBool( sal_Int32 nAttrToken, bool bDefault ) const
{
return getBool( nAttrToken ).get( bDefault );
}
DateTime AttributeList::getDateTime( sal_Int32 nAttrToken, const DateTime& rDefault ) const
{
return getDateTime( nAttrToken ).get( rDefault );
}
// ============================================================================
} // namespace oox
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "oox/helper/attributelist.hxx"
#include <osl/diagnose.h>
#include <rtl/ustrbuf.hxx>
#include "oox/token/tokenmap.hxx"
namespace oox {
// ============================================================================
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::xml::sax;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
// ============================================================================
namespace {
const sal_Int32 XSTRING_ENCCHAR_LEN = 7;
bool lclAddHexDigit( sal_Unicode& orcChar, sal_Unicode cDigit, int nBitShift )
{
if( ('0' <= cDigit) && (cDigit <= '9') ) { orcChar |= ((cDigit - '0') << nBitShift); return true; }
if( ('a' <= cDigit) && (cDigit <= 'f') ) { orcChar |= ((cDigit - 'a' + 10) << nBitShift); return true; }
if( ('A' <= cDigit) && (cDigit <= 'F') ) { orcChar |= ((cDigit - 'A' + 10) << nBitShift); return true; }
return false;
}
sal_Unicode lclGetXChar( const sal_Unicode*& rpcStr, const sal_Unicode* pcEnd )
{
sal_Unicode cChar = 0;
if( (pcEnd - rpcStr >= XSTRING_ENCCHAR_LEN) &&
(rpcStr[ 0 ] == '_') &&
(rpcStr[ 1 ] == 'x') &&
(rpcStr[ 6 ] == '_') &&
lclAddHexDigit( cChar, rpcStr[ 2 ], 12 ) &&
lclAddHexDigit( cChar, rpcStr[ 3 ], 8 ) &&
lclAddHexDigit( cChar, rpcStr[ 4 ], 4 ) &&
lclAddHexDigit( cChar, rpcStr[ 5 ], 0 ) )
{
rpcStr += XSTRING_ENCCHAR_LEN;
return cChar;
}
return *rpcStr++;
}
} // namespace
// ----------------------------------------------------------------------------
sal_Int32 AttributeConversion::decodeToken( const OUString& rValue )
{
return StaticTokenMap::get().getTokenFromUnicode( rValue );
}
OUString AttributeConversion::decodeXString( const OUString& rValue )
{
// string shorter than one encoded character - no need to decode
if( rValue.getLength() < XSTRING_ENCCHAR_LEN )
return rValue;
OUStringBuffer aBuffer;
const sal_Unicode* pcStr = rValue.getStr();
const sal_Unicode* pcEnd = pcStr + rValue.getLength();
while( pcStr < pcEnd )
aBuffer.append( lclGetXChar( pcStr, pcEnd ) );
return aBuffer.makeStringAndClear();
}
double AttributeConversion::decodeDouble( const OUString& rValue )
{
return rValue.toDouble();
}
sal_Int32 AttributeConversion::decodeInteger( const OUString& rValue )
{
return rValue.toInt32();
}
sal_uInt32 AttributeConversion::decodeUnsigned( const OUString& rValue )
{
return getLimitedValue< sal_uInt32, sal_Int64 >( rValue.toInt64(), 0, SAL_MAX_UINT32 );
}
sal_Int64 AttributeConversion::decodeHyper( const OUString& rValue )
{
return rValue.toInt64();
}
sal_Int32 AttributeConversion::decodeIntegerHex( const OUString& rValue )
{
return rValue.toInt32( 16 );
}
// ============================================================================
AttributeList::AttributeList( const Reference< XFastAttributeList >& rxAttribs ) :
mxAttribs( rxAttribs )
{
OSL_ENSURE( mxAttribs.is(), "AttributeList::AttributeList - missing attribute list interface" );
}
bool AttributeList::hasAttribute( sal_Int32 nAttrToken ) const
{
return mxAttribs->hasAttribute( nAttrToken );
}
// optional return values -----------------------------------------------------
OptValue< sal_Int32 > AttributeList::getToken( sal_Int32 nAttrToken ) const
{
sal_Int32 nToken = mxAttribs->getOptionalValueToken( nAttrToken, XML_TOKEN_INVALID );
return OptValue< sal_Int32 >( nToken != XML_TOKEN_INVALID, nToken );
}
OptValue< OUString > AttributeList::getString( sal_Int32 nAttrToken ) const
{
// check if the attribute exists (empty string may be different to missing attribute)
if( mxAttribs->hasAttribute( nAttrToken ) )
return OptValue< OUString >( mxAttribs->getOptionalValue( nAttrToken ) );
return OptValue< OUString >();
}
OptValue< OUString > AttributeList::getXString( sal_Int32 nAttrToken ) const
{
// check if the attribute exists (empty string may be different to missing attribute)
if( mxAttribs->hasAttribute( nAttrToken ) )
return OptValue< OUString >( AttributeConversion::decodeXString( mxAttribs->getOptionalValue( nAttrToken ) ) );
return OptValue< OUString >();
}
OptValue< double > AttributeList::getDouble( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< double >( bValid, bValid ? AttributeConversion::decodeDouble( aValue ) : 0.0 );
}
OptValue< sal_Int32 > AttributeList::getInteger( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int32 >( bValid, bValid ? AttributeConversion::decodeInteger( aValue ) : 0 );
}
OptValue< sal_uInt32 > AttributeList::getUnsigned( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_uInt32 >( bValid, AttributeConversion::decodeUnsigned( aValue ) );
}
OptValue< sal_Int64 > AttributeList::getHyper( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int64 >( bValid, bValid ? AttributeConversion::decodeHyper( aValue ) : 0 );
}
OptValue< sal_Int32 > AttributeList::getIntegerHex( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
bool bValid = !aValue.isEmpty();
return OptValue< sal_Int32 >( bValid, bValid ? AttributeConversion::decodeIntegerHex( aValue ) : 0 );
}
OptValue< bool > AttributeList::getBool( sal_Int32 nAttrToken ) const
{
// boolean attributes may be "t", "f", "true", "false", "on", "off", "1", or "0"
switch( getToken( nAttrToken, XML_TOKEN_INVALID ) )
{
case XML_t: return OptValue< bool >( true ); // used in VML
case XML_true: return OptValue< bool >( true );
case XML_on: return OptValue< bool >( true );
case XML_f: return OptValue< bool >( false ); // used in VML
case XML_false: return OptValue< bool >( false );
case XML_off: return OptValue< bool >( false );
}
OptValue< sal_Int32 > onValue = getInteger( nAttrToken );
return OptValue< bool >( onValue.has(), onValue.get() != 0 );
}
OptValue< DateTime > AttributeList::getDateTime( sal_Int32 nAttrToken ) const
{
OUString aValue = mxAttribs->getOptionalValue( nAttrToken );
DateTime aDateTime;
bool bValid = (aValue.getLength() == 19) && (aValue[ 4 ] == '-') && (aValue[ 7 ] == '-') &&
(aValue[ 10 ] == 'T') && (aValue[ 13 ] == ':') && (aValue[ 16 ] == ':');
if( bValid )
{
aDateTime.Year = static_cast< sal_uInt16 >( aValue.copy( 0, 4 ).toInt32() );
aDateTime.Month = static_cast< sal_uInt16 >( aValue.copy( 5, 2 ).toInt32() );
aDateTime.Day = static_cast< sal_uInt16 >( aValue.copy( 8, 2 ).toInt32() );
aDateTime.Hours = static_cast< sal_uInt16 >( aValue.copy( 11, 2 ).toInt32() );
aDateTime.Minutes = static_cast< sal_uInt16 >( aValue.copy( 14, 2 ).toInt32() );
aDateTime.Seconds = static_cast< sal_uInt16 >( aValue.copy( 17, 2 ).toInt32() );
}
return OptValue< DateTime >( bValid, aDateTime );
}
// defaulted return values ----------------------------------------------------
sal_Int32 AttributeList::getToken( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return mxAttribs->getOptionalValueToken( nAttrToken, nDefault );
}
OUString AttributeList::getString( sal_Int32 nAttrToken, const OUString& rDefault ) const
{
// try to avoid slow exception throw/catch if we can
if (rDefault.isEmpty())
return mxAttribs->getOptionalValue( nAttrToken );
try
{
return mxAttribs->getValue( nAttrToken );
}
catch( Exception& )
{
}
return rDefault;
}
OUString AttributeList::getXString( sal_Int32 nAttrToken, const OUString& rDefault ) const
{
return getXString( nAttrToken ).get( rDefault );
}
double AttributeList::getDouble( sal_Int32 nAttrToken, double fDefault ) const
{
return getDouble( nAttrToken ).get( fDefault );
}
sal_Int32 AttributeList::getInteger( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return getInteger( nAttrToken ).get( nDefault );
}
sal_uInt32 AttributeList::getUnsigned( sal_Int32 nAttrToken, sal_uInt32 nDefault ) const
{
return getUnsigned( nAttrToken ).get( nDefault );
}
sal_Int64 AttributeList::getHyper( sal_Int32 nAttrToken, sal_Int64 nDefault ) const
{
return getHyper( nAttrToken ).get( nDefault );
}
sal_Int32 AttributeList::getIntegerHex( sal_Int32 nAttrToken, sal_Int32 nDefault ) const
{
return getIntegerHex( nAttrToken ).get( nDefault );
}
bool AttributeList::getBool( sal_Int32 nAttrToken, bool bDefault ) const
{
return getBool( nAttrToken ).get( bDefault );
}
DateTime AttributeList::getDateTime( sal_Int32 nAttrToken, const DateTime& rDefault ) const
{
return getDateTime( nAttrToken ).get( rDefault );
}
// ============================================================================
} // namespace oox
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
reduce exception count reading missing attributes.
|
oox: reduce exception count reading missing attributes.
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
6c8454f1edd85979febf15a7aed9483c2464e745
|
examples/cpp/dispatch_freertos.cpp
|
examples/cpp/dispatch_freertos.cpp
|
#include <thread>
#include <functional>
#include <vector>
#include <cstdint>
#include <cstdio>
#include <queue>
#include <mutex>
#include <string>
#include <condition_variable>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/event_groups.h>
#include <freertos/semphr.h>
#pragma mark - Definitions -
/// Definitions for dispatch event flags
#define DISPATCH_WAKE_EVT (0x1)
#define DISPATCH_EXIT_EVT (0x2)
/// Example thread priority and time slice
#define DISPATCH_Q_PRIORITY 15
/// Thread type
struct freertos_thread_t {
TaskHandle_t thread;
std::string name;
};
/// This Bounce implementation is pulled from bounce.cpp
template<class T, class Method, Method m, class ...Params>
static auto bounce(void *priv, Params... params) ->
decltype(((*reinterpret_cast<T *>(priv)).*m)(params...))
{
return ((*reinterpret_cast<T *>(priv)).*m)(params...);
}
/// Convenience macro to simplify bounce statement usage
#define BOUNCE(c,m) bounce<c, decltype(&c::m), &c::m>
#pragma mark - Dispatch Class -
class dispatch_queue {
typedef std::function<void(void)> fp_t;
public:
dispatch_queue(std::string name, size_t thread_cnt = 1, size_t thread_stack = 1024);
~dispatch_queue();
// dispatch and copy
void dispatch(const fp_t& op);
// dispatch and move
void dispatch(fp_t&& op);
// Deleted operations
dispatch_queue(const dispatch_queue& rhs) = delete;
dispatch_queue& operator=(const dispatch_queue& rhs) = delete;
dispatch_queue(dispatch_queue&& rhs) = delete;
dispatch_queue& operator=(dispatch_queue&& rhs) = delete;
private:
std::string name_;
// FreeRTOS uses semaphore handles for mutexes
SemaphoreHandle_t mutex_;
/// Vector of FreeRTOS Threads
std::vector<freertos_thread_t> threads_;
/// FreeRTOS event flags - like condition variable, used for waking queue threads
EventGroupHandle_t notify_flags_;
std::queue<fp_t> q_;
bool quit_ = false;
void dispatch_thread_handler(void);
};
#pragma mark - Implementation -
dispatch_queue::dispatch_queue(std::string name, size_t thread_cnt, size_t thread_stack_size) :
name_(name), threads_(thread_cnt)
{
// Create the Mutex
mutex_ = xSemaphoreCreateRecursiveMutex();
assert(mutex_ != NULL && "Failed to create mutex!");
// Create the event flags
notify_flags_ = xEventGroupCreate();
assert(notify_flags_ != NULL && "Failed to create event group!");
// Dispatch thread setup
for(size_t i = 0; i < threads_.size(); i++)
{
// Define the name
threads_[i].name = std::string("Dispatch Thread " + std::to_string(i));
// Create the thread
BaseType_t status = xTaskCreate(reinterpret_cast<void(*)(void*)>(
BOUNCE(dispatch_queue, dispatch_thread_handler)),
threads_[i].name.c_str(),
thread_stack_size,
reinterpret_cast<void*>(this),
DISPATCH_Q_PRIORITY,
&threads_[i].thread);
assert(status == pdPASS && "Failed to create thread!");
}
}
dispatch_queue::~dispatch_queue()
{
BaseType_t status;
// Signal to dispatch threads that it's time to wrap up
quit_ = true;
// We will join each thread to confirm exiting
for (size_t i = 0; i < threads_.size(); ++i) {
eTaskState state;
do {
// Signal wake - check exit flag
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
// Wait until a thread signals exit. Timeout is acceptable.
xEventGroupWaitBits(notify_flags_, DISPATCH_EXIT_EVT, pdTRUE, pdFALSE, 10);
// If it was not thread_[i], that is ok, but we will loop around
// until threads_[i] has exited
state = eTaskGetState(threads_[i].thread);
} while (state != eDeleted);
threads_[i].name.clear();
}
// Cleanup event flags and mutex
vEventGroupDelete(notify_flags_);
vSemaphoreDelete(mutex_);
}
void dispatch_queue::dispatch(const fp_t& op)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
q_.push(op);
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Notifies threads that new work has been added to the queue
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
}
void dispatch_queue::dispatch(fp_t&& op)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
q_.push(std::move(op));
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Notifies threads that new work has been added to the queue
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
}
void dispatch_queue::dispatch_thread_handler(void)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
do {
//after wait, we own the lock
if(!quit_ && q_.size())
{
auto op = std::move(q_.front());
q_.pop();
//unlock now that we're done messing with the queue
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
op();
status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
}
else if(!quit_)
{
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Wait for new work - clear flags on exit
xEventGroupWaitBits(notify_flags_, DISPATCH_WAKE_EVT, pdTRUE, pdFALSE, portMAX_DELAY);
status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
}
} while (!quit_);
// We were holding the mutex after we woke up
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Set a signal to indicate a thread exited
status = xEventGroupSetBits(notify_flags_, DISPATCH_EXIT_EVT);
assert(status == pdTRUE && "Failed to set event flags!");
// Delete the current thread
vTaskDelete(NULL);
}
|
#include <thread>
#include <functional>
#include <vector>
#include <cstdint>
#include <cstdio>
#include <queue>
#include <mutex>
#include <string>
#include <condition_variable>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/event_groups.h>
#include <freertos/semphr.h>
#pragma mark - Definitions -
/// Definitions for dispatch event flags
#define DISPATCH_WAKE_EVT (0x1)
#define DISPATCH_EXIT_EVT (0x2)
/// Example thread priority and time slice
#define DISPATCH_Q_PRIORITY 15
/// Thread type
struct freertos_thread_t {
TaskHandle_t thread;
std::string name;
};
/// This Bounce implementation is pulled from bounce.cpp
template<class T, class Method, Method m, class ...Params>
static auto bounce(void *priv, Params... params) ->
decltype(((*reinterpret_cast<T *>(priv)).*m)(params...))
{
return ((*reinterpret_cast<T *>(priv)).*m)(params...);
}
/// Convenience macro to simplify bounce statement usage
#define BOUNCE(c,m) bounce<c, decltype(&c::m), &c::m>
#pragma mark - Dispatch Class -
class dispatch_queue {
typedef std::function<void(void)> fp_t;
public:
dispatch_queue(std::string name, size_t thread_cnt = 1, size_t thread_stack = 1024);
~dispatch_queue();
// dispatch and copy
void dispatch(const fp_t& op);
// dispatch and move
void dispatch(fp_t&& op);
// Deleted operations
dispatch_queue(const dispatch_queue& rhs) = delete;
dispatch_queue& operator=(const dispatch_queue& rhs) = delete;
dispatch_queue(dispatch_queue&& rhs) = delete;
dispatch_queue& operator=(dispatch_queue&& rhs) = delete;
private:
std::string name_;
// FreeRTOS uses semaphore handles for mutexes
SemaphoreHandle_t mutex_;
/// Vector of FreeRTOS Threads
std::vector<freertos_thread_t> threads_;
/// FreeRTOS event flags - like condition variable, used for waking queue threads
EventGroupHandle_t notify_flags_;
std::queue<fp_t> q_;
bool quit_ = false;
void dispatch_thread_handler(void);
};
#pragma mark - Implementation -
dispatch_queue::dispatch_queue(std::string name, size_t thread_cnt, size_t thread_stack_size) :
name_(name), threads_(thread_cnt)
{
// Create the Mutex
mutex_ = xSemaphoreCreateRecursiveMutex();
assert(mutex_ != NULL && "Failed to create mutex!");
// Create the event flags
notify_flags_ = xEventGroupCreate();
assert(notify_flags_ != NULL && "Failed to create event group!");
// Dispatch thread setup
for(size_t i = 0; i < threads_.size(); i++)
{
// Define the name
threads_[i].name = std::string("Dispatch Thread " + std::to_string(i));
// Create the thread
BaseType_t status = xTaskCreate(reinterpret_cast<void(*)(void*)>(
BOUNCE(dispatch_queue, dispatch_thread_handler)),
threads_[i].name.c_str(),
thread_stack_size,
reinterpret_cast<void*>(this),
DISPATCH_Q_PRIORITY,
&threads_[i].thread);
assert(status == pdPASS && "Failed to create thread!");
}
}
dispatch_queue::~dispatch_queue()
{
// Signal to dispatch threads that it's time to wrap up
quit_ = true;
// We will join each thread to confirm exiting
for (size_t i = 0; i < threads_.size(); ++i) {
eTaskState state;
do {
// Signal wake - check exit flag
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
// Wait until a thread signals exit. Timeout is acceptable.
xEventGroupWaitBits(notify_flags_, DISPATCH_EXIT_EVT, pdTRUE, pdFALSE, 10);
// If it was not thread_[i], that is ok, but we will loop around
// until threads_[i] has exited
state = eTaskGetState(threads_[i].thread);
} while (state != eDeleted);
threads_[i].name.clear();
}
// Cleanup event flags and mutex
vEventGroupDelete(notify_flags_);
vSemaphoreDelete(mutex_);
}
void dispatch_queue::dispatch(const fp_t& op)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
q_.push(op);
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Notifies threads that new work has been added to the queue
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
}
void dispatch_queue::dispatch(fp_t&& op)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
q_.push(std::move(op));
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Notifies threads that new work has been added to the queue
xEventGroupSetBits(notify_flags_, DISPATCH_WAKE_EVT);
}
void dispatch_queue::dispatch_thread_handler(void)
{
BaseType_t status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
do {
//after wait, we own the lock
if(!quit_ && q_.size())
{
auto op = std::move(q_.front());
q_.pop();
//unlock now that we're done messing with the queue
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
op();
status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
}
else if(!quit_)
{
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Wait for new work - clear flags on exit
xEventGroupWaitBits(notify_flags_, DISPATCH_WAKE_EVT, pdTRUE, pdFALSE, portMAX_DELAY);
status = xSemaphoreTakeRecursive(mutex_, portMAX_DELAY);
assert(status == pdTRUE && "Failed to lock mutex!");
}
} while (!quit_);
// We were holding the mutex after we woke up
status = xSemaphoreGiveRecursive(mutex_);
assert(status == pdTRUE && "Failed to unlock mutex!");
// Set a signal to indicate a thread exited
status = xEventGroupSetBits(notify_flags_, DISPATCH_EXIT_EVT);
assert(status == pdTRUE && "Failed to set event flags!");
// Delete the current thread
vTaskDelete(NULL);
}
|
Delete unused variable
|
Delete unused variable
|
C++
|
cc0-1.0
|
embeddedartistry/embedded-resources
|
be06e2d3ba564e1d0502411f55793c9c6f00f374
|
ext/common/BackgroundEventLoop.cpp
|
ext/common/BackgroundEventLoop.cpp
|
/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2011-2015 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* 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 <cstdlib>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <oxt/thread.hpp>
#include <ev++.h>
#include <eio.h>
#include <BackgroundEventLoop.h>
#include <Logging.h>
#include <Exceptions.h>
#include <SafeLibev.h>
namespace Passenger {
using namespace std;
using namespace boost;
using namespace oxt;
struct BackgroundEventLoopPrivate {
oxt::thread *thr;
boost::mutex lock;
boost::condition_variable cond;
ev_idle eioRepeatWatcher;
ev_async eioReadyWatcher;
bool useLibeio;
bool started;
};
static BackgroundEventLoop *eioInstanceData = NULL;
static void
signalBackgroundEventLoopExit(struct ev_loop *loop, ev_async *async, int revents) {
BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data;
ev_break(bg->loop, EVBREAK_ALL);
}
static void
startBackgroundLoop(BackgroundEventLoop *bg) {
boost::unique_lock<boost::mutex> l(bg->priv->lock);
bg->safe->setCurrentThread();
bg->priv->started = true;
bg->priv->cond.notify_all();
l.unlock();
ev_run(bg->loop, 0);
}
static void
eioRepeat(EV_P_ ev_idle *w, int revents) {
if (eio_poll() != -1) {
ev_idle_stop(EV_A_ w);
}
}
/* eio has some results, process them */
static void
eioReady(EV_P_ ev_async *w, int revents) {
if (eio_poll() == -1) {
ev_idle_start(EV_A_ &eioInstanceData->priv->eioRepeatWatcher);
}
}
/* wake up the event loop */
static void
eioWantPoll(void) {
ev_async_send(eioInstanceData->loop, &eioInstanceData->priv->eioReadyWatcher);
}
BackgroundEventLoop::BackgroundEventLoop(bool scalable, bool useLibeio) {
TRACE_POINT();
if (scalable) {
loop = ev_loop_new(EVBACKEND_KQUEUE);
if (loop == NULL) {
loop = ev_loop_new(EVBACKEND_EPOLL);
}
if (loop == NULL) {
loop = ev_loop_new(EVFLAG_AUTO);
}
} else {
loop = ev_loop_new(EVBACKEND_POLL);
}
if (loop == NULL) {
throw RuntimeException("Cannot create an event loop");
}
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_backend_fd(loop), "libev event loop: backend FD");
async = (ev_async *) malloc(sizeof(ev_async));
async->data = this;
ev_async_init(async, signalBackgroundEventLoopExit);
ev_async_start(loop, async);
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(loop, 0), "libev event loop: async pipe 0");
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(loop, 1), "libev event loop: async pipe 1");
safe = boost::make_shared<SafeLibev>(loop);
priv = new BackgroundEventLoopPrivate();
priv->thr = NULL;
priv->useLibeio = useLibeio;
priv->started = false;
if (useLibeio) {
eioInstanceData = this;
ev_idle_init(&priv->eioRepeatWatcher, eioRepeat);
ev_async_init(&priv->eioReadyWatcher, eioReady);
ev_async_start(loop, &priv->eioReadyWatcher);
eio_init(eioWantPoll, 0);
}
}
BackgroundEventLoop::~BackgroundEventLoop() {
stop();
if (priv->useLibeio) {
ev_idle_stop(loop, &priv->eioRepeatWatcher);
ev_async_stop(loop, &priv->eioReadyWatcher);
eioInstanceData = NULL;
}
ev_async_stop(loop, async);
delete priv;
free(async);
}
void
BackgroundEventLoop::start(const string &threadName, unsigned int stackSize) {
assert(priv->thr == NULL);
boost::unique_lock<boost::mutex> l(priv->lock);
priv->thr = new oxt::thread(
boost::bind(startBackgroundLoop, this),
threadName,
stackSize
);
while (!priv->started) {
priv->cond.wait(l);
}
}
void
BackgroundEventLoop::stop() {
if (priv->thr != NULL) {
ev_async_send(loop, async);
priv->thr->join();
priv->thr = NULL;
}
}
bool
BackgroundEventLoop::isStarted() const {
return priv->thr != NULL;
}
pthread_t
BackgroundEventLoop::getNativeHandle() const {
return priv->thr->native_handle();
}
} // namespace Passenger
|
/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2011-2015 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* 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 <cstdlib>
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <oxt/thread.hpp>
#include <ev++.h>
#include <eio.h>
#include <BackgroundEventLoop.h>
#include <Logging.h>
#include <Exceptions.h>
#include <SafeLibev.h>
namespace Passenger {
using namespace std;
using namespace boost;
using namespace oxt;
struct BackgroundEventLoopPrivate {
oxt::thread *thr;
boost::mutex lock;
boost::condition_variable cond;
ev_idle eioRepeatWatcher;
ev_async eioReadyWatcher;
bool useLibeio;
bool started;
};
static BackgroundEventLoop *eioInstanceData = NULL;
static void
signalBackgroundEventLoopExit(struct ev_loop *loop, ev_async *async, int revents) {
BackgroundEventLoop *bg = (BackgroundEventLoop *) async->data;
ev_break(bg->loop, EVBREAK_ALL);
}
static void
startBackgroundLoop(BackgroundEventLoop *bg) {
boost::unique_lock<boost::mutex> l(bg->priv->lock);
bg->safe->setCurrentThread();
bg->priv->started = true;
bg->priv->cond.notify_all();
l.unlock();
ev_run(bg->loop, 0);
}
static void
eioRepeat(EV_P_ ev_idle *w, int revents) {
if (eio_poll() != -1) {
ev_idle_stop(EV_A_ w);
}
}
/* eio has some results, process them */
static void
eioReady(EV_P_ ev_async *w, int revents) {
if (eio_poll() == -1) {
ev_idle_start(EV_A_ &eioInstanceData->priv->eioRepeatWatcher);
}
}
/* wake up the event loop */
static void
eioWantPoll(void) {
ev_async_send(eioInstanceData->loop, &eioInstanceData->priv->eioReadyWatcher);
}
BackgroundEventLoop::BackgroundEventLoop(bool scalable, bool useLibeio) {
TRACE_POINT();
if (scalable) {
loop = ev_loop_new(EVBACKEND_KQUEUE);
if (loop == NULL) {
loop = ev_loop_new(EVBACKEND_EPOLL);
}
if (loop == NULL) {
loop = ev_loop_new(EVFLAG_AUTO);
}
} else {
loop = ev_loop_new(EVBACKEND_POLL);
}
if (loop == NULL) {
throw RuntimeException("Cannot create an event loop");
}
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_backend_fd(loop), "libev event loop: backend FD");
async = (ev_async *) malloc(sizeof(ev_async));
async->data = this;
ev_async_init(async, signalBackgroundEventLoopExit);
ev_async_start(loop, async);
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(loop, 0), "libev event loop: async pipe 0");
P_LOG_FILE_DESCRIPTOR_OPEN2(ev_loop_get_pipe(loop, 1), "libev event loop: async pipe 1");
safe = boost::make_shared<SafeLibev>(loop);
priv = new BackgroundEventLoopPrivate();
priv->thr = NULL;
priv->useLibeio = useLibeio;
priv->started = false;
if (useLibeio) {
eioInstanceData = this;
ev_idle_init(&priv->eioRepeatWatcher, eioRepeat);
ev_async_init(&priv->eioReadyWatcher, eioReady);
ev_async_start(loop, &priv->eioReadyWatcher);
eio_init(eioWantPoll, 0);
}
}
BackgroundEventLoop::~BackgroundEventLoop() {
stop();
if (priv->useLibeio) {
ev_idle_stop(loop, &priv->eioRepeatWatcher);
ev_async_stop(loop, &priv->eioReadyWatcher);
eioInstanceData = NULL;
}
ev_async_stop(loop, async);
delete priv;
free(async);
}
void
BackgroundEventLoop::start(const string &threadName, unsigned int stackSize) {
assert(priv->thr == NULL);
boost::unique_lock<boost::mutex> l(priv->lock);
priv->thr = new oxt::thread(
boost::bind(startBackgroundLoop, this),
threadName,
stackSize
);
while (!priv->started) {
priv->cond.wait(l);
}
}
void
BackgroundEventLoop::stop() {
if (priv->thr != NULL) {
ev_async_send(loop, async);
priv->thr->join();
delete priv->thr;
priv->thr = NULL;
}
}
bool
BackgroundEventLoop::isStarted() const {
return priv->thr != NULL;
}
pthread_t
BackgroundEventLoop::getNativeHandle() const {
return priv->thr->native_handle();
}
} // namespace Passenger
|
Fix minor memory leak: delete BackgroundEventLoop thread on shutdown
|
Fix minor memory leak: delete BackgroundEventLoop thread on shutdown
|
C++
|
mit
|
phusion/passenger,kewaunited/passenger,kewaunited/passenger,cgvarela/passenger,kewaunited/passenger,clemensg/passenger,cgvarela/passenger,cgvarela/passenger,phusion/passenger,phusion/passenger,clemensg/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,kewaunited/passenger,clemensg/passenger,clemensg/passenger,antek-drzewiecki/passenger,antek-drzewiecki/passenger,kewaunited/passenger,phusion/passenger,clemensg/passenger,cgvarela/passenger,antek-drzewiecki/passenger,phusion/passenger,clemensg/passenger,clemensg/passenger,kewaunited/passenger,phusion/passenger,cgvarela/passenger,antek-drzewiecki/passenger,cgvarela/passenger,phusion/passenger,cgvarela/passenger,kewaunited/passenger,antek-drzewiecki/passenger,cgvarela/passenger,phusion/passenger,kewaunited/passenger,clemensg/passenger
|
403355398acc3ee3280e7e27fa814c26a93e2949
|
cql3/restrictions/single_column_restriction.hh
|
cql3/restrictions/single_column_restriction.hh
|
/*
* 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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/restrictions/abstract_restriction.hh"
#include "cql3/term.hh"
#include "core/shared_ptr.hh"
#include "database.hh"
#include "to_string.hh"
#include "exceptions/exceptions.hh"
namespace cql3 {
namespace restrictions {
class single_column_restriction : public abstract_restriction {
protected:
/**
* The definition of the column to which apply the restriction.
*/
const column_definition& _column_def;
public:
single_column_restriction(const column_definition& column_def)
: _column_def(column_def)
{ }
const column_definition& get_column_def() {
return _column_def;
}
#if 0
@Override
public void addIndexExpressionTo(List<IndexExpression> expressions,
QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> values = values(options);
checkTrue(values.size() == 1, "IN restrictions are not supported on indexed columns");
ByteBuffer value = validateIndexedValue(columnDef, values.get(0));
expressions.add(new IndexExpression(columnDef.name.bytes, Operator.EQ, value));
}
@Override
public boolean hasSupportingIndex(SecondaryIndexManager indexManager)
{
SecondaryIndex index = indexManager.getIndexForColumn(columnDef.name.bytes);
return index != null && isSupportedBy(index);
}
/**
* Check if this type of restriction is supported by the specified index.
*
* @param index the Secondary index
* @return <code>true</code> this type of restriction is supported by the specified index,
* <code>false</code> otherwise.
*/
protected abstract boolean isSupportedBy(SecondaryIndex index);
#endif
class EQ;
#if 0
public static abstract class IN extends SingleColumnRestriction
{
public IN(ColumnDefinition columnDef)
{
super(columnDef);
}
@Override
public final boolean isIN()
{
return true;
}
@Override
public final Restriction mergeWith(Restriction otherRestriction) throws InvalidRequestException
{
throw invalidRequest("%s cannot be restricted by more than one relation if it includes a IN", columnDef.name);
}
@Override
protected final boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.IN);
}
}
public static class InWithValues extends IN
{
protected final List<Term> values;
public InWithValues(ColumnDefinition columnDef, List<Term> values)
{
super(columnDef);
this.values = values;
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return usesFunction(values, ksName, functionName);
}
@Override
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> buffers = new ArrayList<>(values.size());
for (Term value : values)
buffers.add(value.bindAndGet(options));
return buffers;
}
@Override
public String toString()
{
return String.format("IN(%s)", values);
}
}
public static class InWithMarker extends IN
{
protected final AbstractMarker marker;
public InWithMarker(ColumnDefinition columnDef, AbstractMarker marker)
{
super(columnDef);
this.marker = marker;
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return false;
}
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
Term.MultiItemTerminal lval = (Term.MultiItemTerminal) marker.bind(options);
if (lval == null)
throw new InvalidRequestException("Invalid null value for IN restriction");
return lval.getElements();
}
@Override
public String toString()
{
return "IN ?";
}
}
public static class Slice extends SingleColumnRestriction
{
private final TermSlice slice;
public Slice(ColumnDefinition columnDef, Bound bound, boolean inclusive, Term term)
{
super(columnDef);
slice = TermSlice.newInstance(bound, inclusive, term);
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return (slice.hasBound(Bound.START) && usesFunction(slice.bound(Bound.START), ksName, functionName))
|| (slice.hasBound(Bound.END) && usesFunction(slice.bound(Bound.END), ksName, functionName));
}
public boolean isSlice()
{
return true;
}
@Override
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
throw new UnsupportedOperationException();
}
@Override
public boolean hasBound(Bound b)
{
return slice.hasBound(b);
}
@Override
public List<ByteBuffer> bounds(Bound b, QueryOptions options) throws InvalidRequestException
{
return Collections.singletonList(slice.bound(b).bindAndGet(options));
}
@Override
public boolean isInclusive(Bound b)
{
return slice.isInclusive(b);
}
@Override
public Restriction mergeWith(Restriction otherRestriction)
throws InvalidRequestException
{
checkTrue(otherRestriction.isSlice(),
"Column \"%s\" cannot be restricted by both an equality and an inequality relation",
columnDef.name);
SingleColumnRestriction.Slice otherSlice = (SingleColumnRestriction.Slice) otherRestriction;
checkFalse(hasBound(Bound.START) && otherSlice.hasBound(Bound.START),
"More than one restriction was found for the start bound on %s", columnDef.name);
checkFalse(hasBound(Bound.END) && otherSlice.hasBound(Bound.END),
"More than one restriction was found for the end bound on %s", columnDef.name);
return new Slice(columnDef, slice.merge(otherSlice.slice));
}
@Override
public void addIndexExpressionTo(List<IndexExpression> expressions,
QueryOptions options) throws InvalidRequestException
{
for (Bound b : Bound.values())
{
if (hasBound(b))
{
ByteBuffer value = validateIndexedValue(columnDef, slice.bound(b).bindAndGet(options));
Operator op = slice.getIndexOperator(b);
// If the underlying comparator for name is reversed, we need to reverse the IndexOperator: user operation
// always refer to the "forward" sorting even if the clustering order is reversed, but the 2ndary code does
// use the underlying comparator as is.
op = columnDef.isReversedType() ? op.reverse() : op;
expressions.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
}
@Override
protected boolean isSupportedBy(SecondaryIndex index)
{
return slice.isSupportedBy(index);
}
@Override
public String toString()
{
return String.format("SLICE%s", slice);
}
private Slice(ColumnDefinition columnDef, TermSlice slice)
{
super(columnDef);
this.slice = slice;
}
}
#endif
class contains;
};
class single_column_restriction::EQ final : public single_column_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(column_definition& column_def, ::shared_ptr<term> value)
: single_column_restriction(column_def)
, _value(std::move(value))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
virtual bool is_EQ() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> v;
v.push_back(_value->bind_and_get(options));
return v;
}
virtual sstring to_string() override {
return sprint("EQ(%s)", _value->to_string());
}
virtual void merge_with(::shared_ptr<restriction> other) {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes an Equal", _column_def.name_as_text()));
}
#if 0
@Override
protected boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.EQ);
}
#endif
};
// This holds CONTAINS, CONTAINS_KEY, and map[key] = value restrictions because we might want to have any combination of them.
class single_column_restriction::contains final : public single_column_restriction {
private:
std::vector<::shared_ptr<term>> _values;
std::vector<::shared_ptr<term>> _keys;
std::vector<::shared_ptr<term>> _entry_keys;
std::vector<::shared_ptr<term>> _entry_values;
public:
contains(column_definition& column_def, ::shared_ptr<term> t, bool is_key)
: single_column_restriction(column_def) {
if (is_key) {
_keys.emplace_back(std::move(t));
} else {
_values.emplace_back(std::move(t));
}
}
contains(column_definition& column_def, ::shared_ptr<term> map_key, ::shared_ptr<term> map_value)
: single_column_restriction(column_def) {
_entry_keys.emplace_back(std::move(map_key));
_entry_values.emplace_back(std::move(map_value));
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
return bind_and_get(_values, options);
}
virtual bool is_contains() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> other_restriction) override {
if (!other_restriction->is_contains()) {
throw exceptions::invalid_request_exception(sprint(
"Collection column %s can only be restricted by CONTAINS, CONTAINS KEY, or map-entry equality",
get_column_def().name_as_text()));
}
auto other = static_pointer_cast<contains>(other_restriction);
std::copy(other->_values.begin(), other->_values.end(), std::back_inserter(_values));
std::copy(other->_keys.begin(), other->_keys.end(), std::back_inserter(_keys));
std::copy(other->_entry_keys.begin(), other->_entry_keys.end(), std::back_inserter(_entry_keys));
std::copy(other->_entry_values.begin(), other->_entry_values.end(), std::back_inserter(_entry_values));
}
#if 0
virtual void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
add_expressions_for(expressions, values(options), operator_type::CONTAINS);
add_expressions_for(expressions, keys(options), operator_type::CONTAINS_KEY);
add_expressions_for(expressions, entries(options), operator_type::EQ);
}
private void add_expressions_for(std::vector<::shared_ptr<index_expression>>& target, std::vector<bytes_opt> values,
const operator_type& op) {
for (ByteBuffer value : values)
{
validateIndexedValue(columnDef, value);
target.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
virtual bool is_supported_by(SecondaryIndex index) override {
bool supported = false;
if (numberOfValues() > 0)
supported |= index.supportsOperator(Operator.CONTAINS);
if (numberOfKeys() > 0)
supported |= index.supportsOperator(Operator.CONTAINS_KEY);
if (numberOfEntries() > 0)
supported |= index.supportsOperator(Operator.EQ);
return supported;
}
#endif
uint32_t number_of_values() {
return _values.size();
}
uint32_t number_of_keys() {
return _keys.size();
}
uint32_t number_of_entries() {
return _entry_keys.size();
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name)
|| abstract_restriction::uses_function(_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_values, ks_name, function_name);
}
virtual sstring to_string() override {
return sprint("CONTAINS(values=%s, keys=%s, entryKeys=%s, entryValues=%s)",
::to_string(_values), ::to_string(_keys), ::to_string(_entry_keys), ::to_string(_entry_values));
}
virtual bool has_bound(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool is_inclusive(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
#if 0
private List<ByteBuffer> keys(const query_options& options) {
return bindAndGet(keys, options);
}
private List<ByteBuffer> entries(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> entryBuffers = new ArrayList<>(_entry_keys.size());
List<ByteBuffer> keyBuffers = bindAndGet(_entry_keys, options);
List<ByteBuffer> valueBuffers = bindAndGet(_entry_values, options);
for (int i = 0; i < _entry_keys.size(); i++)
{
if (valueBuffers.get(i) == null)
throw new InvalidRequestException("Unsupported null value for map-entry equality");
entryBuffers.add(CompositeType.build(keyBuffers.get(i), valueBuffers.get(i)));
}
return entryBuffers;
}
#endif
private:
/**
* Binds the query options to the specified terms and returns the resulting values.
*
* @param terms the terms
* @param options the query options
* @return the value resulting from binding the query options to the specified terms
* @throws invalid_request_exception if a problem occurs while binding the query options
*/
static std::vector<bytes_opt> bind_and_get(std::vector<::shared_ptr<term>> terms, const query_options& options) {
std::vector<bytes_opt> values;
values.reserve(terms.size());
for (auto&& term : terms) {
values.emplace_back(term->bind_and_get(options));
}
return values;
}
};
}
}
|
/*
* 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 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "cql3/restrictions/abstract_restriction.hh"
#include "cql3/restrictions/term_slice.hh"
#include "cql3/term.hh"
#include "core/shared_ptr.hh"
#include "database.hh"
#include "to_string.hh"
#include "exceptions/exceptions.hh"
namespace cql3 {
namespace restrictions {
class single_column_restriction : public abstract_restriction {
protected:
/**
* The definition of the column to which apply the restriction.
*/
const column_definition& _column_def;
public:
single_column_restriction(const column_definition& column_def)
: _column_def(column_def)
{ }
const column_definition& get_column_def() {
return _column_def;
}
#if 0
@Override
public void addIndexExpressionTo(List<IndexExpression> expressions,
QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> values = values(options);
checkTrue(values.size() == 1, "IN restrictions are not supported on indexed columns");
ByteBuffer value = validateIndexedValue(columnDef, values.get(0));
expressions.add(new IndexExpression(columnDef.name.bytes, Operator.EQ, value));
}
@Override
public boolean hasSupportingIndex(SecondaryIndexManager indexManager)
{
SecondaryIndex index = indexManager.getIndexForColumn(columnDef.name.bytes);
return index != null && isSupportedBy(index);
}
/**
* Check if this type of restriction is supported by the specified index.
*
* @param index the Secondary index
* @return <code>true</code> this type of restriction is supported by the specified index,
* <code>false</code> otherwise.
*/
protected abstract boolean isSupportedBy(SecondaryIndex index);
#endif
class EQ;
#if 0
public static abstract class IN extends SingleColumnRestriction
{
public IN(ColumnDefinition columnDef)
{
super(columnDef);
}
@Override
public final boolean isIN()
{
return true;
}
@Override
public final Restriction mergeWith(Restriction otherRestriction) throws InvalidRequestException
{
throw invalidRequest("%s cannot be restricted by more than one relation if it includes a IN", columnDef.name);
}
@Override
protected final boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.IN);
}
}
public static class InWithValues extends IN
{
protected final List<Term> values;
public InWithValues(ColumnDefinition columnDef, List<Term> values)
{
super(columnDef);
this.values = values;
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return usesFunction(values, ksName, functionName);
}
@Override
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> buffers = new ArrayList<>(values.size());
for (Term value : values)
buffers.add(value.bindAndGet(options));
return buffers;
}
@Override
public String toString()
{
return String.format("IN(%s)", values);
}
}
public static class InWithMarker extends IN
{
protected final AbstractMarker marker;
public InWithMarker(ColumnDefinition columnDef, AbstractMarker marker)
{
super(columnDef);
this.marker = marker;
}
@Override
public boolean usesFunction(String ksName, String functionName)
{
return false;
}
public List<ByteBuffer> values(QueryOptions options) throws InvalidRequestException
{
Term.MultiItemTerminal lval = (Term.MultiItemTerminal) marker.bind(options);
if (lval == null)
throw new InvalidRequestException("Invalid null value for IN restriction");
return lval.getElements();
}
@Override
public String toString()
{
return "IN ?";
}
}
#endif
class slice;
class contains;
};
class single_column_restriction::EQ final : public single_column_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(column_definition& column_def, ::shared_ptr<term> value)
: single_column_restriction(column_def)
, _value(std::move(value))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
virtual bool is_EQ() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
std::vector<bytes_opt> v;
v.push_back(_value->bind_and_get(options));
return v;
}
virtual sstring to_string() override {
return sprint("EQ(%s)", _value->to_string());
}
virtual void merge_with(::shared_ptr<restriction> other) {
throw exceptions::invalid_request_exception(sprint(
"%s cannot be restricted by more than one relation if it includes an Equal", _column_def.name_as_text()));
}
#if 0
@Override
protected boolean isSupportedBy(SecondaryIndex index)
{
return index.supportsOperator(Operator.EQ);
}
#endif
};
class single_column_restriction::slice : public single_column_restriction {
private:
term_slice _slice;
public:
slice(const column_definition& column_def, statements::bound bound, bool inclusive, ::shared_ptr<term> term)
: single_column_restriction(column_def)
, _slice(term_slice::new_instance(bound, inclusive, std::move(term)))
{ }
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return (_slice.has_bound(statements::bound::START) && abstract_restriction::uses_function(_slice.bound(statements::bound::START), ks_name, function_name))
|| (_slice.has_bound(statements::bound::END) && abstract_restriction::uses_function(_slice.bound(statements::bound::END), ks_name, function_name));
}
virtual bool is_slice() override {
return true;
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool has_bound(statements::bound b) override {
return _slice.has_bound(b);
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
return {_slice.bound(b)->bind_and_get(options)};
}
virtual bool is_inclusive(statements::bound b) override {
return _slice.is_inclusive(b);
}
virtual void merge_with(::shared_ptr<restriction> r) override {
if (!r->is_slice()) {
throw exceptions::invalid_request_exception(sprint(
"Column \"%s\" cannot be restricted by both an equality and an inequality relation", _column_def.name_as_text()));
}
auto other_slice = static_pointer_cast<slice>(r);
if (has_bound(statements::bound::START) && other_slice->has_bound(statements::bound::START)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the start bound on %s", _column_def.name_as_text()));
}
if (has_bound(statements::bound::END) && other_slice->has_bound(statements::bound::END)) {
throw exceptions::invalid_request_exception(sprint(
"More than one restriction was found for the end bound on %s", _column_def.name_as_text()));
}
_slice.merge(other_slice->_slice);
}
#if 0
virtual void addIndexExpressionTo(List<IndexExpression> expressions, override
QueryOptions options) throws InvalidRequestException
{
for (statements::bound b : {statements::bound::START, statements::bound::END})
{
if (has_bound(b))
{
ByteBuffer value = validateIndexedValue(columnDef, _slice.bound(b).bindAndGet(options));
Operator op = _slice.getIndexOperator(b);
// If the underlying comparator for name is reversed, we need to reverse the IndexOperator: user operation
// always refer to the "forward" sorting even if the clustering order is reversed, but the 2ndary code does
// use the underlying comparator as is.
op = columnDef.isReversedType() ? op.reverse() : op;
expressions.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
}
virtual bool isSupportedBy(SecondaryIndex index) override
{
return _slice.isSupportedBy(index);
}
#endif
virtual sstring to_string() override {
return sprint("SLICE%s", _slice);
}
};
// This holds CONTAINS, CONTAINS_KEY, and map[key] = value restrictions because we might want to have any combination of them.
class single_column_restriction::contains final : public single_column_restriction {
private:
std::vector<::shared_ptr<term>> _values;
std::vector<::shared_ptr<term>> _keys;
std::vector<::shared_ptr<term>> _entry_keys;
std::vector<::shared_ptr<term>> _entry_values;
public:
contains(column_definition& column_def, ::shared_ptr<term> t, bool is_key)
: single_column_restriction(column_def) {
if (is_key) {
_keys.emplace_back(std::move(t));
} else {
_values.emplace_back(std::move(t));
}
}
contains(column_definition& column_def, ::shared_ptr<term> map_key, ::shared_ptr<term> map_value)
: single_column_restriction(column_def) {
_entry_keys.emplace_back(std::move(map_key));
_entry_values.emplace_back(std::move(map_value));
}
virtual std::vector<bytes_opt> values(const query_options& options) override {
return bind_and_get(_values, options);
}
virtual bool is_contains() override {
return true;
}
virtual void merge_with(::shared_ptr<restriction> other_restriction) override {
if (!other_restriction->is_contains()) {
throw exceptions::invalid_request_exception(sprint(
"Collection column %s can only be restricted by CONTAINS, CONTAINS KEY, or map-entry equality",
get_column_def().name_as_text()));
}
auto other = static_pointer_cast<contains>(other_restriction);
std::copy(other->_values.begin(), other->_values.end(), std::back_inserter(_values));
std::copy(other->_keys.begin(), other->_keys.end(), std::back_inserter(_keys));
std::copy(other->_entry_keys.begin(), other->_entry_keys.end(), std::back_inserter(_entry_keys));
std::copy(other->_entry_values.begin(), other->_entry_values.end(), std::back_inserter(_entry_values));
}
#if 0
virtual void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
add_expressions_for(expressions, values(options), operator_type::CONTAINS);
add_expressions_for(expressions, keys(options), operator_type::CONTAINS_KEY);
add_expressions_for(expressions, entries(options), operator_type::EQ);
}
private void add_expressions_for(std::vector<::shared_ptr<index_expression>>& target, std::vector<bytes_opt> values,
const operator_type& op) {
for (ByteBuffer value : values)
{
validateIndexedValue(columnDef, value);
target.add(new IndexExpression(columnDef.name.bytes, op, value));
}
}
virtual bool is_supported_by(SecondaryIndex index) override {
bool supported = false;
if (numberOfValues() > 0)
supported |= index.supportsOperator(Operator.CONTAINS);
if (numberOfKeys() > 0)
supported |= index.supportsOperator(Operator.CONTAINS_KEY);
if (numberOfEntries() > 0)
supported |= index.supportsOperator(Operator.EQ);
return supported;
}
#endif
uint32_t number_of_values() {
return _values.size();
}
uint32_t number_of_keys() {
return _keys.size();
}
uint32_t number_of_entries() {
return _entry_keys.size();
}
virtual bool uses_function(const sstring& ks_name, const sstring& function_name) override {
return abstract_restriction::uses_function(_values, ks_name, function_name)
|| abstract_restriction::uses_function(_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_keys, ks_name, function_name)
|| abstract_restriction::uses_function(_entry_values, ks_name, function_name);
}
virtual sstring to_string() override {
return sprint("CONTAINS(values=%s, keys=%s, entryKeys=%s, entryValues=%s)",
::to_string(_values), ::to_string(_keys), ::to_string(_entry_keys), ::to_string(_entry_values));
}
virtual bool has_bound(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
virtual std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
virtual bool is_inclusive(statements::bound b) override {
throw exceptions::unsupported_operation_exception();
}
#if 0
private List<ByteBuffer> keys(const query_options& options) {
return bindAndGet(keys, options);
}
private List<ByteBuffer> entries(QueryOptions options) throws InvalidRequestException
{
List<ByteBuffer> entryBuffers = new ArrayList<>(_entry_keys.size());
List<ByteBuffer> keyBuffers = bindAndGet(_entry_keys, options);
List<ByteBuffer> valueBuffers = bindAndGet(_entry_values, options);
for (int i = 0; i < _entry_keys.size(); i++)
{
if (valueBuffers.get(i) == null)
throw new InvalidRequestException("Unsupported null value for map-entry equality");
entryBuffers.add(CompositeType.build(keyBuffers.get(i), valueBuffers.get(i)));
}
return entryBuffers;
}
#endif
private:
/**
* Binds the query options to the specified terms and returns the resulting values.
*
* @param terms the terms
* @param options the query options
* @return the value resulting from binding the query options to the specified terms
* @throws invalid_request_exception if a problem occurs while binding the query options
*/
static std::vector<bytes_opt> bind_and_get(std::vector<::shared_ptr<term>> terms, const query_options& options) {
std::vector<bytes_opt> values;
values.reserve(terms.size());
for (auto&& term : terms) {
values.emplace_back(term->bind_and_get(options));
}
return values;
}
};
}
}
|
Convert SingleColumnRestriction.Slice
|
cql3: Convert SingleColumnRestriction.Slice
|
C++
|
agpl-3.0
|
kangkot/scylla,avikivity/scylla,kangkot/scylla,glommer/scylla,justintung/scylla,shaunstanislaus/scylla,gwicke/scylla,eklitzke/scylla,justintung/scylla,senseb/scylla,scylladb/scylla,capturePointer/scylla,stamhe/scylla,phonkee/scylla,tempbottle/scylla,duarten/scylla,senseb/scylla,eklitzke/scylla,stamhe/scylla,linearregression/scylla,acbellini/scylla,shaunstanislaus/scylla,senseb/scylla,rentongzhang/scylla,eklitzke/scylla,guiquanz/scylla,scylladb/scylla,justintung/scylla,avikivity/scylla,rentongzhang/scylla,respu/scylla,victorbriz/scylla,capturePointer/scylla,kjniemi/scylla,scylladb/scylla,respu/scylla,aruanruan/scylla,linearregression/scylla,kangkot/scylla,acbellini/scylla,glommer/scylla,glommer/scylla,gwicke/scylla,acbellini/scylla,kjniemi/scylla,stamhe/scylla,phonkee/scylla,capturePointer/scylla,aruanruan/scylla,raphaelsc/scylla,aruanruan/scylla,gwicke/scylla,duarten/scylla,rluta/scylla,guiquanz/scylla,asias/scylla,bowlofstew/scylla,duarten/scylla,bowlofstew/scylla,asias/scylla,victorbriz/scylla,phonkee/scylla,raphaelsc/scylla,asias/scylla,wildinto/scylla,bowlofstew/scylla,raphaelsc/scylla,dwdm/scylla,scylladb/scylla,respu/scylla,dwdm/scylla,rluta/scylla,wildinto/scylla,tempbottle/scylla,kjniemi/scylla,dwdm/scylla,rentongzhang/scylla,shaunstanislaus/scylla,victorbriz/scylla,guiquanz/scylla,rluta/scylla,wildinto/scylla,linearregression/scylla,avikivity/scylla,tempbottle/scylla
|
ae4f3cd90c5d2ab5e92d014be84e908717ee93ac
|
Cube/MainScene.hpp
|
Cube/MainScene.hpp
|
#pragma once
#include <EasyDx/Events.hpp>
#include <EasyDx/Scene.hpp>
#include <EasyDx/RenderedObject.hpp>
#include <EasyDx/Shaders.hpp>
#include <DirectXMath.h>
//wrl::ComPtr 对于 incomplete type 的支持问题。
#include <d3d11.h>
class MainScene : public dx::Scene
{
protected:
void Render(ID3D11DeviceContext& context, ID2D1DeviceContext&) override;
void Start() override;
void Destroy() noexcept override;
private:
void InitializeObjects();
DirectX::XMFLOAT4X4 world_;
wrl::ComPtr<ID3D11Buffer> constantBuffer_;
dx::RenderedObject cube_;
dx::VertexShader vs_;
wrl::ComPtr<ID3D11PixelShader> ps_;
std::vector<dx::EventHandle> eventHandles_;
};
|
#pragma once
#include <EasyDx/Events.hpp>
#include <EasyDx/Scene.hpp>
#include <EasyDx/RenderedObject.hpp>
#include <EasyDx/Shaders.hpp>
#include <DirectXMath.h>
//wrl::ComPtr 对于 incomplete type 的支持问题。
#include <d3d11.h>
class MainScene : public dx::Scene
{
protected:
void Render(ID3D11DeviceContext& context, ID2D1DeviceContext&) override;
void Start() override;
void Destroy() noexcept override;
private:
void InitializeObjects();
wrl::ComPtr<ID3D11Buffer> constantBuffer_;
dx::RenderedObject cube_;
dx::VertexShader vs_;
wrl::ComPtr<ID3D11PixelShader> ps_;
std::vector<dx::EventHandle> eventHandles_;
};
|
Remove the redundant `world_` member.
|
Remove the redundant `world_` member.
|
C++
|
apache-2.0
|
LYP951018/EasyDX
|
c0ab92789a7fa9d2e6a9bbdf96442b07006c8e0c
|
DMIC_test/main.cpp
|
DMIC_test/main.cpp
|
//=====================================================================//
/*! @file
@brief デジタル・マイク制御 (R5F100ECA) 40ピン @n
ROM: 32K, RAM: @n
P15: green LED @n
P16: red LED @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/adc_io.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/itimer.hpp"
#include "common/flash_io.hpp"
#include "common/command.hpp"
#include "sw.hpp"
namespace {
typedef device::itimer<uint8_t> ITM;
ITM itm_;
// UART1 の定義(SAU2、SAU3)
typedef utils::fifo<uint8_t, 64> BUFFER;
typedef device::uart_io<device::SAU00, device::SAU01, BUFFER, BUFFER> UART0;
typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1;
UART0 uart0_;
// UART1 uart1_;
typedef device::iica_io<device::IICA0> IICA;
IICA iica_;
// 最終チャネル番号+1を設定
typedef device::adc_io<1, utils::null_task> ADC;
ADC adc_;
typedef device::flash_io FLASH;
FLASH flash_;
// utils::command<64> command_;
// MIC 切り替え、入力定義
typedef device::PORT<device::port_no::P12, device::bitpos::B2> MIC_SW1;
typedef device::PORT<device::port_no::P12, device::bitpos::B1> MIC_SW2;
utils::sw2<MIC_SW1, MIC_SW2> sw2_;
// CH 設定、入力定義
typedef device::PORT<device::port_no::P2, device::bitpos::B1> CH_SW1;
typedef device::PORT<device::port_no::P2, device::bitpos::B0> CH_SW2;
typedef device::PORT<device::port_no::P0, device::bitpos::B1> CH_SW3;
typedef device::PORT<device::port_no::P0, device::bitpos::B0> CH_SW4;
typedef device::PORT<device::port_no::P12, device::bitpos::B0> CH_SW5;
utils::sw5<CH_SW1, CH_SW2, CH_SW3, CH_SW4, CH_SW5> sw5_;
}
extern "C" {
void sci_putch(char ch)
{
uart0_.putch(ch);
}
void sci_puts(const char* str)
{
uart0_.puts(str);
}
char sci_getch(void)
{
return uart0_.getch();
}
uint16_t sci_length()
{
return uart0_.recv_length();
}
void UART0_TX_intr(void)
{
uart0_.send_task();
}
void UART0_RX_intr(void)
{
uart0_.recv_task();
}
void UART0_ER_intr(void)
{
uart0_.error_task();
}
void ADC_intr(void)
{
adc_.task();
}
void ITM_intr(void)
{
itm_.task();
}
};
int main(int argc, char* argv[])
{
using namespace device;
// utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
// itimer の開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART0 の開始
{
uint8_t intr_level = 1;
uart0_.start(115200, intr_level);
}
// IICA(I2C) の開始
{
uint8_t intr_level = 0;
// if(!iica_.start(IICA::speed::fast, intr_level)) {
if(!iica_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
}
// A/D の開始
{
device::PM2.B0 = 1;
uint8_t intr_level = 1; // 割り込み設定
adc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level);
}
// data flash の開始
{
}
ADPC = 0x01; // A/D input All digital port
PM2.B3 = 0; // POWER CTRL (OUTPUT)
P2.B3 = 1; // Active high (ON)
PM1.B5 = 0; // LED G output
PM1.B6 = 0; // LED R output
sw2_.start();
PMC12 = 0xfe; // setup P12_0: digital port
sw5_.start();
utils::format("Start Digital MIC\n");
uint8_t cnt = 0;
uint8_t n = 0;
while(1) {
itm_.sync();
if(sci_length() > 0) {
char ch = sci_getch();
sci_putch(ch);
}
++n;
if(n >= 60) {
utils::format("MIC: %02b\n") % static_cast<uint16_t>(sw2_.get());
utils::format("CH: %05b\n") % static_cast<uint16_t>(sw5_.get());
n = 0;
}
if(cnt >= 20) {
cnt = 0;
}
if(cnt < 10) {
P1.B5 = 1;
P1.B6 = 0;
} else {
P1.B5 = 0;
P1.B6 = 1;
}
++cnt;
}
}
|
//=====================================================================//
/*! @file
@brief デジタル・マイク制御 (R5F100ECA) 40ピン @n
ROM: 32K, RAM: @n
P15: green LED @n
P16: red LED @n
@author 平松邦仁 ([email protected])
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RL78/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/port_utils.hpp"
#include "common/fifo.hpp"
#include "common/uart_io.hpp"
#include "common/adc_io.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/itimer.hpp"
#include "common/flash_io.hpp"
#include "common/command.hpp"
#include "sw.hpp"
namespace {
typedef device::itimer<uint8_t> ITM;
ITM itm_;
// UART1 の定義(SAU2、SAU3)
typedef utils::fifo<uint8_t, 64> BUFFER;
typedef device::uart_io<device::SAU00, device::SAU01, BUFFER, BUFFER> UART0;
typedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1;
UART0 uart0_;
// UART1 uart1_;
typedef device::iica_io<device::IICA0> IICA;
IICA iica_;
// 最終チャネル番号+1を設定
typedef device::adc_io<1, utils::null_task> ADC;
ADC adc_;
typedef device::flash_io FLASH;
FLASH flash_;
// utils::command<64> command_;
// MIC 切り替え、入力定義
typedef device::PORT<device::port_no::P12, device::bitpos::B2> MIC_SW1;
typedef device::PORT<device::port_no::P12, device::bitpos::B1> MIC_SW2;
utils::sw2<MIC_SW1, MIC_SW2> sw2_;
// CH 設定、入力定義
typedef device::PORT<device::port_no::P2, device::bitpos::B1> CH_SW1;
typedef device::PORT<device::port_no::P2, device::bitpos::B0> CH_SW2;
typedef device::PORT<device::port_no::P0, device::bitpos::B1> CH_SW3;
typedef device::PORT<device::port_no::P0, device::bitpos::B0> CH_SW4;
typedef device::PORT<device::port_no::P12, device::bitpos::B0> CH_SW5;
utils::sw5<CH_SW1, CH_SW2, CH_SW3, CH_SW4, CH_SW5> sw5_;
// Volume +/-
typedef device::PORT<device::port_no::P3, device::bitpos::B1> VOL_UP;
typedef device::PORT<device::port_no::P7, device::bitpos::B3> VOL_DN;
utils::sw2<VOL_UP, VOL_DN> vol_;
}
extern "C" {
void sci_putch(char ch)
{
uart0_.putch(ch);
}
void sci_puts(const char* str)
{
uart0_.puts(str);
}
char sci_getch(void)
{
return uart0_.getch();
}
uint16_t sci_length()
{
return uart0_.recv_length();
}
INTERRUPT_FUNC void UART0_TX_intr(void)
{
uart0_.send_task();
}
INTERRUPT_FUNC void UART0_RX_intr(void)
{
uart0_.recv_task();
}
INTERRUPT_FUNC void UART0_ER_intr(void)
{
uart0_.error_task();
}
INTERRUPT_FUNC void ADC_intr(void)
{
adc_.task();
}
INTERRUPT_FUNC void ITM_intr(void)
{
itm_.task();
}
};
int main(int argc, char* argv[])
{
using namespace device;
// utils::port::pullup_all(); ///< 安全の為、全ての入力をプルアップ
// itimer の開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART0 の開始
{
uint8_t intr_level = 1;
uart0_.start(19200, intr_level);
}
// IICA(I2C) の開始
{
uint8_t intr_level = 0;
// if(!iica_.start(IICA::speed::fast, intr_level)) {
if(!iica_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica_.get_last_error());
}
}
// A/D の開始
{
device::PM2.B0 = 1;
uint8_t intr_level = 1; // 割り込み設定
adc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level);
}
// data flash の開始
{
}
ADPC = 0x01; // A/D input All digital port
PM2.B3 = 0; // POWER CTRL (OUTPUT)
P2.B3 = 1; // Active high (ON)
PM1.B5 = 0; // LED G output
PM1.B6 = 0; // LED R output
sw2_.start();
PMC12 = 0b11111110; // setup P12_0: digital port
sw5_.start();
vol_.start();
/// utils::format("Start Digital MIC\n");
uint8_t cnt = 0;
uint8_t vol = 0;
while(1) {
itm_.sync();
vol_.service();
if(vol_.positive() & 1) {
if(vol < 8) {
++vol;
}
}
if(vol_.positive() & 2) {
if(vol > 0) {
--vol;
}
}
if(uart0_.recv_length() > 0) {
char ch = uart0_.getch();
if(ch == 'C') { // CH-SW (0 to 31)
auto n = sw5_.get();
uart0_.putch((n / 10) + '0');
uart0_.putch((n % 10) + '0');
uart0_.putch('\n');
} else if(ch == 'M') { // MIC-SW (0 to 3)
auto n = sw2_.get();
uart0_.putch((n % 10) + '0');
uart0_.putch('\n');
} else if(ch == 'F') { // 混信フラグ (0 to 1)
uart0_.putch('0');
uart0_.putch('\n');
} else if(ch == 'V') { // ボリューム値
uart0_.putch('0' + vol);
uart0_.putch('\n');
}
}
if(cnt >= 20) {
cnt = 0;
}
if(cnt < 10) {
P1.B5 = 1;
P1.B6 = 0;
} else {
P1.B5 = 0;
P1.B6 = 1;
}
++cnt;
}
}
|
update serial management
|
update serial management
|
C++
|
bsd-3-clause
|
hirakuni45/RL78,hirakuni45/RL78,hirakuni45/RL78
|
22655d8e1abbb8e6b0fba9d3a6cd68b1a1709028
|
external/vulkancts/modules/vulkan/texture/vktTextureFilteringAnisotropyTests.cpp
|
external/vulkancts/modules/vulkan/texture/vktTextureFilteringAnisotropyTests.cpp
|
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group 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.
*
*//*!
* \file
* \brief Texture filtering anisotropy tests
*//*--------------------------------------------------------------------*/
#include "vktTextureFilteringAnisotropyTests.hpp"
#include "vktTextureTestUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkQueryUtil.hpp"
#include "tcuImageCompare.hpp"
#include <vector>
using namespace vk;
namespace vkt
{
namespace texture
{
using std::string;
using std::vector;
using std::max;
using std::min;
using tcu::Vec2;
using tcu::Vec4;
using tcu::Sampler;
using tcu::Surface;
using tcu::TextureFormat;
using namespace texture::util;
using namespace glu::TextureTestUtil;
namespace
{
static const deUint32 ANISOTROPY_TEST_RESOLUTION = 128u;
struct AnisotropyParams : public ReferenceParams
{
AnisotropyParams (const TextureType texType_,
const float maxAnisotropy_,
const Sampler::FilterMode minFilter_,
const Sampler::FilterMode magFilter_,
const bool mipMap_ = false)
: ReferenceParams (texType_)
, maxAnisotropy (maxAnisotropy_)
, minFilter (minFilter_)
, magFilter (magFilter_)
, mipMap (mipMap_)
{
}
float maxAnisotropy;
Sampler::FilterMode minFilter;
Sampler::FilterMode magFilter;
bool mipMap;
};
class FilteringAnisotropyInstance : public vkt::TestInstance
{
public:
FilteringAnisotropyInstance (Context& context, const AnisotropyParams& refParams)
: vkt::TestInstance (context)
, m_refParams (refParams)
{
// Sampling parameters.
m_refParams.sampler = util::createSampler(Sampler::CLAMP_TO_EDGE, Sampler::CLAMP_TO_EDGE, m_refParams.minFilter, m_refParams.magFilter);
m_refParams.samplerType = getSamplerType(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
m_refParams.flags = 0u;
m_refParams.lodMode = LODMODE_EXACT;
m_refParams.maxAnisotropy = min(getPhysicalDeviceProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()).limits.maxSamplerAnisotropy, m_refParams.maxAnisotropy);
if (m_refParams.mipMap)
{
m_refParams.maxLevel = deLog2Floor32(ANISOTROPY_TEST_RESOLUTION);
m_refParams.minLod = 0.0f;
m_refParams.maxLod = static_cast<float>(m_refParams.maxLevel);
}
else
m_refParams.maxLevel = 0;
}
tcu::TestStatus iterate (void)
{
// Check device for anisotropic filtering support
if (!m_context.getDeviceFeatures().samplerAnisotropy)
TCU_THROW(NotSupportedError, "Skipping anisotropic tests since the device does not support anisotropic filtering.");
TextureRenderer renderer (m_context, VK_SAMPLE_COUNT_1_BIT, ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
TestTexture2DSp texture = TestTexture2DSp(new pipeline::TestTexture2D(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM), ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION));
for (int levelNdx = 0; levelNdx < m_refParams.maxLevel + 1; levelNdx++)
{
const int gridSize = max(texture->getLevel(levelNdx, 0).getHeight() / 8, 1);
tcu::fillWithGrid(texture->getLevel(levelNdx, 0), gridSize, Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4(1.0f));
}
renderer.setViewport(0.0f, 0.0f, static_cast<float>(ANISOTROPY_TEST_RESOLUTION), static_cast<float>(ANISOTROPY_TEST_RESOLUTION));
renderer.add2DTexture(texture);
{
Surface renderedFrame (ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
Surface renderedAnisotropyFrame (ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
const float position[] =
{
-3.5f, -1.0f, 0.0f, 3.5f,
-3.5f, +1.0f, 0.0f, 1.0f,
+3.5f, -1.0f, 0.0f, 3.5f,
+3.5f, +1.0f, 0.0f, 1.0f
};
vector<float> texCoord;
computeQuadTexCoord2D(texCoord, Vec2(0.0f), Vec2(1.0f));
renderer.renderQuad(renderedFrame, position, 0, &texCoord[0], m_refParams, 1.0f);
renderer.renderQuad(renderedAnisotropyFrame, position, 0, &texCoord[0], m_refParams, m_refParams.maxAnisotropy);
if (!tcu::fuzzyCompare(m_context.getTestContext().getLog(), "Expecting comparison to pass", "Expecting comparison to pass",
renderedFrame.getAccess(), renderedAnisotropyFrame.getAccess(), 0.05f, tcu::COMPARE_LOG_RESULT))
return tcu::TestStatus::fail("Fail");
// Anisotropic filtering is implementation dependent. Expecting differences with minification/magnification filter set to NEAREST is too strict.
if (m_refParams.minFilter != tcu::Sampler::NEAREST && m_refParams.magFilter != tcu::Sampler::NEAREST)
{
if (floatThresholdCompare (m_context.getTestContext().getLog(), "Expecting comparison to fail", "Expecting comparison to fail",
renderedFrame.getAccess(), renderedAnisotropyFrame.getAccess(), Vec4(0.05f), tcu::COMPARE_LOG_RESULT))
return tcu::TestStatus::fail("Fail");
}
}
return tcu::TestStatus::pass("Pass");
}
private:
AnisotropyParams m_refParams;
};
class FilteringAnisotropyTests : public vkt::TestCase
{
public:
FilteringAnisotropyTests (tcu::TestContext& testCtx,
const string& name,
const string& description,
const AnisotropyParams& refParams)
: vkt::TestCase (testCtx, name, description)
, m_refParams (refParams)
{
}
void initPrograms (SourceCollections& programCollection) const
{
std::vector<util::Program> programs;
programs.push_back(util::PROGRAM_2D_FLOAT);
initializePrograms(programCollection,glu::PRECISION_HIGHP, programs);
}
TestInstance* createInstance (Context& context) const
{
return new FilteringAnisotropyInstance(context, m_refParams);
}
private :
const AnisotropyParams m_refParams;
};
} // anonymous
tcu::TestCaseGroup* createFilteringAnisotropyTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> filteringAnisotropyTests (new tcu::TestCaseGroup(testCtx, "filtering_anisotropy", "Filtering anisotropy tests"));
de::MovePtr<tcu::TestCaseGroup> basicTests (new tcu::TestCaseGroup(testCtx, "basic", "Filtering anisotropy tests"));
de::MovePtr<tcu::TestCaseGroup> mipmapTests (new tcu::TestCaseGroup(testCtx, "mipmap", "Filtering anisotropy tests"));
const char* valueName[] =
{
"anisotropy_2",
"anisotropy_4",
"anisotropy_8",
"anisotropy_max"
};
const float maxAnisotropy[] =
{
2.0f,
4.0f,
8.0f,
10000.0f //too huge will be flated to max value
};
const char* magFilterName[] =
{
"nearest",
"linear"
};
const tcu::Sampler::FilterMode magFilters[] =
{
Sampler::NEAREST,
Sampler::LINEAR
};
{
const tcu::Sampler::FilterMode* minFilters = magFilters;
const char** minFilterName = magFilterName;
for (int anisotropyNdx = 0; anisotropyNdx < DE_LENGTH_OF_ARRAY(maxAnisotropy); anisotropyNdx++)
{
de::MovePtr<tcu::TestCaseGroup> levelAnisotropyGroups (new tcu::TestCaseGroup(testCtx, valueName[anisotropyNdx], "Filtering anisotropy tests"));
for (int minFilterNdx = 0; minFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); minFilterNdx++)
for (int magFilterNdx = 0; magFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); magFilterNdx++)
{
AnisotropyParams refParams (TEXTURETYPE_2D, maxAnisotropy[anisotropyNdx] ,minFilters[minFilterNdx], magFilters[magFilterNdx]);
levelAnisotropyGroups->addChild(new FilteringAnisotropyTests(testCtx,
"mag_" + string(magFilterName[magFilterNdx]) + "_min_" + string(minFilterName[minFilterNdx]),
"Texture filtering anisotropy basic tests", refParams));
}
basicTests->addChild(levelAnisotropyGroups.release());
}
filteringAnisotropyTests->addChild(basicTests.release());
}
{
const tcu::Sampler::FilterMode minFilters[] =
{
Sampler::NEAREST_MIPMAP_NEAREST,
Sampler::NEAREST_MIPMAP_LINEAR,
Sampler::LINEAR_MIPMAP_NEAREST,
Sampler::LINEAR_MIPMAP_LINEAR
};
const char* minFilterName[] =
{
"nearest_mipmap_nearest",
"nearest_mipmap_linear",
"linear_mipmap_nearest",
"linear_mipmap_linear"
};
for (int anisotropyNdx = 0; anisotropyNdx < DE_LENGTH_OF_ARRAY(maxAnisotropy); anisotropyNdx++)
{
de::MovePtr<tcu::TestCaseGroup> levelAnisotropyGroups (new tcu::TestCaseGroup(testCtx, valueName[anisotropyNdx], "Filtering anisotropy tests"));
for (int minFilterNdx = 0; minFilterNdx < DE_LENGTH_OF_ARRAY(minFilters); minFilterNdx++)
for (int magFilterNdx = 0; magFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); magFilterNdx++)
{
AnisotropyParams refParams (TEXTURETYPE_2D, maxAnisotropy[anisotropyNdx] ,minFilters[minFilterNdx], magFilters[magFilterNdx], true);
levelAnisotropyGroups->addChild(new FilteringAnisotropyTests(testCtx,
"mag_" + string(magFilterName[magFilterNdx]) + "_min_" + string(minFilterName[minFilterNdx]),
"Texture filtering anisotropy basic tests", refParams));
}
mipmapTests->addChild(levelAnisotropyGroups.release());
}
filteringAnisotropyTests->addChild(mipmapTests.release());
}
return filteringAnisotropyTests.release();
}
} // texture
} // vkt
|
/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2016 The Khronos Group 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.
*
*//*!
* \file
* \brief Texture filtering anisotropy tests
*//*--------------------------------------------------------------------*/
#include "vktTextureFilteringAnisotropyTests.hpp"
#include "vktTextureTestUtil.hpp"
#include "vkImageUtil.hpp"
#include "vkQueryUtil.hpp"
#include "tcuImageCompare.hpp"
#include <vector>
using namespace vk;
namespace vkt
{
namespace texture
{
using std::string;
using std::vector;
using std::max;
using std::min;
using tcu::Vec2;
using tcu::Vec4;
using tcu::Sampler;
using tcu::Surface;
using tcu::TextureFormat;
using namespace texture::util;
using namespace glu::TextureTestUtil;
namespace
{
static const deUint32 ANISOTROPY_TEST_RESOLUTION = 128u;
struct AnisotropyParams : public ReferenceParams
{
AnisotropyParams (const TextureType texType_,
const float maxAnisotropy_,
const Sampler::FilterMode minFilter_,
const Sampler::FilterMode magFilter_,
const bool mipMap_ = false)
: ReferenceParams (texType_)
, maxAnisotropy (maxAnisotropy_)
, minFilter (minFilter_)
, magFilter (magFilter_)
, mipMap (mipMap_)
{
}
float maxAnisotropy;
Sampler::FilterMode minFilter;
Sampler::FilterMode magFilter;
bool mipMap;
};
class FilteringAnisotropyInstance : public vkt::TestInstance
{
public:
FilteringAnisotropyInstance (Context& context, const AnisotropyParams& refParams)
: vkt::TestInstance (context)
, m_refParams (refParams)
{
// Sampling parameters.
m_refParams.sampler = util::createSampler(Sampler::CLAMP_TO_EDGE, Sampler::CLAMP_TO_EDGE, m_refParams.minFilter, m_refParams.magFilter);
m_refParams.samplerType = getSamplerType(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM));
m_refParams.flags = 0u;
m_refParams.lodMode = LODMODE_EXACT;
m_refParams.maxAnisotropy = min(getPhysicalDeviceProperties(m_context.getInstanceInterface(), m_context.getPhysicalDevice()).limits.maxSamplerAnisotropy, m_refParams.maxAnisotropy);
if (m_refParams.mipMap)
{
m_refParams.maxLevel = deLog2Floor32(ANISOTROPY_TEST_RESOLUTION);
m_refParams.minLod = 0.0f;
m_refParams.maxLod = static_cast<float>(m_refParams.maxLevel);
}
else
m_refParams.maxLevel = 0;
}
tcu::TestStatus iterate (void)
{
// Check device for anisotropic filtering support
if (!m_context.getDeviceFeatures().samplerAnisotropy)
TCU_THROW(NotSupportedError, "Skipping anisotropic tests since the device does not support anisotropic filtering.");
TextureRenderer renderer (m_context, VK_SAMPLE_COUNT_1_BIT, ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
TestTexture2DSp texture = TestTexture2DSp(new pipeline::TestTexture2D(vk::mapVkFormat(VK_FORMAT_R8G8B8A8_UNORM), ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION));
for (int levelNdx = 0; levelNdx < m_refParams.maxLevel + 1; levelNdx++)
{
const int gridSize = max(texture->getLevel(levelNdx, 0).getHeight() / 8, 1);
tcu::fillWithGrid(texture->getLevel(levelNdx, 0), gridSize, Vec4(0.0f, 0.0f, 0.0f, 1.0f), Vec4(1.0f));
}
renderer.setViewport(0.0f, 0.0f, static_cast<float>(ANISOTROPY_TEST_RESOLUTION), static_cast<float>(ANISOTROPY_TEST_RESOLUTION));
renderer.add2DTexture(texture);
{
Surface renderedFrame (ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
Surface renderedAnisotropyFrame (ANISOTROPY_TEST_RESOLUTION, ANISOTROPY_TEST_RESOLUTION);
const float position[] =
{
-3.5f, -1.0f, 0.0f, 3.5f,
-3.5f, +1.0f, 0.0f, 1.0f,
+3.5f, -1.0f, 0.0f, 3.5f,
+3.5f, +1.0f, 0.0f, 1.0f
};
vector<float> texCoord;
computeQuadTexCoord2D(texCoord, Vec2(0.0f), Vec2(1.0f));
renderer.renderQuad(renderedFrame, position, 0, &texCoord[0], m_refParams, 1.0f);
renderer.renderQuad(renderedAnisotropyFrame, position, 0, &texCoord[0], m_refParams, m_refParams.maxAnisotropy);
if (!tcu::fuzzyCompare(m_context.getTestContext().getLog(), "Expecting comparison to pass", "Expecting comparison to pass",
renderedFrame.getAccess(), renderedAnisotropyFrame.getAccess(), 0.05f, tcu::COMPARE_LOG_RESULT))
return tcu::TestStatus::fail("Fail");
// Anisotropic filtering is implementation dependent. Expecting differences with minification/magnification filter set to NEAREST is too strict.
// The specification does not require that your aniso & bi-linear filtering are different even in LINEAR, but this check is 'generally' going
// to detect *some* difference and possibly be useful in catching issues where an implementation hasn't setup their filtering modes correctly.
if (m_refParams.minFilter != tcu::Sampler::NEAREST && m_refParams.magFilter != tcu::Sampler::NEAREST)
{
if (floatThresholdCompare (m_context.getTestContext().getLog(), "Expecting comparison to fail", "Expecting comparison to fail",
renderedFrame.getAccess(), renderedAnisotropyFrame.getAccess(), Vec4(0.02f), tcu::COMPARE_LOG_RESULT))
return tcu::TestStatus::fail("Fail");
}
}
return tcu::TestStatus::pass("Pass");
}
private:
AnisotropyParams m_refParams;
};
class FilteringAnisotropyTests : public vkt::TestCase
{
public:
FilteringAnisotropyTests (tcu::TestContext& testCtx,
const string& name,
const string& description,
const AnisotropyParams& refParams)
: vkt::TestCase (testCtx, name, description)
, m_refParams (refParams)
{
}
void initPrograms (SourceCollections& programCollection) const
{
std::vector<util::Program> programs;
programs.push_back(util::PROGRAM_2D_FLOAT);
initializePrograms(programCollection,glu::PRECISION_HIGHP, programs);
}
TestInstance* createInstance (Context& context) const
{
return new FilteringAnisotropyInstance(context, m_refParams);
}
private :
const AnisotropyParams m_refParams;
};
} // anonymous
tcu::TestCaseGroup* createFilteringAnisotropyTests (tcu::TestContext& testCtx)
{
de::MovePtr<tcu::TestCaseGroup> filteringAnisotropyTests (new tcu::TestCaseGroup(testCtx, "filtering_anisotropy", "Filtering anisotropy tests"));
de::MovePtr<tcu::TestCaseGroup> basicTests (new tcu::TestCaseGroup(testCtx, "basic", "Filtering anisotropy tests"));
de::MovePtr<tcu::TestCaseGroup> mipmapTests (new tcu::TestCaseGroup(testCtx, "mipmap", "Filtering anisotropy tests"));
const char* valueName[] =
{
"anisotropy_2",
"anisotropy_4",
"anisotropy_8",
"anisotropy_max"
};
const float maxAnisotropy[] =
{
2.0f,
4.0f,
8.0f,
10000.0f //too huge will be flated to max value
};
const char* magFilterName[] =
{
"nearest",
"linear"
};
const tcu::Sampler::FilterMode magFilters[] =
{
Sampler::NEAREST,
Sampler::LINEAR
};
{
const tcu::Sampler::FilterMode* minFilters = magFilters;
const char** minFilterName = magFilterName;
for (int anisotropyNdx = 0; anisotropyNdx < DE_LENGTH_OF_ARRAY(maxAnisotropy); anisotropyNdx++)
{
de::MovePtr<tcu::TestCaseGroup> levelAnisotropyGroups (new tcu::TestCaseGroup(testCtx, valueName[anisotropyNdx], "Filtering anisotropy tests"));
for (int minFilterNdx = 0; minFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); minFilterNdx++)
for (int magFilterNdx = 0; magFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); magFilterNdx++)
{
AnisotropyParams refParams (TEXTURETYPE_2D, maxAnisotropy[anisotropyNdx] ,minFilters[minFilterNdx], magFilters[magFilterNdx]);
levelAnisotropyGroups->addChild(new FilteringAnisotropyTests(testCtx,
"mag_" + string(magFilterName[magFilterNdx]) + "_min_" + string(minFilterName[minFilterNdx]),
"Texture filtering anisotropy basic tests", refParams));
}
basicTests->addChild(levelAnisotropyGroups.release());
}
filteringAnisotropyTests->addChild(basicTests.release());
}
{
const tcu::Sampler::FilterMode minFilters[] =
{
Sampler::NEAREST_MIPMAP_NEAREST,
Sampler::NEAREST_MIPMAP_LINEAR,
Sampler::LINEAR_MIPMAP_NEAREST,
Sampler::LINEAR_MIPMAP_LINEAR
};
const char* minFilterName[] =
{
"nearest_mipmap_nearest",
"nearest_mipmap_linear",
"linear_mipmap_nearest",
"linear_mipmap_linear"
};
for (int anisotropyNdx = 0; anisotropyNdx < DE_LENGTH_OF_ARRAY(maxAnisotropy); anisotropyNdx++)
{
de::MovePtr<tcu::TestCaseGroup> levelAnisotropyGroups (new tcu::TestCaseGroup(testCtx, valueName[anisotropyNdx], "Filtering anisotropy tests"));
for (int minFilterNdx = 0; minFilterNdx < DE_LENGTH_OF_ARRAY(minFilters); minFilterNdx++)
for (int magFilterNdx = 0; magFilterNdx < DE_LENGTH_OF_ARRAY(magFilters); magFilterNdx++)
{
AnisotropyParams refParams (TEXTURETYPE_2D, maxAnisotropy[anisotropyNdx] ,minFilters[minFilterNdx], magFilters[magFilterNdx], true);
levelAnisotropyGroups->addChild(new FilteringAnisotropyTests(testCtx,
"mag_" + string(magFilterName[magFilterNdx]) + "_min_" + string(minFilterName[minFilterNdx]),
"Texture filtering anisotropy basic tests", refParams));
}
mipmapTests->addChild(levelAnisotropyGroups.release());
}
filteringAnisotropyTests->addChild(mipmapTests.release());
}
return filteringAnisotropyTests.release();
}
} // texture
} // vkt
|
Make texture aniso basic self tests less sensitive
|
Make texture aniso basic self tests less sensitive
The tests cases first check with a fuzzy diff that the images are more
or less the same.
The second diff then checks with a standard image comparison + tolerance
that the images are not identical.
Some of IMG's implementations produce a closer image than the test is
currently expecting - we need to lower the tolerance from 0.05 to 0.02
in order for the diff algorithm to detect that the images are
different 'enough'.
Though there is no actual spec requirement, it is 'generally going to
be the case', for any implementation, that the images will have some
amount of difference. It is potentially useful to still have this test
inplace to check againsty aniso being accidently disabled in the tested
implementation, rather than remove it altogether.
Affects:
dEQP-VK.texture.filtering_anisotropy.basic.*
Components: Vulkan
VK-GL-CTS Issue: 2047
Change-Id: Ia9148e12172ac1c4757f5007e57b3a2b3a3434eb
|
C++
|
apache-2.0
|
KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS
|
2945e4249cace286d7bebcf58f2251193db5d153
|
test/fuzzers/producer_fec_fuzzer.cc
|
test/fuzzers/producer_fec_fuzzer.cc
|
/*
* Copyright (c) 2015 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/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/modules/rtp_rtcp/source/producer_fec.h"
namespace webrtc {
void FuzzOneInput(const uint8_t* data, size_t size) {
ForwardErrorCorrection fec;
ProducerFec producer(&fec);
size_t i = 0;
if (size < 4)
return;
FecProtectionParams params = {data[i++] % 128, data[i++] % 2 == 1,
static_cast<int>(data[i++] % 10),
kFecMaskBursty};
producer.SetFecParameters(¶ms, 0);
uint16_t seq_num = data[i++];
while (i + 3 < size) {
size_t rtp_header_length = data[i++] % 10 + 12;
size_t payload_size = data[i++] % 10;
if (i + payload_size + rtp_header_length + 2 > size)
break;
rtc::scoped_ptr<uint8_t[]> packet(
new uint8_t[payload_size + rtp_header_length]);
memcpy(packet.get(), &data[i], payload_size + rtp_header_length);
ByteWriter<uint16_t>::WriteBigEndian(&packet[2], seq_num++);
i += payload_size + rtp_header_length;
// Make sure sequence numbers are increasing.
const int kRedPayloadType = 98;
rtc::scoped_ptr<RedPacket> red_packet(producer.BuildRedPacket(
packet.get(), payload_size, rtp_header_length, kRedPayloadType));
const bool protect = data[i++] % 2 == 1;
if (protect) {
producer.AddRtpPacketAndGenerateFec(packet.get(), payload_size,
rtp_header_length);
}
const size_t num_fec_packets = producer.NumAvailableFecPackets();
if (num_fec_packets > 0) {
std::vector<RedPacket*> fec_packets =
producer.GetFecPackets(kRedPayloadType, 99, 100, rtp_header_length);
RTC_CHECK_EQ(num_fec_packets, fec_packets.size());
for (RedPacket* fec_packet : fec_packets)
delete fec_packet;
}
}
}
} // namespace webrtc
|
/*
* Copyright (c) 2015 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/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"
#include "webrtc/modules/rtp_rtcp/source/producer_fec.h"
namespace webrtc {
void FuzzOneInput(const uint8_t* data, size_t size) {
ForwardErrorCorrection fec;
ProducerFec producer(&fec);
size_t i = 0;
if (size < 4)
return;
FecProtectionParams params = {
data[i++] % 128, static_cast<int>(data[i++] % 10), kFecMaskBursty};
producer.SetFecParameters(¶ms, 0);
uint16_t seq_num = data[i++];
while (i + 3 < size) {
size_t rtp_header_length = data[i++] % 10 + 12;
size_t payload_size = data[i++] % 10;
if (i + payload_size + rtp_header_length + 2 > size)
break;
rtc::scoped_ptr<uint8_t[]> packet(
new uint8_t[payload_size + rtp_header_length]);
memcpy(packet.get(), &data[i], payload_size + rtp_header_length);
ByteWriter<uint16_t>::WriteBigEndian(&packet[2], seq_num++);
i += payload_size + rtp_header_length;
// Make sure sequence numbers are increasing.
const int kRedPayloadType = 98;
rtc::scoped_ptr<RedPacket> red_packet(producer.BuildRedPacket(
packet.get(), payload_size, rtp_header_length, kRedPayloadType));
const bool protect = data[i++] % 2 == 1;
if (protect) {
producer.AddRtpPacketAndGenerateFec(packet.get(), payload_size,
rtp_header_length);
}
const size_t num_fec_packets = producer.NumAvailableFecPackets();
if (num_fec_packets > 0) {
std::vector<RedPacket*> fec_packets =
producer.GetFecPackets(kRedPayloadType, 99, 100, rtp_header_length);
RTC_CHECK_EQ(num_fec_packets, fec_packets.size());
for (RedPacket* fec_packet : fec_packets)
delete fec_packet;
}
}
}
} // namespace webrtc
|
Fix producer_fec_fuzzer.
|
Fix producer_fec_fuzzer.
A field was removed from FecProtectionParams in
https://codereview.webrtc.org/1917083003.
BUG=webrtc:5066
[email protected], [email protected]
Review URL: https://codereview.webrtc.org/1922283002 .
Cr-Original-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#12518}
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: d6b9d772c2dacecab151f2e1ee5d17de72198eec
|
C++
|
bsd-3-clause
|
jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,jchavanton/webrtc
|
d9160591deb6c3337da7583cc1e56bd0abe52daa
|
lib/node_modules/@stdlib/strided/common/examples/addon-nan-polymorphic/addon.cpp
|
lib/node_modules/@stdlib/strided/common/examples/addon-nan-polymorphic/addon.cpp
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
/**
* Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*/
#include <stdint.h>
#include <nan.h>
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/strided_binary.h"
/**
* Add-on namespace.
*/
namespace addon_strided_add {
using Nan::FunctionCallbackInfo;
using Nan::TypedArrayContents;
using Nan::ThrowTypeError;
using Nan::ThrowError;
using v8::Local;
using v8::Value;
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param x typed array
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( Local<Value> x ) {
if ( x->IsFloat64Array() ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( x->IsFloat32Array() ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( x->IsInt32Array() ) {
return STDLIB_NDARRAY_INT32;
}
if ( x->IsUint32Array() ) {
return STDLIB_NDARRAY_UINT32;
}
if ( x->IsInt16Array() ) {
return STDLIB_NDARRAY_INT16;
}
if ( x->IsUint16Array() ) {
return STDLIB_NDARRAY_UINT16;
}
if ( x->IsInt8Array() ) {
return STDLIB_NDARRAY_INT8;
}
if ( x->IsUint8Array() ) {
return STDLIB_NDARRAY_UINT8;
}
return STDLIB_NDARRAY_UINT8; // Uint8ClampedArray
}
/**
* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
*
* ## Notes
*
* - The function assumes the following argument order:
*
* ```text
* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
* ```
*
* where
*
* - `N` is the number of elements over which to iterate
* - `ia#` is an input strided array
* - `is#` is a corresponding input strided array stride (in units of elements)
* - `oa#` is an output strided array
* - `os#` is a corresponding output strided array stride (in units of elements)
*
* - We **assume** no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more strided input arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer strided input arrays).
*
* @private
* @param info arguments
* @param nargs total number of arguments
* @param nin number of input strided array arguments
* @param nout number of output strided array arguments
* @param arrays destination array containing pointers to both input and output strided byte arrays
* @param shape destination array containing the array shape (dimensions)
* @param strides destination array containing array strides (in bytes) for each strided array
* @param types destination array containing strided array argument data types
* @return number of scalar strided "array" arguments
*/
int64_t stdlib_nan_addon_strided_array_function_arguments( const FunctionCallbackInfo<Value>& info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
int64_t nsargs;
int64_t sargs;
int64_t iout;
int64_t i;
int64_t j;
// Compute the index of the first output strided array argument:
iout = ( nin*2 ) + 1;
// Initialize variables used to track scalar input arguments:
nsargs = 0;
sargs = 0;
if ( info.Length() != nargs ) {
ThrowError( "invalid invocation. Incorrect number of arguments." );
return -1;
}
// The first argument is always the number of elements over which to iterate...
if ( !info[ 0 ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. First argument must be a number." );
return -1;
} else {
shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() );
}
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
if ( !info[ i ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. Stride argument must be a number." );
return -1;
}
j = ( i-2 ) / 2;
strides[ j ] = static_cast<int64_t>( info[ i ]->IntegerValue() );
}
#if defined(V8_MAJOR_VERSION) && ( V8_MAJOR_VERSION > 4 || ( V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3 ) )
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsArrayBufferView() ) {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
nsargs += 1;
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
if ( !info[ i ]->IsArrayBufferView() ) {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return -1;
} else {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
}
}
#else
// TODO: add support for older Node versions (type verification and strides; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc and https://github.com/nodejs/nan/blob/master/nan_typedarray_contents.h)
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
nsargs += 1;
} else if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from the typed array instance)
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from typed array instance)
} else {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return -1;
}
}
#endif
// Check if we have been provided only scalar input arguments...
if ( nin > 0 && nsargs == nin ) {
ThrowError( "invalid input arguments. Must provide at least one input strided array argument." );
return -1;
}
return nsargs;
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* When called from JavaScript, the function expects the following arguments:
*
* * __N__: number of elements.
* * __X__: input typed array.
* * __strideX__: `X` stride length.
* * __Y__: input typed array.
* * __strideY__: `Y` typed array stride length.
* * __Z__: destination typed array.
* * __strideZ__: destination typed array stride length.
*
* @param info arguments
*/
void node_add( const FunctionCallbackInfo<Value>& info ) {
enum STDLIB_NDARRAY_DTYPE types[3];
uint8_t *arrays[3];
int64_t strides[3];
int64_t shape[1];
int64_t nsargs;
int64_t nargs;
int64_t nout;
int64_t nin;
// Total number of input arguments:
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Validate, extract, and transform strided array function arguments:
nsargs = stdlib_nan_addon_strided_array_function_arguments( info, nargs, nin, nout, arrays, shape, strides, types );
if ( nsargs < 0 ) {
return;
}
// Broadcasting of scalar arguments...
if ( nsargs > 0 ) {
// Create an array having the closest "compatible" type...
// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
// Perform addition:
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
}
NAN_MODULE_INIT( Init ) {
Nan::Export( target, "add", node_add );
}
NODE_MODULE( addon, Init )
} // end namespace addon_strided_add
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib 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.
*/
/**
* Add each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*/
#include <stdint.h>
#include <nan.h>
#include "stdlib/ndarray/base/bytes_per_element.h"
#include "stdlib/ndarray/dtypes.h"
#include "stdlib/strided_binary.h"
/**
* Add-on namespace.
*/
namespace addon_strided_add {
using Nan::FunctionCallbackInfo;
using Nan::TypedArrayContents;
using Nan::ThrowTypeError;
using Nan::ThrowError;
using v8::Local;
using v8::Value;
/**
* Adds two doubles.
*
* @private
* @param x first double
* @param y second double
* @return sum
*/
double add( double x, double y ) {
return x + y;
}
/**
* Returns a typed array data type.
*
* @private
* @param x typed array
* @return data type
*/
enum STDLIB_NDARRAY_DTYPE typed_array_data_type( Local<Value> x ) {
if ( x->IsFloat64Array() ) {
return STDLIB_NDARRAY_FLOAT64;
}
if ( x->IsFloat32Array() ) {
return STDLIB_NDARRAY_FLOAT32;
}
if ( x->IsInt32Array() ) {
return STDLIB_NDARRAY_INT32;
}
if ( x->IsUint32Array() ) {
return STDLIB_NDARRAY_UINT32;
}
if ( x->IsInt16Array() ) {
return STDLIB_NDARRAY_INT16;
}
if ( x->IsUint16Array() ) {
return STDLIB_NDARRAY_UINT16;
}
if ( x->IsInt8Array() ) {
return STDLIB_NDARRAY_INT8;
}
if ( x->IsUint8Array() ) {
return STDLIB_NDARRAY_UINT8;
}
return STDLIB_NDARRAY_UINT8; // Uint8ClampedArray
}
/**
* Validates, extracts, and transforms arguments provided to the main entry point for a Node.js add-on to native C types.
*
* ## Notes
*
* - The function assumes the following argument order:
*
* ```text
* [ N, ia1, is1, ia2, is2, ..., oa1, os1, oa2, os2, ... ]
* ```
*
* where
*
* - `N` is the number of elements over which to iterate
* - `ia#` is an input strided array
* - `is#` is a corresponding input strided array stride (in units of elements)
* - `oa#` is an output strided array
* - `os#` is a corresponding output strided array stride (in units of elements)
*
* - We **assume** no more than `64` input strided array arguments, which seems a reasonable assumption, as strided array functions which operate over `65` or more input strided arrays are **exceedingly** unlikely (most strided array functions operate on 3 or fewer input strided arrays).
*
* @private
* @param info arguments
* @param nargs total number of arguments
* @param nin number of input strided array arguments
* @param nout number of output strided array arguments
* @param arrays destination array containing pointers to both input and output strided byte arrays
* @param shape destination array containing the array shape (dimensions)
* @param strides destination array containing array strides (in bytes) for each strided array
* @param types destination array containing strided array argument data types
* @throws must provide expected number of input arguments
* @throws stride arguments must be numbers
* @throws input strided array arguments must be either typed arrays or scalars
* @throws output strided array arguments must be typed arrays
* @throws must provide at least one input strided array
* @return number of scalar strided "array" arguments
*/
int64_t stdlib_nan_addon_strided_array_function_arguments( const FunctionCallbackInfo<Value>& info, const int64_t nargs, const int64_t nin, const int64_t nout, uint8_t *arrays[], int64_t *shape, int64_t *strides, enum STDLIB_NDARRAY_DTYPE *types ) {
int64_t nsargs;
int64_t sargs;
int64_t iout;
int64_t i;
int64_t j;
// Compute the index of the first output strided array argument:
iout = ( nin*2 ) + 1;
// Initialize variables used to track scalar input arguments:
nsargs = 0;
sargs = 0;
if ( info.Length() != nargs ) {
ThrowError( "invalid invocation. Incorrect number of arguments." );
return -1;
}
// The first argument is always the number of elements over which to iterate...
if ( !info[ 0 ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. First argument must be a number." );
return -1;
} else {
shape[ 0 ] = static_cast<int64_t>( info[ 0 ]->IntegerValue() );
}
// Stride arguments for both input and output strided arrays are every other argument beginning from the third argument...
for ( i = 2; i < nargs; i += 2 ) {
if ( !info[ i ]->IsNumber() ) {
ThrowTypeError( "invalid input argument. Stride argument must be a number." );
return -1;
}
j = ( i-2 ) / 2;
strides[ j ] = static_cast<int64_t>( info[ i ]->IntegerValue() );
}
#if defined(V8_MAJOR_VERSION) && ( V8_MAJOR_VERSION > 4 || ( V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3 ) )
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsArrayBufferView() ) {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
} else if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
nsargs += 1;
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
if ( !info[ i ]->IsArrayBufferView() ) {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return -1;
} else {
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = typed_array_data_type( info[ i ] );
strides[ j ] *= stdlib_ndarray_bytes_per_element( types[ j ] );
}
}
#else
// TODO: add support for older Node versions (type verification and strides; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc and https://github.com/nodejs/nan/blob/master/nan_typedarray_contents.h)
// Input strided array arguments are every other argument beginning from the second argument...
for ( i = 1; i < iout; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsNumber() ) {
sargs |= (1<<j);
nsargs += 1;
} else if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from the typed array instance)
} else {
ThrowTypeError( "invalid input argument. Input strided array argument must be a typed array or scalar." );
return -1;
}
}
// Output strided array arguments are every other argument beginning from the argument following the last input strided array stride argument...
for ( i = iout; i < nargs; i += 2 ) {
j = ( i-1 ) / 2;
if ( info[ i ]->IsObject() && !info[ i ]->IsNull() ) {
// Assume a typed array:
TypedArrayContents<uint8_t> TypedArray( info[ i ] );
arrays[ j ] = *TypedArray;
types[ j ] = STDLIB_NDARRAY_FLOAT64; // TODO: determine data type (will require determining the typed array "class"; see https://github.com/nodejs/node/blob/v0.10.39-release/src/v8_typed_array.cc#L462)
strides[ j ] *= 8; // TODO: compute based on data type (or glean directly from typed array instance)
} else {
ThrowTypeError( "invalid input argument. Output strided array arguments must be typed arrays." );
return -1;
}
}
#endif
// Check if we have been provided only scalar input arguments...
if ( nin > 0 && nsargs == nin ) {
ThrowError( "invalid input arguments. Must provide at least one input strided array argument." );
return -1;
}
return nsargs;
}
/**
* Adds each element in `X` to a corresponding element in `Y` and assigns the result to an element in `Z`.
*
* When called from JavaScript, the function expects the following arguments:
*
* * __N__: number of elements.
* * __X__: input typed array.
* * __strideX__: `X` stride length.
* * __Y__: input typed array.
* * __strideY__: `Y` typed array stride length.
* * __Z__: destination typed array.
* * __strideZ__: destination typed array stride length.
*
* @param info arguments
*/
void node_add( const FunctionCallbackInfo<Value>& info ) {
enum STDLIB_NDARRAY_DTYPE types[3];
uint8_t *arrays[3];
int64_t strides[3];
int64_t shape[1];
int64_t nsargs;
int64_t nargs;
int64_t nout;
int64_t nin;
// Total number of input arguments:
nargs = 7;
// Number of input and output strided array arguments:
nin = 2;
nout = 1;
// Validate, extract, and transform strided array function arguments:
nsargs = stdlib_nan_addon_strided_array_function_arguments( info, nargs, nin, nout, arrays, shape, strides, types );
if ( nsargs < 0 ) {
return;
}
// Broadcasting of scalar arguments...
if ( nsargs > 0 ) {
// Create an array having the closest "compatible" type...
// arrays[ 0 ] = broadcast( static_cast<double>( info[ 1 ]->NumberValue() ), types[ 0 ] );
}
// Perform addition:
stdlib_strided_dd_d( arrays, shape, strides, (void *)add );
}
NAN_MODULE_INIT( Init ) {
Nan::Export( target, "add", node_add );
}
NODE_MODULE( addon, Init )
} // end namespace addon_strided_add
|
Document thrown errors
|
Document thrown errors
|
C++
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
838a038cbdce8b6ea503e1b7b1954efafa7fc752
|
log.cc
|
log.cc
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
/*
* 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 "log.hh"
#include "core/array_map.hh"
#include <cxxabi.h>
#include <system_error>
#include <boost/range/adaptor/map.hpp>
#include <map>
#include <syslog.h>
#include <seastar/core/reactor.hh>
namespace logging {
registry& logger_registry();
const std::map<log_level, sstring> log_level_names = {
{ log_level::trace, "trace" },
{ log_level::debug, "debug" },
{ log_level::info, "info" },
{ log_level::warn, "warn" },
{ log_level::error, "error" },
};
}
using namespace logging;
std::ostream& operator<<(std::ostream& out, log_level level) {
return out << log_level_names.at(level);
}
std::istream& operator>>(std::istream& in, log_level& level) {
sstring s;
in >> s;
if (!in) {
return in;
}
for (auto&& x : log_level_names) {
if (s == x.second) {
level = x.first;
return in;
}
}
in.setstate(std::ios::failbit);
return in;
}
namespace logging {
std::atomic<bool> logger::_stdout = { true };
std::atomic<bool> logger::_syslog = { false };
logger::logger(sstring name) : _name(std::move(name)) {
logger_registry().register_logger(this);
}
logger::logger(logger&& x) : _name(std::move(x._name)), _level(x._level.load(std::memory_order_relaxed)) {
logger_registry().moved(&x, this);
}
logger::~logger() {
logger_registry().unregister_logger(this);
}
void
logger::really_do_log(log_level level, const char* fmt, stringer** s, size_t n) {
int syslog_offset = 0;
std::ostringstream out;
static array_map<sstring, 20> level_map = {
{ int(log_level::debug), "DEBUG" },
{ int(log_level::info), "INFO " },
{ int(log_level::trace), "TRACE" },
{ int(log_level::warn), "WARN " },
{ int(log_level::error), "ERROR" },
};
out << level_map[int(level)];
syslog_offset += 5;
if (_stdout.load(std::memory_order_relaxed)) {
auto now = std::chrono::system_clock::now();
auto residual_millis =
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() % 1000;
auto tm = std::chrono::system_clock::to_time_t(now);
char tmp[100];
strftime(tmp, sizeof(tmp), " %Y-%m-%d %T", std::localtime(&tm));
out << tmp << sprint(",%03d", residual_millis);
syslog_offset += 24;
}
out << " [shard " << engine().cpu_id() << "] " << _name << " - ";
const char* p = fmt;
while (*p != '\0') {
if (*p == '{' && *(p+1) == '}') {
p += 2;
if (n > 0) {
try {
(*s)->append(out);
} catch (...) {
out << '<' << std::current_exception() << '>';
}
++s;
--n;
} else {
out << "???";
}
} else {
out << *p++;
}
}
out << "\n";
auto msg = out.str();
if (_stdout.load(std::memory_order_relaxed)) {
std::cout << msg;
}
if (_syslog.load(std::memory_order_relaxed)) {
static array_map<int, 20> level_map = {
{ int(log_level::debug), LOG_DEBUG },
{ int(log_level::info), LOG_INFO },
{ int(log_level::trace), LOG_DEBUG }, // no LOG_TRACE
{ int(log_level::warn), LOG_WARNING },
{ int(log_level::error), LOG_ERR },
};
// NOTE: syslog() can block, which will stall the reactor thread.
// this should be rare (will have to fill the pipe buffer
// before syslogd can clear it) but can happen. If it does,
// we'll have to implement some internal buffering (which
// still means the problem can happen, just less frequently).
// syslog() interprets % characters, so send msg as a parameter
syslog(level_map[int(level)], "%s", msg.c_str() + syslog_offset);
}
}
void
logger::set_stdout_enabled(bool enabled) {
_stdout.store(enabled, std::memory_order_relaxed);
}
void
logger::set_syslog_enabled(bool enabled) {
_syslog.store(enabled, std::memory_order_relaxed);
}
void
registry::set_all_loggers_level(log_level level) {
std::lock_guard<std::mutex> g(_mutex);
for (auto&& l : _loggers | boost::adaptors::map_values) {
l->set_level(level);
}
}
log_level
registry::get_logger_level(sstring name) const {
std::lock_guard<std::mutex> g(_mutex);
return _loggers.at(name)->level();
}
void
registry::set_logger_level(sstring name, log_level level) {
std::lock_guard<std::mutex> g(_mutex);
_loggers.at(name)->set_level(level);
}
std::vector<sstring>
registry::get_all_logger_names() {
std::lock_guard<std::mutex> g(_mutex);
auto ret = _loggers | boost::adaptors::map_keys;
return std::vector<sstring>(ret.begin(), ret.end());
}
void
registry::register_logger(logger* l) {
std::lock_guard<std::mutex> g(_mutex);
_loggers[l->name()] = l;
}
void
registry::unregister_logger(logger* l) {
std::lock_guard<std::mutex> g(_mutex);
_loggers.erase(l->name());
}
void
registry::moved(logger* from, logger* to) {
std::lock_guard<std::mutex> g(_mutex);
_loggers[from->name()] = to;
}
sstring pretty_type_name(const std::type_info& ti) {
int status;
std::unique_ptr<char[], void (*)(void*)> result(
abi::__cxa_demangle(ti.name(), 0, 0, &status), std::free);
return result.get() ? result.get() : ti.name();
}
registry& logger_registry() {
static registry g_registry;
return g_registry;
}
sstring level_name(log_level level) {
return log_level_names.at(level);
}
}
namespace boost {
template <>
logging::log_level lexical_cast(const std::string& source) {
std::istringstream in(source);
logging::log_level level;
// Using the operator normall fails.
if (!::operator>>(in, level)) {
throw boost::bad_lexical_cast();
}
return level;
}
}
namespace std {
std::ostream& operator<<(std::ostream& out, const std::exception_ptr& eptr) {
if (!eptr) {
out << "<no exception>";
return out;
}
try {
std::rethrow_exception(eptr);
} catch(...) {
auto tp = abi::__cxa_current_exception_type();
if (tp) {
out << logging::pretty_type_name(*tp);
} else {
// This case shouldn't happen...
out << "<unknown exception>";
}
// Print more information on some familiar exception types
try {
throw;
} catch(const std::system_error &e) {
out << " (error " << e.code() << ", " << e.code().message() << ")";
} catch(const std::exception& e) {
out << " (" << e.what() << ")";
}
}
return out;
}
}
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
/*
* 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 "log.hh"
#include "core/array_map.hh"
#include <cxxabi.h>
#include <system_error>
#include <boost/range/adaptor/map.hpp>
#include <map>
#include <syslog.h>
#include <seastar/core/reactor.hh>
namespace logging {
registry& logger_registry();
const std::map<log_level, sstring> log_level_names = {
{ log_level::trace, "trace" },
{ log_level::debug, "debug" },
{ log_level::info, "info" },
{ log_level::warn, "warn" },
{ log_level::error, "error" },
};
}
using namespace logging;
std::ostream& operator<<(std::ostream& out, log_level level) {
return out << log_level_names.at(level);
}
std::istream& operator>>(std::istream& in, log_level& level) {
sstring s;
in >> s;
if (!in) {
return in;
}
for (auto&& x : log_level_names) {
if (s == x.second) {
level = x.first;
return in;
}
}
in.setstate(std::ios::failbit);
return in;
}
namespace logging {
std::atomic<bool> logger::_stdout = { true };
std::atomic<bool> logger::_syslog = { false };
logger::logger(sstring name) : _name(std::move(name)) {
logger_registry().register_logger(this);
}
logger::logger(logger&& x) : _name(std::move(x._name)), _level(x._level.load(std::memory_order_relaxed)) {
logger_registry().moved(&x, this);
}
logger::~logger() {
logger_registry().unregister_logger(this);
}
void
logger::really_do_log(log_level level, const char* fmt, stringer** s, size_t n) {
int syslog_offset = 0;
std::ostringstream out;
static array_map<sstring, 20> level_map = {
{ int(log_level::debug), "DEBUG" },
{ int(log_level::info), "INFO " },
{ int(log_level::trace), "TRACE" },
{ int(log_level::warn), "WARN " },
{ int(log_level::error), "ERROR" },
};
out << level_map[int(level)];
syslog_offset += 5;
if (_stdout.load(std::memory_order_relaxed)) {
auto now = std::chrono::system_clock::now();
auto residual_millis =
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() % 1000;
auto tm = std::chrono::system_clock::to_time_t(now);
char tmp[100];
strftime(tmp, sizeof(tmp), " %Y-%m-%d %T", std::localtime(&tm));
out << tmp << sprint(",%03d", residual_millis);
syslog_offset += 24;
}
out << " [shard " << engine().cpu_id() << "] " << _name << " - ";
const char* p = fmt;
while (*p != '\0') {
if (*p == '{' && *(p+1) == '}') {
p += 2;
if (n > 0) {
try {
(*s)->append(out);
} catch (...) {
out << '<' << std::current_exception() << '>';
}
++s;
--n;
} else {
out << "???";
}
} else {
out << *p++;
}
}
out << "\n";
auto msg = out.str();
if (_stdout.load(std::memory_order_relaxed)) {
std::cout << msg;
}
if (_syslog.load(std::memory_order_relaxed)) {
static array_map<int, 20> level_map = {
{ int(log_level::debug), LOG_DEBUG },
{ int(log_level::info), LOG_INFO },
{ int(log_level::trace), LOG_DEBUG }, // no LOG_TRACE
{ int(log_level::warn), LOG_WARNING },
{ int(log_level::error), LOG_ERR },
};
// NOTE: syslog() can block, which will stall the reactor thread.
// this should be rare (will have to fill the pipe buffer
// before syslogd can clear it) but can happen. If it does,
// we'll have to implement some internal buffering (which
// still means the problem can happen, just less frequently).
// syslog() interprets % characters, so send msg as a parameter
syslog(level_map[int(level)], "%s", msg.c_str() + syslog_offset);
}
}
void
logger::set_stdout_enabled(bool enabled) {
_stdout.store(enabled, std::memory_order_relaxed);
}
void
logger::set_syslog_enabled(bool enabled) {
_syslog.store(enabled, std::memory_order_relaxed);
}
void
registry::set_all_loggers_level(log_level level) {
std::lock_guard<std::mutex> g(_mutex);
for (auto&& l : _loggers | boost::adaptors::map_values) {
l->set_level(level);
}
}
log_level
registry::get_logger_level(sstring name) const {
std::lock_guard<std::mutex> g(_mutex);
return _loggers.at(name)->level();
}
void
registry::set_logger_level(sstring name, log_level level) {
std::lock_guard<std::mutex> g(_mutex);
_loggers.at(name)->set_level(level);
}
std::vector<sstring>
registry::get_all_logger_names() {
std::lock_guard<std::mutex> g(_mutex);
auto ret = _loggers | boost::adaptors::map_keys;
return std::vector<sstring>(ret.begin(), ret.end());
}
void
registry::register_logger(logger* l) {
std::lock_guard<std::mutex> g(_mutex);
_loggers[l->name()] = l;
}
void
registry::unregister_logger(logger* l) {
std::lock_guard<std::mutex> g(_mutex);
_loggers.erase(l->name());
}
void
registry::moved(logger* from, logger* to) {
std::lock_guard<std::mutex> g(_mutex);
_loggers[from->name()] = to;
}
sstring pretty_type_name(const std::type_info& ti) {
int status;
std::unique_ptr<char[], void (*)(void*)> result(
abi::__cxa_demangle(ti.name(), 0, 0, &status), std::free);
return result.get() ? result.get() : ti.name();
}
registry& logger_registry() {
static registry g_registry;
return g_registry;
}
sstring level_name(log_level level) {
return log_level_names.at(level);
}
}
namespace boost {
template <>
logging::log_level lexical_cast(const std::string& source) {
std::istringstream in(source);
logging::log_level level;
// Using the operator normall fails.
if (!::operator>>(in, level)) {
throw boost::bad_lexical_cast();
}
return level;
}
}
namespace std {
std::ostream& operator<<(std::ostream& out, const std::exception_ptr& eptr) {
if (!eptr) {
out << "<no exception>";
return out;
}
try {
std::rethrow_exception(eptr);
} catch(...) {
auto tp = abi::__cxa_current_exception_type();
if (tp) {
out << logging::pretty_type_name(*tp);
} else {
// This case shouldn't happen...
out << "<unknown exception>";
}
// Print more information on some familiar exception types
try {
throw;
} catch(const std::system_error &e) {
out << " (error " << e.code() << ", " << e.code().message() << ")";
} catch(const std::exception& e) {
out << " (" << e.what() << ")";
} catch(...) {
// no extra info
}
}
return out;
}
}
|
Fix operator<<(std::ostream&, const std::exception_ptr&)
|
log: Fix operator<<(std::ostream&, const std::exception_ptr&)
Attempt to print std::nested_exception currently results in exception
to leak outside the printer. Fix by capturing all exception in the
final catch block.
For nested exception, the logger will print now just
"std::nested_exception". For nested exceptions specifically we should
log more, but that is a separate problem to solve.
Message-Id: <[email protected]>
|
C++
|
agpl-3.0
|
scylladb/scylla,avikivity/scylla,kjniemi/scylla,raphaelsc/scylla,avikivity/scylla,scylladb/scylla,raphaelsc/scylla,duarten/scylla,scylladb/scylla,avikivity/scylla,kjniemi/scylla,duarten/scylla,kjniemi/scylla,raphaelsc/scylla,duarten/scylla,scylladb/scylla
|
cf6e08aa52867558b977ad2699227ec487dd8bc4
|
plugins/input/ogr/ogr_index_featureset.cpp
|
plugins/input/ogr/ogr_index_featureset.cpp
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/value_types.hpp>
#include <mapnik/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/mapped_memory_cache.hpp>
#include <mapnik/feature_factory.hpp>
// boost
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
// ogr
#include "ogr_index_featureset.hpp"
#include "ogr_converter.hpp"
#include "ogr_index.hpp"
using mapnik::query;
using mapnik::box2d;
using mapnik::feature_ptr;
using mapnik::geometry_utils;
using mapnik::transcoder;
using mapnik::feature_factory;
template <typename filterT>
ogr_index_featureset<filterT>::ogr_index_featureset(mapnik::context_ptr const & ctx,
OGRLayer & layer,
filterT const& filter,
std::string const& index_file,
std::string const& encoding)
: ctx_(ctx),
layer_(layer),
layerdef_(layer.GetLayerDefn()),
filter_(filter),
tr_(new transcoder(encoding)),
fidcolumn_(layer_.GetFIDColumn()),
feature_envelope_()
{
boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(index_file, true);
if (memory)
{
boost::interprocess::ibufferstream file(static_cast<char*>((*memory)->get_address()),(*memory)->get_size());
ogr_index<filterT,boost::interprocess::ibufferstream >::query(filter,file,ids_);
}
std::sort(ids_.begin(),ids_.end());
MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Query size=" << ids_.size();
itr_ = ids_.begin();
// reset reading
layer_.ResetReading();
}
template <typename filterT>
ogr_index_featureset<filterT>::~ogr_index_featureset() {}
template <typename filterT>
feature_ptr ogr_index_featureset<filterT>::next()
{
while (itr_ != ids_.end())
{
int pos = *itr_++;
layer_.SetNextByIndex (pos);
OGRFeature *poFeature = layer_.GetNextFeature();
if (poFeature == NULL)
{
return feature_ptr();
}
// ogr feature ids start at 0, so add one to stay
// consistent with other mapnik datasources that start at 1
mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
feature_ptr feature(feature_factory::create(ctx_,feature_id));
OGRGeometry* geom=poFeature->GetGeometryRef();
if (geom && !geom->IsEmpty())
{
geom->getEnvelope(&feature_envelope_);
if (!filter_.pass(mapnik::box2d<double>(feature_envelope_.MinX,feature_envelope_.MinY,
feature_envelope_.MaxX,feature_envelope_.MaxY))) continue;
ogr_converter::convert_geometry (geom, feature);
}
else
{
MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Feature with null geometry="
<< poFeature->GetFID();
OGRFeature::DestroyFeature( poFeature );
continue;
}
int fld_count = layerdef_->GetFieldCount();
for (int i = 0; i < fld_count; i++)
{
OGRFieldDefn* fld = layerdef_->GetFieldDefn (i);
OGRFieldType type_oid = fld->GetType ();
std::string fld_name = fld->GetNameRef ();
switch (type_oid)
{
case OFTInteger:
{
feature->put<mapnik::value_integer>(fld_name,poFeature->GetFieldAsInteger (i));
break;
}
case OFTReal:
{
feature->put(fld_name,poFeature->GetFieldAsDouble (i));
break;
}
case OFTString:
case OFTWideString: // deprecated !
{
UnicodeString ustr = tr_->transcode(poFeature->GetFieldAsString (i));
feature->put(fld_name,ustr);
break;
}
case OFTIntegerList:
case OFTRealList:
case OFTStringList:
case OFTWideStringList: // deprecated !
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
break;
}
case OFTBinary:
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
//feature->put(name,feat->GetFieldAsBinary (i, size));
break;
}
case OFTDate:
case OFTTime:
case OFTDateTime: // unhandled !
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
break;
}
}
}
OGRFeature::DestroyFeature( poFeature );
return feature;
}
return feature_ptr();
}
template class ogr_index_featureset<mapnik::filter_in_box>;
template class ogr_index_featureset<mapnik::filter_at_point>;
|
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/value_types.hpp>
#include <mapnik/global.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_layer_desc.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/feature_factory.hpp>
// boost
#ifdef SHAPE_MEMORY_MAPPED_FILE
#include <mapnik/mapped_memory_cache.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/streams/bufferstream.hpp>
#endif
// ogr
#include "ogr_index_featureset.hpp"
#include "ogr_converter.hpp"
#include "ogr_index.hpp"
using mapnik::query;
using mapnik::box2d;
using mapnik::feature_ptr;
using mapnik::geometry_utils;
using mapnik::transcoder;
using mapnik::feature_factory;
template <typename filterT>
ogr_index_featureset<filterT>::ogr_index_featureset(mapnik::context_ptr const & ctx,
OGRLayer & layer,
filterT const& filter,
std::string const& index_file,
std::string const& encoding)
: ctx_(ctx),
layer_(layer),
layerdef_(layer.GetLayerDefn()),
filter_(filter),
tr_(new transcoder(encoding)),
fidcolumn_(layer_.GetFIDColumn()),
feature_envelope_()
{
#ifdef SHAPE_MEMORY_MAPPED_FILE
boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(index_file, true);
if (memory)
{
boost::interprocess::ibufferstream file(static_cast<char*>((*memory)->get_address()),(*memory)->get_size());
ogr_index<filterT,boost::interprocess::ibufferstream >::query(filter,file,ids_);
}
#else
#if defined (WINDOWS)
std::ifstream file(mapnik::utf8_to_utf16(index_file), std::ios::in | std::ios::binary);
#else
std::ifstream file(index_file.c_str(), std::ios::in | std::ios::binary);
#endif
ogr_index<filterT,std::ifstream>::query(filter,file,ids_);
#endif
std::sort(ids_.begin(),ids_.end());
MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Query size=" << ids_.size();
itr_ = ids_.begin();
// reset reading
layer_.ResetReading();
}
template <typename filterT>
ogr_index_featureset<filterT>::~ogr_index_featureset() {}
template <typename filterT>
feature_ptr ogr_index_featureset<filterT>::next()
{
while (itr_ != ids_.end())
{
int pos = *itr_++;
layer_.SetNextByIndex (pos);
OGRFeature *poFeature = layer_.GetNextFeature();
if (poFeature == NULL)
{
return feature_ptr();
}
// ogr feature ids start at 0, so add one to stay
// consistent with other mapnik datasources that start at 1
mapnik::value_integer feature_id = (poFeature->GetFID() + 1);
feature_ptr feature(feature_factory::create(ctx_,feature_id));
OGRGeometry* geom=poFeature->GetGeometryRef();
if (geom && !geom->IsEmpty())
{
geom->getEnvelope(&feature_envelope_);
if (!filter_.pass(mapnik::box2d<double>(feature_envelope_.MinX,feature_envelope_.MinY,
feature_envelope_.MaxX,feature_envelope_.MaxY))) continue;
ogr_converter::convert_geometry (geom, feature);
}
else
{
MAPNIK_LOG_DEBUG(ogr) << "ogr_index_featureset: Feature with null geometry="
<< poFeature->GetFID();
OGRFeature::DestroyFeature( poFeature );
continue;
}
int fld_count = layerdef_->GetFieldCount();
for (int i = 0; i < fld_count; i++)
{
OGRFieldDefn* fld = layerdef_->GetFieldDefn (i);
OGRFieldType type_oid = fld->GetType ();
std::string fld_name = fld->GetNameRef ();
switch (type_oid)
{
case OFTInteger:
{
feature->put<mapnik::value_integer>(fld_name,poFeature->GetFieldAsInteger (i));
break;
}
case OFTReal:
{
feature->put(fld_name,poFeature->GetFieldAsDouble (i));
break;
}
case OFTString:
case OFTWideString: // deprecated !
{
UnicodeString ustr = tr_->transcode(poFeature->GetFieldAsString (i));
feature->put(fld_name,ustr);
break;
}
case OFTIntegerList:
case OFTRealList:
case OFTStringList:
case OFTWideStringList: // deprecated !
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
break;
}
case OFTBinary:
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
//feature->put(name,feat->GetFieldAsBinary (i, size));
break;
}
case OFTDate:
case OFTTime:
case OFTDateTime: // unhandled !
{
MAPNIK_LOG_WARN(ogr) << "ogr_index_featureset: Unhandled type_oid=" << type_oid;
break;
}
}
}
OGRFeature::DestroyFeature( poFeature );
return feature;
}
return feature_ptr();
}
template class ogr_index_featureset<mapnik::filter_in_box>;
template class ogr_index_featureset<mapnik::filter_at_point>;
|
disable (by default) use of shared memory in ogr plugin
|
disable (by default) use of shared memory in ogr plugin
|
C++
|
lgpl-2.1
|
yiqingj/work,tomhughes/python-mapnik,naturalatlas/mapnik,jwomeara/mapnik,lightmare/mapnik,mbrukman/mapnik,whuaegeanse/mapnik,mapnik/python-mapnik,mbrukman/mapnik,qianwenming/mapnik,garnertb/python-mapnik,mapnik/python-mapnik,Uli1/mapnik,mapycz/mapnik,davenquinn/python-mapnik,CartoDB/mapnik,Mappy/mapnik,manz/python-mapnik,sebastic/python-mapnik,yohanboniface/python-mapnik,mapnik/mapnik,mapycz/python-mapnik,Mappy/mapnik,lightmare/mapnik,rouault/mapnik,yiqingj/work,mapnik/mapnik,tomhughes/mapnik,manz/python-mapnik,garnertb/python-mapnik,whuaegeanse/mapnik,Airphrame/mapnik,Mappy/mapnik,sebastic/python-mapnik,zerebubuth/mapnik,naturalatlas/mapnik,mbrukman/mapnik,rouault/mapnik,kapouer/mapnik,CartoDB/mapnik,Uli1/mapnik,jwomeara/mapnik,qianwenming/mapnik,yohanboniface/python-mapnik,sebastic/python-mapnik,qianwenming/mapnik,qianwenming/mapnik,lightmare/mapnik,Uli1/mapnik,zerebubuth/mapnik,pramsey/mapnik,cjmayo/mapnik,zerebubuth/mapnik,kapouer/mapnik,garnertb/python-mapnik,mapnik/python-mapnik,tomhughes/mapnik,tomhughes/mapnik,pnorman/mapnik,naturalatlas/mapnik,mapnik/mapnik,tomhughes/python-mapnik,pramsey/mapnik,kapouer/mapnik,mbrukman/mapnik,cjmayo/mapnik,cjmayo/mapnik,stefanklug/mapnik,rouault/mapnik,rouault/mapnik,tomhughes/mapnik,mapycz/mapnik,tomhughes/python-mapnik,Airphrame/mapnik,mapnik/mapnik,Airphrame/mapnik,kapouer/mapnik,stefanklug/mapnik,mapycz/python-mapnik,jwomeara/mapnik,qianwenming/mapnik,naturalatlas/mapnik,yiqingj/work,pnorman/mapnik,cjmayo/mapnik,davenquinn/python-mapnik,Uli1/mapnik,pramsey/mapnik,whuaegeanse/mapnik,jwomeara/mapnik,yohanboniface/python-mapnik,mapycz/mapnik,Airphrame/mapnik,davenquinn/python-mapnik,pnorman/mapnik,CartoDB/mapnik,manz/python-mapnik,lightmare/mapnik,pramsey/mapnik,Mappy/mapnik,pnorman/mapnik,whuaegeanse/mapnik,yiqingj/work,stefanklug/mapnik,stefanklug/mapnik
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.